Example usage for com.mongodb DBCollection save

List of usage examples for com.mongodb DBCollection save

Introduction

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

Prototype

public WriteResult save(final DBObject document) 

Source Link

Document

Update an existing document or insert a document depending on the parameter.

Usage

From source file:ch.windmobile.server.social.mongodb.UserServiceImpl.java

License:Open Source License

@Override
public List<Favorite> removeFromFavorites(String email, List<Favorite> favoritesToRemove) throws UserNotFound {
    if (email == null) {
        throw new IllegalArgumentException("Email cannot be null");
    }/*from www . j  a v  a2  s. c om*/
    DBCollection col = db.getCollection(MongoDBConstants.COLLECTION_USERS);
    // Search user by email
    DBObject userDb = col.findOne(new BasicDBObject(MongoDBConstants.USER_PROP_EMAIL, email));
    if (userDb == null) {
        throw new UserNotFound("Unable to find user with email '" + email + "'");
    }

    DBObject favoritesDb = (DBObject) userDb.get(MongoDBConstants.USER_PROP_FAVORITES);
    if (favoritesDb == null) {
        favoritesDb = new BasicDBObject();
    }

    if (favoritesToRemove != null) {
        for (Favorite favoriteToRemove : favoritesToRemove) {
            DBObject favoriteItemsDb = (DBObject) favoritesDb.get(favoriteToRemove.getStationId());
            if (favoriteItemsDb != null) {
                favoritesDb.removeField(favoriteToRemove.getStationId());
            }
        }
    }
    userDb.put(MongoDBConstants.USER_PROP_FAVORITES, favoritesDb);
    col.save(userDb);

    List<Favorite> returnValue = new ArrayList<Favorite>(favoritesDb.keySet().size());
    for (String stationId : favoritesDb.keySet()) {
        Favorite favorite = new Favorite();
        favorite.setStationId(stationId);
        DBObject favoriteItemDb = (DBObject) favoritesDb.get(stationId);
        favorite.setLastMessageId((Long) favoriteItemDb.get(MongoDBConstants.USER_PROP_FAVORITE_LASTMESSAGEID));
        returnValue.add(favorite);
    }
    return returnValue;
}

From source file:ch.windmobile.server.social.mongodb.UserServiceImpl.java

License:Open Source License

@Override
public void clearFavorites(String email) throws UserNotFound {
    if (email == null) {
        throw new IllegalArgumentException("Email cannot be null");
    }//from  w  w  w . j  a  v a2 s.com
    DBCollection col = db.getCollection(MongoDBConstants.COLLECTION_USERS);
    // Search user by email
    DBObject userDb = col.findOne(new BasicDBObject(MongoDBConstants.USER_PROP_EMAIL, email));
    if (userDb == null) {
        throw new UserNotFound("Unable to find user with email '" + email + "'");
    }

    userDb.removeField(MongoDBConstants.USER_PROP_FAVORITES);
    col.save(userDb);
}

From source file:com.arquivolivre.mongocom.utils.IntegerGenerator.java

License:Apache License

@Override
public Integer generateValue(Class parent, DB db) {
    DBCollection collection = db.getCollection("values_" + parent.getSimpleName());
    DBObject o = collection.findOne();/*from  w ww .ja v  a2s  .com*/
    int value = 0;
    if (o != null) {
        value = (int) o.get("generatedValue");
    } else {
        o = new BasicDBObject("generatedValue", value);
    }
    o.put("generatedValue", ++value);
    collection.save(o);
    return value;
}

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

License:Apache License

public void save(final ButtonBase button) {
    final DBCollection col = getCollectionNode().getCollection();
    final BasicDBObject doc = (BasicDBObject) ((DocBuilderField) getBoundUnit(Item.saveDoc)).getDBObject();

    new DbJob() {
        @Override/*from   ww  w .  j a  v  a  2 s  .c  o  m*/
        public Object doRun() throws IOException {
            return col.save((DBObject) doc.copy());
        }

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

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

        @Override
        public DBObject getRoot(Object result) {
            return doc;
        }

        @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;// www . j  a  v a  2s .co  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 editTagRange(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);
    String value = getComponentStringFieldValue(Item.tagRangeList);
    BasicDBObject range = (BasicDBObject) JSON.parse(value);
    dia.resetForEdit(config, range);/*from w  w  w  . j a  v a2s.  co m*/
    if (!dia.show()) {
        return;
    }

    final BasicDBObject doc = dia.getRange(ns);

    new DbJob() {

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

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

        @Override
        public String getShortName() {
            return "Edit 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 editUser(ButtonBase button) {
    final DB db = getDbNode().getDb();
    final DBCollection col = db.getCollection("system.users");

    final String user = getComponentStringFieldValue(Item.userList);
    if (user == null) {
        return;//  w  ww.  j  ava 2  s .c  o m
    }

    final BasicDBObject userObj = (BasicDBObject) col.findOne(new BasicDBObject("user", user));
    UserDialog ud = (UserDialog) getBoundUnit(Item.userDialog);
    ud.resetForEdit(userObj);
    if (!ud.show()) {
        return;
    }

    final BasicDBObject newUser = ud.getUser(userObj);

    new DbJob() {

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

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

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

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

}

From source file:com.englishtown.vertx.GridFSModule.java

License:Open Source License

public void saveFile(Message<JsonObject> message, JsonObject jsonObject) {

    ObjectId id = getObjectId(message, jsonObject, "id");
    if (id == null) {
        return;//from w  w  w.j  a v a 2  s.  c  om
    }

    Integer length = getRequiredInt("length", message, jsonObject, 1);
    if (length == null) {
        return;
    }

    Integer chunkSize = getRequiredInt("chunkSize", message, jsonObject, 1);
    if (chunkSize == null) {
        return;
    }

    long uploadDate = jsonObject.getLong("uploadDate", 0);
    if (uploadDate <= 0) {
        uploadDate = System.currentTimeMillis();
    }

    String filename = jsonObject.getString("filename");
    String contentType = jsonObject.getString("contentType");
    JsonObject metadata = jsonObject.getObject("metadata");

    try {
        BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add("_id", id).add("length", length)
                .add("chunkSize", chunkSize).add("uploadDate", new Date(uploadDate));

        if (filename != null)
            builder.add("filename", filename);
        if (contentType != null)
            builder.add("contentType", contentType);
        if (metadata != null)
            builder.add("metadata", JSON.parse(metadata.encode()));

        DBObject dbObject = builder.get();

        String bucket = jsonObject.getString("bucket", GridFS.DEFAULT_BUCKET);
        DBCollection collection = db.getCollection(bucket + ".files");

        // Ensure standard indexes as long as collection is small
        if (collection.count() < 1000) {
            collection.ensureIndex(BasicDBObjectBuilder.start().add("filename", 1).add("uploadDate", 1).get());
        }

        collection.save(dbObject);
        sendOK(message);

    } catch (Exception e) {
        sendError(message, "Error saving file", e);
    }
}

From source file:com.englishtown.vertx.GridFSModule.java

License:Open Source License

public void saveChunk(Message<Buffer> message, JsonObject jsonObject, byte[] data) {

    if (data == null || data.length == 0) {
        sendError(message, "chunk data is missing");
        return;/*from   ww  w  . ja  v  a2s .c  o  m*/
    }

    ObjectId id = getObjectId(message, jsonObject, "files_id");
    if (id == null) {
        return;
    }

    Integer n = getRequiredInt("n", message, jsonObject, 0);
    if (n == null) {
        return;
    }

    try {
        DBObject dbObject = BasicDBObjectBuilder.start().add("files_id", id).add("n", n).add("data", data)
                .get();

        String bucket = jsonObject.getString("bucket", GridFS.DEFAULT_BUCKET);
        DBCollection collection = db.getCollection(bucket + ".chunks");

        // Ensure standard indexes as long as collection is small
        if (collection.count() < 1000) {
            collection.ensureIndex(BasicDBObjectBuilder.start().add("files_id", 1).add("n", 1).get(),
                    BasicDBObjectBuilder.start().add("unique", 1).get());
        }

        collection.save(dbObject);
        sendOK(message);

    } catch (RuntimeException e) {
        sendError(message, "Error saving chunk", e);
    }

}

From source file:com.gigaspaces.persistency.MongoClientConnector.java

License:Open Source License

public void introduceType(SpaceTypeDescriptor typeDescriptor) {

    DBCollection m = getConnection().getCollection(METADATA_COLLECTION_NAME);

    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add(Constants.ID_PROPERTY,
            typeDescriptor.getTypeName());
    try {//  www  .  j av  a  2 s.  co m
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bos);
        IOUtils.writeObject(out,
                SpaceTypeDescriptorVersionedSerializationUtils.toSerializableForm(typeDescriptor));

        builder.add(TYPE_DESCRIPTOR_FIELD_NAME, bos.toByteArray());

        WriteResult wr = m.save(builder.get());

        if (logger.isTraceEnabled())
            logger.trace(wr);

        indexBuilder.ensureIndexes(typeDescriptor);

    } catch (IOException e) {
        logger.error(e);

        throw new SpaceMongoException(
                "error occurs while serialize and save type descriptor: " + typeDescriptor, e);
    }
}