Example usage for com.mongodb DBCursor toArray

List of usage examples for com.mongodb DBCursor toArray

Introduction

In this page you can find the example usage for com.mongodb DBCursor toArray.

Prototype

public List<DBObject> toArray() 

Source Link

Document

Converts this cursor to an array.

Usage

From source file:com.ebay.oss.bark.repo.SampleFilePathRepoImpl.java

License:Apache License

@Override
public List<DBObject> findByModelName(String name) {

    DBCursor temp = dbCollection.find(new BasicDBObject("modelName", name)).limit(20)
            .sort(new BasicDBObject("timestamp", -1));
    return temp.toArray();
}

From source file:com.example.labs.actions.data.ProjectsAction.java

License:Apache License

public String execute() throws Exception {
    connection = MongoDBConnection.getInstance();
    connection.connect("turbines");
    DBCollection turbineData = connection.getMongoCollection("turbineData");
    DBObject searchQuery = new BasicDBObject();
    searchQuery.put("date", BasicDBObjectBuilder.start("$gte", startDate).add("$lte", endDate).get());

    DBObject keys = new BasicDBObject();
    keys.put("date", "1");

    //from query param
    if (StringUtils.isEmpty(fields)) {
        success = 0;//from  www. j  a  v  a2  s  . com
        error = "Please provide valid fields";
        return ERROR;
    }

    String[] fieldKeys = fields.split(",");
    for (String k : fieldKeys) {
        keys.put(k, "1");
    }

    DBCursor cursor = turbineData.find(searchQuery, keys);
    DBObject sortTime = new BasicDBObject();

    sortTime.put("date", 1);
    cursor.sort(sortTime);
    List<DBObject> dataPoints = cursor.toArray();

    LOG.debug("Number of data points: " + dataPoints.size());
    data = new ArrayList<Object>();
    for (DBObject dataP : dataPoints) {
        data.add(dataP);
    }
    success = 1;
    return SUCCESS;
}

From source file:com.ff.reportgenerator.mongodb.DynamicDatabase.java

public String query(String condition) {
    List<DBObject> list = null;

    DB myDB = getDB(DB_NAME);//from w  ww.j  av  a2  s  .  com
    DBCollection coll = myDB.getCollection("projects");

    DBCursor ret = coll.find();
    BasicDBObject sort = new BasicDBObject("PROJECT_ID", 1);
    ret.sort(sort);

    try {
        list = ret.toArray();
    } finally {
        ret.close();
    }

    System.out.println("quering...." + condition);
    return list.toString();
}

From source file:com.ff.reportgenerator.mongodb.DynamicDatabase.java

public String query(Hashtable conditions) {
    List<DBObject> list = null;

    DB myDB = getDB(DB_NAME);/* ww  w. ja v  a2 s  .c om*/
    DBCollection coll = myDB.getCollection("projects");

    BasicDBObject cond = new BasicDBObject();

    Set<String> keySet = conditions.keySet();
    Iterator<String> it = keySet.iterator();

    while (it.hasNext()) {
        String key = it.next();
        String value = (String) conditions.get(key);
        if (value == null || value.equals("All")) {
            continue;
        }

        Pattern pattern = null;
        if (key.equals("Project_Phase")) {
            if (value.equals("Ongoing")) {
                BasicDBList dlist = new BasicDBList();
                dlist.add(new BasicDBObject(key, new BasicDBObject("$ne", "Completed")));
                dlist.add(new BasicDBObject(key, new BasicDBObject("$ne", "Eng-Complete")));
                dlist.add(new BasicDBObject(key, new BasicDBObject("$ne", "Canceled")));
                dlist.add(new BasicDBObject(key, new BasicDBObject("$ne", "Publication")));
                cond.append("$and", dlist);
            } else if (value.equals("Complete")) {
                ArrayList<String> slist = new ArrayList();
                slist.add("Completed");
                slist.add("Eng-Complete");
                slist.add("Publication");
                cond.append(key, new BasicDBObject("$in", slist));

                //Limited to FY15 projects
                //pattern = Pattern.compile("^.*15-\\[.*$", Pattern.CASE_INSENSITIVE);

                //Limited to FY16 projects
                pattern = Pattern.compile("^.*16-.*$", Pattern.CASE_INSENSITIVE);
                cond.append("ISVe_Goal", pattern);
            }
        } else if (key.equals("Keywords") && value.equals("Non-OPI")) { // not like 'OPI'
            pattern = Pattern.compile("^((?!OPI).)*$", Pattern.CASE_INSENSITIVE);
            cond.append(key, pattern);
        } else { // like '*OPI*'
            pattern = Pattern.compile("^.*" + value + ".*$", Pattern.CASE_INSENSITIVE);
            cond.append(key, pattern);
        }

        System.out.println(key + ":" + value);
    }

    DBCursor ret = coll.find(cond);

    BasicDBObject sort = new BasicDBObject("PROJECT_ID", 1);
    ret.sort(sort);

    try {
        list = ret.toArray();
    } finally {
        ret.close();
    }

    //System.out.println(list.toString());
    return list.toString();
}

From source file:com.hangum.tadpole.importdb.core.dialog.importdb.utils.MongoDBQueryUtil.java

License:Open Source License

/**
 * ??  ./*from w  w w.jav a  2  s .c  om*/
 */
private void runSQLSelect() throws Exception {

    DBCollection dbCollection = MongoDBQuery.findCollection(userDB, requestQuery);
    DBCursor dbCursor = dbCollection.find().skip(startPoint).limit(DATA_COUNT);

    listDBOject = dbCursor.toArray();
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * all Server Side Java Script//from w  w w  .ja  v  a  2 s .  c o m
 * @param userDB
 * @throws Exception
 */
public static List<MongoDBServerSideJavaScriptDAO> listAllJavaScript(UserDBDAO userDB) throws Exception {
    List<MongoDBServerSideJavaScriptDAO> listReturn = new ArrayList<MongoDBServerSideJavaScriptDAO>();

    DBCursor dbCursor = findDB(userDB).getCollection("system.js").find();
    List<DBObject> lsitCursor = dbCursor.toArray();
    for (DBObject dbObject : lsitCursor) {
        listReturn.add(new MongoDBServerSideJavaScriptDAO(dbObject.get("_id").toString(),
                dbObject.get("value").toString()));
    }

    return listReturn;
}

From source file:com.hangum.tadpole.mongodb.core.test.MongoTestRunCommand.java

License:Open Source License

/**
 * @param args//from w  ww .  jav a  2  s .  c om
 */
public static void main(String[] args) throws Exception {
    ConAndAuthentication testMongoCls = new ConAndAuthentication();
    Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, 27017);//ConAndAuthentication.port);
    DB db = mongo.getDB("test");

    DBCollection dbColl = db.getCollection("user");

    DBObject cmdObj = (DBObject) JSON.parse("{language  : 'en_us'}, {seq: true, email:true}, {seq, -1}");
    DBCursor dbCur = dbColl.find(cmdObj);
    for (DBObject obj : dbCur.toArray()) {
        System.out.println(obj);
    }

    //      CommandResult cr = db.command(cmdObj);//new BasicDBObject("create", "hyunjong"));
    //      System.out.println( cr.toString() );      

    mongo.close();
}

From source file:com.hangum.tadpole.mongodb.core.test.MongoTestServerSideJavascript.java

License:Open Source License

/**
 *  ? // ww w  . j  a v a2  s .c om
 * @param db
 */
private static void findAllServerSideJavaScript(DB db) {
    DBCursor dbCursor = db.getCollection("system.js").find();
    List<DBObject> lsitCursor = dbCursor.toArray();
    for (DBObject dbObject : lsitCursor) {
        System.out.println(dbObject.toString());
    }
}

From source file:com.ikanow.infinit.e.api.config.source.SourceHandler.java

License:Open Source License

/**
 * getGoodSources/*from   w  w w .  j a v a  2s. c  o  m*/
 * Get a list of approved sources for a list of one or more
 * community IDs passed via the communityid parameter
 * @param communityIdStrList
 * @return
 */
public ResponsePojo getGoodSources(String userIdStr, String communityIdStrList, boolean bStrip) {
    ResponsePojo rp = new ResponsePojo();
    try {
        String[] communityIdStrs = SocialUtils.getCommunityIds(userIdStr, communityIdStrList);
        ObjectId userId = null;
        boolean bAdmin = RESTTools.adminLookup(userIdStr);
        if (!bAdmin) {
            userId = new ObjectId(userIdStr); // (ie not admin, may not see 
        }
        Set<ObjectId> communityIdSet = new TreeSet<ObjectId>();
        Set<ObjectId> ownedOrModeratedCommunityIdSet = new TreeSet<ObjectId>();
        for (String s : communityIdStrs) {
            ObjectId communityId = new ObjectId(s);
            communityIdSet.add(communityId);
            if (null != userId) {
                if (isOwnerOrModerator(communityId.toString(), userIdStr)) {
                    ownedOrModeratedCommunityIdSet.add(communityId);
                }
            }
        }
        //TESTED (owner and community owner, public and not public) 

        // Set up the query
        BasicDBObject query = new BasicDBObject();
        // (allow failed harvest sources because they might have previously had good data)
        query.put(SourcePojo.isApproved_, true);
        query.put(SourcePojo.communityIds_, new BasicDBObject(MongoDbManager.in_, communityIdSet));
        BasicDBObject fields = new BasicDBObject();
        if (bStrip) {
            setStrippedFields(fields);
        }

        DBCursor dbc = DbManager.getIngest().getSource().find(query, fields);

        // Remove communityids we don't want the user to see:
        if (bStrip && sanityCheckStrippedSources(dbc.toArray(), bAdmin)) {
            rp.setData(dbc.toArray(), (BasePojoApiMap<DBObject>) null);
        } else {
            rp.setData(SourcePojo.listFromDb(dbc, SourcePojo.listType()),
                    new SourcePojoApiMap(userId, communityIdSet, ownedOrModeratedCommunityIdSet));
        }
        rp.setResponse(new ResponseObject("Good Sources", true, "successfully returned good sources"));
    } catch (Exception e) {
        // If an exception occurs log the error
        logger.error("Exception Message: " + e.getMessage(), e);
        rp.setResponse(new ResponseObject("Good Sources", false, "error returning good sources"));
    }
    // Return Json String representing the user
    return rp;
}

From source file:com.ikanow.infinit.e.api.config.source.SourceHandler.java

License:Open Source License

/**
 * getBadSources/*w w  w  . j a v a  2s .  co  m*/
 * Get a list of sources with harvester errors for a list of one or more
 * community IDs passed via the communityid parameter
 * @param communityIdStrList
 * @return
 */
public ResponsePojo getBadSources(String userIdStr, String communityIdStrList, boolean bStrip) {
    ResponsePojo rp = new ResponsePojo();
    try {
        String[] communityIdStrs = SocialUtils.getCommunityIds(userIdStr, communityIdStrList);
        ObjectId userId = null;
        boolean bAdmin = RESTTools.adminLookup(userIdStr);
        if (!bAdmin) {
            userId = new ObjectId(userIdStr); // (ie not admin, may not see 
        }
        Set<ObjectId> communityIdSet = new TreeSet<ObjectId>();
        Set<ObjectId> ownedOrModeratedCommunityIdSet = new TreeSet<ObjectId>();
        for (String s : communityIdStrs) {
            ObjectId communityId = new ObjectId(s);
            communityIdSet.add(communityId);
            if (null != userId) {
                if (isOwnerOrModerator(communityId.toString(), userIdStr)) {
                    ownedOrModeratedCommunityIdSet.add(communityId);
                }
            }
        }
        //TESTED (owner and community owner, public and not public) 

        // Set up the query
        BasicDBObject query = new BasicDBObject();
        query.put(SourceHarvestStatusPojo.sourceQuery_harvest_status_, HarvestEnum.error.toString());
        query.put(SourcePojo.communityIds_, new BasicDBObject(MongoDbManager.in_, communityIdSet));
        BasicDBObject fields = new BasicDBObject();
        if (bStrip) {
            setStrippedFields(fields);
        }
        DBCursor dbc = DbManager.getIngest().getSource().find(query, fields);

        // Remove communityids we don't want the user to see:
        if (bStrip && sanityCheckStrippedSources(dbc.toArray(), bAdmin)) {
            rp.setData(dbc.toArray(), (BasePojoApiMap<DBObject>) null);
        } else {
            rp.setData(SourcePojo.listFromDb(dbc, SourcePojo.listType()),
                    new SourcePojoApiMap(userId, communityIdSet, ownedOrModeratedCommunityIdSet));
        }
        rp.setResponse(new ResponseObject("Bad Sources", true, "Successfully returned bad sources"));
    } catch (Exception e) {
        // If an exception occurs log the error
        logger.error("Exception Message: " + e.getMessage(), e);
        rp.setResponse(new ResponseObject("Bad Sources", false, "error returning bad sources"));
    }
    // Return Json String representing the user
    return rp;
}