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:org.apache.rya.indexing.pcj.storage.mongo.MongoPcjDocuments.java

License:Apache License

/**
 * List the document Ids of the PCJs that are stored in MongoDB
 * for this instance of Rya./*from w  w  w .j  a v  a  2 s.c  o m*/
 *
 * @return A list of pcj document Ids that hold PCJ index data for the current
 *   instance of Rya.
 */
public List<String> listPcjDocuments() {
    final List<String> pcjIds = new ArrayList<>();

    //This Bson string reads as:
    //{} - no search criteria: find all
    //{ _id: 1 } - only return the _id, which is the PCJ Id.
    final FindIterable<Document> rez = pcjCollection
            .find((Bson) JSON.parse("{ }, { " + PCJ_METADATA_ID + ": 1 , _id: 0}"));
    final Iterator<Document> iter = rez.iterator();
    while (iter.hasNext()) {
        pcjIds.add(iter.next().get(PCJ_METADATA_ID).toString().replace("_METADATA", ""));
    }

    return pcjIds;
}

From source file:org.apache.rya.mongodb.iter.RyaStatementBindingSetCursorIterator.java

License:Apache License

private void findNextResult() {
    if (!currentBatchQueryResultCursorIsValid()) {
        submitBatchQuery();/*w w  w. java  2 s  .c  o  m*/
    }

    if (currentBatchQueryResultCursorIsValid()) {
        // convert to Rya Statement
        final Document queryResult = batchQueryResultsIterator.next();
        final DBObject dbo = (DBObject) JSON.parse(queryResult.toJson());
        currentResultStatement = strategy.deserializeDBObject(dbo);

        // Find all of the queries in the executed RangeMap that this result matches
        // and collect all of those binding sets
        Set<BindingSet> bsList = new HashSet<>();
        for (RyaStatement executedQuery : executedRangeMap.keys()) {
            if (isResultForQuery(executedQuery, currentResultStatement)) {
                bsList.addAll(executedRangeMap.get(executedQuery));
            }
        }
        currentBindingSetIterator = bsList.iterator();
    }

    // Handle case of invalid currentResultStatement or no binding sets returned
    if ((currentBindingSetIterator == null || !currentBindingSetIterator.hasNext())
            && (currentBatchQueryResultCursorIsValid() || queryIterator.hasNext())) {
        findNextResult();
    }
}

From source file:org.apache.sling.mongodb.impl.MongoDBResourceProvider.java

License:Apache License

public Iterator<Resource> findResources(final ResourceResolver resolver, String query, String language) {
    if (!language.equals("mongodb") || query == null || query.length() == 0 || query.indexOf(".find(") <= 0) {
        return null;
    }/* w  w w. jav a2s  .com*/
    Iterator<Resource> returnValue = null;
    final String collectionName = query.substring(0, query.indexOf(".find("));
    DBCollection col = this.getCollection(collectionName);
    if (col != null) {
        String criteria = query.trim().substring(query.indexOf(".find(") + 6, query.length() - 1);
        DBObject dbObject = (DBObject) JSON.parse(criteria);
        final DBCursor cur = col.find(dbObject);
        final String rootPath = context.getRootWithSlash();

        return new Iterator<Resource>() {

            public boolean hasNext() {
                return cur.hasNext();
            }

            public Resource next() {
                final DBObject obj = cur.next();
                final String objPath = obj.get(getPROP_PATH()).toString();
                final int lastSlash = objPath.lastIndexOf('/');
                final String name;
                if (lastSlash == -1) {
                    name = objPath;
                } else {
                    name = objPath.substring(lastSlash + 1);
                }
                return new MongoDBResource(resolver, rootPath + collectionName + "/" + name, collectionName,
                        obj, MongoDBResourceProvider.this);
            }

            public void remove() {
                throw new UnsupportedOperationException("remove");
            }

        };
    }

    return returnValue;
}

From source file:org.apache.streams.mongo.MongoPersistWriter.java

License:Apache License

protected DBObject prepareObject(StreamsDatum streamsDatum) {
    DBObject dbObject = null;/*w  ww . j  ava 2 s  . c o  m*/
    if (streamsDatum.getDocument() instanceof String) {
        dbObject = (DBObject) JSON.parse((String) streamsDatum.getDocument());
    } else {
        try {
            ObjectNode node = mapper.valueToTree(streamsDatum.getDocument());
            dbObject = (DBObject) JSON.parse(node.toString());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("Unsupported type: " + streamsDatum.getDocument().getClass(), e);
        }
    }
    return dbObject;
}

From source file:org.apereo.openlrs.model.event.Event.java

License:Educational Community License

protected DBObject toDBObject(String json) {
    return (DBObject) JSON.parse(json);
}

From source file:org.aw20.mongoworkbench.command.MongoCommand.java

License:Open Source License

public String getExceptionMessage() {
    if (lastException == null)
        return "";

    if (lastException instanceof MongoException) {
        String e = lastException.getMessage();
        if (e.startsWith("command failed [$eval]: {") && e.endsWith("}")) {
            try {
                Map m = (Map) JSON.parse(e.substring(e.indexOf("{")));
                return (String) m.get("errmsg");
            } catch (Exception ee) {
                return lastException.getMessage();
            }/*w w w.ja v a 2  s  . co  m*/
        }
    }

    return lastException.getMessage();
}

From source file:org.aw20.mongoworkbench.command.RemoveMongoCommand.java

License:Open Source License

@Override
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    if (sDb == null)
        throw new Exception("no database selected");

    MongoFactory.getInst().setActiveDB(sDb);

    DB db = mdb.getDB(sDb);//from w  w  w.  j a  v  a  2 s . c  o  m
    BasicDBObject cmdMap = parseMongoCommandString(db, cmd);

    if (!cmdMap.containsField("removeArgs"))
        throw new Exception("no remove document");

    DBCollection collection = db.getCollection(sColl);

    BasicDBList args = (BasicDBList) cmdMap.get("removeArgs");

    // Run the command
    db.requestStart();
    WriteResult writeresult;
    try {
        writeresult = collection.remove((DBObject) args.get(0), WriteConcern.JOURNAL_SAFE);
    } finally {
        db.requestDone();
    }

    // Get the result
    Map mwriteresult = (Map) JSON.parse(writeresult.toString());
    mwriteresult.put("exeDate", new Date());

    EventWorkBenchManager.getInst().onEvent(Event.WRITERESULT, mwriteresult);

    setMessage("Removed");
}

From source file:org.aw20.mongoworkbench.command.SaveMongoCommand.java

License:Open Source License

@Override
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    if (sDb == null)
        throw new Exception("no database selected");

    MongoFactory.getInst().setActiveDB(sDb);

    DB db = mdb.getDB(sDb);//from  www  .  j av  a  2s  .co  m
    BasicDBObject cmdMap = parseMongoCommandString(db, cmd);

    if (!cmdMap.containsField("saveArg"))
        throw new Exception("no save document");

    DBObject document = fixNumbers((BasicDBObject) cmdMap.get("saveArg"));
    DBCollection collection = db.getCollection(sColl);

    // Run the command
    db.requestStart();
    WriteResult writeresult;
    try {
        writeresult = collection.save(document, WriteConcern.JOURNAL_SAFE);
        id = document.get("_id");
    } finally {
        db.requestDone();
    }

    // Get the result
    Map mwriteresult = (Map) JSON.parse(writeresult.toString());
    mwriteresult.put("exeDate", new Date());

    EventWorkBenchManager.getInst().onEvent(Event.WRITERESULT, mwriteresult);

    setMessage("Saved: updatedExisting=" + mwriteresult.get("updatedExisting") + "; documentsUpdated="
            + mwriteresult.get("n"));
}

From source file:org.aw20.mongoworkbench.command.UpdateMongoCommand.java

License:Open Source License

@Override
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    if (sDb == null)
        throw new Exception("no database selected");

    MongoFactory.getInst().setActiveDB(sDb);

    DB db = mdb.getDB(sDb);//from   w  w w  . j  ava2 s .co m
    BasicDBObject cmdMap = parseMongoCommandString(db, cmd);

    if (!cmdMap.containsField("updateArg"))
        throw new Exception("no update document");

    List argList = (List) cmdMap.get("updateArg");
    if (argList.size() == 1)
        throw new Exception("not enough parameters; db.collection.update(query, update, <upsert>, <multi>)");

    DBCollection collection = db.getCollection(sColl);

    db.requestStart();
    WriteResult writeresult = null;
    try {

        if (argList.size() == 2) {

            writeresult = collection.update((DBObject) argList.get(0),
                    fixNumbers((BasicDBObject) argList.get(1)));

        } else if (argList.size() == 3) {

            boolean upsert = StringUtil.toBoolean(argList.get(2), false);
            writeresult = collection.update((DBObject) argList.get(0),
                    fixNumbers((BasicDBObject) argList.get(1)), upsert, false);

        } else if (argList.size() == 4) {

            boolean upsert = StringUtil.toBoolean(argList.get(2), false);
            boolean multi = StringUtil.toBoolean(argList.get(3), false);
            writeresult = collection.update((DBObject) argList.get(0),
                    fixNumbers((BasicDBObject) argList.get(1)), upsert, multi);

        } else
            throw new Exception("too many parameters; db.collection.update(query, update, <upsert>, <multi>)");

    } finally {
        db.requestDone();
    }

    // Get the result
    Map mwriteresult = (Map) JSON.parse(writeresult.toString());
    mwriteresult.put("exeDate", new Date());

    EventWorkBenchManager.getInst().onEvent(Event.WRITERESULT, mwriteresult);

    setMessage("Updated: updatedExisting=" + mwriteresult.get("updatedExisting") + "; documentsUpdated="
            + mwriteresult.get("n"));
}

From source file:org.axonframework.mongo.serialization.StringToDBObjectContentTypeConverter.java

License:Apache License

@Override
public DBObject convert(String original) {
    return (DBObject) JSON.parse(original);
}