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:edu.stanford.epad.common.util.MongoDBOperations.java

License:Open Source License

/**
 * Saves a json doc to mongoDB//from  w w w  .j a v  a 2  s.c  o m
 * @param jsonString
 * @param collection
 * @throws Exception
 */
public static void saveJsonToMongo(String jsonString, String collection) throws Exception {
    try {
        DB db = MongoDBOperations.getMongoDB();
        if (db == null) {
            log.warning("No connection to Mongo DB");
            return;
        }
        DBCollection coll = db.getCollection(collection);
        DBObject dbObject = (DBObject) JSON.parse(jsonString);
        //TODO: Check if document exists and replace instead of insert
        coll.insert(dbObject);
    } catch (Exception e) {
        log.warning("Error saving to mongodb:", e);
        throw e;
    }
}

From source file:edu.stanford.epad.common.util.MongoDBOperations.java

License:Open Source License

/**
 * Get number of documents in mongoDB/* w w  w  .  j  a v a2 s. c o  m*/
 * @param jsonQuery
 * @param collection
 * @return
 * @throws Exception
 */
public static int getNumberOfDocuments(String jsonQuery, String collection) throws Exception {
    try {
        int count = 0;
        DB db = MongoDBOperations.getMongoDB();
        if (db == null) {
            log.warning("No connection to Mongo DB");
            return count;
        }
        DBCollection dbColl = db.getCollection(collection);
        if (jsonQuery != null && jsonQuery.trim().length() > 0) {
            DBObject dbQuery = (DBObject) JSON.parse(jsonQuery);
            return dbColl.find(dbQuery).count();
        } else {
            return dbColl.find().count();
        }

    } catch (Exception e) {
        log.warning("Error querying mongodb:", e);
        throw e;
    }
}

From source file:edu.stanford.epad.common.util.MongoDBOperations.java

License:Open Source License

/**
 * Converts and saves an annotation to mongoDB
 * @param annotationID//from w ww  .  j a v a2 s  .c  o m
 * @param aimXML
 * @param collection
 * @throws Exception
 */
public static void saveAnnotationToMongo(String annotationID, String aimXML, String collection)
        throws Exception {
    try {
        DB db = MongoDBOperations.getMongoDB();
        if (db == null) {
            log.warning("No connection to Mongo DB");
            return;
        }
        if (aimXML == null || aimXML.trim().length() == 0)
            return;
        String jsonString = XML.toJSONObject(aimXML).toString(0);
        ;
        if (jsonString == null)
            throw new Exception("Error converting to json");
        DBCollection dbColl = db.getCollection(collection);
        BasicDBObject dbObj = new BasicDBObject("ImageAnnotationCollection.uniqueIdentifier.root", 1);
        dbColl.createIndex(dbObj, "uid_idx", true); // Does not create index, if it already exists
        BasicDBObject query = new BasicDBObject();
        query.put("ImageAnnotationCollection.uniqueIdentifier.root", annotationID);
        DBObject dbObject = (DBObject) JSON.parse(jsonString);
        DBCursor cursor = dbColl.find(query);
        if (cursor.count() > 0) {
            log.info("Updating existing annotation in mongoDB:" + annotationID + " in " + collection);
            dbColl.update(query, dbObject, true, false);
        } else {
            log.info("Creating new annotation in mongoDB:" + annotationID + " in " + collection);
            dbColl.insert(dbObject);
        }
    } catch (Exception e) {
        log.warning("Error saving AIM to mongodb:", e);
        throw e;
    }
}

From source file:edu.stanford.epad.epadws.aim.AIMQueries.java

License:Open Source License

/**
 * Read the annotations from the AIM database by patient name, patient id, series id, annotation id, or just get all
 * of them on a GET. Can also delete by annotation id.
 * //w  w  w  . j  av  a 2 s.com
 * @param aimSearchType One of personName, patientId, seriesUID, annotationUID, deleteUID
 * @param value
 * @param user
 * @return List<ImageAnnotationCollection>
 * @throws edu.stanford.hakan.aim4api.base.AimException
 */
public static List<String> getJsonAnnotations(String projectID, AIMSearchType aimSearchType, String value,
        String username) throws Exception {
    //db.Test.find( { 'ImageAnnotationCollection.uniqueIdentifier.root': { $in: [ 'drr7d3pp5sr3up1hbt1v53cf4va5ga57fv8aeri6', 'iqn1vvxtdptm0wtzsc43kptl26oft5c08wxz0w1t' ] } } )
    List<String> results = new ArrayList<String>();
    long time1 = System.currentTimeMillis();
    DBObject query = null;
    if (aimSearchType == AIMSearchType.PERSON_NAME) {
        String personName = value;
        query = new BasicDBObject("ImageAnnotationCollection.person.name.value", personName);
    } else if (aimSearchType == AIMSearchType.PATIENT_ID) {
        String patientId = value;
        query = new BasicDBObject("ImageAnnotationCollection.person.id.value", patientId);
    } else if (aimSearchType == AIMSearchType.SERIES_UID) {
        String seriesUID = value;
        query = new BasicDBObject(
                "ImageAnnotationCollection.imageAnnotations.ImageAnnotation.imageReferenceEntityCollection.ImageReferenceEntity.imageStudy.imageSeries.instanceUid.root",
                seriesUID);
    } else if (aimSearchType == AIMSearchType.ANNOTATION_UID) {
        String annotationUID = value;
        if (value.equals("all")) {
        } else if (value.contains(",")) {
            String[] ids = value.split(",");
            BasicDBList aimIds = new BasicDBList();
            for (String id : ids) {
                aimIds.add(id);
            }
            DBObject inClause = new BasicDBObject("$in", aimIds);
            query = new BasicDBObject("ImageAnnotationCollection.uniqueIdentifier.root", inClause);
        } else {
            query = new BasicDBObject("ImageAnnotationCollection.uniqueIdentifier.root", value);
        }
    } else if (aimSearchType.equals(AIMSearchType.JSON_QUERY)) {
        String jsonQuery = value;
        query = (DBObject) JSON.parse(jsonQuery);
    } else {
        log.warning("Unsupported AIM search type for mongoDB:" + aimSearchType.getName());
    }
    DB mongoDB = MongoDBOperations.getMongoDB();
    if (mongoDB == null)
        throw new Exception("Error connecting to MongoDB");
    DBCollection coll = mongoDB.getCollection(projectID);
    DBCursor cursor = null;
    try {
        cursor = coll.find(query);
        while (cursor.hasNext()) {
            DBObject obj = cursor.next();
            results.add(obj.toString());
        }
    } finally {
        cursor.close();
    }
    long time2 = System.currentTimeMillis();
    log.info("MongoDB query took " + (time2 - time1) + " msecs for " + results.size() + " aims in projectID:"
            + projectID);
    return results;
}

From source file:edu.umass.cs.gnsserver.database.MongoRecords.java

License:Apache License

@Override
public void insert(String collectionName, String guid, JSONObject value)
        throws FailedDBOperationException, RecordExistsException {
    db.requestStart();/* w w w.  ja  v  a  2  s.com*/
    try {
        db.requestEnsureConnection();

        DBCollection collection = db.getCollection(collectionName);
        DBObject dbObject;
        try {
            dbObject = (DBObject) JSON.parse(value.toString());
        } catch (Exception e) {
            throw new FailedDBOperationException(collectionName, guid, "Unable to parse json" + e.getMessage());
        }
        try {
            collection.insert(dbObject);
        } catch (DuplicateKeyException e) {
            throw new RecordExistsException(collectionName, guid);
        } catch (MongoException e) {
            DatabaseConfig.getLogger().log(Level.FINE, "{0} insert failed: {1}",
                    new Object[] { dbName, e.getMessage() });
            throw new FailedDBOperationException(collectionName, dbObject.toString(),
                    "Original mongo exception:" + e.getMessage());
        }
    } finally {
        db.requestDone();
    }
}

From source file:edu.umass.cs.gnsserver.database.MongoRecords.java

License:Apache License

@Override
public void updateEntireRecord(String collectionName, String guid, ValuesMap valuesMap)
        throws FailedDBOperationException {
    BasicDBObject updates = new BasicDBObject();
    try {/*  w  w w  .ja  va  2 s  . co  m*/
        updates.append(NameRecord.VALUES_MAP.getName(), JSON.parse(valuesMap.toString()));
    } catch (Exception e) {
        throw new FailedDBOperationException(collectionName, guid, "Unable to parse json" + e.getMessage());
    }
    doUpdate(collectionName, guid, updates);
}

From source file:edu.umass.cs.gnsserver.database.MongoRecords.java

License:Apache License

/**
 *
 * @param collectionName//from   w  ww .  j a  v a  2s  .c o  m
 * @param values
 * @throws FailedDBOperationException
 * @throws RecordExistsException
 */
public void bulkUpdate(String collectionName, Map<String, JSONObject> values)
        throws FailedDBOperationException, RecordExistsException {
    //String primaryKey = mongoCollectionSpecs.getCollectionSpec(collectionName).getPrimaryKey().getName();
    DBCollection collection = db.getCollection(collectionName);
    String primaryKey = mongoCollectionSpecs.getCollectionSpec(collectionName).getPrimaryKey().getName();
    db.requestEnsureConnection();
    BulkWriteOperation unordered = collection.initializeUnorderedBulkOperation();
    for (Map.Entry<String, JSONObject> entry : values.entrySet()) {
        BasicDBObject query = new BasicDBObject(primaryKey, entry.getKey());
        JSONObject value = entry.getValue();
        if (value != null) {
            DBObject document;
            try {
                document = (DBObject) JSON.parse(value.toString());
            } catch (Exception e) {
                throw new FailedDBOperationException(collectionName, "bulkUpdate",
                        "Unable to parse json" + e.getMessage());
            }
            unordered.find(query).upsert().replaceOne(document);
        } else {
            unordered.find(query).removeOne();
        }
    }
    // Maybe check the result?
    unordered.execute();
}

From source file:edu.umass.cs.gnsserver.database.MongoRecords.java

License:Apache License

private Object JSONParse(Object object) {
    if (object instanceof String || object instanceof Number) {
        return object;
    } else {/*from  w w w . j a  v  a2  s.  com*/
        return JSON.parse(object.toString());
    }
}

From source file:edu.umass.cs.gnsserver.database.MongoRecords.java

License:Apache License

private DBObject parseMongoQuery(String query, ColumnField valuesMapField) {
    // convert something like this: ~fred : ($gt: 0) into the queryable 
    // format, namely this: {~nr_valuesMap.fred : ($gt: 0)}
    String edittedQuery = query;//from   www .ja  v  a  2s .c o  m
    edittedQuery = "{" + edittedQuery + "}";
    edittedQuery = edittedQuery.replace("(", "{");
    edittedQuery = edittedQuery.replace(")", "}");
    edittedQuery = edittedQuery.replace("~", valuesMapField.getName() + ".");
    // Filter out HRN records
    String guidFilter = "{" + NameRecord.VALUES_MAP.getName() + "." + AccountAccess.GUID_INFO
            + ": { $exists: true}}";
    edittedQuery = buildAndQuery(guidFilter, edittedQuery);
    try {
        DatabaseConfig.getLogger().log(Level.FINE, "{0} Edited query = {1}",
                new Object[] { dbName, edittedQuery });
        DBObject parse = (DBObject) JSON.parse(edittedQuery);
        DatabaseConfig.getLogger().log(Level.FINE, "{0} Parse = {1}",
                new Object[] { dbName, parse.toString() });
        return parse;
    } catch (Exception e) {
        throw new MongoException("Unable to parse query", e);
    }
}

From source file:es.bsc.amon.controller.AppsDBMapper.java

License:Open Source License

public void addAppInstance(String appInstanceJson) {
    BasicDBObject dbo = (BasicDBObject) JSON.parse(appInstanceJson);
    BasicDBObject data = ((BasicDBObject) dbo.get(FIELD_DATA));
    if (data == null || dbo.get(FIELD_APP_ID) == null || dbo.get(FIELD_INSTANCE_ID) == null
            || data.get(FIELD_DATA_START) == null || data.get(FIELD_DATA_END) == null
            || data.get(FIELD_DATA_POWER) == null) {
        throw new AppException("The App document must have the following structure:\n" + "{'appId' : ...\n"
                + "'instanceId' : ...\n" + "'data' : {\n" + "\t'start' : ....\n" + "\t'end' : ....\n"
                + "\t'power' : ....\n" + "}}");
    }//from  w w w.ja v  a  2 s.  com
    long timestamp = System.currentTimeMillis();
    dbo.put(FIELD_TIMESTAMP, timestamp);
    colAppInstances.insert(dbo);
}