Example usage for com.mongodb DBCollection insert

List of usage examples for com.mongodb DBCollection insert

Introduction

In this page you can find the example usage for com.mongodb DBCollection insert.

Prototype

public WriteResult insert(final List<? extends DBObject> documents) 

Source Link

Document

Insert documents into a collection.

Usage

From source file:com.ebay.jetstream.configurationmanagement.MongoLogDAO.java

License:MIT License

/**
 * UPLOAD TO DB//w ww . ja  v  a  2  s . c  o  m
 */
public static void insertJetStreamConfiguration(BasicDBObject dbObject, MongoLogConnection mongoLogConnection) {
    JetStreamBeanConfigurationLogDo beanConfig = null;
    DBCollection dbCol = mongoLogConnection.getDBCollection();

    if (dbCol == null) {
        throw new MongoConfigRuntimeException("jetstreamconfig collection is unknown");
    }

    WriteResult result = dbCol.insert(dbObject);
    if (result.getError() != null) {
        throw new MongoConfigRuntimeException(result.getError());
    }
}

From source file:com.edduarte.argus.document.DocumentCollection.java

License:Apache License

/**
 * Adds the specified document to the local database.
 *///w  ww . ja v a 2  s  .c om
public void add(Document d) {
    if (d == null) {
        return;
    }
    DBCollection collection = documentsDB.getCollection(collectionName);
    collection.insert(d);
}

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  w  w .ja  v  a  2  s . co m
        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 doImport(final ButtonBase button) throws IOException {
    ImportDialog dia = UMongo.instance.getGlobalStore().getImportDialog();
    if (!dia.show()) {
        return;//from  w w w. j ava2 s.  c o m
    }
    final boolean dropCollection = dia.getBooleanFieldValue(ImportDialog.Item.dropCollection);
    final boolean continueOnError = dia.getBooleanFieldValue(ImportDialog.Item.continueOnError);
    final boolean upsert = dia.getBooleanFieldValue(ImportDialog.Item.upsert);
    final boolean bulk = dia.getBooleanFieldValue(ImportDialog.Item.bulk);
    String supsertFields = dia.getStringFieldValue(ImportDialog.Item.upsertFields);
    final String[] upsertFields = supsertFields != null ? supsertFields.split(",") : null;
    if (upsertFields != null) {
        for (int i = 0; i < upsertFields.length; ++i) {
            upsertFields[i] = upsertFields[i].trim();
        }
    }
    final DocumentDeserializer dd = dia.getDocumentDeserializer();
    final DBCollection col = getCollectionNode().getCollection();

    new DbJob() {
        @Override
        public Object doRun() throws Exception {
            try {
                if (dropCollection) {
                    col.drop();
                }
                DBObject obj = null;
                List<DBObject> batch = new ArrayList<DBObject>();
                while ((obj = dd.readObject()) != null) {
                    try {
                        if (upsert) {
                            if (upsertFields == null) {
                                col.save(obj);
                            } else {
                                BasicDBObject query = new BasicDBObject();
                                for (int i = 0; i < upsertFields.length; ++i) {
                                    String field = upsertFields[i];
                                    if (!obj.containsField(field)) {
                                        throw new Exception("Upsert field " + field + " not present in object "
                                                + obj.toString());
                                    }
                                    query.put(field, obj.get(field));
                                }
                                col.update(query, obj, true, false);
                            }
                        } else {
                            if (bulk) {
                                if (batch.size() > 1000) {
                                    col.insert(batch);
                                    batch.clear();
                                }
                                batch.add(obj);
                            } else {
                                col.insert(obj);
                            }
                        }
                    } catch (Exception e) {
                        if (continueOnError) {
                            getLogger().log(Level.WARNING, null, e);
                        } else {
                            throw e;
                        }
                    }
                }

                if (!batch.isEmpty()) {
                    col.insert(batch);
                }

            } finally {
                dd.close();
            }
            return null;
        }

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

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

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

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

License:Apache License

public void fixCollection(ButtonBase button) {
    final MongoClient m = getCollectionNode().getDbNode().getMongoNode().getMongoClient();
    ArrayList<MongoNode> mongoNodes = UMongo.instance.getMongos();
    String[] mongonames = new String[mongoNodes.size() - 1];
    MongoClient[] mongos = new MongoClient[mongonames.length];
    int i = 0;//from   www.  j a v  a 2  s .c  o  m
    for (MongoNode node : mongoNodes) {
        MongoClient m2 = node.getMongoClient();
        if (m == m2) {
            continue;
        }
        mongonames[i] = m2.toString();
        mongos[i] = m2;
        ++i;
    }
    ComboBox src = (ComboBox) getBoundUnit(Item.fcSrcMongo);
    src.items = mongonames;
    src.structureComponent();
    FormDialog dialog = (FormDialog) getBoundUnit(Item.fcDialog);
    if (!dialog.show()) {
        return;
    }

    final DBCollection dstCol = getCollectionNode().getCollection();
    final MongoClient srcMongo = mongos[src.getIntValue()];
    final boolean upsert = getBooleanFieldValue(Item.fcUpsert);

    final String dbname = dstCol.getDB().getName();
    final String colname = dstCol.getName();
    final DBCollection srcCol = srcMongo.getDB(dbname).getCollection(colname);
    String txt = "About to copy from ";
    txt += srcMongo.getConnectPoint() + "(" + srcCol.count() + ")";
    txt += " to ";
    txt += m.getConnectPoint() + "(" + dstCol.count() + ")";
    if (!new ConfirmDialog(null, "Confirm Fix Collection", null, txt).show()) {
        return;
    }

    new DbJob() {
        @Override
        public Object doRun() {
            DBCursor cur = srcCol.find();
            int count = 0;
            int dup = 0;
            while (cur.hasNext()) {
                DBObject obj = cur.next();
                if (upsert) {
                    BasicDBObject id = new BasicDBObject("_id", obj.get("_id"));
                    dstCol.update(id, obj, true, false);
                } else {
                    try {
                        dstCol.insert(obj);
                    } catch (DuplicateKey e) {
                        // dup keys are expected here
                        ++dup;
                    }
                }
                ++count;
            }
            DBObject res = new BasicDBObject("count", count);
            res.put("dups", dup);
            return res;
        }

        @Override
        public String getNS() {
            return "*";
        }

        @Override
        public String getShortName() {
            return "Fix Collection";
        }
    }.addJob();
}

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

License:Apache License

public void addTagRange(ButtonBase button) {
    final DB config = getCollectionNode().getCollection().getDB().getSisterDB("config");
    final DBCollection col = config.getCollection("tags");
    final String ns = getCollectionNode().getCollection().getFullName();

    TagRangeDialog dia = (TagRangeDialog) getBoundUnit(Item.tagRangeDialog);
    dia.resetForNew(config, ns);//ww w.  j av  a2s .  com
    if (!dia.show()) {
        return;
    }

    final BasicDBObject doc = dia.getRange(ns);

    new DbJob() {

        @Override
        public Object doRun() {
            return col.insert(doc);
        }

        @Override
        public String getNS() {
            return ns;
        }

        @Override
        public String getShortName() {
            return "Add Tag Range";
        }

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

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

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

License:Apache License

public void addUser(ButtonBase button) {
    final DB db = getDbNode().getDb();
    final DBCollection col = db.getCollection("system.users");

    UserDialog ud = (UserDialog) getBoundUnit(Item.userDialog);
    ud.resetForNew();//from  w  w w.java2s . c o  m
    if (!ud.show()) {
        return;
    }

    final BasicDBObject newUser = ud.getUser(null);

    new DbJob() {

        @Override
        public Object doRun() throws IOException {
            return col.insert(newUser);
        }

        @Override
        public String getNS() {
            return "system.users";
        }

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

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

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

License:Apache License

public void addJSFunction(final ButtonBase button) {
    final DB db = getDbNode().getDb();
    final DBCollection col = db.getCollection("system.js");
    final String name = getStringFieldValue(Item.addJSFunctionName);
    final String code = getStringFieldValue(Item.addJSFunctionCode);
    CollectionPanel.doFind(col, new BasicDBObject("_id", name));

    new DbJob() {

        @Override/*from  ww  w.j  a  v a2s.  co  m*/
        public Object doRun() throws Exception {
            DBObject obj = new BasicDBObject("_id", name);
            obj.put("value", new Code(code));
            return col.insert(obj);
        }

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

        @Override
        public String getShortName() {
            return "Add JS Function";
        }

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

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

License:Apache License

public void regenConfigDB(ButtonBase button) throws UnknownHostException {
    MongoClient cmongo = getRouterNode().getMongoClient();
    String servers = getStringFieldValue(Item.regenServers);
    final String db = getStringFieldValue(Item.regenDB);
    final String col = getStringFieldValue(Item.regenCollection);
    final String ns = db + "." + col;
    final DBObject shardKey = ((DocBuilderField) getBoundUnit(Item.regenShardKey)).getDBObject();
    final boolean unique = getBooleanFieldValue(Item.regenKeyUnique);
    final BasicDBObject result = new BasicDBObject();
    result.put("ns", ns);
    result.put("shardKey", shardKey);
    result.put("unique", unique);

    // create direct mongo for each replica set
    String[] serverList = servers.split("\n");
    List<ServerAddress> list = new ArrayList<ServerAddress>();
    String txt = "";
    String primaryShard = null;/* w  w  w  .j  av a2  s  .c  o  m*/
    final BasicDBObject shardList = new BasicDBObject();
    HashMap<MongoClient, String> mongoToShard = new HashMap<MongoClient, String>();
    sLoop: for (String server : serverList) {
        server = server.trim();
        String[] tokens = server.split("/");
        if (tokens.length != 2) {
            new InfoDialog(null, "Error", null, "Server format must be like 'hostname:port/shard', one by line")
                    .show();
            return;
        }
        server = tokens[0];
        String shard = tokens[1];
        if (primaryShard == null) {
            primaryShard = shard;
        }
        ServerAddress addr = new ServerAddress(server);

        // filter out if replset already exists
        for (MongoClient replset : mongoToShard.keySet()) {
            if (replset.getServerAddressList().contains(addr)) {
                continue sLoop;
            }
        }

        list.clear();
        list.add(addr);
        MongoClient mongo = new MongoClient(list);
        //            UMongo.instance.addMongoClient(mongo, null);
        // make request to force server detection
        mongo.getDatabaseNames();
        mongoToShard.put(mongo, shard);

        String desc = null;
        if (!mongo.getDatabaseNames().contains(db) || !mongo.getDB(db).getCollectionNames().contains(col)) {
            desc = "Collection not present!";
        } else {
            // try to see if shard key has index
            DBObject index = mongo.getDB(db).getCollection("system.indexes")
                    .findOne(new BasicDBObject("key", shardKey));
            if (index != null) {
                desc = "shard key found";
            } else {
                desc = "shard key NOT found!";
            }
        }
        txt += mongo.toString() + " shard=" + shard + " - " + desc + "\n";
        BasicDBObject shardObj = new BasicDBObject("servers", mongo.toString());
        shardObj.put("status", desc);
        if (shardList.containsField(shard)) {
            new InfoDialog(null, "Error", null, "Duplicate Shard name " + shard).show();
            return;
        }
        shardList.put(shard, shardObj);
    }
    result.put("shards", shardList);

    FormDialog dia = (FormDialog) getBoundUnit(Item.regenRSList);
    dia.setStringFieldValue(Item.regenRSListArea, txt);
    if (!dia.show()) {
        return;
    }

    DB config = cmongo.getDB("config");

    // add database record
    BasicDBObject doc = new BasicDBObject("_id", db);
    doc.put("partitioned", true);
    doc.put("primary", primaryShard);
    config.getCollection("databases").save(doc);

    // add collection record
    doc = new BasicDBObject("_id", ns);
    doc.put("lastmod", new Date());
    doc.put("dropped", false);
    doc.put("key", shardKey);
    doc.put("unique", unique);
    config.getCollection("collections").save(doc);

    final DBCollection chunks = config.getCollection("chunks");
    long count = chunks.count(new BasicDBObject("ns", ns));
    if (count > 0) {
        dia = (FormDialog) getBoundUnit(Item.regenDeleteChunks);
        if (dia.show()) {
            chunks.remove(new BasicDBObject("ns", ns));
        } else {
            return;
        }
    }

    // add temp collection to sort chunks with shard key
    final DBCollection tmpchunks = config.getCollection("_tmpchunks_" + col);
    tmpchunks.drop();
    // should be safe environment, and dup keys should be ignored
    tmpchunks.setWriteConcern(WriteConcern.NORMAL);
    // can use shardKey as unique _id
    //        tmpchunks.ensureIndex(shardKey, "shardKey", true);

    // create filter for shard fields
    final DBObject shardKeyFilter = new BasicDBObject();
    //        final DBObject shardKeyDescend = new BasicDBObject();
    boolean hasId = false;
    for (String key : shardKey.keySet()) {
        shardKeyFilter.put(key, 1);
        if (key.equals("_id")) {
            hasId = true;
        }
    }
    if (!hasId) {
        shardKeyFilter.put("_id", 0);
    }

    dia = (FormDialog) getBoundUnit(Item.regenConfirm);
    if (!dia.show()) {
        return;
    }

    // now fetch all records from each shard
    final AtomicInteger todo = new AtomicInteger(mongoToShard.size());
    for (Map.Entry<MongoClient, String> entry : mongoToShard.entrySet()) {
        final MongoClient mongo = entry.getKey();
        final String shard = entry.getValue();
        new DbJob() {

            @Override
            public Object doRun() throws Exception {
                BasicDBObject shardObj = (BasicDBObject) shardList.get(shard);
                long count = mongo.getDB(db).getCollection(col).count();
                shardObj.put("count", count);
                DBCursor cur = mongo.getDB(db).getCollection(col).find(new BasicDBObject(), shardKeyFilter);
                long i = 0;
                int inserted = 0;
                long start = System.currentTimeMillis();
                while (cur.hasNext() && !isCancelled()) {
                    BasicDBObject key = (BasicDBObject) cur.next();
                    setProgress((int) ((++i * 100.0f) / count));
                    try {
                        BasicDBObject entry = new BasicDBObject("_id", key);
                        entry.put("_shard", shard);
                        tmpchunks.insert(entry);
                        ++inserted;
                    } catch (Exception e) {
                        getLogger().log(Level.WARNING, e.getMessage(), e);
                    }
                }

                if (isCancelled()) {
                    shardObj.put("cancelled", true);
                }
                shardObj.put("inserted", inserted);
                shardObj.put("scanTime", System.currentTimeMillis() - start);
                todo.decrementAndGet();
                return null;
            }

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

            @Override
            public String getShortName() {
                return "Scanning " + shard;
            }

            @Override
            public boolean isDeterminate() {
                return true;
            }
        }.addJob();

    }

    new DbJob() {

        @Override
        public Object doRun() throws Exception {
            // wait for all shards to be done
            long start = System.currentTimeMillis();
            while (todo.get() > 0 && !isCancelled()) {
                Thread.sleep(2000);
            }

            if (isCancelled()) {
                result.put("cancelled", true);
                return result;
            }

            // find highest current timestamp
            DBCursor cur = chunks.find().sort(new BasicDBObject("lastmod", -1)).batchSize(-1);
            BasicDBObject chunk = (BasicDBObject) (cur.hasNext() ? cur.next() : null);
            BSONTimestamp ts = (BSONTimestamp) (chunk != null ? chunk.get("lastmod") : null);

            // now infer chunk ranges
            long count = tmpchunks.count();
            result.put("uniqueKeys", count);
            int numChunks = 0;
            cur = tmpchunks.find().sort(new BasicDBObject("_id", 1));
            BasicDBObject prev = (BasicDBObject) cur.next();
            BasicDBObject next = null;
            // snap prev to minkey
            BasicDBObject theid = (BasicDBObject) prev.get("_id");
            for (String key : shardKey.keySet()) {
                theid.put(key, new MinKey());
            }
            String currentShard = prev.getString("_shard");

            int i = 1;
            while (cur.hasNext()) {
                next = (BasicDBObject) cur.next();
                setProgress((int) ((++i * 100.0f) / count));
                String newShard = next.getString("_shard");
                if (newShard.equals(currentShard))
                    continue;

                // add chunk
                ts = getNextTimestamp(ts);
                chunk = getChunk(ns, shardKey, prev, next, ts);
                chunks.insert(chunk);
                prev = next;
                currentShard = prev.getString("_shard");
                ++numChunks;
            }

            // build max
            next = new BasicDBObject();
            for (String key : shardKey.keySet()) {
                next.put(key, new MaxKey());
            }
            next = new BasicDBObject("_id", next);
            ts = getNextTimestamp(ts);
            chunk = getChunk(ns, shardKey, prev, next, ts);
            chunks.insert(chunk);
            ++numChunks;
            result.put("numChunks", numChunks);
            result.put("totalTime", System.currentTimeMillis() - start);
            return result;
        }

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

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

        @Override
        public boolean isDeterminate() {
            return true;
        }
    }.addJob();
}

From source file:com.emuneee.camerasyncmanager.util.DatabaseUtil.java

License:Apache License

/**
 * Inserts a list of cameras//from   w w  w . java 2s. c om
 * @param cameras
 * @return
 */
public boolean insertCameras(List<Camera> cameras) {
    sLogger.info("Inserting " + cameras.size() + " cameras");
    boolean result = false;
    DB db = getDatabase();

    try {
        DBCollection collection = db.getCollection("camera");

        for (Camera camera : cameras) {
            BasicDBObject dbObj = cameraToDBObject(camera);
            sLogger.debug("Inserting: " + dbObj.toString());
            collection.insert(dbObj);
            result = true;
        }
    } catch (Exception e) {
        sLogger.error("Exception inserting cameras");
        sLogger.error(e);
    }

    return result;
}