Example usage for com.mongodb BasicDBList get

List of usage examples for com.mongodb BasicDBList get

Introduction

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

Prototype

public Object get(final String key) 

Source Link

Document

Gets a value at an index.

Usage

From source file:eu.cassandra.server.mongo.MongoPersons.java

License:Apache License

public static String getParentId(String id) {
    BasicDBList list = ((BasicDBList) ((DBObject) JSON.parse(new MongoPersons().getPerson(null, id)))
            .get("data"));
    if (list == null || list.isEmpty())
        return null;
    return (String) ((DBObject) list.get(0)).get(REF_INSTALLATION);
}

From source file:eu.cassandra.server.mongo.MongoPersons.java

License:Apache License

private int addToList(String ref_id, BasicDBList list, String filters, String sort, boolean count,
        HttpHeaders httpHeaders) {/*  w  w w. j  a va  2  s  .com*/
    String apps = new MongoDBQueries().getEntity(httpHeaders, COL_PERSONS, "inst_id", ref_id, filters, sort, 0,
            0, "Appliances retrieved successfully", count).toString();
    String countResponse = new MongoDBQueries().getEntity(httpHeaders, COL_PERSONS, "inst_id", ref_id, null,
            null, 0, 0, "Appliances retrieved successfully", true).toString();
    DBObject response = (DBObject) JSON.parse(countResponse);
    BasicDBList alist = (BasicDBList) response.get("data");
    DBObject object = (DBObject) alist.get(0);
    Integer aint = (Integer) object.get("count");

    DBObject jsonResponse = (DBObject) JSON.parse(apps);
    BasicDBList appsInstList = (BasicDBList) jsonResponse.get("data");
    list.addAll(appsInstList);
    return aint.intValue();
}

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

License:Apache License

/**
 * /* w  w w .j  a  v  a  2s .c om*/
 * @param coll
 * @param entityName
 * @return
 */
public DBObject getInternalEntities(HttpHeaders httpHeaders, String coll, String entityName, String parentID) {
    try {
        BasicDBObject query = new BasicDBObject("_id", new ObjectId(parentID));
        BasicDBObject fields = new BasicDBObject(entityName, 1);
        DBObject result = new MongoDBQueries().executeFindQuery(httpHeaders, coll, query, fields,
                "Get " + entityName + " with " + " from " + coll + " with _id=" + parentID);
        @SuppressWarnings("unchecked")
        Vector<DBObject> data = (Vector<DBObject>) result.get("data");
        BasicDBList internalEntities = (BasicDBList) data.get(0).get(entityName);
        Vector<DBObject> recordsVec = new Vector<DBObject>();
        for (int i = 0; i < internalEntities.size(); i++) {
            BasicDBObject entity = (BasicDBObject) internalEntities.get(i);
            recordsVec.add(entity);
        }
        return jSON2Rrn.createJSON(recordsVec,
                "Internal entites " + entityName + " from " + coll + " with _id=" + parentID);
    } catch (Exception e) {
        return jSON2Rrn.createJSONError(
                "Cannot get internal entities " + entityName + " from " + coll + " with _id=" + parentID, e);
    }
}

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

License:Apache License

/**
 * /*from   w w w.  java 2 s.  co m*/
 * @param coll
 * @param entityName
 * @param cid
 * @param successMsg
 * @return
 */
public DBObject getInternalEntity(HttpHeaders httpHeaders, String coll, String entityName, String cid,
        String successMsg) {
    BasicDBObject internalEntity = null;
    try {
        BasicDBObject query = new BasicDBObject(entityName + ".cid", new ObjectId(cid));
        BasicDBObject fields = new BasicDBObject(entityName, 1);
        DBObject result = new MongoDBQueries().executeFindQuery(httpHeaders, coll, query, fields,
                "Get " + entityName + " with cid=" + " from " + coll);
        @SuppressWarnings("unchecked")
        Vector<DBObject> data = (Vector<DBObject>) result.get("data");
        BasicDBList internalEntities = (BasicDBList) data.get(0).get(entityName);
        for (int i = 0; i < internalEntities.size(); i++) {
            BasicDBObject entity = (BasicDBObject) internalEntities.get(i);
            if (cid.equals(entity.get("cid").toString())) {
                internalEntity = entity;
                if (successMsg == null)
                    successMsg = "Internal entity " + entityName + " with cid=" + cid + " from collection="
                            + coll + " successfully retrieved";
                return jSON2Rrn.createJSON(internalEntity, successMsg);
            }
        }
        throw new MongoRefNotFoundException("RefNotFound: Cannot get internal entity " + entityName
                + " with cid=" + cid + " from collection: " + coll);
    } catch (Exception e) {
        return jSON2Rrn.createJSONError("GetInternalEntityError: Cannot get internal entity " + entityName
                + " with cid=" + cid + " from collection: " + coll, e);
    }
}

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

License:Apache License

/**
 * curl -i  --header "dbname:run_id" 'http://localhost:8080/cassandra/api/results?inst_id=instID_&aggr_unit=3&metric=1&from=3&to=100'
 * //from   w w w . j a  v a 2 s  .  c  om
 * @param installationId
 * @param metric
 * @param aggregationUnit
 * @param fromTick
 * @param toTick
 * @return
 */
public DBObject mongoResultQuery(HttpHeaders httpHeaders, String installationId, String metricS,
        String aggregationUnitS, String fromTickS, String toTickS) {
    try {
        String runId = getDbNameFromHTTPHeader(httpHeaders);
        if (runId == null && installationId == null)
            throw new RestQueryParamMissingException(
                    "QueryParamMissing: Both run_id and installation_id are null");

        String aggrUnit = " (Minute)";
        String defaultAggrUnit = " (Minute)";
        Integer aggregationUnit = null;
        Integer defaultAggregationUnit = null;
        if (aggregationUnitS != null) {
            aggregationUnit = Integer.parseInt(aggregationUnitS);
            aggrUnit = " " + aggregationUnit + " Minute" + (aggregationUnit == 1 ? "" : "s") + ")";
        }
        int numberOfDays = Integer.parseInt(
                DBConn.getConn(runId).getCollection("sim_param").findOne().get("numberOfDays").toString());
        if (numberOfDays == 1) {
            defaultAggregationUnit = 5;
            defaultAggrUnit = " (5 Minutes)";
        } else if (numberOfDays <= 5) {
            defaultAggregationUnit = 15;
            defaultAggrUnit = " (15 Minutes)";
        } else if (numberOfDays <= 20) {
            defaultAggregationUnit = 60;
            defaultAggrUnit = " (1 Hour)";
        } else if (numberOfDays <= 60) {
            defaultAggregationUnit = 180;
            defaultAggrUnit = " (3 Hours)";
        } else if (numberOfDays <= 360) {
            defaultAggregationUnit = 720;
            defaultAggrUnit = " (12 Hours)";
        }
        if (aggregationUnit == null) {
            aggregationUnit = defaultAggregationUnit;
            aggrUnit = defaultAggrUnit;
        }

        Integer fromTick = null;
        if (fromTickS != null)
            fromTick = Integer.parseInt(fromTickS);
        Integer toTick = null;
        if (toTickS != null)
            toTick = Integer.parseInt(toTickS);
        String coll = MongoResults.COL_AGGRRESULTS;
        if (aggregationUnit == null || aggregationUnit <= 0)
            aggregationUnit = 1;
        if (installationId != null)
            coll = MongoResults.COL_INSTRESULTS;

        String yMetric = ACTIVE_POWER_P;
        if (metricS != null && metricS.equalsIgnoreCase(REACTIVE_POWER_Q))
            yMetric = REACTIVE_POWER_Q;
        //db.inst_results.find({inst_id:"dszfs123",tick:{$gt:1}}).sort({tick:1}).pretty()
        //db.inst_results.group(
        //   {
        //    keyf:function(doc)
        //      {var key=new NumberInt(doc.tick/4); return {x:key}
        //      } , 
        //    cond:{inst_id:"instID_"}, 
        //    reduce:function(obj,prev)
        //      {prev.csum+=obj.p},
        //    initial:{csum:0}
        //   }
        //)
        BasicDBObject condition = null;
        if (installationId != null || fromTick != null || toTick != null)
            condition = new BasicDBObject();
        if (installationId != null)
            condition.append("inst_id", installationId);

        if (fromTick != null && toTick != null)
            condition.append("tick", BasicDBObjectBuilder.start("$gte", fromTick).add("$lte", toTick).get());
        else if (fromTick != null)
            condition.append("tick", new BasicDBObject("$gte", fromTick));
        else if (toTick != null)
            condition.append("tick", new BasicDBObject("$lte", toTick));

        BasicDBObject groupCmd = new BasicDBObject("ns", coll);
        groupCmd.append("$keyf",
                "function(doc){var key=new NumberInt(doc.tick/" + aggregationUnit + "); return {x:key}}");
        if (condition != null)
            groupCmd.append("cond", condition);
        groupCmd.append("$reduce", "function(obj,prev){prev.y+=obj." + yMetric + "}");
        groupCmd.append("initial", new BasicDBObject("y", 0));

        @SuppressWarnings("deprecation")
        BasicDBList dbList = (BasicDBList) DBConn.getConn(getDbNameFromHTTPHeader(httpHeaders))
                .getCollection(coll).group(groupCmd);

        if (aggregationUnit > 1) {
            for (int i = 0; i < dbList.size(); i++) {
                BasicDBObject obj = (BasicDBObject) dbList.get(i);
                obj.put("y", Double.parseDouble(obj.get("y").toString()) / aggregationUnit);
            }
        }
        return jSON2Rrn.createJSONPlot(dbList, "Data for plot retrieved successfully",
                "Consumption "
                        + (yMetric.equalsIgnoreCase(REACTIVE_POWER_Q) ? "Reactive Power" : "Active Power"),
                "Time" + aggrUnit, yMetric.equalsIgnoreCase(REACTIVE_POWER_Q) ? "VAr" : "W",
                defaultAggregationUnit, numberOfDays);

    } catch (Exception e) {
        e.printStackTrace();
        return jSON2Rrn.createJSONError("Error in retrieving results", e.getMessage());
    }
}

From source file:eu.cassandra.sim.entities.appliances.ConsumptionModel.java

License:Apache License

public void init(DBObject modelObj, String type) throws BadParameterException {

    try {//  w  w  w  . j a v a 2 s. co m

        try {
            outerN = ((Integer) modelObj.get("n")).intValue();
        } catch (ClassCastException e) {
            try {
                outerN = ((Long) modelObj.get("n")).intValue();
            } catch (ClassCastException e1) {
                outerN = ((Double) modelObj.get("n")).intValue();
            }
        } catch (NullPointerException npe) {
            throw new BadParameterException("Bad parameter: outer iterations parameter name should be n");
        }
        BasicDBList patternsObj = (BasicDBList) modelObj.get("params");
        patternN = patternsObj.size();
        patterns = new ArrayList[patternN];
        n = new int[patternN];
        patternDuration = new int[patternN];
        for (int i = 0; i < patternN; i++) {
            try {
                n[i] = ((Integer) ((DBObject) patternsObj.get(i)).get("n")).intValue();
            } catch (ClassCastException e) {
                try {
                    n[i] = ((Long) ((DBObject) patternsObj.get(i)).get("n")).intValue();
                } catch (ClassCastException e1) {
                    n[i] = ((Double) ((DBObject) patternsObj.get(i)).get("n")).intValue();
                }
            } catch (NullPointerException npe) {
                throw new BadParameterException("Bad parameter: inner iterations parameter name should be n");
            }
            BasicDBList values = ((BasicDBList) ((DBObject) patternsObj.get(i)).get("values"));
            int tripplets = values.size();
            patterns[i] = new ArrayList<Tripplet>(tripplets);
            for (int j = 0; j < tripplets; j++) {
                Tripplet t = new Tripplet();
                try {
                    t.v = ((Double) ((DBObject) values.get(j)).get(type)).doubleValue();
                } catch (ClassCastException e) {
                    try {
                        t.v = (double) ((Integer) ((DBObject) values.get(j)).get(type)).intValue();
                    } catch (ClassCastException e1) {
                        t.v = (double) ((Long) ((DBObject) values.get(j)).get(type)).intValue();
                    }
                } catch (NullPointerException npe) {
                    throw new BadParameterException("Bad parameter: power parameter name should be " + type);
                }
                try {
                    t.d = ((Integer) ((DBObject) values.get(j)).get("d")).intValue();
                } catch (ClassCastException e) {
                    try {
                        t.d = ((Double) ((DBObject) values.get(j)).get("d")).intValue();
                    } catch (ClassCastException e1) {
                        t.d = ((Long) ((DBObject) values.get(j)).get("d")).intValue();
                    }
                } catch (NullPointerException npe) {
                    throw new BadParameterException("Bad parameter: duration parameter name should be d");
                }
                patternDuration[i] += t.d;
                totalDuration += (n[i] * t.d);
                try {
                    t.s = ((Double) ((DBObject) values.get(j)).get("s")).doubleValue();
                } catch (ClassCastException e) {
                    try {
                        t.s = (double) ((Integer) ((DBObject) values.get(j)).get("s")).intValue();
                    } catch (ClassCastException e1) {
                        t.s = (double) ((Long) ((DBObject) values.get(j)).get("s")).intValue();
                    }
                } catch (NullPointerException npe) {
                    throw new BadParameterException("Bad parameter: slope parameter name should be s");
                }
                patterns[i].add(t);
            }
        }
    } catch (BadParameterException bpe) {
        throw bpe;
    }

}

From source file:eu.cassandra.sim.math.GUIDistribution.java

License:Apache License

/**
 * //from   w w w.j  ava  2s . co m
 * @param type
 * @param dbo
 * @throws JSONSchemaNotValidException 
 */
public GUIDistribution(String type, DBObject dbo) throws JSONSchemaNotValidException {
    String distrType = dbo.get("distrType").toString();
    BasicDBList tempList = (BasicDBList) dbo.get("parameters");
    if (tempList.size() == 0)
        return;

    DBObject parameters = (DBObject) JSON.parse(tempList.get(0).toString());

    int endValue = 0;
    switch (type) {
    case MongoActivityModels.REF_DISTR_STARTTIME:
        endValue = 1440;
        break;
    case MongoActivityModels.REF_DISTR_DURATION:
        endValue = 180;
        break;
    case MongoActivityModels.REF_DISTR_REPEATS:
        endValue = 10;
        break;
    default:
        throw new JSONSchemaNotValidException("Invalid distr type: " + type);
    }
    switch (distrType) {
    case "Normal Distribution":
        double mean = Double.parseDouble(parameters.get("mean").toString());
        double std = Double.parseDouble(parameters.get("std").toString());
        prob = new Gaussian(mean, std);
        if (type.equalsIgnoreCase("Duration") || type.equalsIgnoreCase("Daily Times"))
            endValue = (int) (mean + 4 * std);
        prob.precompute(endValue);
        break;
    case "Uniform Distribution":
        double start = Double.parseDouble(parameters.get("start").toString());
        double end = Double.parseDouble(parameters.get("end").toString());
        prob = new Uniform(start, end);
        if (type.equalsIgnoreCase("duration")) {
            endValue = (int) end + 10;
        }
        prob.precompute(endValue);
        break;
    case "Gaussian Mixture Models":
        int length = tempList.size();
        double[] w = new double[length];
        double[] means = new double[length];
        double[] stds = new double[length];
        for (int i = 0; i < tempList.size(); i++) {
            DBObject tuple = (DBObject) tempList.get(i);
            w[i] = Double.parseDouble(tuple.get("w").toString());
            means[i] = Double.parseDouble(tuple.get("mean").toString());
            stds[i] = Double.parseDouble(tuple.get("std").toString());
        }
        prob = new GaussianMixtureModels(length, w, means, stds);
        prob.precompute(0, 1439, 1440);
        break;
    case "Histogram":
        double[] values = Utils.dblist2doubleArr((BasicDBList) parameters.get("values"));
        prob = new Histogram(values);
        break;
    default:
        throw new JSONSchemaNotValidException("Invalid distribution2 type: " + distrType);

    }
}

From source file:eu.cassandra.sim.PricingPolicy.java

License:Apache License

public PricingPolicy(DBObject dbo) throws ParseException {
    type = dbo.get("type").toString();
    switch (type) {
    case "TOUPricing":
        billingCycle = Integer.parseInt(dbo.get("billingCycle").toString());
        fixedCharge = Double.parseDouble(dbo.get("fixedCharge").toString());
        // Parse levels
        BasicDBList periodsObj = (BasicDBList) dbo.get("timezones");
        DBObject periodObj;//from w w w . j  a  v  a2s  .c o  m
        periods = new ArrayList<Period>();
        for (int i = 0; i < periodsObj.size(); i++) {
            periodObj = (DBObject) periodsObj.get(i);
            String from = periodObj.get("starttime").toString();
            String to = periodObj.get("endtime").toString();
            double price = Double.parseDouble(periodObj.get("price").toString());
            Period p = new Period(from, to, price);
            periods.add(p);
        }
        break;
    case "ScalarEnergyPricing":
        billingCycle = Integer.parseInt(dbo.get("billingCycle").toString());
        fixedCharge = Double.parseDouble(dbo.get("fixedCharge").toString());
        // Parse levels
        BasicDBList levelsObj = (BasicDBList) dbo.get("levels");
        DBObject levelObj;
        levels = new ArrayList<Level>();
        for (int i = 0; i < levelsObj.size(); i++) {
            levelObj = (DBObject) levelsObj.get(i);
            double price = Double.parseDouble(levelObj.get("price").toString());
            double level = Double.parseDouble(levelObj.get("level").toString());
            Level l = new Level(price, level);
            levels.add(l);
        }
        break;
    case "ScalarEnergyPricingTimeZones":
        billingCycle = Integer.parseInt(dbo.get("billingCycle").toString());
        fixedCharge = Double.parseDouble(dbo.get("fixedCharge").toString());
        offpeakPrice = Double.parseDouble(dbo.get("offpeakPrice").toString());
        // Parse levels
        BasicDBList levelsObj2 = (BasicDBList) dbo.get("levels");
        DBObject levelObj2;
        levels = new ArrayList<Level>();
        for (int i = 0; i < levelsObj2.size(); i++) {
            levelObj2 = (DBObject) levelsObj2.get(i);
            double price = Double.parseDouble(levelObj2.get("price").toString());
            double level = Double.parseDouble(levelObj2.get("level").toString());
            Level l = new Level(price, level);
            levels.add(l);
        }
        // Parse timezones
        BasicDBList tzs = (BasicDBList) dbo.get("offpeak");
        DBObject tz;
        offpeaks = new ArrayList<Offpeak>();
        for (int i = 0; i < levelsObj2.size(); i++) {
            levelObj2 = (DBObject) levelsObj2.get(i);
            String from = levelObj2.get("from").toString();
            String to = levelObj2.get("to").toString();
            Offpeak o = new Offpeak(from, to);
            offpeaks.add(o);
        }
        break;
    case "EnergyPowerPricing":
        billingCycle = Integer.parseInt(dbo.get("billingCycle").toString());
        fixedCharge = Double.parseDouble(dbo.get("fixedCharge").toString());
        contractedCapacity = Integer.parseInt(dbo.get("contractedCapacity").toString());
        energyPricing = Double.parseDouble(dbo.get("energyPrice").toString());
        powerPricing = Double.parseDouble(dbo.get("powerPrice").toString());
        break;
    case "AllInclusivePricing":
        billingCycle = Integer.parseInt(dbo.get("billingCycle").toString());
        fixedCharge = Double.parseDouble(dbo.get("fixedCharge").toString());
        fixedCost = Integer.parseInt(dbo.get("fixedCost").toString());
        additionalCost = Double.parseDouble(dbo.get("additionalCost").toString());
        contractedEnergy = Double.parseDouble(dbo.get("contractedEnergy").toString());
    default:
        break;
    }
}

From source file:eu.cassandra.sim.Simulation.java

License:Apache License

public void staticSetup(DBObject jsonScenario) throws Exception {
    int numOfInstallations = ((Integer) jsonScenario.get("instcount")).intValue();
    queue = new PriorityBlockingQueue<Event>(2 * numOfInstallations);
    for (int i = 1; i <= numOfInstallations; i++) {
        DBObject instDoc = (DBObject) jsonScenario.get("inst" + i);
        String id = ((ObjectId) instDoc.get("_id")).toString();
        String name = (String) instDoc.get("name");
        String description = (String) instDoc.get("description");
        String type = (String) instDoc.get("type");
        Installation inst = new Installation.Builder(id, name, description, type).build();
        // Thermal module if exists
        DBObject thermalDoc = (DBObject) instDoc.get("thermal");
        if (thermalDoc != null && pricing.getType().equalsIgnoreCase("TOUPricing")) {
            ThermalModule tm = new ThermalModule(thermalDoc, pricing.getTOUArray());
            inst.setThermalModule(tm);// w w  w . j a va 2 s  . c o  m
        }

        int appcount = ((Integer) instDoc.get("appcount")).intValue();
        // Create the appliances
        HashMap<String, Appliance> existing = new HashMap<String, Appliance>();
        for (int j = 1; j <= appcount; j++) {
            DBObject applianceDoc = (DBObject) instDoc.get("app" + j);
            String appid = ((ObjectId) applianceDoc.get("_id")).toString();
            String appname = (String) applianceDoc.get("name");
            String appdescription = (String) applianceDoc.get("description");
            String apptype = (String) applianceDoc.get("type");
            double standy = Utils.getDouble(applianceDoc.get("standy_consumption"));
            boolean base = Utils.getBoolean(applianceDoc.get("base"));
            DBObject consModDoc = (DBObject) applianceDoc.get("consmod");
            ConsumptionModel pconsmod = new ConsumptionModel(consModDoc.get("pmodel").toString(), "p");
            ConsumptionModel qconsmod = new ConsumptionModel(consModDoc.get("qmodel").toString(), "q");
            Appliance app = new Appliance.Builder(appid, appname, appdescription, apptype, inst, pconsmod,
                    qconsmod, standy, base).build();
            existing.put(appid, app);
            inst.addAppliance(app);
        }
        DBObject personDoc = (DBObject) instDoc.get("person1");
        String personid = ((ObjectId) personDoc.get("_id")).toString();
        String personName = (String) personDoc.get("name");
        String personDescription = (String) personDoc.get("description");
        String personType = (String) personDoc.get("type");
        double awareness = Utils.getDouble(personDoc.get("awareness"));
        double sensitivity = Utils.getDouble(personDoc.get("sensitivity"));
        Person person = new Person.Builder(personid, personName, personDescription, personType, inst, awareness,
                sensitivity).build();
        inst.addPerson(person);
        int actcount = ((Integer) personDoc.get("activitycount")).intValue();
        for (int j = 1; j <= actcount; j++) {
            DBObject activityDoc = (DBObject) personDoc.get("activity" + j);
            String activityName = (String) activityDoc.get("name");
            String activityType = (String) activityDoc.get("type");
            int actmodcount = ((Integer) activityDoc.get("actmodcount")).intValue();
            Activity act = new Activity.Builder(activityName, "", activityType, simulationWorld).build();
            ProbabilityDistribution startDist;
            ProbabilityDistribution durDist;
            ProbabilityDistribution timesDist;
            for (int k = 1; k <= actmodcount; k++) {
                DBObject actmodDoc = (DBObject) activityDoc.get("actmod" + k);
                String actmodName = (String) actmodDoc.get("name");
                String actmodType = (String) actmodDoc.get("type");
                String actmodDayType = (String) actmodDoc.get("day_type");
                boolean shiftable = Utils.getBoolean(actmodDoc.get("shiftable"));
                DBObject duration = (DBObject) actmodDoc.get("duration");
                durDist = json2dist(duration);
                DBObject start = (DBObject) actmodDoc.get("start");
                startDist = json2dist(start);
                DBObject rep = (DBObject) actmodDoc.get("repetitions");
                timesDist = json2dist(rep);
                act.addDuration(actmodDayType, durDist);
                act.addStartTime(actmodDayType, startDist);
                act.addTimes(actmodDayType, timesDist);
                act.addShiftable(actmodDayType, shiftable);
                // add appliances
                BasicDBList containsAppliances = (BasicDBList) actmodDoc.get("containsAppliances");
                for (int l = 0; l < containsAppliances.size(); l++) {
                    String containAppId = (String) containsAppliances.get(l);
                    Appliance app = existing.get(containAppId);
                    act.addAppliance(actmodDayType, app, 1.0 / containsAppliances.size());
                }
            }
            person.addActivity(act);
        }
        installations.add(inst);
    }
}

From source file:eu.cassandra.sim.Simulation.java

License:Apache License

public void dynamicSetup(DBObject jsonScenario, boolean jump) throws Exception {
    DBObject scenario = (DBObject) jsonScenario.get("scenario");
    String scenario_id = ((ObjectId) scenario.get("_id")).toString();
    DBObject demog = (DBObject) jsonScenario.get("demog");
    BasicDBList generators = (BasicDBList) demog.get("generators");
    // Initialize simulation variables
    int numOfInstallations = Utils.getInt(demog.get("numberOfEntities"));
    //System.out.println(numOfInstallations+"");
    queue = new PriorityBlockingQueue<Event>(2 * numOfInstallations);
    for (int i = 1; i <= numOfInstallations; i++) {
        DBObject instDoc = (DBObject) jsonScenario.get("inst" + 1);
        String id = i + "";
        String name = ((String) instDoc.get("name")) + i;
        String description = (String) instDoc.get("description");
        String type = (String) instDoc.get("type");
        Installation inst = new Installation.Builder(id, name, description, type).build();
        inst.setParentId(scenario_id);//w  w  w  .j  av a  2  s  .  c o m
        String inst_id = addEntity(inst, jump);
        inst.setId(inst_id);
        int appcount = Utils.getInt(instDoc.get("appcount"));
        // Create the appliances
        HashMap<String, Appliance> existing = new HashMap<String, Appliance>();
        for (int j = 1; j <= appcount; j++) {
            DBObject applianceDoc = (DBObject) instDoc.get("app" + j);
            String appid = ((ObjectId) applianceDoc.get("_id")).toString();
            String appname = (String) applianceDoc.get("name");
            String appdescription = (String) applianceDoc.get("description");
            String apptype = (String) applianceDoc.get("type");
            double standy = Utils.getDouble(applianceDoc.get("standy_consumption"));
            boolean base = Utils.getBoolean(applianceDoc.get("base"));
            DBObject consModDoc = (DBObject) applianceDoc.get("consmod");
            ConsumptionModel pconsmod = new ConsumptionModel(consModDoc.get("pmodel").toString(), "p");
            ConsumptionModel qconsmod = new ConsumptionModel(consModDoc.get("qmodel").toString(), "q");
            Appliance app = new Appliance.Builder(appid, appname, appdescription, apptype, inst, pconsmod,
                    qconsmod, standy, base).build();
            existing.put(appid, app);
        }

        HashMap<String, Double> gens = new HashMap<String, Double>();
        for (int k = 0; k < generators.size(); k++) {
            DBObject generator = (DBObject) generators.get(k);
            String entityId = (String) generator.get("entity_id");
            double prob = Utils.getDouble(generator.get("probability"));
            gens.put(entityId, new Double(prob));
        }

        Set<String> keys = existing.keySet();
        for (String key : keys) {
            Double prob = gens.get(key);
            if (prob != null) {
                double probValue = prob.doubleValue();
                if (RNG.nextDouble() < probValue) {
                    Appliance selectedApp = existing.get(key);
                    selectedApp.setParentId(inst.getId());
                    String app_id = addEntity(selectedApp, jump);
                    selectedApp.setId(app_id);
                    inst.addAppliance(selectedApp);
                    ConsumptionModel cm = selectedApp.getPConsumptionModel();
                    cm.setParentId(app_id);
                    String cm_id = addEntity(cm, jump);
                    cm.setId(cm_id);
                }
            }
        }

        int personcount = Utils.getInt(instDoc.get("personcount"));
        // Create the appliances
        HashMap<String, Person> existingPersons = new HashMap<String, Person>();
        for (int j = 1; j <= personcount; j++) {
            DBObject personDoc = (DBObject) instDoc.get("person" + j);
            String personid = ((ObjectId) personDoc.get("_id")).toString();
            String personName = (String) personDoc.get("name");
            String personDescription = (String) personDoc.get("description");
            String personType = (String) personDoc.get("type");
            double awareness = Utils.getDouble(personDoc.get("awareness"));
            double sensitivity = Utils.getDouble(personDoc.get("sensitivity"));
            Person person = new Person.Builder(personid, personName, personDescription, personType, inst,
                    awareness, sensitivity).build();
            int actcount = Utils.getInt(personDoc.get("activitycount"));
            //System.out.println("Act-Count: " + actcount);
            for (int k = 1; k <= actcount; k++) {
                DBObject activityDoc = (DBObject) personDoc.get("activity" + k);
                String activityName = (String) activityDoc.get("name");
                String activityType = (String) activityDoc.get("type");
                int actmodcount = Utils.getInt(activityDoc.get("actmodcount"));
                Activity act = new Activity.Builder(activityName, "", activityType, simulationWorld).build();
                ProbabilityDistribution startDist;
                ProbabilityDistribution durDist;
                ProbabilityDistribution timesDist;
                for (int l = 1; l <= actmodcount; l++) {
                    DBObject actmodDoc = (DBObject) activityDoc.get("actmod" + l);
                    act.addModels(actmodDoc);
                    String actmodName = (String) actmodDoc.get("name");
                    String actmodType = (String) actmodDoc.get("type");
                    String actmodDayType = (String) actmodDoc.get("day_type");
                    boolean shiftable = Utils.getBoolean(actmodDoc.get("shiftable"));
                    DBObject duration = (DBObject) actmodDoc.get("duration");
                    act.addDurations(duration);
                    durDist = json2dist(duration);
                    //System.out.println(durDist.getPrecomputedBin());
                    DBObject start = (DBObject) actmodDoc.get("start");
                    act.addStarts(start);
                    startDist = json2dist(start);
                    //System.out.println(startDist.getPrecomputedBin());
                    DBObject rep = (DBObject) actmodDoc.get("repetitions");
                    act.addTimes(rep);
                    timesDist = json2dist(rep);
                    //System.out.println(timesDist.getPrecomputedBin());
                    act.addDuration(actmodDayType, durDist);
                    act.addStartTime(actmodDayType, startDist);
                    act.addTimes(actmodDayType, timesDist);
                    act.addShiftable(actmodDayType, shiftable);
                    // add appliances
                    BasicDBList containsAppliances = (BasicDBList) actmodDoc.get("containsAppliances");
                    for (int m = 0; m < containsAppliances.size(); m++) {
                        String containAppId = (String) containsAppliances.get(m);
                        Appliance app = existing.get(containAppId);
                        //act.addAppliance(actmodDayType,app,1.0/containsAppliances.size());
                        act.addAppliance(actmodDayType, app, 1.0);
                    }
                }
                person.addActivity(act);
            }
            existingPersons.put(personid, person);
        }

        double roulette = RNG.nextDouble();
        double sum = 0;
        for (int k = 0; k < generators.size(); k++) {
            DBObject generator = (DBObject) generators.get(k);
            String entityId = (String) generator.get("entity_id");
            if (existingPersons.containsKey(entityId)) {
                double prob = Utils.getDouble(generator.get("probability"));
                sum += prob;
                if (roulette < sum) {
                    Person selectedPerson = existingPersons.get(entityId);
                    selectedPerson.setParentId(inst.getId());
                    String person_id = addEntity(selectedPerson, jump);
                    selectedPerson.setId(person_id);
                    inst.addPerson(selectedPerson);
                    Vector<Activity> activities = selectedPerson.getActivities();
                    for (Activity a : activities) {
                        a.setParentId(person_id);
                        String act_id = addEntity(a, jump);
                        a.setId(act_id);
                        Vector<DBObject> models = a.getModels();
                        Vector<DBObject> starts = a.getStarts();
                        Vector<DBObject> durations = a.getDurations();
                        Vector<DBObject> times = a.getTimes();
                        for (int l = 0; l < models.size(); l++) {
                            DBObject m = models.get(l);
                            m.put("act_id", act_id);
                            if (!jump)
                                DBConn.getConn(dbname).getCollection(MongoActivityModels.COL_ACTMODELS)
                                        .insert(m);
                            ObjectId objId = (ObjectId) m.get("_id");
                            String actmod_id = objId.toString();
                            DBObject s = starts.get(l);
                            s.put("actmod_id", actmod_id);
                            if (!jump)
                                DBConn.getConn(dbname).getCollection(MongoDistributions.COL_DISTRIBUTIONS)
                                        .insert(s);
                            DBObject d = durations.get(l);
                            d.put("actmod_id", actmod_id);
                            if (!jump)
                                DBConn.getConn(dbname).getCollection(MongoActivityModels.COL_ACTMODELS)
                                        .insert(d);
                            DBObject t = times.get(l);
                            t.put("actmod_id", actmod_id);
                            if (!jump)
                                DBConn.getConn(dbname).getCollection(MongoActivityModels.COL_ACTMODELS)
                                        .insert(t);
                        }
                    }
                    break;
                }
            }
        }

        installations.add(inst);
    }

}