Example usage for com.mongodb DBCollection distinct

List of usage examples for com.mongodb DBCollection distinct

Introduction

In this page you can find the example usage for com.mongodb DBCollection distinct.

Prototype

public List distinct(final String fieldName) 

Source Link

Document

Find the distinct values for a specified field across a collection and returns the results in an array.

Usage

From source file:bhl.pages.database.MongoConnection.java

License:Open Source License

/**
 * Get the set of distinct keys for a collection
 * @param collection the collection name
 * @param field the field name for distinct values
 * @return and array of field values//from ww w  .  j  a  va 2  s . c o m
 * @throws Exception 
 */
@Override
public String[] getDistinctKeys(String collection, String field) throws DbException {
    try {
        connect();
        DBCollection coll = db.getCollection(Database.PAGES);
        List keys = coll.distinct(field);
        String[] list = new String[keys.size()];
        keys.toArray(list);
        return list;
    } catch (Exception e) {
        throw new DbException(e);
    }
}

From source file:br.bireme.scl.MongoOperations.java

License:Open Source License

public static Set<String> getDatabases(final DBCollection coll) {
    if (coll == null) {
        throw new NullPointerException("coll");
    }/*from  w w w . java  2  s  .  co m*/

    return new TreeSet<String>(coll.distinct("mst"));
}

From source file:com.andreig.jetty.DistinctServlet.java

License:GNU General Public License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doGet()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);//from www .  ja  va2 s  .  c  o m
        return;
    }

    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    String key = req.getParameter("key");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }
    if (key == null) {
        error(res, SC_BAD_REQUEST, Status.get("param name missing"));
        return;
    }

    DB db = mongo.getDB(db_name);
    DBCollection col = db.getCollection(col_name);

    List<?> l = col.distinct(key);
    if (l == null || l.size() == 0) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    res.setIntHeader("X-Documents-Count", l.size());

    StringBuilder buf = tl.get();
    buf.setLength(0);

    JSON.serialize(l, buf);
    out_str(req, buf.toString(), "application/json");

}

From source file:com.azure.api.MongoDAO.java

public static LinkedList<Pojoo> MongoConnection() throws IOException {

    MongoClient mongo = new MongoClient("localhost", 27017);

    DB db = mongo.getDB("test");

    DBCollection table = db.getCollection("DataFinal");

    List<String> uniId = table.distinct("Asin");

    //BasicDBObject searchQuery = new BasicDBObject();
    //searchQuery.put("Asin", "000100039X");
    DBObject groupFields = new BasicDBObject("_id", "$Asin");

    groupFields.put("count", new BasicDBObject("$sum", 1));
    //DBObject group = new BasicDBObject("$group", groupFields );
    DBObject sortFields = new BasicDBObject("count", -1);
    //AggregationOutput output = table.aggregate(group, new BasicDBObject("$sort", sortFields ));
    //System.out.println(output.results());//Top reviews 

    groupFields.put("average", new BasicDBObject("$avg", "$Ratings"));
    DBObject group2 = new BasicDBObject("$group", groupFields);

    AggregationOutput output2 = table.aggregate(group2, new BasicDBObject("$sort", sortFields));

    Iterable<DBObject> iterable = output2.results();

    //LinkedList<String>stringResult = new LinkedList<String>();

    //LinkedList<String>stringrating = new LinkedList<String>();

    //if(awsResult.size()!=0){awsResult.remove();}
    //if(stringResult.size()!=0){stringResult.remove();}

    //System.out.println("fffffffffffffffff"+stringResult.size());

    int count = 0;

    LinkedList<Pojoo> uiList = new LinkedList<Pojoo>();
    for (DBObject res : output2.results()) {

        //System.out.println("TTTTTTTT "+res.get("_id").toString());
        //System.out.println("VVVVVVVV "+res.get("average").toString());
        String awsResult = awsApi.getDetails(res.get("_id").toString());
        //stringResult.add(res.get("_id").toString());
        //stringrating.add(res.get("average").toString());
        Pojoo polo = new Pojoo();
        polo.setStringResult(awsResult);
        polo.setStringrating(res.get("average").toString());
        uiList.add(polo);/*from   ww w .  java 2  s  .co  m*/

        count++;
        if (count == 8) {
            res = null;
            break;
        }
    }

    count = 0;

    //awsResult = awsApi.getDetails(stringResult);
    //for(String htp: awsResult){
    //Pojoo polo = new Pojoo();
    //polo.setStringResult(htp);
    //polo.setStringrating(res.get("average").toString());
    //uiList.add(polo);
    //}

    // System.out.println("WWWWWW"+awsResult);
    //Pojoo img = new Pojoo();
    //img.setStringrating(stringrating);
    //img.setStringResult(awsResult);
    //stringResult.remove();

    //System.out.println("eeeeeeeeeeeeeee"+awsResult.size());
    //for(String ret:awsResult)
    //{
    //   System.out.println(ret);
    //}

    return uiList;

}

From source file:com.callidusrobotics.droptables.model.DocumentDao.java

License:Open Source License

/**
 * Finds distinct values for a specified key among documents in a collection.
 *
 * @param collectionName// ww  w .  ja  v  a 2 s. c o  m
 *          The collection to search
 * @param key
 *          The document key to select on
 * @return A list of distinct values, never null
 */
public List<String> getDistinctValues(String collectionName, String key) {
    DBCollection collection = getCollection(collectionName);
    List<String> result = new LinkedList<String>();
    for (Object value : collection.distinct(key)) {
        result.add(value.toString());
    }

    return result;
}

From source file:com.cyslab.craftvm.rest.mongo.DistinctServlet.java

License:GNU General Public License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doGet()");

    if (!can_read(req)) {
        res.sendError(SC_UNAUTHORIZED);/*from w  w w .j  ava 2  s. c o m*/
        return;
    }

    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    String key = req.getParameter("key");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }
    if (key == null) {
        error(res, SC_BAD_REQUEST, Status.get("param name missing"));
        return;
    }

    DB db = mongo.getDB(db_name);
    DBCollection col = db.getCollection(col_name);

    List l = col.distinct(key);
    if (l == null || l.size() == 0) {
        error(res, SC_NOT_FOUND, Status.get("no documents found"));
        return;
    }

    res.setIntHeader("X-Documents-Count", l.size());

    StringBuilder buf = tl.get();
    buf.setLength(0);

    JSON.serialize(l, buf);
    out_str(req, buf.toString(), "application/json");

}

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

License:Open Source License

/**
 * @param args//from ww  w  .  j av a  2 s.  c  o  m
 */

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;

    ///*from  w  w  w .jav a 2  s.  co  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.artist.postmigration.nfrvt.strategy.benchmark.AvailabilityCalculator.java

License:Open Source License

public static MultipleDCResults calculateCloudSleuthAvailability(int startYear, int startMonth, int startDay,
        int stopYear, int stopMonth, int stopDay) {

    try {/* www. ja  v a2  s  .  com*/
        Properties propertiesFile = BenchmarkConstants.getProperties();
        String databaseIP = propertiesFile.getProperty("3alibIP");
        MultipleDCResults response = new MultipleDCResults();
        double CloudSleuthAvailability = 0;
        double CloudSleuthDowntime = 0;
        Mongo mongoClient;
        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");

        for (int i = 0; i < distinctTemplates.size(); i++) {
            System.out.println("Region ID:" + distinctTemplates.get(i).toString());
            BasicDBObject queryPerRegionOverall = new BasicDBObject("_id",
                    new BasicDBObject("$gte", from).append("$lte", to)).append("location.parent.id",
                            distinctTemplates.get(i).toString());

            DBCursor cursorOverall;
            cursorOverall = coll.find(queryPerRegionOverall);
            cursorOverall.addOption(com.mongodb.Bytes.QUERYOPTION_NOTIMEOUT);

            System.out.println("Overall records:" + cursorOverall.length());

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

            DBCursor cursorUnavailable = coll.find(queryUnavailable);
            cursorUnavailable.addOption(com.mongodb.Bytes.QUERYOPTION_NOTIMEOUT);
            System.out.println("Unavailable records:" + cursorUnavailable.length());

            CloudSleuthAvailability = 100
                    * (((double) cursorOverall.length() - (double) cursorUnavailable.length())
                            / cursorOverall.length());
            System.out.println("Cloudsleuth based availability:" + CloudSleuthAvailability);
            CloudSleuthDowntime = 100.0 - CloudSleuthAvailability;
            response.DC.add(distinctTemplates.get(i).toString());
            response.availability.add((Double) CloudSleuthDowntime);
        }
        return response;

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

From source file:fr.cirad.web.controller.gigwa.base.AbstractVariantController.java

License:Open Source License

/**
 * Distinct sequences in selection.//from w  ww.  j  a  v a2 s. c  o  m
 *
 * @param request the request
 * @param sModule the module
 * @param projId the proj id
 * @param processID the process id
 * @return the collection
 * @throws Exception the exception
 */
@RequestMapping(distinctSequencesInSelectionURL)
protected @ResponseBody Collection<String> distinctSequencesInSelection(HttpServletRequest request,
        @RequestParam("module") String sModule, @RequestParam("project") int projId,
        @RequestParam("processID") String processID) throws Exception {
    processID = URLDecoder.decode(processID, "UTF-8");
    String token = processID.substring(1 + processID.indexOf('|'));
    DBCollection tmpVarColl = getTemporaryVariantCollection(sModule, token, false);
    if (tmpVarColl.count() == 0)
        return listSequences(request, sModule, projId); // working on full dataset

    List<String> distinctSequences = tmpVarColl
            .distinct(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ReferencePosition.FIELDNAME_SEQUENCE);
    TreeSet<String> sortedResult = new TreeSet<String>(new AlphaNumericComparator());
    sortedResult.addAll(distinctSequences);
    return sortedResult;
}