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:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public int viewFriendReq(int profileOwnerID, Vector<HashMap<String, ByteIterator>> values, boolean insertImage,
        boolean testMode) {
    int retVal = 0;
    if (profileOwnerID < 0)
        return -1;

    // first get all pending friendids for profileOwnerID
    com.mongodb.DB db = null;//ww w  .ja  v a2s . com

    try {
        db = mongo.getDB(database);
        db.requestStart();
        DBCollection collection = db.getCollection("users");
        DBObject q = new BasicDBObject().append("_id", profileOwnerID);
        q.removeField("pic");
        BasicDBObject fields = new BasicDBObject("pic", 0);

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

        String x = queryResult.get("PendFriends").toString();
        if (!x.equals("")) {
            x = x.substring(2, x.length() - 1);
            if (!x.equals("")) {
                String friendIds[] = x.split(",");
                BasicDBObject query = new BasicDBObject();

                List<Integer> list = new ArrayList<Integer>();
                if (!friendListReq) {
                    int cnt = 0;
                    for (int i = 0; i < friendIds.length; i++) {
                        cnt++;
                        HashMap<String, ByteIterator> vals = new HashMap<String, ByteIterator>();
                        DBObject frnd = new BasicDBObject().append("_id",
                                Integer.parseInt(friendIds[i].trim()));
                        frnd.removeField("pic");
                        DBObject frndQueryResult = null;
                        frndQueryResult = collection.findOne(frnd, fields);
                        if (frndQueryResult.get("tpic") != null) {
                            byte[] myPic = (byte[]) frndQueryResult.get("tpic");
                            vals.put("tpic", new ObjectByteIterator(myPic));
                            if (testMode) {
                                // Save loaded image from database into new
                                // image file
                                FileOutputStream fos = new FileOutputStream(
                                        profileOwnerID + "-" + i + "-mthumbimage.bmp");
                                fos.write(myPic);
                                fos.close();
                            }
                            frndQueryResult.removeField("tpic");
                        }
                        if (frndQueryResult != null) {
                            frndQueryResult.removeField("ConfFriends");
                            frndQueryResult.removeField("PendFriends");
                            frndQueryResult.removeField("wallResources");
                            vals.putAll(frndQueryResult.toMap());
                        }
                        if (vals.get("_id") != null) {
                            String tmp = vals.get("_id") + "";
                            vals.remove("_id");
                            vals.put("userid", new ObjectByteIterator(tmp.getBytes()));
                        }
                        values.add(vals);
                    }
                } else if (friendListReq) {// retrive one list
                    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, fields);
                    int cnt = 0;
                    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("PendFriends");
                        vals.remove("ConfFriends");
                        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()));
                        }
                        values.add(vals);
                    }
                    cursor.close();
                }

            }

        }

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

}

From source file:net.bunselmeyer.mongo.migrate.Migration.java

License:Apache License

protected void renameField(DB db, String collectionName, String from, String to) {
    DBCollection collection = db.getCollection(collectionName);
    DBObject query = new BasicDBObject(from, new BasicDBObject("$exists", true));
    DBCursor dbObjects = collection.find(query);
    for (DBObject dbObject : dbObjects) {
        dbObject.put(to, dbObject.get(from));
        dbObject.removeField(from);
        collection.save(dbObject);//from  w w  w.  j a v  a  2s. c o  m
    }
}

From source file:net.kamradtfamily.mongorest.QueryServlet.java

License:GNU General Public License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doPost()");

    // server auth
    String ret;//from   w w  w.jav  a 2  s  .c om

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }
    String skip = req.getParameter("skip");
    String limit = req.getParameter("limit");

    String _fields = req.getParameter("fields");
    String fields[] = null;
    if (_fields != null)
        fields = _fields.split("[,]");

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    StringBuilder buf = tl.get();
    // reset buf
    buf.setLength(0);

    BufferedReader r = null;
    DBObject q = null, sort = null;

    try {

        r = new BufferedReader(new InputStreamReader(is));
        String data = r.readLine();
        if (data == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(data);
            if (cache != null) {
                buf.append(db_name);
                buf.append(col_name);
                buf.append(data);
            }
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }
        // sort param
        data = r.readLine();
        if (data != null) {
            try {
                sort = (DBObject) JSON.parse(data);
            } catch (JSONParseException e) {
                error(res, SC_BAD_REQUEST, Status.get("can not parse sort arg"));
                return;
            }
            if (cache != null)
                buf.append(data);
        }

    } finally {
        if (r != null)
            r.close();
    }

    // limit
    int lim;
    if (limit != null) {
        try {
            lim = Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN);
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse limit"));
            return;
        }
    } else {
        lim = MAX_FIELDS_TO_RETURN;
    }
    if (cache != null) {
        buf.append(";limit=");
        buf.append(lim);
    }

    // skip
    int sk = -1;
    if (skip != null) {
        try {
            sk = Integer.parseInt(skip);
            if (cache != null) {
                buf.append(";skip=");
                buf.append(sk);
            }
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse skip"));
            return;
        }
    }

    // fields
    if (cache != null && _fields != null) {
        buf.append(";fields=");
        buf.append(_fields);
    }

    // from cache
    String cache_key = null;
    if (cache != null) {
        cache_key = buf.toString();
        try {
            ret = (String) cache.get(cache_key);
        }
        // some wrong char in key
        catch (IllegalArgumentException e) {
            int l = buf.length();
            for (int i = 0; i < l; i++) {
                if (buf.charAt(i) == ' ')
                    buf.setCharAt(i, '*');
            }
            cache_key = buf.toString();
            ret = (String) cache.get(cache_key);
        }
        if (ret != null) {
            out_str(req, ret, "application/json");
            return;
        }
    }

    // cursor
    DBCursor c;
    if (fields != null) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        int len = fields.length;
        for (int i = 0; i < len; i++) {
            String s = fields[i];
            sb.append('"');
            sb.append(s);
            sb.append('"');
            sb.append(":1");
            if (i != (len - 1))
                sb.append(",");
        }
        sb.append("}");
        c = col.find(q, (DBObject) JSON.parse(sb.toString()));
    } else
        c = col.find(q);

    if (c == null || c.count() == 0) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    if (sort != null)
        c.sort(sort);

    res.setIntHeader("X-Documents-Count", c.count());

    c.limit(lim);
    if (sk != -1)
        c.skip(sk);

    // reset buf
    buf.setLength(0);

    int no = 0;
    buf.append("[");
    while (c.hasNext()) {

        DBObject o = c.next();
        if (rm_id)
            o.removeField("_id");
        JSON.serialize(o, buf);
        buf.append(",");
        no++;

    }
    c.close();

    if (no > 0)
        buf.setCharAt(buf.length() - 1, ']');
    else
        buf.append(']');

    res.setIntHeader("X-Documents-Returned", no);

    ret = buf.toString();
    if (cache != null)
        cache.set(cache_key, ret);

    out_str(req, ret, "application/json");

}

From source file:net.kamradtfamily.mongorest.QueryServlet.java

License:GNU General Public License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doGet()");

    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];/*from  ww  w . j a v a  2s .  c  o  m*/
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }
    String skip = req.getParameter("skip");
    String limit = req.getParameter("limit");

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    DBCursor c = col.find();
    if (c == null || c.count() == 0) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    res.setIntHeader("X-Documents-Count", c.count());

    if (limit != null) {
        try {
            c.limit(Math.min(Integer.parseInt(limit), MAX_FIELDS_TO_RETURN));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse limit"));
            c.close();
            return;
        }
    } else
        c.limit(MAX_FIELDS_TO_RETURN);

    if (skip != null) {
        try {
            c.skip(Integer.parseInt(skip));
        } catch (NumberFormatException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse skip"));
            c.close();
            return;
        }
    }

    StringBuilder buf = tl.get();
    buf.setLength(0);

    int no = 0;
    buf.append("[");
    while (c.hasNext()) {

        DBObject o = c.next();
        if (rm_id)
            o.removeField("_id");
        JSON.serialize(o, buf);
        buf.append(",");
        no++;

    }
    c.close();

    if (no > 0)
        buf.setCharAt(buf.length() - 1, ']');
    else
        buf.append(']');

    res.setIntHeader("X-Documents-Returned", no);

    out_str(req, buf.toString(), "application/json");

}

From source file:net.tbnr.gearz.activerecord.GModel.java

License:Open Source License

/**
 * Turns this into a DBObject//from w ww  .j  ava2  s  .co  m
 *
 * @return DBObject
 */
DBObject getObjectValue(boolean includeNulls) {
    updateObjects();
    DBObject dbObject = basicDBObjectBuilder.get();
    if (includeNulls)
        return dbObject;
    DBObject object2 = cloneObject(dbObject);
    for (String s : dbObject.keySet()) {
        Object o = dbObject.get(s);
        if (o == null) {
            object2.removeField(s);
            continue;
        }
        if (o instanceof BasicDBObject && ((BasicDBObject) o).size() == 0) {
            object2.removeField(s);
            continue;
        }
        if (o instanceof BasicDBList && ((BasicDBList) o).size() == 0) {
            object2.removeField(s);
        }
    }
    return object2;
}

From source file:net.ymate.platform.persistence.mongodb.support.DefaultMongoSession.java

License:Apache License

public <T> WriteResult update(T entity) throws OperatorException {
    DBObject _value = MongoEntitySupport.randerToDBObject(entity);
    DBObject _cond = new BasicDBObject(MongoDB.OPT.ID, _value.removeField(MongoDB.OPT.ID));
    DBObject _set = new BasicDBObject(MongoDB.OPT.SET, _value);
    ////from  w ww.  j a  va  2s  .  c  om
    if (__sessionEvent != null) {
        __sessionEvent.onUpdateBefore(SessionEventObject.createUpdateEvent(entity, null));
    }
    //
    WriteResult _result = __clientHolder.getDB()
            .getCollection(MongoEntitySupport.getEntityName(entity.getClass()))
            .update(_cond, _set, false, false, __clientHolder.getWriteConcern());
    //
    if (__sessionEvent != null) {
        __sessionEvent.onUpdateAfter(SessionEventObject.createUpdateEvent(entity, null).addExtraParam(_result));
    }
    //
    return _result;
}

From source file:net.ymate.platform.persistence.mongodb.support.DefaultMongoSession.java

License:Apache License

public <T> WriteResult update(T entity, String[] fieldFilter) throws OperatorException {
    DBObject _value = MongoEntitySupport.randerToDBObject(entity);
    DBObject _cond = new BasicDBObject(MongoDB.OPT.ID, _value.removeField(MongoDB.OPT.ID));
    DBObject _set = null;//from   ww  w.  j av a 2 s  . c om
    if (fieldFilter != null && fieldFilter.length > 0) {
        DBObject _filterValue = new BasicDBObject();
        for (String _field : fieldFilter) {
            if (_field.equals(MongoDB.OPT.ID)) {
                continue;
            }
            _filterValue.put(_field, _value.get(_field));
        }
        _set = new BasicDBObject(MongoDB.OPT.SET, _filterValue.keySet().isEmpty() ? _value : _filterValue);
    } else {
        _set = new BasicDBObject(MongoDB.OPT.SET, _value);
    }
    //
    if (__sessionEvent != null) {
        __sessionEvent.onUpdateBefore(SessionEventObject.createUpdateEvent(entity, fieldFilter));
    }
    //
    WriteResult _result = __clientHolder.getDB()
            .getCollection(MongoEntitySupport.getEntityName(entity.getClass()))
            .update(_cond, _set, false, false, __clientHolder.getWriteConcern());
    //
    if (__sessionEvent != null) {
        __sessionEvent.onUpdateAfter(
                SessionEventObject.createUpdateEvent(entity, fieldFilter).addExtraParam(_result));
    }
    //
    return _result;
}

From source file:nl.knaw.huygens.timbuctoo.storage.mongo.MongoDiff.java

License:Open Source License

public static DBObject getObjectForDoc(Object doc) throws IOException {
    if (doc == null) {
        return null;
    }/*  w  w w. j a  va 2s.  c o m*/
    BsonObjectGenerator generator = new BsonObjectGenerator();
    dbWriter.writeValue(generator, doc);
    DBObject dbObject = generator.getDBObject();
    dbObject.removeField("@type");

    return generator.getDBObject();
}

From source file:org.alfresco.bm.event.mongo.MongoEventService.java

License:Open Source License

@Override
public String putEvent(Event event) {
    if (event == null) {
        throw new IllegalArgumentException("'event' may not be null.");
    }/*from   w w  w .j a  va2  s  . c  o  m*/
    DBObject insertObj = convertEvent(event);

    // Was the event's ID supplied to us
    ObjectId eventIdObj = (ObjectId) insertObj.get(Event.FIELD_ID);
    if (eventIdObj == null) {
        // We make up an ID here so that we can record the in-memory object, if necessary
        eventIdObj = new ObjectId();
        insertObj.put(Event.FIELD_ID, eventIdObj);
    }
    String eventId = eventIdObj.toString();

    // Replace the data with a key, if necessary
    Object data = event.getData();
    boolean storeInMem = event.getDataInMemory();
    if (storeInMem && data != null) {
        // We will only store the data if the insertion works
        insertObj.put(Event.FIELD_DATA_OWNER, dataOwner);
        insertObj.removeField(Event.FIELD_DATA);
        // The data will be removed when the event is plucked for processing
        // If we do an insert before putting this in the map, then it's possible for another
        // thread to pull the event before the local data is even in the map.
        runLocalData.put(eventId, data);
    }

    try {
        collection.insert(insertObj);
    } catch (MongoException e) {
        runLocalData.remove(eventId);
        throw new RuntimeException("Failed to insert event:\n" + "   Event: " + insertObj, e);
    }

    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("Put event: " + insertObj);
    }
    return eventId;
}

From source file:org.alfresco.bm.event.mongo.MongoResultService.java

License:Open Source License

@Override
public void recordResult(EventRecord result) {
    if (result == null) {
        throw new IllegalArgumentException("EventRecord may not be null.");
    }/*from  w  w w. ja  va  2  s .c om*/

    Event event = result.getEvent();
    if (event == null) {
        throw new IllegalArgumentException("EventRecord must contain an Event.");
    }

    DBObject eventObj = MongoEventService.convertEvent(event);
    // Remove the event data if it is not persistable
    if (event.getDataInMemory()) {
        eventObj.removeField(Event.FIELD_DATA);
    }
    // Remove data that is captured in the result
    eventObj.removeField(Event.FIELD_DATA_OWNER); // This is covered by the processedBy
    eventObj.removeField(Event.FIELD_ID); // Internal and not required
    eventObj.removeField(Event.FIELD_SCHEDULED_TIME); // This is the (startTime - startDelay)
    eventObj.removeField(Event.FIELD_LOCK_TIME); // Locking was an internal function
    eventObj.removeField(Event.FIELD_LOCK_OWNER); // Locking was an internal function

    BasicDBObjectBuilder insertObjBuilder = BasicDBObjectBuilder.start()
            .add(EventRecord.FIELD_PROCESSED_BY, result.getProcessedBy())
            .add(EventRecord.FIELD_CHART, result.isChart()).add(EventRecord.FIELD_DATA, result.getData())
            .add(EventRecord.FIELD_DRIVER_ID, result.getDriverId())
            .add(EventRecord.FIELD_START_DELAY, result.getStartDelay())
            .add(EventRecord.FIELD_START_TIME, new Date(result.getStartTime()))
            .add(EventRecord.FIELD_SUCCESS, result.isSuccess()).add(EventRecord.FIELD_TIME, result.getTime())
            .add(EventRecord.FIELD_EVENT, eventObj);
    if (result.getWarning() != null) {
        insertObjBuilder.add(EventRecord.FIELD_WARNING, result.getWarning());
    }
    DBObject insertObj = insertObjBuilder.get();

    try {
        collection.insert(insertObj);
    } catch (MongoException e) {
        throw new RuntimeException("Failed to insert event result:\n" + "   Result: " + insertObj, e);
    }
    // Done
    if (logger.isDebugEnabled()) {
        logger.debug("Recorded result: " + insertObj);
    }
}