Example usage for com.mongodb Mongo Mongo

List of usage examples for com.mongodb Mongo Mongo

Introduction

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

Prototype

Mongo(final MongoClientURI mongoURI) 

Source Link

Usage

From source file:edu.sjsu.carbonated.mongodbaccessors.MongoDBGroup.java

License:Apache License

public MongoDBGroup() {

    try {//from   w w  w . java 2 s .  c om
        m = new Mongo(sHost);
        DB db = m.getDB(sDB);
        collection = db.getCollection(sCollection);
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MongoException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

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

License:Open Source License

/**
 * @param args//from w ww  .ja  va  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.cloud.auditors.AbstractedAvailabilityLogger.java

License:Open Source License

/**
 * @param args//ww w  .j av  a  2s.c om
 */
public void logAvailability(ArrayList<String> TemplateIDs, String DBuser, String DBpass, String databaseIP)
        throws UnknownHostException, MongoException {
    // TODO Auto-generated method stub

    //needs to be periodic - but periodicity may be on the previous level-> Availability Auditor
    //better on the Availability Auditor level, since it will have refreshed also the state
    //needs to raise one thread per node, concurrent requests for all nodes?
    //sla is per template id? logically yes, so thread must be per template id

    //mongodb connection
    //we need to pass an object that will be the DB record and will contain all necessary information
    //this object will be transformed to json
    //more efficient to pass an arraylist of these objects (for all template IDs in one sample) and make once
    //the connection to the DB (for needed in the basic operation)

    for (String record : TemplateIDs) {
        Mongo mongoClient = new Mongo(databaseIP);
        DB db = mongoClient.getDB("3alib");
        System.out.println("Host address for Backend DB:" + databaseIP);
        Set<String> colls = db.getCollectionNames();

        for (String s : colls) {
            System.out.println("These are the collections... " + s);
        }
        DBCollection coll = db.getCollection("log_samples");

        //log sample
        /*BasicDBObject doc = new BasicDBObject("name1", "MongoDB2").
        append("type", "database").
        append("count", 1).
        append("info", new BasicDBObject("x", 203).append("y", 102));
        */
        //DBObject obj=new DBObject();

        JSON jsonObj = new JSON();

        DBObject obj = (DBObject) jsonObj.parse(record);
        //BasicDBObject doc=new BasicDBObject(record);

        ObjectId obid = new ObjectId();
        //System.out.println("This is the id:"+obj.get("_id"));
        coll.insert(obj);

        DBObject myDoc = coll.findOne();
        //System.out.println(myDoc);
        //coll.
        mongoClient.close();
        //log file must be per template ID so that it can be appended each time, if we start stop the auditing action
        //ideally templateID_month_year

        //return 0;
    }
    System.out.println("Records included");
}

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 ww .j a va2 s  . 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.artist.postmigration.nfrvt.strategy.benchmark.AvailabilityCalculator.java

License:Open Source License

public static boolean isDBAvailable() {
    try {//  w  w  w.  j  a v  a  2 s  . c o  m
        Properties propertiesFile = BenchmarkConstants.getProperties();
        String databaseIP = propertiesFile.getProperty("3alibIP");
        Mongo mongoClient = new Mongo(databaseIP);
        DB db = mongoClient.getDB("3alib");
        return db != null;
    } catch (MongoException | IOException e) {
        return false;
    }
}

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 {/*  w  ww .j ava 2 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:eu.cassandra.csn.mongo.DBConn.java

License:Apache License

/**
 * /*from   w  w w.j  a va2 s . co  m*/
 * @param dbHost
 */
public static void initDBConn(String dbHost) {
    try {
        if (dbHost != null)
            DB_HOST = dbHost;
        m = new Mongo(DB_HOST);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (MongoException e) {
        e.printStackTrace();
    }
}

From source file:eu.cassandra.server.api.Runs.java

License:Apache License

private static DB createDB(String dbname) throws UnknownHostException, MongoException {
    Mongo m = new Mongo("localhost");
    return m.getDB(dbname);
}

From source file:eu.cassandra.server.api.UploadFileService.java

License:Apache License

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("prj_id") String prj_id) {

    String filename = fileDetail.getFileName();
    String uploadedFileLocation = context.getRealPath("/resources") + "/" + filename;

    System.out.println(uploadedFileLocation);

    try {//from   w ww.  ja v  a 2  s. c o  m
        // Save it
        writeToFile(uploadedInputStream, uploadedFileLocation);
        // TODO: Create a Run and return the id in the response
        ObjectId objid = ObjectId.get();
        DBObject run = new BasicDBObject();
        String dbname = objid.toString();
        Mongo m = new Mongo("localhost");
        DB db = m.getDB(dbname);
        MongoResults mr = new MongoResults(dbname);
        mr.createIndexes();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmm");
        String runName = "Run for " + filename + " on " + sdf.format(calendar.getTime());
        run.put("_id", objid);
        run.put("name", runName);
        run.put("started", System.currentTimeMillis());
        run.put("ended", System.currentTimeMillis());
        run.put("type", "file");
        run.put("prj_id", prj_id);
        run.put("percentage", 100);
        DBConn.getConn().getCollection(MongoRuns.COL_RUNS).insert(run);

        // Find the project
        DBObject query = new BasicDBObject();
        query.put("_id", new ObjectId(prj_id));
        DBObject project = DBConn.getConn().getCollection(MongoProjects.COL_PROJECTS).findOne(query);
        db.getCollection(MongoProjects.COL_PROJECTS).insert(project);
        // Make a scenario
        DBObject scenario = new BasicDBObject();
        scenario.put("name", filename);
        scenario.put("project_id", prj_id);
        db.getCollection(MongoScenarios.COL_SCENARIOS).insert(scenario);
        // Get the scenario id
        query = new BasicDBObject();
        query.put("project_id", prj_id);
        DBObject insertedScenario = db.getCollection(MongoScenarios.COL_SCENARIOS).findOne(query);
        ObjectId scnIdObj = (ObjectId) insertedScenario.get("_id");
        String scnId = scnIdObj.toString();
        // TODO: Parse and calculate KPIs
        File f = new File(uploadedFileLocation);
        Scanner sc = new Scanner(f);
        String header = sc.next();
        String[] headerTokens = header.split(",");
        int numOfInstallations = headerTokens.length - 1;
        double maxPower = 0;
        double[] maxPowerInst = new double[numOfInstallations];
        double avgPower = 0;
        double[] avgPowerInst = new double[numOfInstallations];
        double energy = 0;
        double[] energyInst = new double[numOfInstallations];
        int tick = 0;
        while (sc.hasNext()) {
            tick++;
            String line = sc.next();
            String[] tokens = line.split(",");
            double powerSum = 0;
            for (int i = 1; i < tokens.length; i++) {
                double power = Double.parseDouble(tokens[i]);
                energyInst[i - 1] += (power / 1000.0) * Constants.MINUTE_HOUR_RATIO;
                avgPowerInst[i - 1] += power;
                if (maxPowerInst[i - 1] < power) {
                    maxPowerInst[i - 1] = power;
                }
                powerSum += power;
                mr.addTickResultForInstallation(tick, headerTokens[i], power, 0, MongoResults.COL_INSTRESULTS);
            }
            mr.addAggregatedTickResult(tick, powerSum, 0, MongoResults.COL_AGGRRESULTS);
            energy += (powerSum / 1000.0) * Constants.MINUTE_HOUR_RATIO;
            avgPower += powerSum;
            if (maxPower < powerSum) {
                maxPower = powerSum;
            }
        }

        // TODO: Add ticks and KPIs in the db
        for (int i = 0; i < numOfInstallations; i++) {
            mr.addKPIs(headerTokens[i + 1], maxPowerInst[i], avgPowerInst[i] / tick, energyInst[i], 0, 0);
        }
        mr.addKPIs(MongoResults.AGGR, maxPower, avgPower / tick, energy, 0, 0);

        String output = "File uploaded to : " + uploadedFileLocation;
        // Make sim params
        DBObject sim_params = new BasicDBObject();
        sim_params.put("name", filename);
        sim_params.put("scn_id", scnId);
        sim_params.put("numberOfDays", (tick / 1440));
        sim_params.put("mcruns", 1);
        db.getCollection(MongoSimParam.COL_SIMPARAM).insert(sim_params);
        return Response.status(200).entity(output).build();
    } catch (Exception exp) {
        JSONtoReturn jsonMsg = new JSONtoReturn();
        String json = PrettyJSONPrinter.prettyPrint(jsonMsg.createJSONError("Error", exp));
        Response r = Response.status(Response.Status.BAD_REQUEST).entity(json).build();
        return r;
    }

}

From source file:eu.cassandra.server.mongo.util.DBConn.java

License:Apache License

private DBConn() {
    try {/*  www.  j  av  a2s.c  om*/
        InitialContext ic = new InitialContext();
        DB_NAME = (String) ic.lookup("java:/comp/env/mongo.db");
        DB_HOST = (String) ic.lookup("java:/comp/env/mongo.host.address");
        m = new Mongo(DB_HOST);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (MongoException e) {
        e.printStackTrace();
    } catch (NamingException e) {
        e.printStackTrace();
    }
    db = m.getDB(DB_NAME);
}