Example usage for com.mongodb BasicDBObject removeField

List of usage examples for com.mongodb BasicDBObject removeField

Introduction

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

Prototype

public Object removeField(final String key) 

Source Link

Document

Deletes a field from this object.

Usage

From source file:br.bireme.scl.UndoUpdate.java

License:Open Source License

private static void undo(final String host, final int port, final String database, final String fromDate,
        final String docId) throws UnknownHostException, ParseException {
    assert host != null;
    assert port > 0;
    assert database != null;
    assert (fromDate != null || docId != null);

    final MongoClient client = new MongoClient(host, port);
    final DB db = client.getDB(database);
    final DBCollection from_coll = db.getCollection(HISTORY_COL);
    final DBCollection to_coll = db.getCollection(BROKEN_LINKS_COL);
    final String prefix = ELEM_LST_FIELD + ".0.";
    final BasicDBObject query;

    if (fromDate == null) {
        query = new BasicDBObject("_id", docId);
    } else {/* w  w w . java2 s  .  co  m*/
        final SimpleDateFormat simple = new SimpleDateFormat(
                "yyyyMMdd" + (fromDate.contains(":") ? "-HH:mm:ss" : ""));
        final Date fDate = simple.parse(fromDate);
        query = new BasicDBObject(prefix + LAST_UPDATE_FIELD, new BasicDBObject("$gte", fDate));
    }
    final DBCursor cursor = from_coll.find(query);
    int total = 0;
    int reverted = 0;

    System.out.println("host=" + host);
    System.out.println("port=" + port);
    System.out.println("database=" + database);
    if (fromDate == null) {
        System.out.println("doc id=" + docId);
    } else {
        System.out.println("from date=" + fromDate);
    }
    System.out.println("found=" + cursor.size());

    while (cursor.hasNext()) {
        final BasicDBObject doc_from = (BasicDBObject) cursor.next();
        final BasicDBObject doc_to = new BasicDBObject(doc_from);
        final String id = doc_from.getString(ID_FIELD);
        final BasicDBList list = (BasicDBList) doc_from.get(ELEM_LST_FIELD);
        final BasicDBObject elem = (BasicDBObject) list.get(0);
        final Date date = elem.getDate(LAST_UPDATE_FIELD);

        doc_to.put(LAST_UPDATE_FIELD, date);
        doc_to.put(BROKEN_URL_FIELD, elem.getString(BROKEN_URL_FIELD));
        doc_to.put(MSG_FIELD, elem.getString(MSG_FIELD));
        doc_to.put(CENTER_FIELD, elem.get(CENTER_FIELD));
        doc_to.removeField(ELEM_LST_FIELD);

        final WriteResult wr = to_coll.save(doc_to, WriteConcern.ACKNOWLEDGED);
        if (wr.getCachedLastError().ok()) {
            final WriteResult wr2 = from_coll.remove(doc_from, WriteConcern.ACKNOWLEDGED);
            if (wr2.getCachedLastError().ok()) {
                reverted++;
                System.out.println("+++id=" + id + " date=" + date);
            } else {
                System.err.println("Document[" + id + "] delete error.");
            }
        } else {
            System.err.println("Document[" + id + "] update error.");
        }
        total++;
    }
    cursor.close();

    System.out.println("total/undo: " + total + "/" + reverted);
}

From source file:com.ca.apm.mongo.Collector.java

License:Open Source License

private boolean isValidData(BasicDBObject bdo) {
    Object ok = bdo.get("ok");
    Object error = bdo.get("errmsg");
    if (ok != null && ((Number) ok).intValue() == 1 && error == null) {
        bdo.removeField("ok");
        return true;
    }//from w  w  w.ja v  a2s  .  co  m
    if (error != null) {
        logger.log(Level.WARNING, "Error from mongo command: {0}", error);
    } else {
        logger.log(Level.WARNING, "Invalid/unexpected mongo command output: {0}", bdo);
    }
    return false;
}

From source file:com.clavain.workers.MongoCheckWorker.java

License:Apache License

@Override
public void run() {

    String dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbchecks");
    db = m.getDB(dbName);/*from   ww  w.j a  va2 s .c  o  m*/

    logger.info("Started MongoCheckWorker");

    while (true) {
        try {
            BasicDBObject doc = mongo_check_queue.take();
            if (doc != null) {

                // index
                if (doc.getString("type").equals("check")) {
                    col = db.getCollection(doc.getString("user_id") + "cid" + doc.getString("cid"));
                } else {
                    col = db.getCollection(doc.getString("user_id") + "traces" + doc.getString("cid"));
                }
                doc.removeField("user_id");
                doc.removeField("type");

                col.insert(doc);
                if (logMore) {
                    logger.info("Mongo: Wrote " + doc.getString("hread") + " / " + doc.getString("cid"));
                }
                //db.requestDone();
            } else {
                Thread.sleep(50);
            }

        } catch (Exception ex) {
            logger.fatal("Error in MongoCheckWorker: " + ex.getLocalizedMessage());
            ex.printStackTrace();
        }

    }
}

From source file:com.clavain.workers.MongoEssentialWorker.java

License:Apache License

@Override
public void run() {

    String dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbessentials");
    db = m.getDB(dbName);/*from   w ww  . ja v a2  s  . co m*/

    logger.info("Started MongoWorker for MuninMX Essentials");
    String plugin = "";
    while (true) {
        try {
            BasicDBObject doc = mongo_essential_queue.take();
            if (doc != null) {
                // if trackpkg, add package entry, if essential information, store somewhere else
                if (doc.getString("type").equals("trackpkg")) {
                    col = db.getCollection("trackpkg");
                    doc.removeField("type");
                } else {
                    col = db.getCollection(doc.getString("node") + "_ess");
                    doc.removeField("node");
                    doc.removeField("type");
                }

                col.insert(doc);
                if (logMore) {
                    logger.info("Mongo: Wrote " + plugin + " / " + doc.getString("graph") + " / "
                            + doc.getString("value"));
                }
                //db.requestDone();
            } else {
                Thread.sleep(50);
            }

        } catch (Exception ex) {
            logger.fatal("Error in MongoEssentialWorker: " + ex.getLocalizedMessage());
            ex.printStackTrace();
        }

    }
}

From source file:com.clavain.workers.MongoWorker.java

License:Apache License

@Override
public void run() {

    String dbName = com.clavain.muninmxcd.p.getProperty("mongo.dbname");
    db = m.getDB(dbName);/*from  ww w  .ja va  2 s.  co m*/

    logger.info("Started MongoWorker");
    String plugin = "";
    while (true) {
        try {
            BasicDBObject doc = mongo_queue.take();
            if (doc != null) {
                plugin = doc.getString("plugin");
                // each hostname got its own collection
                col = db.getCollection(doc.getString("user_id") + "_" + doc.getString("nodeid"));
                doc.removeField("hostname");
                doc.removeField("nodeid");
                doc.removeField("user_id");
                //doc.removeField("plugin");
                //db.requestStart();
                col.insert(doc);
                if (logMore) {
                    logger.info("Mongo: Wrote " + plugin + " / " + doc.getString("graph") + " / "
                            + doc.getString("value"));
                }
                //db.requestDone();
            } else {
                Thread.sleep(50);
            }

        } catch (Exception ex) {
            logger.fatal("Error in MongoWorker: " + ex.getLocalizedMessage());
            ex.printStackTrace();
        }

    }
}

From source file:com.ebay.cloud.cms.dal.persistence.flatten.impl.embed.EmbedFieldDeleteCommand.java

License:Apache License

@Override
protected DBObject buildModifyBody(BitSet arrayBits, DBObject rootObject, MetaClass rootMetaClass) {
    MetaField field = getField();/* w  ww.  j a va  2 s  . c o  m*/
    BasicDBObject embedObject = (BasicDBObject) EmbedDBObjectFilter.filter(entity.getId(), rootObject,
            rootMetaClass, null, helper);
    embedObject.removeField(field.getFlattenValueDbName());
    // field properties
    for (FieldProperty fp : FieldProperty.values()) {
        String fpValueDbName = field.getFlattenPropertyValueDbName(fp);
        embedObject.removeField(fpValueDbName);
    }

    // need to update expression fields : set the payload from the given object to found rootObject
    MetaClass meta = getEntity().getMetaClass();
    if (meta.hasExpressionFields()) {
        List<MetaAttribute> expFields = meta.getExpressionFields();
        for (MetaAttribute expField : expFields) {
            String fieldValueDbName = expField.getFlattenValueDbName();
            embedObject.put(fieldValueDbName, getEntity().getNode().get(fieldValueDbName));
            // updateFieldProperty
            updateFieldProperty(embedObject, expField);
        }
    }

    embedObject.put(InternalFieldEnum.MODIFIER.getDbName(), entity.getModifier());
    embedObject.put(InternalFieldEnum.LASTMODIFIED.getDbName(), entity.getLastModified());

    return buildSetBody(rootObject);
}

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

License:Apache License

private DBObject buildModifyBody() {
    //Only root document have version, it's controlled by $inc
    BasicDBObject modifyBody = new BasicDBObject();
    BasicDBObject bsonObject = entity.getNode();

    //jianxu1: 2012/7/16 remove _id and _version
    bsonObject.removeField("_id");
    bsonObject.removeField(InternalFieldEnum.VERSION.getDbName());

    // CMS-2657 : for audit use case, make sure _status are in the modify body
    if (!entity.hasField(InternalFieldEnum.STATUS.getName())) {
        bsonObject.put(InternalFieldEnum.STATUS.getDbName(), StatusEnum.ACTIVE.toString());
    }/*w  w w.j a v a  2s. c o m*/

    modifyBody.put("$set", bsonObject);

    BasicDBObject versionObject = new BasicDBObject();
    versionObject.put(InternalFieldEnum.VERSION.getDbName(), 1);
    modifyBody.put("$inc", versionObject);
    return modifyBody;
}

From source file:com.ebay.cloud.cms.dal.persistence.impl.embed.EmbedFieldDeleteCommand.java

License:Apache License

@Override
protected DBObject buildModifyBody(BitSet arrayBits, DBObject rootObject, MetaClass rootMetaClass) {
    BasicDBObject embedObject = (BasicDBObject) EmbedDBObjectFilter.filter(entity.getId(), rootObject,
            rootMetaClass, null, helper);
    embedObject.removeField(getField().getDbName());

    MetaClass meta = getEntity().getMetaClass();
    if (meta.hasExpressionFields()) {
        List<MetaAttribute> expFields = meta.getExpressionFields();
        for (MetaAttribute expField : expFields) {
            String fieldDbName = expField.getDbName();
            embedObject.put(fieldDbName, getEntity().getNode().get(fieldDbName));
        }/*  w  ww . j  a  v a  2 s. com*/
    }

    embedObject.put(InternalFieldEnum.MODIFIER.getDbName(), entity.getModifier());
    embedObject.put(InternalFieldEnum.LASTMODIFIED.getDbName(), entity.getLastModified());

    return buildSetBody(rootObject);
}

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

License:Apache License

public void balancer(ButtonBase button) {
    final MongoClient mongo = getRouterNode().getMongoClient();
    final DB config = mongo.getDB("config");
    final DBCollection settings = config.getCollection("settings");

    FormDialog diag = (FormDialog) ((MenuItem) getBoundUnit(Item.balancer)).getDialog();
    diag.xmlLoadCheckpoint();//from   w  w w  .j  a  v a 2  s  .c om

    final BasicDBObject query = new BasicDBObject("_id", "balancer");
    BasicDBObject balDoc = (BasicDBObject) settings.findOne(query);
    if (balDoc != null) {
        if (balDoc.containsField("stopped"))
            setIntFieldValue(Item.balStopped, balDoc.getBoolean("stopped") ? 1 : 2);
        if (balDoc.containsField("_secondaryThrottle"))
            setIntFieldValue(Item.balSecThrottle, balDoc.getBoolean("_secondaryThrottle") ? 1 : 2);
        BasicDBObject window = (BasicDBObject) balDoc.get("activeWindow");
        if (window != null) {
            setStringFieldValue(Item.balStartTime, window.getString("start"));
            setStringFieldValue(Item.balStopTime, window.getString("stop"));
        }
    }

    if (!diag.show())
        return;

    if (balDoc == null)
        balDoc = new BasicDBObject("_id", "balancer");
    int stopped = getIntFieldValue(Item.balStopped);
    if (stopped > 0)
        balDoc.put("stopped", stopped == 1 ? true : false);
    else
        balDoc.removeField("stopped");
    int throttle = getIntFieldValue(Item.balSecThrottle);
    if (throttle > 0)
        balDoc.put("_secondaryThrottle", throttle == 1 ? true : false);
    else
        balDoc.removeField("_secondaryThrottle");

    if (!getStringFieldValue(Item.balStartTime).trim().isEmpty()) {
        BasicDBObject aw = new BasicDBObject();
        aw.put("start", getStringFieldValue(Item.balStartTime).trim());
        aw.put("stop", getStringFieldValue(Item.balStopTime).trim());
        balDoc.put("activeWindow", aw);
    }
    final BasicDBObject newDoc = balDoc;

    new DbJob() {

        @Override
        public Object doRun() throws IOException {
            return settings.update(query, newDoc, true, false);
        }

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

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

        @Override
        public void wrapUp(Object res) {
            updateComponent();
            super.wrapUp(res);
        }
    }.addJob();
}

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

License:Apache License

BasicDBObject getUser(BasicDBObject userObj) {
    final String user = getStringFieldValue(Item.user);
    if (userObj == null)
        userObj = new BasicDBObject("user", user);

    // do not overwrite password if not set
    final String pass = getStringFieldValue(Item.password);
    if (!pass.isEmpty())
        userObj.put("pwd", _hash(user, pass.toCharArray()));

    String userSrc = getStringFieldValue(Item.userSource);
    if (!userSrc.trim().isEmpty()) {
        userObj.put(Item.userSource.name(), userSrc);
        // cant have pwd
        userObj.removeField("pwd");
    }/*from   www .  ja v a2  s.  c  om*/

    if (!getBooleanFieldValue(Item.version22)) {
        // format from 2.4
        BasicDBList roles = new BasicDBList();
        for (Role role : Role.values()) {
            if (getBooleanFieldValue(role.item))
                roles.add(role.name());
        }
        userObj.put("roles", roles);

        // readOnly flag must be dropped
        userObj.removeField("readOnly");
    } else {
        // keep it simple: if readWrite is not checked, then readOnly
        if (!getBooleanFieldValue(Item.readWrite))
            userObj.put("readOnly", true);

        // remove roles
        userObj.removeField("roles");

        // all other flags should still be accepted
    }

    return userObj;
}