Example usage for com.mongodb DBCursor close

List of usage examples for com.mongodb DBCursor close

Introduction

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

Prototype

@Override
    public void close() 

Source Link

Usage

From source file:com.linuxbox.enkive.statistics.gathering.mongodb.MongoGathererMessageSearchService.java

License:Open Source License

@Override
public int getNumberOfMessages(Date startDate, Date endDate) throws MessageSearchException {
    String dateEarliest = new StringBuilder(SIMPLE_DATE.format(startDate)).toString();
    String dateLatest = new StringBuilder(SIMPLE_DATE.format(endDate)).toString();

    HashMap<String, String> fields = new HashMap<String, String>();
    fields.put(DATE_EARLIEST_PARAMETER, dateEarliest);
    fields.put(DATE_LATEST_PARAMETER, dateLatest);
    fields.put(DATE_TYPE, ARCHIVE_TIME);

    try {/*from   w  ww.j  a  v  a2  s . c  o  m*/
        final DBObject query = buildQueryObject(fields);
        final DBCursor results = messageColl.find(query, ID_ONLY_QUERY);
        final int numOfMessages = results.count();
        results.close();
        return numOfMessages;
    } catch (EmptySearchResultsException e) {
        return 0;
    }
}

From source file:com.miya.twit.mongodb.DBConnectSentiment.java

public ArrayList getTwitterFindAll() {
    ArrayList arr = new ArrayList();
    DBCollection collection = dbConnection();
    DBCursor cursor = collection.find();
    try {//from ww  w .  j a  v a 2  s.co  m
        String str = "";
        while (cursor.hasNext()) {
            str = cursor.curr().get("text").toString();
            arr.add(str);
        }
    } finally {
        cursor.close();
    }

    return arr;

}

From source file:com.miya.twit.mongodb.DBConnectSentiment.java

public void getTweetWithUserId(int userId) {

    DBCollection collection = dbConnection();
    if (collection != null) {

        DBCursor cursor = collection.find();
        try {/*from   w  ww .j  a  va2 s.  com*/
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }
        //------------------------------------

        // get documents by query
        BasicDBObject query = new BasicDBObject("userid", new BasicDBObject("$gt", userId));

        cursor = collection.find(query);
        System.out.println("twit bulundu : " + cursor.count());

        //
        //            /**
        //             * ** Update ***
        //             */
        //            //update documents found by query "age > 30" with udpateObj "age = 20"
        //            BasicDBObject newDocument = new BasicDBObject();
        //            newDocument.put("age", 20);
        //
        //            BasicDBObject updateObj = new BasicDBObject();
        //            updateObj.put("$set", newDocument);
        //
        //            collection.update(query, updateObj, false, true);
        //
        //            /**
        //             * ** Find and display ***
        //             */
        //            cursor = collection.find(query);
        //            System.out.println("Person with age > 40 after update --> " + cursor.count());
        //
        //
        //            //get all again
        //            cursor = collection.find();
        //            try {
        //                while (cursor.hasNext()) {
        //                    System.out.println(cursor.next());
        //                }
        //            } finally {
        //                cursor.close();
        //            }
    }

}

From source file:com.nlp.twitterstream.MongoUtil.java

License:Open Source License

/**
 * Get all documents in collection/*from   w w w . j a v  a2 s  .  c o m*/
 * 
 * @param collection
 */
public List<DBObject> getAllDocuments(DBCollection collection) {

    List<DBObject> dbObjList = new ArrayList<DBObject>();

    DBCursor cursor = collection.find();
    try {
        while (cursor.hasNext()) {
            dbObjList.add(cursor.next());
        }
    } finally {
        cursor.close();
    }

    return dbObjList;
}

From source file:com.nlp.twitterstream.MongoUtil.java

License:Open Source License

/**
 * Get document list based on query/*from w  ww.  j  a va2  s  . co  m*/
 * 
 * @param collection
 * @param query
 * @return List<DBObject>
 */
public List<DBObject> getDocuments(DBCollection collection, BasicDBObject query) {

    List<DBObject> dbObjList = new ArrayList<DBObject>();

    // Get cursor on documents
    DBCursor cursor = collection.find(query);

    try {
        while (cursor.hasNext()) {
            dbObjList.add(cursor.next());
        }
    } finally {
        cursor.close();
    }

    return dbObjList;
}

From source file:com.owly.srv.RemoteBasicStatMongoDAOImpl.java

License:Apache License

public ArrayList<BasicStat> getMetricDetails(ShortRemoteServerId shortRemoteServer, String typeOfStat,
        String typeOfMetric, Integer minutesToCheck) {

    getLogger().info("MONGODB : Get a metric in a period of time vbased in minutes");

    GregorianCalendar cal = new GregorianCalendar();
    Date nowDate = cal.getTime();
    cal.add(Calendar.MINUTE, -minutesToCheck);
    Date beforeDate = cal.getTime();
    SimpleDateFormat dtformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    getLogger().info("MONGODB : Get a metric in a period of time starting : " + dtformat.format(beforeDate)
            + " and ending : " + dtformat.format(nowDate));

    //Create a List BasicStat Object
    ArrayList<BasicStat> ListMetrics = new ArrayList<BasicStat>();

    //Create the query
    BasicDBObject query = new BasicDBObject("NameServer", shortRemoteServer.getName())
            .append("ServerIP", shortRemoteServer.getNodeIPAddress()).append("StatType", typeOfStat)
            .append("StatDate", new BasicDBObject("$gt", beforeDate).append("$lt", nowDate));

    getLogger().debug("MONGODB : query =" + query.toString());

    //Create the selector
    BasicDBObject obj = new BasicDBObject("Metrics." + typeOfMetric, true).append("StatDate", true)
            .append("_id", false);

    getLogger().debug("MONGODB : selector =" + obj.toString());

    //Create the ordeby
    BasicDBObject orderBy = new BasicDBObject("StatDate", -1);

    DBCursor cursor = remoteStatCollection.find(query, obj).sort(orderBy);

    while (cursor.hasNext()) {
        DBObject cur = cursor.next();/*from w  ww . ja  v a2 s  . c  o  m*/

        BasicStat basicStat = new BasicStat();

        //logger.debug("MONGODB : query result"+cur.toString());
        //logger.debug("MONGODB : query result"+((BSONObject)cur.get("Metrics")).get(typeOfMetric));
        basicStat.setValue((String) ((BSONObject) cur.get("Metrics")).get(typeOfMetric).toString());
        basicStat.setDate((Date) cur.get("StatDate"));

        // Add this object into the list.
        ListMetrics.add(basicStat);
    }
    getLogger().debug("MONGODB : List obtained" + ListMetrics.toString());
    cursor.close();

    getLogger().info("MONGODB : List obtained");

    return ListMetrics;

}

From source file:com.owly.srv.RemoteBasicStatMongoDAOImpl.java

License:Apache License

public ArrayList<BasicStat> getMetricDetails(ShortRemoteServerId shortRemoteServer, String typeOfStat,
        String typeOfMetric, Integer minutesToCheck, Integer numerOfMetrics, long repeatInterval,
        double value_inteporlation) {

    getLogger().info("MONGODB : Get a metric in a period of time vbased in minutes");

    GregorianCalendar cal = new GregorianCalendar();
    Date nowDate = cal.getTime();
    cal.add(Calendar.MINUTE, -minutesToCheck);
    Date beforeDate = cal.getTime();
    SimpleDateFormat dtformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    getLogger().info("MONGODB : Get a metric in a period of time starting : " + dtformat.format(beforeDate)
            + " and ending : " + dtformat.format(nowDate));

    //Create a List BasicStat Object
    ArrayList<BasicStat> ListMetrics = new ArrayList<BasicStat>();

    //Create the query
    BasicDBObject query = new BasicDBObject("NameServer", shortRemoteServer.getName())
            .append("ServerIP", shortRemoteServer.getNodeIPAddress()).append("StatType", typeOfStat)
            .append("StatDate", new BasicDBObject("$gt", beforeDate).append("$lt", nowDate));

    getLogger().debug("MONGODB : query =" + query.toString());

    //Create the selector
    BasicDBObject obj = new BasicDBObject("Metrics." + typeOfMetric, true).append("StatDate", true)
            .append("_id", false);

    getLogger().debug("MONGODB : selector =" + obj.toString());

    //Create the ordeby
    BasicDBObject orderBy = new BasicDBObject("StatDate", -1);

    DBCursor cursor = remoteStatCollection.find(query, obj).sort(orderBy);

    while (cursor.hasNext()) {
        DBObject cur = cursor.next();/*from   w  w w .jav  a  2s . c om*/

        BasicStat basicStat = new BasicStat();

        //logger.debug("MONGODB : query result"+cur.toString());
        //logger.debug("MONGODB : query result"+((BSONObject)cur.get("Metrics")).get(typeOfMetric));
        basicStat.setValue((String) ((BSONObject) cur.get("Metrics")).get(typeOfMetric).toString());
        basicStat.setDate((Date) cur.get("StatDate"));

        // Add this object into the list.
        ListMetrics.add(basicStat);
    }

    //Execute the interpolation of data
    //Execute the interpolation of data            
    ArrayList<BasicStat> AddZerosListMetrics = new ArrayList<BasicStat>();
    AddZerosListMetrics = addValuesToList(ListMetrics, repeatInterval, value_inteporlation);

    Integer numberMetricsCollected = AddZerosListMetrics.size();
    getLogger().debug("Number of metricis collected = " + numberMetricsCollected
            + " and number of metrics to return = " + numerOfMetrics);

    if (numerOfMetrics < numberMetricsCollected) {
        // New List of metrics with number of metrics selected in  numerOfMetrics
        //Create a List BasicStat Object
        ArrayList<BasicStat> AvgListMetrics = new ArrayList<BasicStat>();
        double gapBetweenMetrics = (double) numberMetricsCollected / (double) numerOfMetrics; // Number of metrics in the original List between two metrics to exported to the new Genereated List.
        getLogger().debug("gapBetweenMetrics = " + gapBetweenMetrics);
        //Initialize first value
        getLogger().debug("We need to create a new List with Avg");
        //getLogger().debug("initialize firts value = " + AddZerosListMetrics.get(0));
        AvgListMetrics.add(0, AddZerosListMetrics.get(0));

        for (int j = 1; j < numerOfMetrics - 1; j++) {
            //getLogger().debug("Previous metrics is = "+ (int)Math.round((j-1)*gapBetweenMetrics) + ";Next metric to get = " + (int)Math.round(j*gapBetweenMetrics));

            ArrayList<BasicStat> tmpListMetrics = new ArrayList<BasicStat>();
            for (int k = ((int) Math.round((j - 1) * gapBetweenMetrics))
                    + 1; k <= ((int) Math.round(j * gapBetweenMetrics)); k++) {
                //getLogger().debug("Adding this indexes to the tmp List ="+k);
                tmpListMetrics.add(AddZerosListMetrics.get(k));
            }
            BasicStat AvgMetric = new BasicStat();
            AvgMetric.setAvgBasicStatList(tmpListMetrics);

            //getLogger().debug("Avg generated is  = "+AvgMetric.toString());

            AvgListMetrics.add(j, AvgMetric);

        }
        //Last value
        //getLogger().debug("Last metric to get = " + (numberMetricsCollected -1));
        AvgListMetrics.add(numerOfMetrics - 1, AddZerosListMetrics.get(numberMetricsCollected - 1));

        //Result with Avg
        getLogger().debug("MONGODB : List obtained" + AvgListMetrics.toString());

        cursor.close();

        getLogger().info("MONGODB : List obtained");

        return AvgListMetrics;

    } else {
        getLogger().debug("MONGODB : List obtained" + AddZerosListMetrics.toString());

        cursor.close();

        getLogger().info("MONGODB : List obtained");

        return AddZerosListMetrics;

    }

}

From source file:com.owly.srv.RemoteBasicStatMongoDAOImpl.java

License:Apache License

public ArrayList<BasicStat> getMetricDetails(ShortRemoteServerId shortRemoteServer, String typeOfStat,
        String typeOfMetric, Date startDate, Date endDate) {

    getLogger().info("MONGODB : get info of type of stats for an specific server");
    getLogger().info(/*from   w w w.  j  a va2  s  . c  o  m*/
            "MONGODB : Get a metric in a period of time starting : " + startDate + " and ending : " + endDate);

    //Create a List BasicStat Object
    ArrayList<BasicStat> ListMetrics = new ArrayList<BasicStat>();

    //Create the query
    BasicDBObject query = new BasicDBObject("NameServer", shortRemoteServer.getName())
            .append("ServerIP", shortRemoteServer.getNodeIPAddress()).append("StatType", typeOfStat)
            .append("StatDate", new BasicDBObject("$gt", startDate).append("$lt", endDate));

    getLogger().debug("MONGODB : query =" + query.toString());

    //Create the selector
    BasicDBObject obj = new BasicDBObject("Metrics." + typeOfMetric, true).append("StatDate", true)
            .append("_id", false);

    getLogger().debug("MONGODB : selector =" + obj.toString());

    //Create the ordeby
    BasicDBObject orderBy = new BasicDBObject("StatDate", -1);

    DBCursor cursor = remoteStatCollection.find(query, obj).sort(orderBy);

    while (cursor.hasNext()) {
        DBObject cur = cursor.next();

        BasicStat basicStat = new BasicStat();

        //logger.debug("MONGODB : query result"+cur.toString());
        //logger.debug("MONGODB : query result"+((BSONObject)cur.get("Metrics")).get(typeOfMetric));
        basicStat.setValue((String) ((BSONObject) cur.get("Metrics")).get(typeOfMetric).toString());
        basicStat.setDate((Date) cur.get("StatDate"));

        // Add this object into the list.
        ListMetrics.add(basicStat);
    }
    getLogger().debug("MONGODB : List obtained" + ListMetrics.toString());
    cursor.close();

    getLogger().info("MONGODB : List obtained");

    return ListMetrics;

}

From source file:com.owly.srv.RemoteBasicStatMongoDAOImpl.java

License:Apache License

public ArrayList<BasicStat> getMetricDetails(ShortRemoteServerId shortRemoteServer, String typeOfStat,
        String typeOfMetric, Date startDate, Date endDate, Integer numerOfMetrics, long repeatInterval,
        double value_inteporlation) {

    getLogger().info("MONGODB : get info of type of stats for an specific server");
    getLogger().info(/*from w w w  . j ava 2  s . c o  m*/
            "MONGODB : Get a metric in a period of time starting : " + startDate + " and ending : " + endDate);

    //Create a List BasicStat Object
    ArrayList<BasicStat> ListMetrics = new ArrayList<BasicStat>();

    //Create the query
    BasicDBObject query = new BasicDBObject("NameServer", shortRemoteServer.getName())
            .append("ServerIP", shortRemoteServer.getNodeIPAddress()).append("StatType", typeOfStat)
            .append("StatDate", new BasicDBObject("$gt", startDate).append("$lt", endDate));

    getLogger().debug("MONGODB : query =" + query.toString());

    //Create the selector
    BasicDBObject obj = new BasicDBObject("Metrics." + typeOfMetric, true).append("StatDate", true)
            .append("_id", false);

    getLogger().debug("MONGODB : selector =" + obj.toString());

    //Create the ordeby
    BasicDBObject orderBy = new BasicDBObject("StatDate", -1);

    DBCursor cursor = remoteStatCollection.find(query, obj).sort(orderBy);

    while (cursor.hasNext()) {
        DBObject cur = cursor.next();

        BasicStat basicStat = new BasicStat();

        //logger.debug("MONGODB : query result"+cur.toString());
        //logger.debug("MONGODB : query result"+((BSONObject)cur.get("Metrics")).get(typeOfMetric));
        basicStat.setValue((String) ((BSONObject) cur.get("Metrics")).get(typeOfMetric).toString());
        basicStat.setDate((Date) cur.get("StatDate"));

        // Add this object into the list.
        ListMetrics.add(basicStat);
    }

    //Execute the interpolation of data            
    ArrayList<BasicStat> AddZerosListMetrics = new ArrayList<BasicStat>();
    AddZerosListMetrics = addValuesToList(ListMetrics, repeatInterval, value_inteporlation);

    Integer numberMetricsCollected = AddZerosListMetrics.size();
    getLogger().debug("Number of metricis collected = " + numberMetricsCollected
            + " and number of metrics to return = " + numerOfMetrics);

    if (numerOfMetrics < numberMetricsCollected) {
        // New List of metrics with number of metrics selected in  numerOfMetrics
        //Create a List BasicStat Object
        ArrayList<BasicStat> AvgListMetrics = new ArrayList<BasicStat>();
        double gapBetweenMetrics = (double) numberMetricsCollected / (double) numerOfMetrics; // Number of metrics in the original List between two metrics to exported to the new Genereated List.
        getLogger().debug("gapBetweenMetrics = " + gapBetweenMetrics);
        //Initialize first value
        getLogger().debug("We need to create a new List with Avg");
        //getLogger().debug("initialize firts value = " + AddZerosListMetrics.get(0));
        AvgListMetrics.add(0, AddZerosListMetrics.get(0));

        for (int j = 1; j < numerOfMetrics - 1; j++) {
            //getLogger().debug("Previous metrics is = "+ (int)Math.round((j-1)*gapBetweenMetrics) + ";Next metric to get = " + (int)Math.round(j*gapBetweenMetrics));

            ArrayList<BasicStat> tmpListMetrics = new ArrayList<BasicStat>();
            for (int k = ((int) Math.round((j - 1) * gapBetweenMetrics))
                    + 1; k <= ((int) Math.round(j * gapBetweenMetrics)); k++) {
                //getLogger().debug("Adding this indexes to the tmp List ="+k);
                tmpListMetrics.add(AddZerosListMetrics.get(k));
            }
            BasicStat AvgMetric = new BasicStat();
            AvgMetric.setAvgBasicStatList(tmpListMetrics);

            //getLogger().debug("Avg generated is  = "+AvgMetric.toString());

            AvgListMetrics.add(j, AvgMetric);

        }
        //Last value
        //getLogger().debug("Last metric to get = " + (numberMetricsCollected -1));
        AvgListMetrics.add(numerOfMetrics - 1, AddZerosListMetrics.get(numberMetricsCollected - 1));

        //Result with Avg
        getLogger().debug("MONGODB : List obtained" + AvgListMetrics.toString());

        cursor.close();

        getLogger().info("MONGODB : List obtained");

        return AvgListMetrics;

    } else {
        getLogger().debug("MONGODB : List obtained" + AddZerosListMetrics.toString());

        cursor.close();

        getLogger().info("MONGODB : List obtained");

        return AddZerosListMetrics;

    }

}

From source file:com.owly.srv.RemoteServerMongoDAOImpl.java

License:Apache License

public ArrayList<String> listIPRemoteServer() {
    logger.debug("Get the IPs of remote serverssaved in the database");
    ArrayList<String> ipSrv = new ArrayList<String>();

    // create an empty query
    BasicDBObject query = new BasicDBObject();
    BasicDBObject obj = new BasicDBObject("NodeIPAddress", true).append("_id", false);

    //logger.info("MONGODB : FInd this object : " + obj.toString());

    DBCursor cursor = remoteSrvCfgCollection.find(query, obj);

    try {//from   w  w  w.  ja  v a2s .com
        while (cursor.hasNext()) {
            DBObject cur = cursor.next();
            logger.debug("NodeIPAddress : " + cur.get("NodeIPAddress"));
            ipSrv.add((String) cur.get("NodeIPAddress"));

        }
    } finally {
        cursor.close();
    }

    logger.info("MONGODB : List obtained");
    return ipSrv;
}