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:de.uni_koeln.spinfo.maalr.mongo.core.Database.java

License:Apache License

public LexEntryList queryForLexEntries(String login, Role role, Verification verification, String verifier,
        long startTime, long endTime, Status[] states, int limit, int offset, String orderField,
        boolean ascending) {
    logger.info("Query Params: " + login + ", " + role + ", " + verification + ", " + startTime + ", " + endTime
            + ", " + states + ", " + limit + ", " + offset + ", " + orderField + ", " + ascending);
    DBCursor cursor = query(login, role, verification, verifier, startTime, endTime, states, limit, offset,
            orderField, ascending);/*w w w  . ja  va2 s  . co m*/
    List<LexEntry> results = new ArrayList<LexEntry>();
    while (cursor.hasNext()) {
        DBObject next = cursor.next();
        LexEntry entry = Converter.convertToLexEntry(next);
        results.add(entry);
    }
    int count = cursor.count();
    cursor.close();
    return new LexEntryList(results, count);
}

From source file:edu.csulaerp.db.ReferenceMongo.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes no args//from  w ww .  j  a  v a 2s.  c o  m
 * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017
 */
public static void main(final String[] args) throws UnknownHostException {
    // connect to the local database server
    MongoClient mongoClient = new MongoClient();

    /*
    // Authenticate - optional
    MongoCredential credential = MongoCredential.createMongoCRCredential(userName, database, password);
    MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential));
    */

    // get handle to "mydb"
    DB db = mongoClient.getDB("mydb");

    // get a list of the collections in this database and print them out
    Set<String> collectionNames = db.getCollectionNames();
    for (final String s : collectionNames) {
        System.out.println(s);
    }

    // get a collection object to work with
    DBCollection coll = db.getCollection("testCollection");

    // drop all the data in it
    coll.drop();

    // make a document and insert it
    BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1)
            .append("info", new BasicDBObject("x", 203).append("y", 102));

    coll.insert(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    DBObject myDoc = coll.findOne();
    System.out.println(myDoc);

    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    for (int i = 0; i < 100; i++) {
        coll.insert(new BasicDBObject().append("i", i));
    }
    System.out
            .println("total # of documents after inserting 100 small ones (should be 101) " + coll.getCount());

    // lets get all the documents in the collection and print them out
    DBCursor cursor = coll.find();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // now use a query to get 1 document out
    BasicDBObject query = new BasicDBObject("i", 71);
    cursor = coll.find(query);

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // $ Operators are represented as strings
    query = new BasicDBObject("j", new BasicDBObject("$ne", 3)).append("k", new BasicDBObject("$gt", 10));

    cursor = coll.find(query);

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // now use a range query to get a larger subset
    // find all where i > 50
    query = new BasicDBObject("i", new BasicDBObject("$gt", 50));
    cursor = coll.find(query);

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // range query with multiple constraints
    query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30));
    cursor = coll.find(query);

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // Count all documents in a collection but take a maximum second to do so
    coll.find().maxTime(1, SECONDS).count();

    // Bulk operations
    BulkWriteOperation builder = coll.initializeOrderedBulkOperation();
    builder.insert(new BasicDBObject("_id", 1));
    builder.insert(new BasicDBObject("_id", 2));
    builder.insert(new BasicDBObject("_id", 3));

    builder.find(new BasicDBObject("_id", 1)).updateOne(new BasicDBObject("$set", new BasicDBObject("x", 2)));
    builder.find(new BasicDBObject("_id", 2)).removeOne();
    builder.find(new BasicDBObject("_id", 3)).replaceOne(new BasicDBObject("_id", 3).append("x", 4));

    BulkWriteResult result = builder.execute();
    System.out.println("Ordered bulk write result : " + result);

    // Unordered bulk operation - no guarantee of order of operation
    builder = coll.initializeUnorderedBulkOperation();
    builder.find(new BasicDBObject("_id", 1)).removeOne();
    builder.find(new BasicDBObject("_id", 2)).removeOne();

    result = builder.execute();
    System.out.println("Ordered bulk write result : " + result);

    // parallelScan
    ParallelScanOptions parallelScanOptions = ParallelScanOptions.builder().numCursors(3).batchSize(300)
            .build();

    List<Cursor> cursors = coll.parallelScan(parallelScanOptions);
    for (Cursor pCursor : cursors) {
        while (pCursor.hasNext()) {
            System.out.println(pCursor.next());
        }
    }

    // release resources
    db.dropDatabase();
    mongoClient.close();
}

From source file:edu.stanford.epad.epadws.aim.AIMQueries.java

License:Open Source License

/**
 * Read the annotations from the AIM database by patient name, patient id, series id, annotation id, or just get all
 * of them on a GET. Can also delete by annotation id.
 * /*from   www. j a v  a  2s . c  o  m*/
 * @param aimSearchType One of personName, patientId, seriesUID, annotationUID, deleteUID
 * @param value
 * @param user
 * @return List<ImageAnnotationCollection>
 * @throws edu.stanford.hakan.aim4api.base.AimException
 */
public static List<String> getJsonAnnotations(String projectID, AIMSearchType aimSearchType, String value,
        String username) throws Exception {
    //db.Test.find( { 'ImageAnnotationCollection.uniqueIdentifier.root': { $in: [ 'drr7d3pp5sr3up1hbt1v53cf4va5ga57fv8aeri6', 'iqn1vvxtdptm0wtzsc43kptl26oft5c08wxz0w1t' ] } } )
    List<String> results = new ArrayList<String>();
    long time1 = System.currentTimeMillis();
    DBObject query = null;
    if (aimSearchType == AIMSearchType.PERSON_NAME) {
        String personName = value;
        query = new BasicDBObject("ImageAnnotationCollection.person.name.value", personName);
    } else if (aimSearchType == AIMSearchType.PATIENT_ID) {
        String patientId = value;
        query = new BasicDBObject("ImageAnnotationCollection.person.id.value", patientId);
    } else if (aimSearchType == AIMSearchType.SERIES_UID) {
        String seriesUID = value;
        query = new BasicDBObject(
                "ImageAnnotationCollection.imageAnnotations.ImageAnnotation.imageReferenceEntityCollection.ImageReferenceEntity.imageStudy.imageSeries.instanceUid.root",
                seriesUID);
    } else if (aimSearchType == AIMSearchType.ANNOTATION_UID) {
        String annotationUID = value;
        if (value.equals("all")) {
        } else if (value.contains(",")) {
            String[] ids = value.split(",");
            BasicDBList aimIds = new BasicDBList();
            for (String id : ids) {
                aimIds.add(id);
            }
            DBObject inClause = new BasicDBObject("$in", aimIds);
            query = new BasicDBObject("ImageAnnotationCollection.uniqueIdentifier.root", inClause);
        } else {
            query = new BasicDBObject("ImageAnnotationCollection.uniqueIdentifier.root", value);
        }
    } else if (aimSearchType.equals(AIMSearchType.JSON_QUERY)) {
        String jsonQuery = value;
        query = (DBObject) JSON.parse(jsonQuery);
    } else {
        log.warning("Unsupported AIM search type for mongoDB:" + aimSearchType.getName());
    }
    DB mongoDB = MongoDBOperations.getMongoDB();
    if (mongoDB == null)
        throw new Exception("Error connecting to MongoDB");
    DBCollection coll = mongoDB.getCollection(projectID);
    DBCursor cursor = null;
    try {
        cursor = coll.find(query);
        while (cursor.hasNext()) {
            DBObject obj = cursor.next();
            results.add(obj.toString());
        }
    } finally {
        cursor.close();
    }
    long time2 = System.currentTimeMillis();
    log.info("MongoDB query took " + (time2 - time1) + " msecs for " + results.size() + " aims in projectID:"
            + projectID);
    return results;
}

From source file:epoxide.lpa.impl.mongodb.MongoRecordSet.java

License:Apache License

@Override
public T getEntity(Object id) {
    DBCursor cursor = coll.find(new BasicDBObject("_id", id));
    if (cursor.hasNext()) {
        DBObject result = cursor.next();
        cursor.close();
        return cls.cast(conv.decode(result));
    }/*from w  w  w .j  ava2 s .  c  o m*/
    cursor.close();
    return null;
}

From source file:es.bsc.amon.DBManager.java

License:Open Source License

public BasicDBList find(String collectionName, DBObject query, DBObject orderby, Integer limit) {
    BasicDBList result = new BasicDBList();

    DBCursor c = null;
    if (query == null) {
        c = database.getCollection(collectionName).find();
    } else {/*from   w w w.  j av  a2 s  .c om*/
        c = database.getCollection(collectionName).find(query);
    }

    if (orderby == null) {
        c.sort(orderby);
    }

    if (limit != null && limit > 0) {
        c = c.limit(limit);
    }

    while (c.hasNext()) {
        result.add(c.next());
    }
    c.close();
    return result;
}

From source file:eu.artist.cloud.auditors.AbstractedAvailabilityCalculator.java

License:Open Source License

/**
 * @param args/*from  w w  w. j av a 2 s  . com*/
 */

public double calculateAvailability(String databaseIP, int DefinedQuantumofTimeInSeconds) {// (Date thisDate,
    // String userID,){

    double result = 0;

    //is this correct here?if the entire AWS is down, then it will add all 
    //intervals of all VMs--FIX
    long OVERALL_MONTH_INTERVAL_SECONDS = 0;

    //

    // DB interface part
    Mongo mongoClient;
    try {
        mongoClient = new Mongo(databaseIP);
        DB db = mongoClient.getDB("3alib");
        System.out.println("Host address:" + databaseIP);
        Set<String> colls = db.getCollectionNames();
        DBCollection coll = db.getCollection("log_samples");

        // get date and time of interest
        // preparation only once, usage in query for each distinct template
        // ID

        Scanner reader = new Scanner(System.in);
        System.out.println("Enter start year");

        int startYear = reader.nextInt();

        System.out.println("Enter start month");

        int startMonth = reader.nextInt() - 1;//needs +1 since month numbering begins from 0

        System.out.println("Enter start day of month");

        int startDay = reader.nextInt();

        System.out.println("Enter stop year");

        int stopYear = reader.nextInt();

        System.out.println("Enter stop month");
        int stopMonth = reader.nextInt() - 1;//needs +1 since month numbering begins from 0

        System.out.println("Enter stop day of month");

        int stopDay = reader.nextInt();
        Date date = new Date();
        Calendar calendarFrom = Calendar.getInstance();
        calendarFrom.setTime(date);
        calendarFrom.set(startYear, startMonth, startDay, 0, 0, 0);

        Date dateFrom = calendarFrom.getTime();

        Calendar calendarTo = Calendar.getInstance();
        calendarTo.setTime(date);
        calendarTo.set(stopYear, stopMonth, stopDay, 23, 59, 59);

        Date dateTo = calendarTo.getTime();

        System.out.println("Date beginning:" + dateFrom.toString());
        System.out.println("Date ending:" + dateTo.toString());
        ObjectId from = new ObjectId(dateFrom);
        ObjectId to = new ObjectId(dateTo);
        // we need a query to get the distinct templateIDs logged
        // in the DB
        // then based on this iteration we can get the actual values

        //get distinct template IDs
        List distinctTemplates = coll.distinct("imageId");

        for (int i = 0; i < distinctTemplates.size(); i++) {

            String index = "-1";

            System.out.println("Distinct template IDs:" + distinctTemplates.get(i).toString());

            // query based on date to filter needed month

            BasicDBObject query = new BasicDBObject("_id", new BasicDBObject("$gte", from).append("$lte", to))
                    .append("imageId", distinctTemplates.get(i).toString());

            DBCursor cursor = coll.find(query);

            //here the code to extract actual stats for a given template ID

            //abstraction should be achieved also in the status messages
            //inside MongoDB add the field "reachability" should be REACHABLE OR UNREACHABLE
            //the insertion should be performed with an abstracted method at the auditors side

            try {
                long startID = 0;
                long stopID = 0;
                long diffSeconds = 0;
                long PREDEFINED_LOGICAL_SAMPLE_INTERVAL_IN_SECONDS = 500;//interval in which we would logically
                //have at least one sample if the daemon is running

                DBObject thisObject = cursor.next();
                System.out.println("First object:" + thisObject.toString());
                DBObject previousObject = thisObject;
                int k = 0;
                while (k < (cursor.count() + 1)) {

                    System.out.println("Times:" + ((ObjectId) thisObject.get("_id")).getTime());
                    //thisObject=cursor.next();
                    System.out.println("Filtered objects:" + thisObject.get("_id"));

                    // index is a flag to indicate if the unreachable sample is the first of a sequence
                    //of unreachable samples
                    //if -1 it is the first sample in the series
                    if (((thisObject.get("reachability")).equals("UNREACHABLE")) && index.equals("-1")) { //if it is the first unavailable sample
                        //index= this db index
                        //ObjectId thisBSON= (ObjectId) thisObject.get("_id");

                        System.out.println("Changing index to 1...");
                        startID = ((ObjectId) thisObject.get("_id")).getTime();//this line's id
                        System.out.println("StartID is: " + startID);
                        index = "1";
                    }

                    if (((thisObject.get("reachability")).equals("UNREACHABLE")) && (!(index.equals("-1")))) {
                        //necessary for the case that two consecutive unavailable samples are too far apart (defined in variable 
                        //PREDEFINED_LOGICAL_SAMPLE_INTERVAL_IN_SECONDS) in time, indicative that the image id
                        //was not in the valid list during this time. Thus this interval should not count in the overall unavailable period

                        long gapstopID = ((ObjectId) thisObject.get("_id")).getTime();
                        long gapstartID = ((ObjectId) previousObject.get("_id")).getTime();
                        //System.out.println("StopID is: "+stopID);
                        long GapdiffSeconds = (gapstopID - gapstartID) / 1000; // 60;
                        if (GapdiffSeconds > PREDEFINED_LOGICAL_SAMPLE_INTERVAL_IN_SECONDS) {
                            System.out.println("Found gap...");

                            stopID = ((ObjectId) previousObject.get("_id")).getTime();//this line's id to end interval
                            System.out.println("StopID is previous: " + stopID);
                            diffSeconds = (stopID - startID) / 1000; // 60;
                            //System.out.println("Unavailable Interval is:"+diffSeconds);
                            if (diffSeconds > DefinedQuantumofTimeInSeconds) {

                                //needs global variable

                                OVERALL_MONTH_INTERVAL_SECONDS = OVERALL_MONTH_INTERVAL_SECONDS + diffSeconds;
                                System.out.println("Overall month interval in seconds now:"
                                        + OVERALL_MONTH_INTERVAL_SECONDS);
                            }

                            //we must not initialize the index to -1 at this point!!!!!!!we must just reset the startID to point to the current
                            //point
                            startID = ((ObjectId) thisObject.get("_id")).getTime();//this line's id

                        } else {
                            //standard logic to cover generic case of consecutive unavailable samples

                        }

                    }

                    if (((((thisObject.get("reachability")).equals("REACHABLE")) || (!(cursor.hasNext()))))
                            && (!(index.equals("-1")))) {
                        //calculate interval from index to (this index-1)
                        if (!(cursor.hasNext())) {
                            System.out.println("FINAL ELEMENT REACHED");
                        }
                        //we always get the previous sample, assuming that in the meantime
                        //up to the available sample
                        //it was available
                        stopID = ((ObjectId) previousObject.get("_id")).getTime();
                        /*
                        long gapstopID=((ObjectId)thisObject.get("_id")).getTime();
                        long gapstartID=((ObjectId)previousObject.get("_id")).getTime();
                        //System.out.println("StopID is: "+stopID);
                        long GapdiffSeconds = (gapstopID-gapstartID) / 1000; // 60;
                        if (GapdiffSeconds>PREDEFINED_LOGICAL_SAMPLE_INTERVAL_IN_SECONDS){
                           System.out.println("Found gap...");
                                
                           stopID=((ObjectId)previousObject.get("_id")).getTime();//this line's id to end interval
                           System.out.println("StopID is previous: "+stopID);
                        }else
                        {stopID=((ObjectId)previousObject.get("_id")).getTime();//this line's id to end interval
                        System.out.println("StopID is: "+stopID);}
                        */
                        diffSeconds = (stopID - startID) / 1000; // 60;
                        //System.out.println("final segment Unavailable Interval is:"+diffSeconds);
                        //if interval>Quantum add intervall to OVERALL MONTH interval

                        if (diffSeconds > DefinedQuantumofTimeInSeconds) {

                            //needs global variable

                            OVERALL_MONTH_INTERVAL_SECONDS = OVERALL_MONTH_INTERVAL_SECONDS + diffSeconds;
                            System.out.println(
                                    "Overall month interval in seconds now:" + OVERALL_MONTH_INTERVAL_SECONDS);
                        }

                        //set index=-1
                        System.out.println("Resetting index to -1...");
                        index = "-1";
                    }

                    if ((cursor.hasNext())) {
                        previousObject = thisObject;
                        thisObject = cursor.next();
                    }
                    k++;
                } //end of while for resultset analysis

                System.out.println("Final Overall month unavailable interval in seconds now:"
                        + OVERALL_MONTH_INTERVAL_SECONDS);

                //part for measuring percentage of availability based on provider definition
                double OverallUnavailableIntervalInMinutes = OVERALL_MONTH_INTERVAL_SECONDS / 60;
                System.out
                        .println("OverallUnavailableIntervalInMinutes:" + OverallUnavailableIntervalInMinutes);
                double OverallIntervalInSeconds = (dateTo.getTime() - dateFrom.getTime()) / 1000;
                //System.out.println("OVERALLINTERVAL IN SECONDS:"+OverallIntervalInSeconds);
                double OverallIntervalInMinutes = OverallIntervalInSeconds / 60;

                //System.out.println("OVERALLINTERVAL IN Minutes:"+OverallIntervalInMinutes);
                double finalAvailabilityPercentage = 100.0
                        * ((OverallIntervalInMinutes - OverallUnavailableIntervalInMinutes)
                                / OverallIntervalInMinutes);
                System.out.println(
                        "Final percentage of availability based on provider definition in the given interval:"
                                + finalAvailabilityPercentage);
            } catch (Exception e1) {

                e1.printStackTrace();

            } finally {
                cursor.close();
            }

        } //end of for for distinct template IDs
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MongoException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
        System.out.println("No available data for this period...");
    }

    return result;

}

From source file:eu.artist.postmigration.nfrvt.strategy.benchmark.AvailabilityCalculator.java

License:Open Source License

public static MultipleDCResults calculateAvailability(int DefinedQuantumofTimeInSeconds, int startYear,
        int startMonth, int startDay, int stopYear, int stopMonth, int stopDay) {// (Date thisDate,

    double OVERALL_MONTH_INTERVAL_SECONDS = 0;

    //// w  w  w .  j av a 2s.c o m
    try {
        Properties propertiesFile = BenchmarkConstants.getProperties();
        String databaseIP = propertiesFile.getProperty("3alibIP");
        MultipleDCResults response = new MultipleDCResults();
        Mongo mongoClient;

        System.out.println("DB NoSQL:" + databaseIP);
        mongoClient = new Mongo(databaseIP);
        DB db = mongoClient.getDB("3alib");
        System.out.println("Host address:" + databaseIP);
        DBCollection coll = db.getCollection("log_samples");

        Date date = new Date();
        Calendar calendarFrom = Calendar.getInstance();
        calendarFrom.setTime(date);
        calendarFrom.set(startYear, startMonth - 1, startDay, 0, 0, 0);

        Date dateFrom = calendarFrom.getTime();

        Calendar calendarTo = Calendar.getInstance();
        calendarTo.setTime(date);
        calendarTo.set(stopYear, stopMonth - 1, stopDay, 23, 59, 59);

        Date dateTo = calendarTo.getTime();

        System.out.println("Date beginning:" + dateFrom.toString());
        System.out.println("Date ending:" + dateTo.toString());
        ObjectId from = new ObjectId(dateFrom);
        ObjectId to = new ObjectId(dateTo);

        List<?> distinctTemplates = coll.distinct("location.parent.id");//distinct("imageId");

        for (int i = 0; i < distinctTemplates.size(); i++) {

            String index = "-1";

            System.out.println("Distinct Region IDs:" + distinctTemplates.get(i).toString());

            // query based on date to filter needed month

            BasicDBObject query = new BasicDBObject("_id", new BasicDBObject("$gte", from).append("$lte", to))
                    .append("location.parent.id", distinctTemplates.get(i).toString());

            DBCursor cursor = coll.find(query);
            cursor.addOption(com.mongodb.Bytes.QUERYOPTION_NOTIMEOUT);
            cursor.batchSize(100);

            try {
                long startID = 0;
                long stopID = 0;
                long diffSeconds = 0;
                double PREDEFINED_LOGICAL_SAMPLE_INTERVAL_IN_SECONDS = 500;//interval in which we would logically
                //have at least one sample if the daemon is running

                DBObject thisObject = cursor.next();
                System.out.println("First object:" + thisObject.toString());
                int cursorCount = cursor.count();
                System.out.println("Cursor count:" + cursor.count());
                DBObject previousObject = thisObject;
                int k = 0;
                while (k < (cursorCount + 1)) {

                    if ((k % 1000) == 0) {
                        System.out.println("Progress:" + k + " from " + cursorCount + " overall records");
                    }

                    if (((thisObject.get("reachability")).equals("UNREACHABLE")) && index.equals("-1")) { //if it is the first unavailable sample
                        System.out.println("Changing index to 1...");
                        startID = ((ObjectId) thisObject.get("_id")).getTime();//this line's id
                        System.out.println("StartID is: " + startID);
                        index = "1";
                    }

                    if (((thisObject.get("reachability")).equals("UNREACHABLE")) && (!(index.equals("-1")))) {
                        long gapstopID = ((ObjectId) thisObject.get("_id")).getTime();
                        long gapstartID = ((ObjectId) previousObject.get("_id")).getTime();
                        long GapdiffSeconds = (gapstopID - gapstartID) / 1000; // 60;
                        if (GapdiffSeconds > PREDEFINED_LOGICAL_SAMPLE_INTERVAL_IN_SECONDS) {
                            System.out.println("Found gap...");

                            stopID = ((ObjectId) previousObject.get("_id")).getTime();//this line's id to end interval
                            System.out.println("StopID is previous: " + stopID);
                            diffSeconds = (stopID - startID) / 1000;

                            if (diffSeconds > DefinedQuantumofTimeInSeconds) {
                                OVERALL_MONTH_INTERVAL_SECONDS = OVERALL_MONTH_INTERVAL_SECONDS + diffSeconds;
                                System.out.println("Overall month interval in seconds now:"
                                        + OVERALL_MONTH_INTERVAL_SECONDS);
                            }
                            startID = ((ObjectId) thisObject.get("_id")).getTime();//this line's id

                        } else {
                            //standard logic to cover generic case of consecutive unavailable samples
                        }

                    }

                    if (((((thisObject.get("reachability")).equals("REACHABLE")) || (!(cursor.hasNext()))))
                            && (!(index.equals("-1")))) {
                        if (!(cursor.hasNext())) {
                            System.out.println("FINAL ELEMENT REACHED");
                        }
                        stopID = ((ObjectId) previousObject.get("_id")).getTime();
                        diffSeconds = (stopID - startID) / 1000; // 60;

                        if (diffSeconds > DefinedQuantumofTimeInSeconds) {
                            OVERALL_MONTH_INTERVAL_SECONDS = OVERALL_MONTH_INTERVAL_SECONDS + diffSeconds;
                            System.out.println(
                                    "Overall month interval in seconds now:" + OVERALL_MONTH_INTERVAL_SECONDS);
                        }
                        System.out.println("Resetting index to -1...");
                        index = "-1";
                    }

                    if ((cursor.hasNext())) {
                        previousObject = thisObject;
                        thisObject = cursor.next();
                    }
                    k++;
                }

                System.out.println("Final Overall month unavailable interval in seconds now:"
                        + OVERALL_MONTH_INTERVAL_SECONDS);
                double OverallUnavailableIntervalInMinutes = OVERALL_MONTH_INTERVAL_SECONDS / 60;
                System.out
                        .println("OverallUnavailableIntervalInMinutes:" + OverallUnavailableIntervalInMinutes);
                double OverallIntervalInSeconds = (dateTo.getTime() - dateFrom.getTime()) / 1000;
                double OverallIntervalInMinutes = OverallIntervalInSeconds / 60;
                double finalAvailabilityPercentage = 100.0
                        * ((OverallIntervalInMinutes - OverallUnavailableIntervalInMinutes)
                                / OverallIntervalInMinutes);
                double downtimeInPercent = 100.0 - finalAvailabilityPercentage;
                response.DC.add(distinctTemplates.get(i).toString());
                response.availability.add((Double) downtimeInPercent);
                System.out.println(
                        "Final percentage of availability based on provider definition in the given interval:"
                                + finalAvailabilityPercentage);
            } catch (NoSuchElementException e2) {

                System.out.println("No available data for this period...");

            } catch (Exception e1) {

                e1.printStackTrace();

            } finally {
                cursor.close();
            }

        }
        return response;

    } catch (UnknownHostException e) {
        e.printStackTrace();
        return null;
    } catch (MongoException e) {
        System.out.println("No available data for this period...");
        return null;
    }
}

From source file:eu.cassandra.csn.mongo.MongoQueries.java

License:Apache License

public static String[][] getRuns() {
    DBCursor cursor = DBConn.getConn("test").getCollection("runs").find();

    String[][] data = new String[cursor.size()][3];
    int counter = 0;
    while (cursor.hasNext()) {
        DBObject obj = cursor.next();/*from   w ww. jav  a2s.c  om*/
        if ((Integer) obj.get("percentage") == 100) {
            String c = String.valueOf(counter);
            String id = "";

            id = obj.get("_id").toString();

            int instCounter = DBConn.getMongo().getDB(id).getCollection("installations").find().count();
            if (instCounter > limit)
                instCounter = limit;

            data[counter][0] = c;
            data[counter][1] = id;
            data[counter][2] = String.valueOf(instCounter);
            counter++;
        }
    }
    cursor.close();
    return data;
}

From source file:eu.cassandra.csn.mongo.MongoQueries.java

License:Apache License

/**
 * // w  w w . jav  a  2 s  .c o m
 * @param numberOfNodes
 * @param inst_id
 * @return
 */
public static ConsumptionInfo calculateGraphStats(int numberOfNodes, String inst_id) {
    double max = 0.0;
    double sum = 0.0;
    double avg = 0.0;

    DBCursor simParam = DBConn.getConn().getCollection("sim_param").find();
    int days = 0;
    while (simParam.hasNext()) {
        DBObject o = simParam.next();
        if (days == 0)
            days = Integer.parseInt(o.get("numberOfDays").toString());
        else
            break;
    }
    simParam.close();

    DBCursor res2;
    if (inst_id == null) {
        res2 = DBConn.getConn().getCollection("inst_results")
                .find(new BasicDBObject(), new BasicDBObject("p", 1)).sort(new BasicDBObject("p", -1)).limit(1);
    } else {
        res2 = DBConn.getConn().getCollection("inst_results")
                .find(new BasicDBObject("inst_id", inst_id), new BasicDBObject("p", 1))
                .sort(new BasicDBObject("p", -1)).limit(1);
    }
    while (res2.hasNext()) {
        DBObject o = res2.next();
        max = Double.parseDouble(o.get("p").toString());
    }
    res2.close();

    //TODO: Change results to aggregated results, once they have been implemented
    if (numberOfNodes != 1) {
        avg = max / 2.3 * days * 24;
        sum = avg * (double) numberOfNodes;
    } else {
        avg = max / 2.3;
        sum = avg * days * 24 / 1000;
    }

    //Group
    //      BasicDBObject groupCmd = new BasicDBObject("ns","inst_results");
    //      groupCmd.append("$keyf", "");
    //      groupCmd.append("$reduce", "function(obj,prev){prev.y+=obj.p}");
    //      groupCmd.append("initial",  new BasicDBObject("y",0));
    //      DBObject o = DBConn.getConn().getCollection("inst_results").group(groupCmd);

    //Map Reduce
    //      String map = "function(){" +
    //            "emit(this.inst_id, {count: 1, sum: this.p});" +
    //            "};";
    //
    //      String reduce = "function( key , values ){" +
    //            "var n = { count: 0, sum: 0}; " +
    //            "for ( var i = 0; i < values.length; i ++ ) {" +
    //            "n.sum += values[i].sum;" +
    //            "n.count += values[i].count;" +
    //            "};" +
    //            "return n;" +
    //            "};";
    //
    //      MapReduceOutput out = DBConn.getConn().getCollection("inst_results").mapReduce(map, reduce, null, MapReduceCommand.OutputType.INLINE, null);
    //      for ( DBObject obj3 : out.results() ) {
    //      }

    //One by One
    //      DBCursor res = DBConn.getConn().getCollection("inst_results").find(new BasicDBObject(), new BasicDBObject("p",1));
    //      while(res.hasNext()) {
    //         DBObject obj = res.next();
    //         double value = Double.parseDouble(obj.get("p").toString());
    //         sum += value;
    //         if(value > max)
    //            max = value;
    //      }
    //      avg = sum/(double)numberOfNodes;
    return new ConsumptionInfo(days, sum, avg, max);
}

From source file:eu.cassandra.csn.mongo.MongoQueries.java

License:Apache License

/**
 * //from  w  w  w . j  a  v a2 s .  co m
 * @param nodesDiscovered
 * @param nodes
 * @param max
 * @return
 */
public static Vector<MyNode> getMaxMinInstallations(Vector<MyNode> nodesDiscovered, Iterator<MyNode> nodes,
        boolean max) {
    double mValue;
    if (max)
        mValue = Double.MIN_VALUE;
    else
        mValue = Double.MAX_VALUE;
    MyNode mNode = null;
    while (nodes.hasNext()) {
        MyNode n = nodes.next();
        DBCursor res = DBConn.getConn().getCollection("inst_results")
                .find(new BasicDBObject("inst_id", n.getId())).sort(new BasicDBObject("p", -1)).limit(1);
        while (res.hasNext()) {
            Double value = Double.parseDouble(res.next().get("p").toString());
            if (max) {
                if (value >= mValue) {
                    mValue = value;
                    mNode = n;
                }
            } else {
                if (value <= mValue) {
                    mValue = value;
                    mNode = n;
                }
            }
        }
        res.close();
    }
    mNode.setBig(true);
    nodesDiscovered.add(mNode);
    return nodesDiscovered;
}