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:models.OntoProcessor.java

License:Open Source License

protected void saveGraph() {
    DBCollection graphColl = db.getCollection("graph");
    graphColl.drop();//  w  w  w  . j a va  2s.  c  om

    for (SourceRelation sourceRelation : ontology.getSourceRelations().values()) {
        String sourceId = sourceRelation.getSource().getId();
        String destinationId = sourceRelation.getDestination().getId();
        HashMap<String, Object> link = new HashMap<>();
        link.put("id", sourceRelation.getId());
        link.put("source", processGroupsId.indexOf(sourceId));
        link.put("target", processGroupsId.indexOf(destinationId));
        if (sourceRelation.getType() != null)
            link.put("type", sourceRelation.getType().getId());
        else
            link.put("type", "#none");
        links.add(link);
    }

    BasicDBObject dbObject = (BasicDBObject) JSON
            .parse("{nodes:" + toJson(nodes).toString() + ",links:" + toJson(links).toString() + "}");
    graphColl.insert(dbObject);
}

From source file:models.OntoProcessor.java

License:Open Source License

protected void saveDerivedGraph() {
    DBCollection derivedGraphColl = db.getCollection("derivedGraph");
    derivedGraphColl.drop();//  w w  w.  ja v a  2  s .  co  m

    for (DerivedRelation relation : ontology.getDerivedRelations()) {
        String sourceId = relation.getSource().getId();
        String destinationId = relation.getDestination().getId();
        HashMap<String, Object> link = new HashMap<>();
        link.put("source", processesId.indexOf(sourceId));
        link.put("target", processesId.indexOf(destinationId));
        if (relation.getType() != null)
            link.put("type", relation.getType().getId());
        else
            link.put("type", "#none");
        derivedLinks.add(link);
    }

    BasicDBObject dbObject = (BasicDBObject) JSON.parse(
            "{nodes:" + toJson(derivedNodes).toString() + ",links:" + toJson(derivedLinks).toString() + "}");
    derivedGraphColl.insert(dbObject);
}

From source file:models.OntoProcessor.java

License:Open Source License

protected void saveStats() throws JsonProcessingException {
    DBCollection statsColl = db.getCollection("ontologyStats");
    statsColl.drop();/*from w ww  .  j  a  v  a 2s  .co m*/

    HashMap<String, Integer> stats = new HashMap<>();
    stats.put("coefficientGroups", ontology.getCoefficientGroups().size());
    stats.put("processGroups", ontology.getProcessGroups().size());
    stats.put("coefficients", ontology.getCoefficients().size());
    stats.put("processes", ontology.getProcesses().size());
    Integer numberOfInputElementaryFlow = 0;
    Integer numberOfCalculatedElementaryFlow = 0;
    Integer numberOfImpact = 0;
    for (Process process : ontology.getProcesses()) {
        numberOfInputElementaryFlow += process.getInputFlows().size();
        numberOfCalculatedElementaryFlow += process.getCalculatedFlows().size();
        numberOfImpact += process.getImpacts().size();
    }
    stats.put("inputFlows", numberOfInputElementaryFlow);
    stats.put("calculatedFlows", numberOfCalculatedElementaryFlow);
    stats.put("impacts", numberOfImpact);
    stats.put("sourceRelations", ontology.getSourceRelations().size());
    stats.put("derivedRelations", ontology.getDerivedRelations().size());
    stats.put("references", ontology.getReferences().size());

    BasicDBObject dbObject = (BasicDBObject) JSON.parse(mapper.writeValueAsString(stats));
    statsColl.insert(dbObject);
}

From source file:mongodb.MongoDBOperations.java

License:Apache License

public static void main(String[] args) {
    if (args.length != 4) {
        System.out.println(/*from w  w  w.java 2s. c o  m*/
                "FindAndUpdate:\nargs[0]: Configuration File.\nargs[1]: DB Name.\nargs[2]: Collection Name.\nargs[3]: Query in JSON format.");
        System.out.println("Please check the parameters.");
        return;
    }
    String ConfigPath = args[0];
    String DBName = args[1];
    String CollectionName = args[2];
    String QueryFile = args[3];
    MongoDBOperations mdbops;

    try {
        mdbops = new MongoDBOperations(ConfigPath);

        mdbops.listDB();
        DBCollection coll = mdbops.getCollection(DBName, CollectionName);
        String queryString = mdbops.readFile(QueryFile);
        System.out.println(queryString);
        BasicDBObject queryObject = (BasicDBObject) JSON.parse(queryString);
        mdbops.geoFindAndUpdate(coll, queryObject);
        //mdbops.printQueryResult(coll, queryObject);

    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:mongodb.performance.MongoDBPerformance.java

/**
 * @param args the command line arguments
 *///from w  w  w  .j  a v  a 2s.  c om
public static void main(String[] args) throws UnknownHostException, FileNotFoundException, IOException {
    if (args.length == 0) {
        System.out.println("Parmetro no informado!");
        System.exit(-1);
    }
    System.out.println("Parmetro: " + args[0]);

    MongoClient mongoClient = new MongoClient();
    //MongoClient mongoClient = new MongoClient( "54.172.218.64" , 27017 );
    DB db = mongoClient.getDB("myDatabase");

    DBCollection collection = db.getCollection("ads");
    collection.drop();

    BulkWriteOperation builder = collection.initializeUnorderedBulkOperation();

    FileInputStream fileInputStream = new FileInputStream(".\\resources\\MongoDB" + args[0] + ".txt");
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
    // Insert
    // Time start    
    long start = System.currentTimeMillis();

    String line;
    while ((line = bufferedReader.readLine()) != null) {
        DBObject bson = (DBObject) JSON.parse(line);
        builder.insert(bson);
    }
    bufferedReader.close();
    builder.execute();
    //Time end
    long elapsed = System.currentTimeMillis() - start;
    System.out.println("[insert] Time elapsed: " + elapsed + " ms");

    // Update
    // Time start    
    start = System.currentTimeMillis();
    collection.updateMulti(new BasicDBObject(),
            new BasicDBObject("$set", new BasicDBObject().append("ano", 2006)));
    // Time end
    elapsed = System.currentTimeMillis() - start;
    System.out.println("[update] Time elapsed: " + elapsed + " ms");

    // Select
    // Time start    
    start = System.currentTimeMillis();
    BasicDBObject keys = new BasicDBObject();
    keys.put("_id", 1);
    keys.put("modeloCarro.marca", 1);
    keys.put("modeloCarro.nome", 1);
    keys.put("uf", 1);
    keys.put("placa_carro", 1);
    keys.put("qtd_portas", 1);
    keys.put("cambio", 1);
    keys.put("combustivel", 1);
    keys.put("cor", 1);
    keys.put("km", 1);
    keys.put("valor", 1);
    keys.put("detalhe", 1);
    BasicDBObject sort = new BasicDBObject("_id", 1);

    DBCursor cursor = collection.find(new BasicDBObject(), keys).sort(sort);
    while (cursor.hasNext()) {
        cursor.next();
    }
    // Time end
    elapsed = System.currentTimeMillis() - start;
    System.out.println("[select] Time elapsed: " + elapsed + " ms");

    // Delete
    // Time start    
    start = System.currentTimeMillis();
    collection.remove(new BasicDBObject());
    // Time end
    elapsed = System.currentTimeMillis() - start;
    System.out.println("[delete] Time elapsed: " + elapsed + " ms");
}

From source file:mongodbutils.MongodbConnection.java

public boolean insertJSON(String dbName, String collectionName, String json) {
    try {//from  w  ww  .  ja v  a  2 s .  co  m
        //System.out.println("mongo start insert");

        if (mongoClient == null) {
            //System.out.println("client is null");
        }

        db = mongoClient.getDB(dbName);

        //System.out.println("mongo get collection");
        DBCollection coll = db.getCollection(collectionName);

        //System.out.println("parse json");
        DBObject dbObject = (DBObject) JSON.parse(json);

        //System.out.println("insert data");
        //coll.insert(dbObject,WriteConcern.JOURNALED);
        coll.insert(dbObject, WriteConcern.NORMAL);

        return true;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }

}

From source file:mongosensors_server.MapReduce.java

License:Open Source License

public String[] getAverageValue(String sensorType, String tags, String id, double range) {
    //AVERAGE TAGS:SENROSTYPE
    DBObject query = (DBObject) JSON.parse("{}");
    if (!tags.equals("")) {
        query.put(this.tag, tags);
    }/*from w w  w .j a v a 2s  .c  o m*/
    if (!id.equals("")) {
        query.put(this.id, id);
    }

    map = "function () {" + "emit(this.tags, this['" + sensorType + "']);" + "}";

    reduce = "function(key, values) {" + "title_list =0;" + "j=0;" + "mid = values.length/2 | 0;"
            + "values = values.sort();" + "for(var i in values) {" + "if(values[i]>(values[mid]-" + range
            + ") && values[i]<(values[mid]+" + range + ")){" + "title_list += values[i];" + "j++}" + "}"
            + "return title_list/j;" + "}";

    List<String> stringValue = new ArrayList<String>();
    int i = 0;
    for (DBObject o : ((MongoTools) this.client).mongoMapReduce(this.collection, map, reduce, query)
            .results()) {
        stringValue.add(o.toString());
        i++;
    }
    String[] array = new String[stringValue.size()];
    stringValue.toArray(array);
    return array;
}

From source file:mongosensors_server.MapReduce.java

License:Open Source License

public String[] getAverageValue(String sensorType, String tags, String id, double range, String[] time) {
    //AVERAGE TAGS:SENROSTYPE the query can define a time period
    DBObject query = (DBObject) JSON.parse("{'Last update':{$gt:'" + time[0] + "',$lt:'" + time[1] + "'}}");
    if (!tags.equals("")) {
        query.put(this.tag, tags);
    }/*from  ww w  .  jav  a  2  s.com*/
    if (!id.equals("")) {
        query.put(this.id, id);
    }
    System.out.println(query.toString());

    map = "function () {" + "emit(this.tags, this['" + sensorType + "']);" + "}";

    reduce = "function(key, values) {" + "title_list =0;" + "j=0;" + "mid = values.length/2 | 0;"
            + "values = values.sort();" + "for(var i in values) {" + "if(values[i]>(values[mid]-" + range
            + ") && values[i]<(values[mid]+" + range + ")){" + "title_list += values[i];" + "j++}" + "}"
            + "return title_list/j;" + "}";

    List<String> stringValue = new ArrayList<String>();
    int i = 0;
    for (DBObject o : ((MongoTools) this.client).mongoMapReduce(this.collection, map, reduce, query)
            .results()) {
        stringValue.add(o.toString());
        i++;

    }
    String[] array = new String[stringValue.size()];
    stringValue.toArray(array);
    return array;
}

From source file:mongosensors_server.MapReduce.java

License:Open Source License

public String[] getAverageValue(String sensorType, String tags, double range, double[] loc, double radius) {
    //AVERAGE TAGS:SENROSTYPE the query can define geographical area
    DBObject query;/*from   w w  w  .j av a  2s  .c om*/
    radius = radius / 6378160.0;
    if (!tags.equals("")) {
        query = (DBObject) JSON.parse("{loc: { $geoWithin: { $centerSphere: [[" + loc[0] + "," + loc[1] + "],"
                + radius + "] } },'" + this.tag + "':'" + tags + "'}");
    } else {
        query = (DBObject) JSON.parse(
                "{loc: { $geoWithin: { $centerSphere: [[" + loc[0] + "," + loc[1] + "]," + radius + "]}}}");
    }

    map = "function () {" + "emit(this.tags, this['" + sensorType + "']);" + "}";

    reduce = "function(key, values) {" + "title_list =0;" + "j=0;" + "mid = values.length/2 | 0;"
            + "values = values.sort();" + "for(var i in values) {" + "if(values[i]>(values[mid]-" + range
            + ") && values[i]<(values[mid]+" + range + ")){" + "title_list += values[i];" + "j++}" + "}"
            + "return title_list/j;" + "}";

    List<String> stringValue = new ArrayList<String>();
    int i = 0;
    for (DBObject o : ((MongoTools) this.client).mongoMapReduce(this.collection, map, reduce, query).results())// <!>
    {
        stringValue.add(o.toString());
        i++;
    }
    String[] array = new String[stringValue.size()];
    stringValue.toArray(array);
    return array;
}

From source file:mongosensors_server.MapReduce.java

License:Open Source License

public String[] getAverageValue(String sensorType, String tags, double range, String[] time, double[] loc,
        double radius) {
    //AVERAGE TAGS:SENROSTYPE the query can define a time period and geographical area
    DBObject query;/*from w w w  .j a  v a2s.c o m*/
    radius = radius / 6378160.0;
    if (!tags.equals("")) {
        query = (DBObject) JSON.parse("{'Last update':{$gt:'" + time[0] + "',$lt:'" + time[1]
                + "'},loc: { $geoWithin: { $centerSphere: [[" + loc[0] + "," + loc[1] + "]," + radius
                + "] } },'" + this.tag + "':'" + tags + "'}");
    } else {
        query = (DBObject) JSON.parse("{'Last update':{$gt:'" + time[0] + "',$lt:'" + time[1]
                + "'},loc: { $geoWithin: { $centerSphere: [[" + loc[0] + "," + loc[1] + "]," + radius
                + "] } }}");
    }

    map = "function () {" + "emit(this.tags, this['" + sensorType + "']);" + "}";

    reduce = "function(key, values) {" + "title_list =0;" + "j=0;" + "mid = values.length/2 | 0;"
            + "values = values.sort();" + "for(var i in values) {" + "if(values[mid]-" + range
            + "<values[i] && values[mid]+" + range + ">values[i]){" + "title_list += values[i];" + "j++}" + "}"
            + "return title_list/j;" + "}";

    List<String> stringValue = new ArrayList<String>();
    int i = 0;
    for (DBObject o : ((MongoTools) this.client).mongoMapReduce(this.collection, map, reduce, query)
            .results()) {
        stringValue.add(o.toString());
        i++;
    }
    String[] array = new String[stringValue.size()];
    stringValue.toArray(array);
    return array;
}