Example usage for com.mongodb DBObject keySet

List of usage examples for com.mongodb DBObject keySet

Introduction

In this page you can find the example usage for com.mongodb DBObject keySet.

Prototype

Set<String> keySet();

Source Link

Document

Returns this object's fields' names

Usage

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  ww.  ja  va 2s  .  c  o m*/
    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.crud.mongo.Merge.java

License:Open Source License

private void findInvisibleFields_dbobj(DBObject dbObject, MutablePath path) {
    Set<String> fields = dbObject.keySet();
    for (String field : fields) {
        path.push(field);/* ww w  . j a  va2 s  . co m*/
        LOGGER.debug("Processing {}", path);
        Object value = dbObject.get(field);
        try {
            md.resolve(path);
            findInvisibleFields_obj(value, path);
        } catch (Error e) {
            // Invisible field 
            LOGGER.debug("Invisible field {}", path);
            invisibleFields.add(new IField(path.immutableCopy(), value));
        }
        path.pop();
    }
}

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

License:Open Source License

public static ObjectNode rawObjectToJson(DBObject obj) {
    ObjectNode ret = JsonNodeFactory.instance.objectNode();
    for (String key : obj.keySet()) {
        Object value = obj.get(key);
        if (value instanceof DBObject) {
            ret.set(key, rawObjectToJson((DBObject) value));
        } else if (value instanceof List) {
            ret.set(key, rawArrayToJson((List) value));
        } else {//from   w  ww.  j  ava  2  s.  co m
            ret.set(key, rawValueToJson(value));
        }
    }
    return ret;
}

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;// www . j av  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 void dbRefToRelation(DBObject dbObject) {
    if (dbObject == null) {
        return;//from  w w  w.j  a v  a  2 s. co m
    }
    if (dbObject.containsField("_id"))
        dbObject.put("_id", ((ObjectId) dbObject.get("_id")).toHexString());
    for (String key : dbObject.keySet()) {
        Object obj = dbObject.get(key);
        if (obj instanceof DBRef) {
            DBRef ref = (DBRef) obj;
            dbObject.put(key, dbRefToRel(ref));
        } else if (obj instanceof DBObject) {
            dbRefToRelation((DBObject) obj);
        }
    }

}

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

License:Apache License

private void relationToDBRef(DBObject dbObject, String projectId) {
    for (String key : dbObject.keySet()) {
        Object obj = dbObject.get(key);
        if (obj instanceof DBObject) {
            DBObject doc = (DBObject) obj;
            if (doc.containsField("_rel")) {
                DBObject relation = (DBObject) doc.get("_rel");
                dbObject.put(key, new DBRef(projectId + "_" + (String) relation.get("entity"),
                        new ObjectId((String) relation.get("_id"))));
            } else {
                relationToDBRef(doc, projectId);
            }/*from w  ww  .j av  a 2 s  .co m*/
        }
    }
}

From source file:com.ricardolorenzo.identity.user.impl.UserIdentityManagerMongoDB.java

License:Open Source License

private UserIdentity getUserIdentity(final DBObject data) throws IdentityException {
    final UserIdentity sourceUser = new UserIdentity();
    final UserIdentity destinationUser = new UserIdentity();
    for (final String field : data.keySet()) {
        getUserIdentityAttributes(data, field, sourceUser);
    }/*from ww w.  j av  a 2s.c  o m*/
    loadReadAttributesFromMap(sourceUser, destinationUser);
    return destinationUser;
}

From source file:com.ricardolorenzo.identity.user.impl.UserIdentityManagerMongoDB.java

License:Open Source License

/**
 * All the scripts should have the following format:
 *
 * {/*ww w.ja v  a2 s. c  o m*/
 *    database.collection: {
 *        operation: insert|update|find|aggregate|delete
 *        query: {}
 *    }
 * }
 *
 * For update operations, you should specify the following:
 *
 * query: {
 *     find: {}
 *     update: {}
 * }
 */
private List<DBObject> runQueryScript(final String scriptType, final Map<String, Object[]> attributes)
        throws IdentityException {
    List<DBObject> results = new ArrayList<>();
    try {
        DB database = mongoClient.getDB(this.properties.getProperty("mongodb.database"));
        final ScriptCollection sc = getScriptCollection();
        if (sc.hasScript(scriptType)) {
            final String scriptContent = sc.getScript(scriptType);
            String query = createQueryFromScript(scriptContent, attributes);
            DBObject collectionOperation = DBObject.class.cast(JSON.parse(query));

            for (String collection : collectionOperation.keySet()) {
                if (!database.collectionExists(collection)) {
                    throw new IdentityException("collection [" + collection + "] does not exists");
                }

                DBObject dbObject = DBObject.class.cast(collectionOperation.get(collection));
                if (!dbObject.containsField("operation")) {
                    throw new IdentityException("operation field not specified");
                }

                String dbOperation = String.class.cast(dbObject.get("operation")).toLowerCase();
                if (!OPERATIONS.contains(dbOperation)) {
                    throw new IdentityException("operation [" + dbOperation + "] not supported");
                }

                DBObject dbQuery = DBObject.class.cast(dbObject.get("query"));
                if (dbQuery == null) {
                    throw new IdentityException("query field not specified");
                }

                DBCollection coll = database.getCollection(collection);
                switch (dbOperation) {
                case "insert": {
                    coll.insert(dbQuery);
                }
                case "update": {
                    if (!dbObject.containsField("find")) {
                        throw new IdentityException("find field not found inside the update operation");
                    }
                    if (!dbObject.containsField("update")) {
                        throw new IdentityException("update field not found inside the update operation");
                    }
                    DBObject dbUpdateFind = DBObject.class.cast(dbQuery.get("find"));
                    DBObject dbUpdateFields = DBObject.class.cast(dbQuery.get("update"));
                    coll.update(dbUpdateFind, dbUpdateFields, false, false);
                }
                case "delete": {
                    coll.remove(dbQuery);
                }
                case "find": {
                    DBCursor cursor = coll.find(dbQuery);
                    while (cursor.hasNext()) {
                        results.add(cursor.next());
                    }
                }
                case "aggregate": {
                    List<DBObject> aggregate = new ArrayList<DBObject>();
                    aggregate.add(dbQuery);
                    for (DBObject o : coll.aggregate(aggregate).results()) {
                        results.add(o);
                    }
                }
                }
            }
            return results;
        }
    } catch (final NoSuchAlgorithmException e) {
        throw new IdentityException(e.getMessage());
    } finally {
        /**
         * TODO close cursors
         */
    }
    return null;
}

From source file:com.sangupta.dryrun.mongo.DryRunGridFSDBFile.java

License:Apache License

public void setMetaData(DBObject metadata) {
    if (metadata == null) {
        return;/*w ww.  ja  v  a2  s . co  m*/
    }

    Set<String> keySet = metadata.keySet();
    if (keySet.isEmpty()) {
        return;
    }

    for (String key : keySet) {
        this.metadata.put(key, metadata.get(key));
    }
}

From source file:com.sitewhere.mongodb.common.MongoMetadataProvider.java

License:Open Source License

/**
 * Load data from a DBObject.//from w w w. j  ava2s  .  c  o m
 * 
 * @param PropertyName
 * @param source
 * @param target
 */
public static void fromDBObject(String propertyName, DBObject source, IMetadataProvider target) {
    DBObject metadata = (DBObject) source.get(propertyName);
    if (metadata != null) {
        for (String key : metadata.keySet()) {
            target.addOrReplaceMetadata(key, (String) metadata.get(key));
        }
    }
}