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:com.lakeside.data.mongo.MongoDbRestore.java

License:Open Source License

protected void write(CollectionInfo info, DBObject dbo) throws Exception {
    DB db = MongoDBConnectionManager.getConnection(DATABASE_HOST, DATABASE_NAME, DATABASE_USER_NAME,
            DATABASE_PASSWORD);//from  www .j a  va 2s  .  co  m

    DBCollection coll = db.getCollection(info.getName());
    coll.save(dbo);
}

From source file:com.mebigfatguy.mongobrowser.actions.DeleteAction.java

License:Apache License

@Override
public void actionPerformed(ActionEvent e) {
    MongoTreeNode node = context.getSelectedNode();
    switch (node.getType()) {
    case Collection: {
        DBCollection collection = (DBCollection) node.getUserObject();
        collection.drop();/*ww w  . java 2  s.  c  o  m*/
        MongoTreeNode dbNode = (MongoTreeNode) node.getParent();
        dbNode.remove(node);
        DefaultTreeModel model = (DefaultTreeModel) context.getTree().getModel();
        model.nodeStructureChanged(dbNode);
    }
        break;

    case Object: {
        DBObject object = (DBObject) node.getUserObject();
        MongoTreeNode collectionNode = TreeUtils.findCollectionNode(node);
        DBCollection collection = (DBCollection) collectionNode.getUserObject();
        collection.remove(object);
        collectionNode.remove(node);
        DefaultTreeModel model = (DefaultTreeModel) context.getTree().getModel();
        model.nodeStructureChanged(collectionNode);
    }
        break;

    case KeyValue: {
        MongoTreeNode.KV kv = (MongoTreeNode.KV) node.getUserObject();
        String key = kv.getKey();
        if (!key.startsWith("_")) {
            MongoTreeNode objectNode = (MongoTreeNode) node.getParent();
            DBObject object = (DBObject) objectNode.getUserObject();
            object.removeField(key);
            MongoTreeNode collectionNode = TreeUtils.findCollectionNode(objectNode);
            DBCollection collection = (DBCollection) collectionNode.getUserObject();
            collection.save(object);
            objectNode.remove(node);
            DefaultTreeModel model = (DefaultTreeModel) context.getTree().getModel();
            model.nodeStructureChanged(objectNode);
        }
    }
        break;
    }
}

From source file:com.mebigfatguy.mongobrowser.actions.EditKeyValueAction.java

License:Apache License

@Override
public void actionPerformed(ActionEvent e) {
    JTree tree = context.getTree();
    MongoTreeNode[] selectedNodes = TreeUtils.getSelectedNodes(tree);

    if (selectedNodes.length == 1) {

        MongoTreeNode.KV keyValue = ((MongoTreeNode.KV) selectedNodes[0].getUserObject());

        String key = keyValue.getKey();
        Object value = keyValue.getValue();

        KeyValueDialog dialog = new KeyValueDialog(key, value);
        dialog.setLocationRelativeTo(tree);
        dialog.setModal(true);/*from  w w  w . j a v  a  2  s. c  om*/
        dialog.setVisible(true);

        if (dialog.isOK()) {
            DBObject dbObject = (DBObject) ((MongoTreeNode) selectedNodes[0].getParent()).getUserObject();
            key = dialog.getKey();
            value = dialog.getValue();

            dbObject.put(key, value);
            keyValue.setValue(value);

            MongoTreeNode collectionNode = TreeUtils.findCollectionNode(selectedNodes[0]);
            DBCollection collection = (DBCollection) collectionNode.getUserObject();
            collection.save(dbObject);
        }
    }
}

From source file:com.mebigfatguy.mongobrowser.actions.NewKeyValueAction.java

License:Apache License

@Override
public void actionPerformed(ActionEvent e) {
    JTree tree = context.getTree();
    KeyValueDialog dialog = new KeyValueDialog();
    dialog.setLocationRelativeTo(tree);//from w  w w .  j  a  v  a  2s  .  c  o m
    dialog.setModal(true);
    dialog.setVisible(true);
    if (dialog.isOK()) {
        String key = dialog.getKey();
        Object value = dialog.getValue();
        TreePath path = tree.getSelectionPath();
        MongoTreeNode selectedNode = (MongoTreeNode) path.getLastPathComponent();
        DBObject object;

        if (selectedNode.getType() == MongoTreeNode.Type.KeyValue) {
            object = (DBObject) ((MongoTreeNode.KV) selectedNode.getUserObject()).getValue();
        } else {
            object = (DBObject) selectedNode.getUserObject();
        }

        object.put(key, value);
        MongoTreeNode kv = new MongoTreeNode(new MongoTreeNode.KV(key, object.get(key)), false);
        selectedNode.add(kv);
        if (value instanceof DBObject) {
            MongoTreeNode slug = new MongoTreeNode();
            kv.add(slug);
        }
        MongoTreeNode collectionNode = TreeUtils.findCollectionNode(selectedNode);
        DBCollection collection = (DBCollection) collectionNode.getUserObject();
        collection.save(object);
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        model.nodeStructureChanged((MongoTreeNode) model.getRoot());
        TreePath selection = new TreePath(kv.getPath());
        tree.scrollPathToVisible(selection);
        tree.setSelectionPath(selection);
    }
}

From source file:com.ratzia.pfc.webpageanalyticaltool.dbupdater.Watcher.java

public void processDatabase(LinkedList<String> pluginsCode, String currentVersion) throws UnknownHostException {
    /**** Plugins ****/
    LinkedList<SysPlugin> plugins = loadPlugins(pluginsCode);
    /*****************/

    /*SecurityManager oldSecurityManager = System.getSecurityManager();
    DBPluginSecurityManager dbPluginSecurityManager = new DBPluginSecurityManager();
    System.setSecurityManager(dbPluginSecurityManager);
    //Will open the security manager so we need to ensure it is closed afterwards
    try{*//* w  w w  .  j a va2s  .c om*/
    MongoClient mongoClient = new MongoClient(serverAddress);
    DB local = mongoClient.getDB(db);
    DBCollection dbCol = local.getCollection(collection);
    BasicDBObject query = new BasicDBObject();
    query.put(PLUGIN_VERSION_FIELD, new BasicDBObject("$ne", currentVersion));
    DBCursor cursor = dbCol.find(query);
    long count = 0;
    while (cursor.hasNext()) {
        DBObject obj = cursor.next();

        //Copy contents
        BasicDBObject res = new BasicDBObject();
        for (String k : obj.keySet()) {
            res.put(k, obj.get(k));
        }

        //Plugin operations
        for (SysPlugin plugin : plugins) {
            try {
                plugin.run(res);
            } catch (Exception ex) {
                System.out.println("Error en " + plugin.getClass());
                Logger.getLogger(Watcher.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        //Put plugin only fields into the original object
        for (String k : res.keySet()) {
            if ((k.substring(0, 2)).compareTo("p_") == 0) {
                obj.put(k, res.get(k));
            }
        }

        //Update version on object
        obj.put(PLUGIN_VERSION_FIELD, currentVersion);

        dbCol.save(obj);
        count++;
    }
    cursor.close();

    if (count > 0) {
        System.out.println(count + " updated");
    }

    /*}catch(Exception ex){
    Logger.getLogger(Watcher.class.getName()).log(Level.SEVERE, null, ex);
    }
    //close sandbox
    System.setSecurityManager(oldSecurityManager);*/

}

From source file:com.redhat.lightblue.mongo.crud.MongoCRUDController.java

License:Open Source License

protected void populateHiddenFields(EntityInfo ei, Metadata md, String version, List<Path> fields,
        QueryExpression query) throws IOException {
    LOGGER.info("Starting population of hidden fields due to new or modified indexes.");
    MongoDataStore ds = (MongoDataStore) ei.getDataStore();
    DB entityDB = dbResolver.get(ds);/*from w ww  . ja v a2  s .c om*/
    DBCollection coll = entityDB.getCollection(ds.getCollectionName());
    DBCursor cursor = null;
    try {
        if (query != null) {
            MetadataResolver mdResolver = new MetadataResolver() {
                @Override
                public EntityMetadata getEntityMetadata(String entityName) {
                    String v = version == null ? ei.getDefaultVersion() : version;
                    return md.getEntityMetadata(entityName, v);
                }
            };
            ExpressionTranslator trans = new ExpressionTranslator(mdResolver, JsonNodeFactory.instance);
            DBObject mongoQuery = trans.translate(mdResolver.getEntityMetadata(ei.getName()), query);
            cursor = coll.find(mongoQuery);
        } else {
            cursor = coll.find();
        }
        while (cursor.hasNext()) {
            DBObject doc = cursor.next();
            DBObject original = (DBObject) ((BasicDBObject) doc).copy();
            try {
                DocTranslator.populateDocHiddenFields(doc, fields);
                LOGGER.debug("Original doc:{}, new doc:{}", original, doc);
                if (!doc.equals(original)) {
                    coll.save(doc);
                }
            } catch (Exception e) {
                // skip the doc if there's a problem, don't outright fail
                LOGGER.error(e.getMessage());
                LOGGER.debug("Original doc:\n{}", original);
                LOGGER.debug("Error saving doc:\n{}", doc);
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error during reindexing");
        LOGGER.error(e.getMessage());
        throw new RuntimeException(e);
    } finally {
        cursor.close();
    }
    LOGGER.info("Finished population of hidden fields.");
}

From source file:com.restfeel.controller.rest.EntityDataController.java

License:Apache License

/**
 * [NOTE] http://stackoverflow.com/questions/25953056/how-to-access-fields-of-converted-json-object-sent-in-post-body
 *//*from   www .  ja  v  a  2s  .  co m*/
@RequestMapping(value = "/api/{projectId}/entities/{name}", method = RequestMethod.POST, headers = "Accept=application/json", consumes = "application/json")
public @ResponseBody String createEntityData(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @RequestBody Object genericEntityDataDTO,
        @RequestHeader(value = "authToken", required = false) String authToken) {

    String data;
    if (!(genericEntityDataDTO instanceof Map)) {
        return null;
    } else {
        // Note : Entity data is accessible through this map.
        Map map = (Map) genericEntityDataDTO;
        JSONObject jsonObj = createJsonFromMap(map);
        data = jsonObj.toString();
    }

    DBObject dbObject = (DBObject) JSON.parse(data);

    if (entityName.equals("User")) {
        return handleUserEntityData(projectId, dbObject, true);
    }

    DBRef user;
    JSONObject authRes = authService.authorize(projectId, authToken, "USER");
    if (authRes.getBoolean(SUCCESS)) {
        user = (DBRef) authRes.get("user");
    } else {
        return authRes.toString(4);
    }

    // Create a new document for the entity.
    DBCollection dbCollection = mongoTemplate.getCollection(projectId + "_" + entityName);

    relationToDBRef(dbObject, projectId);

    dbObject.put("createdBy", user);
    dbObject.put("createdAt", new Date());

    dbCollection.save(dbObject);
    dbRefToRelation(dbObject);
    String json = dbObject.toString();

    // Indentation
    JSONObject jsonObject = new JSONObject(json);
    return jsonObject.toString(4);
}

From source file:com.restfeel.controller.rest.EntityDataController.java

License:Apache License

@RequestMapping(value = "/api/{projectId}/entities/{name}/{uuid}", method = RequestMethod.PUT, headers = "Accept=application/json", consumes = "application/json")
public @ResponseBody String updateEntityData(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @PathVariable("uuid") String uuid,
        @RequestBody Object genericEntityDataDTO,
        @RequestHeader(value = "authToken", required = false) String authToken) {

    DBRef user;/*from   w w w  .  jav a2  s  .  c o m*/
    JSONObject authRes = authService.authorize(projectId, authToken, "USER");
    if (authRes.getBoolean(SUCCESS)) {
        user = (DBRef) authRes.get("user");
    } else {
        return authRes.toString(4);
    }

    DBObject resultObject = new BasicDBObject();
    if (genericEntityDataDTO instanceof Map) {
        Map map = (Map) genericEntityDataDTO;
        if (map.get("id") != null && map.get("id") instanceof String) {
            String entityDataId = (String) map.get("id");
            logger.debug("Updating Entity Data with Id " + entityDataId);
        }
        JSONObject uiJson = new JSONObject(map);
        // ID is stored separately (in a different column).
        DBObject obj = (DBObject) JSON.parse(uiJson.toString());
        obj.removeField("_id");

        DBCollection dbCollection = mongoTemplate.getCollection(projectId + "_" + entityName);
        BasicDBObject queryObject = new BasicDBObject();
        queryObject.append("_id", new ObjectId(uuid));
        resultObject = dbCollection.findOne(queryObject);

        Set<String> keySet = obj.keySet();
        for (String key : keySet) {
            resultObject.put(key, obj.get(key));
        }

        if (entityName.equals("User")) {
            DBObject loggedInUser = dbCollection.findOne(user);
            if (loggedInUser.get(USERNAME).equals(resultObject.get(USERNAME))) {
                return handleUserEntityData(projectId, resultObject, obj.containsField(PASSWORD));
            } else {
                return new JSONObject().put(SUCCESS, false).put("msg", "unauthorized").toString(4);
            }
        }

        relationToDBRef(resultObject, projectId);

        resultObject.put("updatedBy", user);
        resultObject.put("updatedAt", new Date());

        dbCollection.save(resultObject);
    }
    dbRefToRelation(resultObject);
    String json = resultObject.toString();

    // Indentation
    JSONObject jsonObject = new JSONObject(json);
    return jsonObject.toString(4);
}

From source file:com.restfeel.controller.rest.EntityDataController.java

License:Apache License

private String handleUserEntityData(String projectId, DBObject user, boolean encryptPassword) {
    JSONObject response = new JSONObject();

    if (!user.containsField(USERNAME)) {
        response.put("msg", "username is mandotary");
        return response.toString(4);
    }/*ww w  .j a  v a  2s.com*/

    if (((String) user.get(USERNAME)).length() < 3) {
        response.put("msg", "username must be more then 3 character");
        return response.toString(4);
    }

    if (!user.containsField(PASSWORD)) {
        response.put("msg", "password is mandotary");
        return response.toString(4);
    }

    if (((String) user.get(PASSWORD)).length() < 3) {
        response.put("msg", "password must be more then 3 character");
        return response.toString(4);
    }

    DBCollection dbCollection = mongoTemplate.getCollection(projectId + "_User");

    BasicDBObject query = new BasicDBObject();
    query.append(USERNAME, user.get(USERNAME));

    DBObject existingUser = dbCollection.findOne(query);

    if (existingUser != null && !existingUser.get("_id").equals(user.get("_id"))) {
        response.put("msg", "username already exists");
        return response.toString(4);
    }

    if (encryptPassword) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.put(PASSWORD, encoder.encode((String) user.get(PASSWORD)));
    }

    relationToDBRef(user, projectId);

    dbCollection.save(user);
    user.removeField(PASSWORD);
    dbRefToRelation(user);
    String json = user.toString();

    // Indentation
    response = new JSONObject(json);
    return response.toString(4);
}

From source file:com.restfiddle.controller.rest.EntityDataController.java

License:Apache License

/**
 * [NOTE] http://stackoverflow.com/questions/25953056/how-to-access-fields-of-converted-json-object-sent-in-post-body
 *//*from   w w  w. jav a 2 s .  c  o m*/
@RequestMapping(value = "/api/{projectId}/entities/{name}", method = RequestMethod.POST, headers = "Accept=application/json", consumes = "application/json")
public @ResponseBody String createEntityData(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @RequestBody Object genericEntityDataDTO) {
    String data = "";
    if (!(genericEntityDataDTO instanceof Map)) {
        return null;
    } else {
        // Note : Entity data is accessible through this map.
        Map map = (Map) genericEntityDataDTO;
        JSONObject jsonObj = createJsonFromMap(map);
        data = jsonObj.toString();
    }
    // Create a new document for the entity.
    DBCollection dbCollection = mongoTemplate.getCollection(entityName);

    Object dbObject = JSON.parse(data);
    dbCollection.save((BasicDBObject) dbObject);
    String json = dbObject.toString();

    // Indentation
    JSONObject jsonObject = new JSONObject(json);
    return jsonObject.toString(4);
}