Example usage for com.mongodb.util JSON parse

List of usage examples for com.mongodb.util JSON parse

Introduction

In this page you can find the example usage for com.mongodb.util JSON parse.

Prototype

public static Object parse(final String jsonString) 

Source Link

Document

Parses a JSON string and returns a corresponding Java object.

Usage

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

License:Apache License

/**
 * /*from  w  ww  . j av  a 2  s.  c o m*/
 * @param httpHeaders
 * @param dbName
 * @param coll
 * @param qKey
 * @param qValue
 * @param filters
 * @param sort
 * @param limit
 * @param skip
 * @param successMsg
 * @param count
 * @param fieldNames
 * @return
 */
public DBObject getEntity(HttpHeaders httpHeaders, String dbName, String coll, String qKey, String qValue,
        String filters, String sort, int limit, int skip, String successMsg, boolean count,
        String... fieldNames) {
    DBObject query;
    BasicDBObject fields = null;
    try {
        query = new BasicDBObject();
        if (qKey != null && qValue != null && (qKey.equalsIgnoreCase("_id") || qKey.endsWith(".cid"))) {
            query.put(qKey, new ObjectId(qValue));
        } else if (qKey != null && qValue != null) {
            try {
                if (filters != null) {
                    System.out.println(PrettyJSONPrinter.prettyPrint(filters));
                    query = (DBObject) JSON.parse(filters);
                } else
                    query = new BasicDBObject();
            } catch (Exception e) {
                return jSON2Rrn.createJSONError(
                        "Cannot get entity for collection: " + coll + ", error in filters: " + filters, e);
            }
            query.put(qKey, qValue);
        }
        if (fieldNames != null) {
            fields = new BasicDBObject();
            for (String fieldName : fieldNames) {
                fields.put(fieldName, 1);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return jSON2Rrn.createJSONError(
                "Cannot get entity for collection: " + coll + " with qKey=" + qKey + " and qValue=" + qValue,
                e);
    }
    return new MongoDBQueries().executeFindQuery(httpHeaders, dbName, coll, query, fields, successMsg, sort,
            limit, skip, count);
}

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

License:Apache License

/**
 * /*from   w ww .  j a  v  a2  s.  c om*/
 * @param httpHeaders
 * @param collection
 * @param dbObj1
 * @param dbObj2
 * @param successMsg
 * @param sort
 * @param limit
 * @param skip
 * @param count
 * @return
 */
public DBObject executeFindQuery(HttpHeaders httpHeaders, String dbName, String collection, DBObject dbObj1,
        DBObject dbObj2, String successMsg, String sort, int limit, int skip, boolean count) {
    try {
        if (dbName == null)
            dbName = getDbNameFromHTTPHeader(httpHeaders);
        DBCursor cursorDoc = null;
        if (count) {
            BasicDBObject dbObject = new BasicDBObject();
            dbObject.put("count", DBConn.getConn(dbName).getCollection(collection).find(dbObj1).count());
            return jSON2Rrn.createJSON(dbObject, successMsg);
        } else {
            if (dbObj2 == null) {
                cursorDoc = DBConn.getConn(dbName).getCollection(collection).find(dbObj1);
            } else {
                cursorDoc = DBConn.getConn(dbName).getCollection(collection).find(dbObj1, dbObj2);
            }
        }
        if (sort != null) {
            try {
                DBObject sortObj = (DBObject) JSON.parse(sort);
                cursorDoc = cursorDoc.sort(sortObj);
            } catch (Exception e) {
                return jSON2Rrn.createJSONError("Error in filtering JSON sorting object: " + sort, e);
            }
        }
        if (skip != 0)
            cursorDoc = cursorDoc.skip(skip);
        if (limit != 0)
            cursorDoc = cursorDoc.limit(limit);

        Vector<DBObject> recordsVec = new Vector<DBObject>();
        while (cursorDoc.hasNext()) {
            DBObject obj = cursorDoc.next();

            if (collection.equalsIgnoreCase(MongoDistributions.COL_DISTRIBUTIONS)
                    && dbObj1.containsField("_id")) {
                obj = getValues(obj, httpHeaders, dbName, obj.get("_id").toString(),
                        MongoDistributions.COL_DISTRIBUTIONS);
            } else if (collection.equalsIgnoreCase(MongoConsumptionModels.COL_CONSMODELS)
                    && dbObj1.containsField("_id")) {
                obj = getValues(obj, httpHeaders, dbName, obj.get("_id").toString(),
                        MongoConsumptionModels.COL_CONSMODELS);
            } else if (collection.equalsIgnoreCase(MongoPricingPolicy.COL_PRICING)) {
                PricingPolicy pp = new PricingPolicy(obj);
                double oneKw24Cost = pp.calcOneKw24();
                obj.put("onekw24", oneKw24Cost);
            }

            if (obj.containsField("_id"))
                obj = addChildrenCounts(httpHeaders, collection, obj);
            recordsVec.add(obj);
        }
        cursorDoc.close();
        return jSON2Rrn.createJSON(recordsVec, successMsg);
    } catch (Exception e) {
        e.printStackTrace();
        return jSON2Rrn.createJSONError("MongoQueryError: Cannot execute find query for collection: "
                + collection + " with qKey=" + dbObj1 + " and qValue=" + dbObj2, e);
    }
}

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

License:Apache License

/**
 * /*from w  w  w . ja  va2 s .c om*/
 * @param qKey
 * @param qValue
 * @param jsonToUpdate
 * @param collection
 * @param successMsg
 * @param refColl
 * @param refKeyName
 * @param intDocKey
 * @return
 */
public DBObject updateDocument(String qKey, String qValue, String jsonToUpdate, String collection,
        String successMsg, String refColl, String refKeyName, String intDocKey, int schemaType) {
    Vector<String> keysUpdated = new Vector<String>();
    try {
        DBObject dbObject = (DBObject) JSON.parse(jsonToUpdate);
        if (dbObject.containsField("_id")) {
            dbObject.removeField("_id");
            jsonToUpdate = dbObject.toString();
        }
        new JSONValidator().isValid(jsonToUpdate, schemaType, true);
        if (intDocKey != null && refKeyName != null && dbObject.containsField(refKeyName)) {
            ensureThatRefKeysMatch(dbObject, collection, refKeyName, intDocKey, qValue);
        } else if ((refColl != null || refKeyName != null) && dbObject.get(refKeyName) != null) {
            ensureThatRefKeyExists(dbObject, refColl, refKeyName, false);
        }
        for (String key : dbObject.keySet()) {
            if (!key.equalsIgnoreCase("id")) {
                keysUpdated.add(key);
                BasicDBObject keyToUpdate;
                if (qKey.equalsIgnoreCase("_id") || qKey.endsWith(".cid")) {
                    keyToUpdate = new BasicDBObject().append(qKey, new ObjectId(qValue));
                } else {
                    keyToUpdate = new BasicDBObject().append(qKey, qValue);
                }
                String keyName = key;
                if (intDocKey != null)
                    keyName = intDocKey + "." + key;
                DBConn.getConn().getCollection(collection).update(keyToUpdate,
                        new BasicDBObject().append("$set", new BasicDBObject(keyName, dbObject.get(key))));
            }
        }
    } catch (Exception e) {
        return jSON2Rrn.createJSONError("Update Failed for " + jsonToUpdate, e);
    }
    return getEntity(null, collection, qKey, qValue, successMsg, false,
            keysUpdated.toArray(new String[keysUpdated.size()]));
}

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

License:Apache License

/**
 * /* www.java  2 s. c o m*/
 * db.installations.update({"appliances.cid":ObjectId("4ff16606e4b0f2b1e00c4d49")},{    $set :  {"appliances.$.description":"ff"}     })
 * 
 * @param coll
 * @param refColl
 * @param cid
 * @param jsonToUpdate
 * @param successMsg
 * @return
 */
public DBObject updateArrayDocument(String coll, String entityName, String cid, String refColl,
        String refKeyName, String jsonToUpdate) {
    Vector<String> keysUpdated = new Vector<String>();
    try {
        DBObject dbObject = (DBObject) JSON.parse(jsonToUpdate);

        if ((refColl != null || refKeyName != null) && dbObject.get(refKeyName) != null) {
            ensureThatRefKeyExists(dbObject, refColl, refKeyName, false);
        }
        DBObject q = new BasicDBObject(entityName + ".cid", new ObjectId(cid));

        for (String key : dbObject.keySet()) {
            if (!key.equalsIgnoreCase("cid")) {
                keysUpdated.add(key);
                DBObject o = new BasicDBObject("$set",
                        new BasicDBObject(entityName + ".$." + key, dbObject.get(key)));
                DBConn.getConn().getCollection(coll).update(q, o);
            }
        }
    } catch (Exception e) {
        return jSON2Rrn.createJSONError("Update Failed for " + jsonToUpdate, e);
    }
    return getInternalEntity(null, coll, entityName, cid, "Internal document " + coll + "." + entityName
            + " with cid=" + cid + " was successfullylly updated");
}

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

License:Apache License

/**
 * /*from www.ja  va  2s .c  om*/
 * @param coll
 * @param qField
 * @param parentKeyFieldName
 * @param updateFieldName
 * @param newData
 * @return
 */
public DBObject updateInternalDocumentDump(String coll, String qField, String parentKeyFieldName,
        String updateFieldName, String newData) {
    DBObject newObject = (DBObject) JSON.parse(newData);
    String parentID = newObject.get(parentKeyFieldName).toString();
    DBObject q = new BasicDBObject(qField, new ObjectId(parentID));
    DBObject o = new BasicDBObject("$set", new BasicDBObject(updateFieldName, newObject));
    DBConn.getConn().getCollection(coll).update(q, o, false, true);
    return new BasicDBObject("a", "b");
}

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

License:Apache License

/**
 * //from  w  w  w . j  a  v  a  2 s . c  o m
 * @param coll
 * @param dataToInsert
 * @param successMessage
 * @param refColl
 * @param refKeyName
 * @param canBeNull
 * @param schemaType
 * @param httpHeaders
 * @return
 */
public DBObject insertData(String coll, String dataToInsert, String successMessage, String[] refColl,
        String[] refKeyName, boolean[] canBeNull, int schemaType, HttpHeaders httpHeaders) {
    DBObject data;
    try {
        data = (DBObject) JSON.parse(dataToInsert);
        if (data.containsField("_id")) {
            data.removeField("_id");
            dataToInsert = data.toString();
        }
        new JSONValidator().isValid(dataToInsert, schemaType);
        if (refColl != null && refKeyName != null) {
            for (int i = 0; i < refColl.length; i++) {
                ensureThatRefKeyExists(data, refColl[i], refKeyName[i], canBeNull[i]);
            }
        }
        if (httpHeaders == null)
            DBConn.getConn().getCollection(coll).insert(data);
        else
            DBConn.getConn(MongoDBQueries.getDbNameFromHTTPHeader(httpHeaders)).getCollection(coll)
                    .insert(data);
    } catch (com.mongodb.util.JSONParseException e) {
        return jSON2Rrn.createJSONError("Error parsing JSON input", e.getMessage());
    } catch (Exception e) {
        return jSON2Rrn.createJSONError(dataToInsert, e);
    }
    return jSON2Rrn.createJSONInsertPostMessage(successMessage, data);
}

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

License:Apache License

public ConsumptionModel(String amodel, String type) throws BadParameterException {
    model = amodel;
    DBObject modelObj = (DBObject) JSON.parse(model);
    init(modelObj, type);
}

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

License:Apache License

public static void main(String[] args) throws IOException, BadParameterException {

    String s = Utils.readFile("laptopcm.json");
    DBObject dbo = (DBObject) JSON.parse(s);
    System.out.println(dbo.toString());

    GUIConsumptionModel tester = new GUIConsumptionModel(dbo, "p");
    System.out.println(Arrays.toString(tester.getValues(P)));
    // Utils.createHistogram("Test", "Power", "Power", tester.getValues());

}

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

License:Apache License

/**
 * /*from  w  w w . j a va  2s . c o 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.Simulation.java

License:Apache License

public void setup(boolean jump) throws Exception {
    installations = new Vector<Installation>();
    /* TODO  Change the Simulation Calendar initialization */
    logger.info("Simulation setup started: " + dbname);
    DBObject jsonScenario = (DBObject) JSON.parse(scenario);
    DBObject scenarioDoc = (DBObject) jsonScenario.get("scenario");
    DBObject simParamsDoc = (DBObject) jsonScenario.get("sim_params");
    simulationWorld = new SimulationParams(simParamsDoc);
    DBObject pricingDoc = (DBObject) jsonScenario.get("pricing");
    DBObject basePricingDoc = (DBObject) jsonScenario.get("baseline_pricing");
    if (pricingDoc != null) {
        pricing = new PricingPolicy(pricingDoc);
    } else {/*www .j  a v a2s.c o  m*/
        pricing = new PricingPolicy();
    }
    if (basePricingDoc != null) {
        baseline_pricing = new PricingPolicy(basePricingDoc);
    } else {
        baseline_pricing = new PricingPolicy();
    }
    int numOfDays = ((Integer) simParamsDoc.get("numberOfDays")).intValue();

    endTick = Constants.MIN_IN_DAY * numOfDays;
    mcruns = ((Integer) simParamsDoc.get("mcruns")).intValue();
    co2 = Utils.getDouble(simParamsDoc.get("co2"));
    // Check type of setup
    String setup = (String) scenarioDoc.get("setup");
    if (setup.equalsIgnoreCase("static")) {
        staticSetup(jsonScenario);
    } else if (setup.equalsIgnoreCase("dynamic")) {
        dynamicSetup(jsonScenario, jump);
    } else {
        throw new Exception("Problem with setup property!!!");
    }
    logger.info("Simulation setup finished: " + dbname);
}