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:com.avanza.ymer.MirrorEnvironment.java

License:Apache License

public void removeFormatVersion(Class<?> dataType, Object id) {
    String collectionName = dataType.getSimpleName().substring(0, 1).toLowerCase()
            + dataType.getSimpleName().substring(1);
    DBCollection collection = getMongoDb().getCollection(collectionName);
    DBObject idQuery = BasicDBObjectBuilder.start("_id", id).get();
    DBCursor cursor = collection.find(idQuery);

    cursor.next();// ww  w  . j a va 2 s .c  o  m
    DBObject obj = cursor.curr();
    cursor.close();

    obj.removeField("_formatVersion");
    collection.update(idQuery, obj);
}

From source file:com.bbc.remarc.ws.MetadataService.java

License:Apache License

/**
 * Core random find service for entities that have metadata
 * /*from w w w .  j a v  a2  s. c om*/
 * @param db
 *            db instance
 * @param limit
 *            number of records to find
 * @param filter
 *            find records that match this filter. Can be null for no
 *            filtering
 * @param collectionName
 *            the database collection name
 * @return collection of found DBObjects
 */
protected List<DBObject> findRandom(DB db, long limit, DBObject filter, final String collectionName) {

    List<DBObject> results = new ArrayList<DBObject>();

    try {
        db.requestStart();
        Random random = new Random();
        DBCollection dbCollection = db.getCollection(collectionName);

        long maxRecords = dbCollection.count();

        if (limit > maxRecords) {
            limit = maxRecords;
        }

        for (int i = 0; i < limit; i++) {

            boolean foundUnique = false;

            int numChecked = 0;

            while (!foundUnique) {

                if (numChecked == limit) {
                    break;
                }

                int randomNumber = random.nextInt((int) dbCollection.count());

                DBObject randomRecord = null;

                if (filter == null) {
                    randomRecord = dbCollection.find().limit(-1).skip(randomNumber).next();
                } else {

                    DBCursor cursor = dbCollection.find(filter).limit(-1);

                    if (i >= cursor.count()) {
                        // we dont have enough records from the filter to
                        // match the limit
                        break;
                    }

                    randomNumber = random.nextInt((int) cursor.count());

                    randomRecord = cursor.skip(randomNumber).next();
                }

                foundUnique = resultsContains(randomRecord, results) == false;

                if (foundUnique) {
                    randomRecord.removeField("_id");
                    results.add(randomRecord);
                }
            }
        }
    } finally {
        db.requestDone();
    }
    return results;
}

From source file:com.caci.dummyserver.MongoRepository.java

private DBObject pruneDBObject(DBObject obj, Collection<String> fields) {
    if (fields != null && fields.size() > 0) {
        ArrayList<String> fieldList = new ArrayList<String>(obj.keySet());
        for (String field : fieldList) {
            if (!fields.contains(field)) {
                obj.removeField(field);
            }//from  w w w  .  j  av a2s  .  c  om
        }
    }
    return obj;
}

From source file:com.cc.manage.logic.BcompanyapplyLogic.java

/**
 * superuser?//from w ww  .j a  v  a 2 s.c  o m
 * 
 * @param request
 */
public String supercheck(HttpServletRequest request) {
    // ???id?1
    String id = RequestUtils.getString(request, "id");
    if (StringUtils.isNotBlank(id)) {
        try {
            String arr[] = StringUtils.stringToArray(id, AplicationKeyConstant.STRING_SPLIT_CHAR);
            List<DBObject> dblist = new ArrayList<DBObject>();
            DBObject conditionBean = new BasicDBObject();
            DBObject conditionBeannew = new BasicDBObject();
            for (String _id : arr) {
                // ?id?1
                conditionBean.put("_id", new ObjectId(_id));
                conditionBeannew.put("state", StateConstant.B_COMPANY_APPLY_STATE1);
                companyapplyDao.update(conditionBean, conditionBeannew);
                HistoryUtils.saveHistory("", request, TableNameConstant.T_COMPANY_APPLY,
                        conditionBean);
                // ??
                List<DBObject> dbobject = companyapplyDao.find(TableNameConstant.T_COMPANY_APPLY,
                        conditionBean);
                DBObject object = dbobject.get(0);
                object.put("companyno", String.valueOf(System.nanoTime()));
                DBObject stateBean = new BasicDBObject();
                stateBean.put("frame", StateConstant.B_COMPANY_UNALLOCAT);
                stateBean.put("role", StateConstant.B_COMPANY_UNALLOCAT);
                stateBean.put("product", StateConstant.B_COMPANY_UNALLOCAT);
                stateBean.put("companycc", StateConstant.B_COMPANY_UNALLOCAT);
                object.put("state", stateBean);
                object.removeField("_id");
                object.removeField("history");
                dblist.add(object);

            }
            companyDao.addBatch(dblist);// ???
            return ResultConstant.SUCCESS;

        } catch (Exception e) {
            log.error(e.getLocalizedMessage(), e);
        }

    }
    return ResultConstant.FAIL;
}

From source file:com.cc.manage.logic.BcompanyapplyLogic.java

/**
 * ?/*from   w  w w  . j a v  a2 s.c o  m*/
 * 
 * @param request
 */
public String check(HttpServletRequest request) {
    String data = RequestUtils.getString(request, "param");

    DBObject updateBean = new BasicDBObject();
    if (StringUtils.isNotBlank(data)) {
        JSONObject jsonBean = JSONObject.fromObject(data);
        String flowno = (String) jsonBean.get("flowno");
        String type = JSONUtils.getString(jsonBean, "type");

        if (AuditKey.AGREE_TYPE.equals(type)) {// ??
            DBObject queryBean = new BasicDBObject();
            queryBean.put("flowid", flowno);
            updateBean.put("state", StateConstant.B_COMPANY_APPLY_STATE1);// ??
            companyapplyDao.update(queryBean, updateBean);
            HistoryUtils.saveHistory("", request, "b_companyapply", queryBean);
            // ??
            List<DBObject> dbobject = companyapplyDao.find(TableNameConstant.T_COMPANY_APPLY, queryBean);
            DBObject object = dbobject.get(0);
            // ??
            object.put("companyno", String.valueOf(System.nanoTime()));
            DBObject stateBean = new BasicDBObject();
            stateBean.put("frame", StateConstant.B_COMPANY_UNALLOCAT);
            stateBean.put("role", StateConstant.B_COMPANY_UNALLOCAT);
            stateBean.put("product", StateConstant.B_COMPANY_UNALLOCAT);
            stateBean.put("companycc", StateConstant.B_COMPANY_UNALLOCAT);
            object.put("state", stateBean);
            object.removeField("_id");
            object.removeField("history");
            companyDao.add(object);
            HistoryUtils.saveHistory(object.get("history"), request, TableNameConstant.T_COMPANY,
                    new BasicDBObject());
        }
        JSONObject userSession = JSONObject
                .fromObject(request.getSession().getAttribute(SessionKey.SESSION_KEY_USER));
        if (userSession == null) {
            return ResultConstant.FAIL;
        }
        String uuid = JSONUtils.getString(userSession, "uuid"); // ?uuid
        jsonBean.put("uuid", uuid);

        AuditUtils.AuditRegister(jsonBean.toString());
        // ?
        return ResultConstant.SUCCESS;
    }
    return ResultConstant.FAIL;
}

From source file:com.cyslab.craftvm.rest.mongo.QueryServlet.java

License:GNU General Public License

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

    log.trace("doPost()");

    // server auth
    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);/*from  www  . j av a2s . co  m*/
        return;
    }

    String ret = null;

    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:com.cyslab.craftvm.rest.mongo.QueryServlet.java

License:GNU General Public License

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

    log.trace("doGet()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);//  w  w w.jav a2 s. c  o m
        return;
    }

    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");

    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:com.ebay.cloud.cms.dal.persistence.flatten.impl.embed.EmbedDBObjectFilter.java

License:Apache License

@SuppressWarnings("unchecked")
private static DBObject filterFields(DBObject currObject, Collection<String> fields) {
    if (fields == null || fields.isEmpty()) {
        return currObject;
    }//  ww w .j  a  va  2 s .  c  o  m

    Set<String> keys = (Set<String>) currObject.toMap().keySet();
    for (String key : keys) {
        if (!fields.contains(key)) {
            currObject.removeField(key);
        }
    }
    return currObject;
}

From source file:com.ebay.cloud.cms.dal.persistence.flatten.impl.root.RootReplaceCommand.java

License:Apache License

@Override
public void execute(PersistenceContext context) {
    DBObject getResult = RootGetCommand.findDBObject(entity.getId(), entity.getBranchId(), context,
            entity.getMetaClass(), ROOT_FIELDS, false);
    if (getResult != null) {
        // check version
        int currentVersion = (Integer) getResult.get(InternalFieldEnum.VERSION.getDbName());
        int version = entity.getVersion();
        if ((version != IEntity.NO_VERSION) && (currentVersion != version)) {
            throw new CmsDalException(DalErrCodeEnum.VERSION_CONFLICT, "current version is " + currentVersion
                    + ", but version in repalce body is " + version + "! entity is " + entity.toString());
        }// www .j ava 2  s  .c o  m

        Date createTime = (Date) getResult.get(InternalFieldEnum.CREATETIME.getDbName());

        DBObject queryObject = buildReplaceRootQuery(currentVersion);
        DBObject updateObject = buildReplaceRootUpdate(currentVersion, createTime);
        try {
            WriteResult result = MongoExecutor.update(context, entity.getMetaClass(), queryObject,
                    updateObject);
            if (result.getN() == 0) {
                throw new CmsDalException(DalErrCodeEnum.VERSION_CONFLICT,
                        "current version is not " + currentVersion + "! entity is " + entity.toString());
            }
            //set version for response
            entity.setVersion(currentVersion + 1);
        } catch (RuntimeException e) {
            entity.setVersion(currentVersion);
            throw e;
        } catch (Throwable t) {
            //if anything bad happens, need to set version back
            entity.setVersion(currentVersion);
        } finally {
            //in update scenario, have to set id value back into entity object because we
            //removed id field before
            entity.setId(entity.getId());
        }
    } else {
        // insert

        //2012/7/13 jianxu1 multi threading issue, if client A and client B send replace at same time
        //at T1, none of A and B find existing entity, so at T2, both A and B call insert, of we do not have 
        //unique index for combination of _branchId and _oid, we end up with duplicated entities.
        //FIX is: http://www.mongodb.org/display/DOCS/Indexes,  composite unique index
        //db.branches.ensureIndex({_branchId: 1, _oid: 1}, {unique: true});
        //TODO: change create repository to add composite unique index for branches, for main branch, we just need unique index on _oid

        DBObject insertObject = entity.getNode();
        insertObject.removeField("_id");
        insertObject.put(InternalFieldEnum.VERSION.getDbName(), IEntity.START_VERSION);
        MongoExecutor.insert(context, entity.getMetaClass(), insertObject);
    }
}

From source file:com.ebay.cloud.cms.dal.persistence.flatten.impl.root.RootReplaceCommand.java

License:Apache License

private DBObject buildReplaceRootUpdate(int currentVersion, Date createTime) {
    // add query version in case somebody make changes between get and update      
    DBObject rootUpdateObject = entity.getNode();
    rootUpdateObject.put(InternalFieldEnum.VERSION.getDbName(), currentVersion + 1);
    rootUpdateObject.put(InternalFieldEnum.CREATETIME.getDbName(), createTime);
    rootUpdateObject.put(InternalFieldEnum.STATUS.getDbName(), StatusEnum.ACTIVE.toString());
    // remove _id for sub branch
    rootUpdateObject.removeField("_id");
    return rootUpdateObject;
}