Example usage for com.mongodb BasicDBObject toString

List of usage examples for com.mongodb BasicDBObject toString

Introduction

In this page you can find the example usage for com.mongodb BasicDBObject toString.

Prototype

@SuppressWarnings("deprecation")
public String toString() 

Source Link

Document

Returns a JSON serialization of this object

The output will look like: {"a":1, "b":["x","y","z"]} }

Usage

From source file:com.apifest.oauth20.persistence.mongodb.MongoDBManager.java

License:Apache License

@SuppressWarnings("unchecked")
@Override// w w w.j a  v  a 2  s .  com
public AccessToken findAccessToken(String accessToken) {
    BasicDBObject dbObject = new BasicDBObject();
    dbObject.put(ACCESS_TOKEN_ID, accessToken);
    dbObject.put(ACCESS_TOKEN_VALID, true);
    DBCollection coll = db.getCollection(ACCESS_TOKEN_COLLECTION_NAME);
    List<DBObject> list = coll.find(dbObject).toArray();
    if (list.size() > 1) {
        // throw exception
        log.warn("Several access tokens found");
        return null;
    }
    if (list.size() > 0) {
        Map<String, Object> mapLoaded = list.get(0).toMap();
        // convert details map to String
        if (mapLoaded.get("details") instanceof BasicDBObject) {
            BasicDBObject details = (BasicDBObject) mapLoaded.get("details");
            mapLoaded.put("details", details.toString());
        }
        return AccessToken.loadFromMap(mapLoaded);
    } else {
        log.debug("No access token found");
        return null;
    }
}

From source file:com.apifest.oauth20.persistence.mongodb.MongoDBManager.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*  ww w. j  a  va  2  s .c  o m*/
public AccessToken findAccessTokenByRefreshToken(String refreshToken, String clientId) {
    BasicDBObject dbObject = new BasicDBObject();
    dbObject.put(ACCESS_TOKEN_REFRESH_TOKEN_ID, refreshToken);
    dbObject.put(CLIENTS_CLIENTID, clientId);
    // Searching for unknown validity token -> no VALID query param
    DBCollection coll = db.getCollection(ACCESS_TOKEN_COLLECTION_NAME);
    List<DBObject> list = coll.find(dbObject).toArray();
    if (list != null && list.size() == 1) {
        Map<String, Object> mapLoaded = list.get(0).toMap();
        // convert details list to String
        if (mapLoaded.get("details") instanceof BasicDBObject) {
            BasicDBObject details = (BasicDBObject) mapLoaded.get("details");
            mapLoaded.put("details", details.toString());
        }
        AccessToken loadedAccessToken = AccessToken.loadFromMap(mapLoaded);
        log.debug(loadedAccessToken.getToken());
        return loadedAccessToken;
    }

    return null;
}

From source file:com.apifest.oauth20.persistence.mongodb.MongoDBManager.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public List<AccessToken> getAccessTokenByUserIdAndClientApp(String userId, String clientId) {
    List<AccessToken> accessTokens = new ArrayList<AccessToken>();
    BasicDBObject dbObject = new BasicDBObject();
    dbObject.put(ACCESS_TOKEN_USER_ID, userId);
    dbObject.put(CLIENTS_CLIENTID, clientId);
    dbObject.put(ACCESS_TOKEN_VALID, true);
    DBCollection coll = db.getCollection(ACCESS_TOKEN_COLLECTION_NAME);
    List<DBObject> list = coll.find(dbObject).toArray();
    for (DBObject object : list) {
        Map<String, Object> mapLoaded = object.toMap();
        // convert details list to String
        if (mapLoaded.get("details") instanceof BasicDBObject) {
            BasicDBObject details = (BasicDBObject) mapLoaded.get("details");
            mapLoaded.put("details", details.toString());
        }// w  ww . j  av a2  s .c o m
        AccessToken loadedAccessToken = AccessToken.loadFromMap(mapLoaded);
        accessTokens.add(loadedAccessToken);
    }
    return accessTokens;
}

From source file:com.avanza.ymer.MirroredObject.java

License:Apache License

/**
 * Patches the given document to the current version. <p>
 *
 * The argument document will not be mutated. <p>
 *
 * @param dbObject/*from www.ja  v a  2s. com*/
 * @return
 */
BasicDBObject patch(BasicDBObject dbObject) {
    if (!requiresPatching(dbObject)) {
        throw new IllegalArgumentException("Document does not require patching: " + dbObject.toString());
    }
    while (requiresPatching(dbObject)) {
        patchToNextVersion(dbObject);
    }
    return dbObject;
}

From source file:com.avanza.ymer.MirroredObject.java

License:Apache License

/**
 * Patches the given document to the next version by writing mutating the passed in document. <p>
 *
 * @param dbObject// w  w  w.ja  v  a2 s .  co m
 */
void patchToNextVersion(BasicDBObject dbObject) {
    if (!requiresPatching(dbObject)) {
        throw new IllegalArgumentException("Document does not require patching: " + dbObject.toString());
    }
    DocumentPatch patch = this.patchChain.getPatch(getDocumentVersion(dbObject));
    patch.apply(dbObject);
    setDocumentVersion(dbObject, patch.patchedVersion() + 1);
}

From source file:com.bugull.mongo.BuguMapper.java

License:Apache License

/**
 * Convert to JSON string./*from  w  w  w  .jav a 2  s  . c  o  m*/
 * @param obj
 * @return 
 */
public static String toJsonString(Object obj) {
    DBObject dbo = MapperUtil.toDBObject(obj);
    BasicDBObject bdbo = (BasicDBObject) dbo;
    return bdbo.toString();
}

From source file:com.ca.apm.mongo.test.MongoReplicaSetForTestFactory.java

License:Open Source License

private boolean isReplicaSetStarted(BasicDBObject setting) {
    if (setting.get("members") == null) {
        return false;
    }/*  w w w  . j av a2  s .co m*/

    BasicDBList members = (BasicDBList) setting.get("members");
    for (Object m : members.toArray()) {
        BasicDBObject member = (BasicDBObject) m;
        logger.info(member.toString());
        int state = member.getInt("state");
        logger.info("state: " + state);
        // 1 - PRIMARY, 2 - SECONDARY, 7 - ARBITER
        if (state != 1 && state != 2 && state != 7) {
            return false;
        }
    }
    return true;
}

From source file:com.continuent.tungsten.replicator.applier.MongoApplier.java

License:Open Source License

/**
 * Applies row updates to MongoDB. Statements are discarded. {@inheritDoc}
 * /*from www  . j  a va2s  .  c  om*/
 * @see com.continuent.tungsten.replicator.applier.RawApplier#apply(com.continuent.tungsten.replicator.event.DBMSEvent,
 *      com.continuent.tungsten.replicator.event.ReplDBMSHeader, boolean,
 *      boolean)
 */
@Override
public void apply(DBMSEvent event, ReplDBMSHeader header, boolean doCommit, boolean doRollback)
        throws ReplicatorException, ConsistencyException, InterruptedException {
    ArrayList<DBMSData> dbmsDataValues = event.getData();

    // Iterate through values inferring the database name.
    for (DBMSData dbmsData : dbmsDataValues) {
        if (dbmsData instanceof StatementData) {
            if (logger.isDebugEnabled())
                logger.debug("Ignoring statement");
        } else if (dbmsData instanceof RowChangeData) {
            RowChangeData rd = (RowChangeData) dbmsData;
            for (OneRowChange orc : rd.getRowChanges()) {
                // Get the action as well as the schema & table name.
                ActionType action = orc.getAction();
                String schema = orc.getSchemaName();
                String table = orc.getTableName();
                if (logger.isDebugEnabled()) {
                    logger.debug("Processing row update: action=" + action + " schema=" + schema + " table="
                            + table);
                }

                // Process the action.
                if (action.equals(ActionType.INSERT)) {
                    // Connect to the schema and collection.
                    DB db = m.getDB(schema);
                    DBCollection coll = db.getCollection(table);

                    // Fetch column names.
                    List<ColumnSpec> colSpecs = orc.getColumnSpec();

                    // Make a document and insert for each row.
                    Iterator<ArrayList<ColumnVal>> colValues = orc.getColumnValues().iterator();
                    while (colValues.hasNext()) {
                        BasicDBObject doc = new BasicDBObject();
                        ArrayList<ColumnVal> row = colValues.next();
                        for (int i = 0; i < row.size(); i++) {
                            Object value = row.get(i).getValue();
                            setValue(doc, colSpecs.get(i), value);
                        }
                        if (logger.isDebugEnabled())
                            logger.debug("Adding document: doc=" + doc.toString());
                        coll.insert(doc);
                    }
                } else if (action.equals(ActionType.UPDATE)) {
                    // Connect to the schema and collection.
                    DB db = m.getDB(schema);
                    DBCollection coll = db.getCollection(table);

                    // Ensure required indexes are present.
                    ensureIndexes(coll, orc);

                    // Fetch key and column names.
                    List<ColumnSpec> keySpecs = orc.getKeySpec();
                    List<ColumnSpec> colSpecs = orc.getColumnSpec();
                    ArrayList<ArrayList<OneRowChange.ColumnVal>> keyValues = orc.getKeyValues();
                    ArrayList<ArrayList<OneRowChange.ColumnVal>> columnValues = orc.getColumnValues();

                    // Iterate across the rows.
                    for (int row = 0; row < columnValues.size() || row < keyValues.size(); row++) {
                        List<ColumnVal> keyValuesOfRow = keyValues.get(row);
                        List<ColumnVal> colValuesOfRow = columnValues.get(row);

                        // Prepare key values query to search for rows.
                        DBObject query = new BasicDBObject();
                        for (int i = 0; i < keyValuesOfRow.size(); i++) {
                            setValue(query, keySpecs.get(i), keyValuesOfRow.get(i).getValue());
                        }

                        BasicDBObject doc = new BasicDBObject();
                        for (int i = 0; i < colValuesOfRow.size(); i++) {
                            setValue(doc, colSpecs.get(i), colValuesOfRow.get(i).getValue());
                        }
                        if (logger.isDebugEnabled()) {
                            logger.debug("Updating document: query=" + query + " doc=" + doc);
                        }
                        DBObject updatedRow = coll.findAndModify(query, doc);
                        if (logger.isDebugEnabled()) {
                            if (updatedRow == null)
                                logger.debug("Unable to find document for update: query=" + query);
                            else
                                logger.debug("Documented updated: doc=" + doc);
                        }
                    }
                } else if (action.equals(ActionType.DELETE)) {
                    // Connect to the schema and collection.
                    DB db = m.getDB(schema);
                    DBCollection coll = db.getCollection(table);

                    // Ensure required indexes are present.
                    ensureIndexes(coll, orc);

                    List<ColumnSpec> keySpecs = orc.getKeySpec();
                    ArrayList<ArrayList<OneRowChange.ColumnVal>> keyValues = orc.getKeyValues();
                    ArrayList<ArrayList<OneRowChange.ColumnVal>> columnValues = orc.getColumnValues();

                    // Iterate across the rows.
                    for (int row = 0; row < columnValues.size() || row < keyValues.size(); row++) {
                        List<ColumnVal> keyValuesOfRow = keyValues.get(row);

                        // Prepare key values query to search for rows.
                        DBObject query = new BasicDBObject();
                        for (int i = 0; i < keyValuesOfRow.size(); i++) {
                            setValue(query, keySpecs.get(i), keyValuesOfRow.get(i).getValue());
                        }

                        if (logger.isDebugEnabled()) {
                            logger.debug("Deleting document: query=" + query);
                        }
                        DBObject deletedRow = coll.findAndRemove(query);
                        if (logger.isDebugEnabled()) {
                            if (deletedRow == null)
                                logger.debug("Unable to find document for delete");
                            else
                                logger.debug("Documented deleted: doc=" + deletedRow);
                        }
                    }
                } else {
                    logger.warn("Unrecognized action type: " + action);
                    return;
                }
            }
        } else if (dbmsData instanceof LoadDataFileFragment) {
            if (logger.isDebugEnabled())
                logger.debug("Ignoring load data file fragment");
        } else if (dbmsData instanceof RowIdData) {
            if (logger.isDebugEnabled())
                logger.debug("Ignoring row ID data");
        } else {
            logger.warn("Unsupported DbmsData class: " + dbmsData.getClass().getName());
        }
    }

    // Mark the current header and commit position if requested.
    this.latestHeader = header;
    if (doCommit)
        commit();
}

From source file:com.DA.assignment1.MovieTojson.java

private String addRows() throws Exception {

    BasicDBObject doc = null;

    String line = br.readLine();// w  ww.j  a  v a 2s  .co m

    if (line != null) {
        String[] items = line.split("::");
        String movieID = items[0];
        String movieTitle = items[1];
        String[] generes = items[2].split("\\|");

        doc = new BasicDBObject();
        doc.put("movieID", movieID);
        doc.put("title", movieTitle);
        doc.put("generes", generes);

        return doc.toString();
    }
    return null;
}

From source file:com.dilmus.dilshad.scabi.db.DTable.java

License:Open Source License

public long executeUpdate(String jsonUpdate, String jsonWhere) throws IOException, DScabiException {
    ArrayList<String> fieldList = fieldNamesUsingFindOne(); // fieldNames();
    DMJson djsonWhere = new DMJson(jsonWhere);
    Set<String> stWhere = djsonWhere.keySet();
    Document documentWhere = new Document();

    DMJson djsonUpdate = new DMJson(jsonUpdate);
    Set<String> stUpdate = djsonUpdate.keySet();
    Document documentUpdate = new Document();

    if (false == isEmpty(fieldList)) {
        if (false == fieldList.containsAll(stWhere)) {
            throw new DScabiException(
                    "One or more field name in jsonWhere doesn't exist in fieldNames list. jsonWhere : "
                            + jsonWhere + " Field Names list : " + fieldList,
                    "DBT.EUE.1");
        }//from   w w  w .  j  a  v a2 s. com
        if (false == fieldList.containsAll(stUpdate)) {
            throw new DScabiException(
                    "One or more field name in jsonUpdate doesn't exist in fieldNames list. jsonUpdate : "
                            + jsonUpdate + " Field Names list : " + fieldList,
                    "DBT.EUE.2");
        }
    }

    for (String keyWhere : stWhere) {
        // create a document to store key and value
        documentWhere.put(keyWhere, djsonWhere.getString(keyWhere));
    }

    for (String keyUpdate : stUpdate) {
        // create a document to store key and value
        documentUpdate.put(keyUpdate, djsonUpdate.getString(keyUpdate));
    }

    BasicDBObject updateObj = new BasicDBObject();
    updateObj.put("$set", documentUpdate);

    UpdateResult result = m_table.updateMany(documentWhere, updateObj);
    log.debug("executeUpdate() result is : {}", result.getModifiedCount());
    if (result.getModifiedCount() <= 0)
        throw new DScabiException("Update failed for documentWhere : " + documentWhere.toString()
                + " updateObj : " + updateObj.toString(), "DBT.EUE.3");

    return result.getModifiedCount();

}