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:nosqltools.DBConnection.java

/**
 * Deletes a JSON object from the collection
 * @param obj JSON Objects to delete//from   w  w  w  . j a  va  2 s .  com
 * @return True if unsuccessful operation, else false
 */
public boolean deleteFromDatabase(String obj) {
    boolean flag = false;
    try {
        //If the object passed as a parameter is a JSON array, it is rejected
        if (json_util.isArray(obj)) {
            JOptionPane.showMessageDialog(null,
                    "JSON Arrays are not allowed - Change details for only one JSON object!", "Error",
                    JOptionPane.ERROR_MESSAGE);
        } else //If the object passed as a parameter is a JSON object
        {
            //Parse the object and find it the collection. The results are stored in a cursor.
            DBObject dbobj = (DBObject) JSON.parse(obj);
            DBCursor cursor = collection.find(dbobj);
            int count = cursor.count();

            //If no  objects were found
            if (cursor.count() == 0) {
                flag = true;
                JOptionPane.showMessageDialog(null, "JSON object " + dbobj + " does not exist in collection!",
                        "Error", JOptionPane.ERROR_MESSAGE);
            } else //if objects were found for deletion
            {
                //Loop on the curser until it is equal to 0
                while (count != 0) {
                    while (cursor.hasNext()) {
                        cursor.next();
                    }

                    //Delete the object from the collection
                    if (count != 0)
                        collection.remove(dbobj);
                    count--;
                }
                JOptionPane.showMessageDialog(null,
                        "JSON Object " + dbobj + " has been removed from Collection!", "Deleted Successfully",
                        JOptionPane.INFORMATION_MESSAGE);
            }
        }
    } catch (MongoException me) {
        JOptionPane.showMessageDialog(null, me.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }

    return flag;
}

From source file:nosqltools.DBConnection.java

public boolean findFromDatabase(String obj) {
    boolean flag = false;
    String result = "";
    try {/*from   w w  w  .java2 s.c om*/
        if (json_util.isArray(obj)) {
            JOptionPane.showMessageDialog(null,
                    "JSON Arrays are not allowed - Change details for only one JSON object!", "Error",
                    JOptionPane.ERROR_MESSAGE);
        } else {

            DBObject dbobj = (DBObject) JSON.parse(obj);

            DBCursor cursor = collection.find(dbobj);
            int count = cursor.count();
            if (cursor.count() == 0) {
                flag = true;
                JOptionPane.showMessageDialog(null, "JSON object " + dbobj + " does not exist in collection!",
                        "Error", JOptionPane.ERROR_MESSAGE);
            } else {
                while (count != 0) {
                    while (cursor.hasNext()) {
                        System.out.println(cursor.next());
                    }

                    if (count != 0) {
                        result += dbobj + "\n";
                    }
                    count--;
                }
                ResultForm results = new ResultForm(result, cursor.count());
                results.setVisible(true);
            }
        }
    } catch (MongoException me) {
        JOptionPane.showMessageDialog(null, me.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }

    return flag;
}

From source file:org.agora.server.Options.java

License:Open Source License

/**
 * Reads Agora Server options from given configuration file.
 *
 * @param Configuration file.//from www .j av  a 2s  .c  o m
 */
public static void readAgoraConfFromFile(String file) {
    String json;
    try {
        Scanner s = new Scanner(new File(file));
        json = s.useDelimiter("\\A").next();
        s.close();
    } catch (FileNotFoundException e) {
        Log.error("[JAgoraServer] Could not find configuration file " + file);
        return;
    }

    // Not even checking whether they exist. They must - boom!
    DBObject bson = (DBObject) JSON.parse(json);
    SERVER_URL = (String) bson.get("url");
    NUM_WORKERS = (Integer) bson.get("number of workers");
    SESSION_BYTE_LENGTH = (Integer) bson.get("session token size");
    REQUEST_WAIT = (Integer) bson.get("request timeout");
    LOG_MESSAGES = (Boolean) bson.get("log");
    DEBUG_MESSAGES = (Boolean) bson.get("debug log");
    ERROR_MESSAGES = (Boolean) bson.get("error log");
    LOG_FILE = (String) bson.get("log file");
    DEBUG_FILE = (String) bson.get("debug log file");
    ERROR_FILE = (String) bson.get("error log file");
}

From source file:org.agora.server.Options.java

License:Open Source License

public static void readAgoraConfFromStream(InputStream is) {
    String json = null;//  w w w  .  j a v  a2 s .co m
    try (Scanner s = new Scanner(is)) {
        json = s.useDelimiter("\\A").next();
    } catch (Exception e) {
        Log.error("[Options] Could not read Agora Conf from stream: " + e.getMessage());
        throw e;
    }

    // Not even checking whether they exist. They must - boom!
    DBObject bson = (DBObject) JSON.parse(json);
    SERVER_URL = (String) bson.get("url");
    NUM_WORKERS = (Integer) bson.get("number of workers");
    SESSION_BYTE_LENGTH = (Integer) bson.get("session token size");
    REQUEST_WAIT = (Integer) bson.get("request timeout");
    LOG_MESSAGES = (Boolean) bson.get("log");
    DEBUG_MESSAGES = (Boolean) bson.get("debug log");
    ERROR_MESSAGES = (Boolean) bson.get("error log");
    LOG_FILE = (String) bson.get("log file");
    DEBUG_FILE = (String) bson.get("debug log file");
    ERROR_FILE = (String) bson.get("error log file");
}

From source file:org.agora.server.Options.java

License:Open Source License

/**
 * Reads Agora Server database options from given configuration file.
 *
 * @param Configuration file./*from w  ww .ja v  a  2 s  .c o  m*/
 */
public static void readDBConfFromFile(String file) {
    String json;
    try {
        Scanner s = new Scanner(new File(file));
        json = s.useDelimiter("\\A").next();
        s.close();
    } catch (FileNotFoundException e) {
        Log.error("[JAgoraServer] Could not find database configuration file " + file);
        return;
    }

    DBObject bson = (DBObject) JSON.parse(json);
    DB_URL = (String) bson.get("url");
    DB_USER = (String) bson.get("user");
    DB_PASS = (String) bson.get("pass");
}

From source file:org.agora.server.Options.java

License:Open Source License

public static void readDBConfFromStream(InputStream is) {
    String json = null;//from  w w  w  . j a va 2  s.  co m
    try (Scanner s = new Scanner(is)) {
        json = s.useDelimiter("\\A").next();
    } catch (Exception e) {
        Log.error("[Options] Could not read Database Conf from stream: " + e.getMessage());
        throw e;
    }

    DBObject bson = (DBObject) JSON.parse(json);
    DB_URL = (String) bson.get("url");
    DB_USER = (String) bson.get("user");
    DB_PASS = (String) bson.get("pass");
}

From source file:org.apache.airavata.userprofile.core.UserProfileDao.java

License:Apache License

public boolean createUserProfile(UserProfile userProfile) throws UserProfileException {
    try {/*  w w  w  .  j av a2 s .  c  o m*/
        WriteResult result = collection
                .insert((DBObject) JSON.parse(modelConversionHelper.serializeObject(userProfile)));
        logger.debug("No of inserted results " + result.getN());
        return true;
    } catch (JsonProcessingException e) {
        throw new UserProfileException(e);
    }
}

From source file:org.apache.airavata.userprofile.core.UserProfileDao.java

License:Apache License

/**
 * The following operation replaces the document with item equal to
 * the given user id. The newly replaced document will only
 * contain the the _id field and the fields in the replacement document.
 * @param userProfile//w w w . ja  va2s.  c  om
 * @throws org.apache.airavata.registry.cpi.UserProfileException
 */
public boolean updateUserProfile(UserProfile userProfile) throws UserProfileException {
    try {
        DBObject query = BasicDBObjectBuilder.start().add(USER_ID, userProfile.getUserId()).get();
        WriteResult result = collection.update(query,
                (DBObject) JSON.parse(modelConversionHelper.serializeObject(userProfile)));
        logger.debug("No of updated results " + result.getN());
        return true;
    } catch (JsonProcessingException e) {
        throw new UserProfileException(e);
    }
}

From source file:org.apache.calcite.adapter.mongodb.MongoTable.java

License:Apache License

/** Executes a "find" operation on the underlying collection.
 *
 * <p>For example,//  ww w.j  ava2 s .c  o  m
 * <code>zipsTable.find("{state: 'OR'}", "{city: 1, zipcode: 1}")</code></p>
 *
 * @param mongoDb MongoDB connection
 * @param filterJson Filter JSON string, or null
 * @param projectJson Project JSON string, or null
 * @param fields List of fields to project; or null to return map
 * @return Enumerator of results
 */
public Enumerable<Object> find(DB mongoDb, String filterJson, String projectJson,
        List<Map.Entry<String, Class>> fields) {
    final DBCollection collection = mongoDb.getCollection(collectionName);
    final DBObject filter = filterJson == null ? null : (DBObject) JSON.parse(filterJson);
    final DBObject project = projectJson == null ? null : (DBObject) JSON.parse(projectJson);
    final Function1<DBObject, Object> getter = MongoEnumerator.getter(fields);
    return new AbstractEnumerable<Object>() {
        public Enumerator<Object> enumerator() {
            final DBCursor cursor = collection.find(filter, project);
            return new MongoEnumerator(cursor, getter);
        }
    };
}

From source file:org.apache.calcite.adapter.mongodb.MongoTable.java

License:Apache License

/** Executes an "aggregate" operation on the underlying collection.
 *
 * <p>For example://  w  w w .jav a 2 s.c  o  m
 * <code>zipsTable.aggregate(
 * "{$filter: {state: 'OR'}",
 * "{$group: {_id: '$city', c: {$sum: 1}, p: {$sum: '$pop'}}}")
 * </code></p>
 *
 * @param mongoDb MongoDB connection
 * @param fields List of fields to project; or null to return map
 * @param operations One or more JSON strings
 * @return Enumerator of results
 */
public Enumerable<Object> aggregate(final DB mongoDb, final List<Map.Entry<String, Class>> fields,
        final List<String> operations) {
    final List<DBObject> list = new ArrayList<DBObject>();
    final BasicDBList versionArray = (BasicDBList) mongoDb.command("buildInfo").get("versionArray");
    final Integer versionMajor = parseIntString(versionArray.get(0).toString());
    final Integer versionMinor = parseIntString(versionArray.get(1).toString());
    //    final Integer versionMaintenance = parseIntString(versionArray
    //      .get(2).toString());
    //    final Integer versionBuild = parseIntString(versionArray
    //      .get(3).toString());

    for (String operation : operations) {
        list.add((DBObject) JSON.parse(operation));
    }
    final DBObject first = list.get(0);
    final List<DBObject> rest = Util.skip(list);
    final Function1<DBObject, Object> getter = MongoEnumerator.getter(fields);
    return new AbstractEnumerable<Object>() {
        public Enumerator<Object> enumerator() {
            final Iterator<DBObject> resultIterator;
            try {
                // Changed in version 2.6: The db.collection.aggregate() method
                // returns a cursor
                // and can return result sets of any size.
                // See: http://docs.mongodb.org/manual/core/aggregation-pipeline
                if (versionMajor > 1) {
                    // MongoDB version 2.6+
                    if (versionMinor > 5) {
                        AggregationOptions options = AggregationOptions.builder()
                                .outputMode(AggregationOptions.OutputMode.CURSOR).build();
                        // Warning - this can result in a very large ArrayList!
                        // but you should know your data and aggregate accordingly
                        ArrayList<DBObject> resultAsArrayList = new ArrayList<DBObject>(
                                Util.toList(mongoDb.getCollection(collectionName).aggregate(list, options)));
                        resultIterator = resultAsArrayList.iterator();
                    } else { // Pre MongoDB version 2.6
                        AggregationOutput result = aggregateOldWay(mongoDb.getCollection(collectionName), first,
                                rest);
                        resultIterator = result.results().iterator();
                    }
                } else { // Pre MongoDB version 2
                    AggregationOutput result = aggregateOldWay(mongoDb.getCollection(collectionName), first,
                            rest);
                    resultIterator = result.results().iterator();
                }
            } catch (Exception e) {
                throw new RuntimeException(
                        "While running MongoDB query " + Util.toString(operations, "[", ",\n", "]"), e);
            }
            return new MongoEnumerator(resultIterator, getter);
        }
    };
}