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:com.hangum.tadpole.mongodb.core.test.MongoTestReferenceCollection.java

License:Open Source License

public static void createRef1Collection(DB db, Object objId) {
    DBObject colInformation = (DBObject) JSON.parse("{capped:true, size:100000}");
    DBCollection ref2Coll = db.getCollection(REF_2);
    if (ref2Coll != null)
        ref2Coll.drop();//w w  w. ja v  a2  s  . co m
    ref2Coll = db.createCollection(REF_2, colInformation);

    BasicDBObject insertObj = new BasicDBObject();
    insertObj.put(REF_1 + "_id", objId);

    DBObject addField = new BasicDBObject();
    addField.put("name", "Reference id");

    insertObj.putAll(addField);

    //      DBObject dbObjRef2 = (DBObject) JSON.parse("{'ref1_id': 50f9437cf023f820730a3b42,  {'names': {'First': 'Gonza', 'Last': 'Vieira'}}}");
    ref2Coll.insert(insertObj);
}

From source file:com.hangum.tadpole.mongodb.core.test.MongoTestRunCommand.java

License:Open Source License

/**
 * @param args/*  w  w w  . j  ava 2s .c  o m*/
 */
public static void main(String[] args) throws Exception {
    ConAndAuthentication testMongoCls = new ConAndAuthentication();
    Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, 27017);//ConAndAuthentication.port);
    DB db = mongo.getDB("test");

    DBCollection dbColl = db.getCollection("user");

    DBObject cmdObj = (DBObject) JSON.parse("{language  : 'en_us'}, {seq: true, email:true}, {seq, -1}");
    DBCursor dbCur = dbColl.find(cmdObj);
    for (DBObject obj : dbCur.toArray()) {
        System.out.println(obj);
    }

    //      CommandResult cr = db.command(cmdObj);//new BasicDBObject("create", "hyunjong"));
    //      System.out.println( cr.toString() );      

    mongo.close();
}

From source file:com.hangum.tadpole.mongodb.core.test.MongoTestServerSideJavascript.java

License:Open Source License

/**
 * update java script//from w ww. j a v a2 s .  c o m
 * 
 * @param db
 * @param id
 * @param content
 */
private static void updateServerSideJavaScript(DB db, String id, String content) {
    DBObject dbFindObject = (DBObject) JSON.parse("{'_id':'" + id + "'}");
    DBObject dbUpdateObject = (DBObject) JSON.parse("{'_id':'" + id + "', 'value':'" + content + "'}");

    db.getCollection("system.js").findAndModify(dbFindObject, dbUpdateObject);

}

From source file:com.health.smart.util.MongoC.java

public static void insert(String collection, String document) throws Exception {
    DBCollection coll = getClient().getDB(database).getCollection(collection);
    coll.insert((DBObject) JSON.parse(document), WriteConcern.ACKNOWLEDGED);
}

From source file:com.health.smart.util.MongoC.java

public static void update(String collection, String document) throws Exception {
    DBCollection coll = getClient().getDB(database).getCollection(collection);
    DBObject docObj = (DBObject) JSON.parse(document);
    coll.update((DBObject) JSON.parse((String) docObj.get("criteria")),
            (DBObject) JSON.parse((String) docObj.get("update")));
}

From source file:com.health.smart.util.MongoC.java

public static String find(String collection, String document) throws Exception {
    DBCollection coll = getClient().getDB(database).getCollection(collection);
    DBObject docObj = (DBObject) JSON.parse(document);
    List<DBObject> objects;
    if (!docObj.containsField("projection")) {
        objects = coll.find((DBObject) JSON.parse((String) docObj.get("criteria"))).toArray();
    } else {//ww  w. ja va2  s  .c om
        objects = coll.find((DBObject) JSON.parse((String) docObj.get("criteria")),
                (DBObject) JSON.parse((String) docObj.get("projection"))).toArray();
    }
    return objects.toString();
}

From source file:com.ikanow.infinit.e.api.config.source.SourceInterface.java

License:Open Source License

/**
 * Represent the user object in the requested format.
 * /*from w  w w .  ja v  a 2s .  c o  m*/
 * @param variant
 * @return
 * @throws ResourceException
 */
@Get
public Representation get() throws ResourceException {
    ResponsePojo rp = new ResponsePojo();
    Date startTime = new Date();

    // If JSON is != null, check that it is valid JSON
    boolean isValidJson = true;
    if (json != null) {
        try {
            JSON.parse(json);
        } catch (Exception e) {
            rp.setResponse(new ResponseObject("Parsing JSON", false,
                    "The value passed via the json parameter could not be" + " parsed as valid JSON."));
            isValidJson = false;
        }
    }

    if (isValidJson) {
        if (needCookie) {
            cookieLookup = RESTTools.cookieLookup(cookie);

            if (cookieLookup == null) {
                rp = new ResponsePojo();
                rp.setResponse(new ResponseObject("Cookie Lookup", false,
                        "Cookie session expired or never existed, please login first"));
            } else {
                // Every call needs communityid so check now

                boolean validCommunities = ((communityid == null) || communityid.startsWith("*")) ? true : // (in this case, we apply the regex to user communities, so don't need to validate)
                        SocialUtils.validateCommunityIds(cookieLookup, communityid);

                if (validCommunities == false) {
                    rp = new ResponsePojo();
                    rp.setResponse(new ResponseObject("Verifying Communities", false,
                            "Community IDs are not valid for this user"));
                } else {
                    if (action.equals("saveSource")) {
                        rp = this.source.saveSource(json, cookieLookup, communityid);
                    } else if (action.equals("testSource")) {
                        rp = this.source.testSource(json, nNumDocsToReturn, bReturnFullText, bRealDedup,
                                cookieLookup);
                    } else if (action.equals("add")) {
                        rp = this.source.addSource(sourcetitle, sourcedesc, sourceurl, extracttype, sourcetags,
                                mediatype, communityid, cookieLookup);
                    } else if (action.equals("info")) {
                        rp = this.source.getInfo(sourceid, cookieLookup);
                    } else if (action.equals("good")) {
                        rp = this.source.getGoodSources(cookieLookup, communityid, bStripped);
                    } else if (action.equals("bad")) {
                        rp = this.source.getBadSources(cookieLookup, communityid, bStripped);
                    } else if (action.equals("pending")) {
                        rp = this.source.getPendingSources(cookieLookup, communityid, bStripped);
                    } else if (action.equals("user")) {
                        rp = this.source.getUserSources(cookieLookup, bStripped);
                    } else if (action.equals("delete") || action.equals("deletedocs")) {
                        rp = this.source.deleteSource(sourceid, communityid, cookieLookup,
                                action.equals("deletedocs"));
                    } else if (action.equals("suspend")) {
                        rp = this.source.suspendSource(sourceid, communityid, cookieLookup, shouldSuspend);
                    }
                }
            } // (end communities valid)
        } // (End login succeeded)
    }

    Date endTime = new Date();
    rp.getResponse().setTime(endTime.getTime() - startTime.getTime());
    if (!rp.getResponse().isSuccess()) {
        if (rp.getResponse().getMessage().contains("ermission")) { // likely to be a permissions error
            RESTTools.logRequest(this);
        }
    } //TOTEST (TODO-2194)
    return new StringRepresentation(rp.toApi(), MediaType.APPLICATION_JSON);
}

From source file:com.ikanow.infinit.e.api.knowledge.aliases.AliasLookupTable.java

License:Open Source License

private void populateAliasTableFromShare(SharePojo share) {
    String json = share.getShare();
    if (null != json) {
        try {//from w  w  w.j a va  2  s . c om
            DBObject dbo = (DBObject) JSON.parse(json);
            if (null != dbo) {
                for (Object entryObj : dbo.toMap().entrySet()) {
                    @SuppressWarnings("unchecked")
                    Map.Entry<String, Object> entry = (Map.Entry<String, Object>) entryObj;

                    String masterAlias = entry.getKey();
                    EntityPojo masterAliasEntity = new EntityPojo();
                    masterAliasEntity.setIndex(masterAlias);

                    BasicDBObject entityFeatureObj = (BasicDBObject) entry.getValue();
                    EntityFeaturePojo aliasInfo = null;
                    try {
                        aliasInfo = EntityFeaturePojo.fromDb(entityFeatureObj, EntityFeaturePojo.class);
                    } catch (Exception e) {
                        logger.debug("Failed to deserialize aliasInfo", e);
                    }

                    if (masterAlias.endsWith("/")) { // it's a regex
                        try {
                            Pattern key = Pattern.compile(masterAlias.substring(0, masterAlias.length() - 1));
                            if (null == _entityRegexes) {
                                _entityRegexes = new HashMap<Pattern, EntityFeaturePojo>();
                            }
                            _entityRegexes.put(key, aliasInfo);
                        } catch (Exception e) {
                        } // ignore regex compile fails
                        continue;
                    }

                    if ((null != aliasInfo) && (null != aliasInfo.getAlias())) {
                        aliasInfo.setIndex(masterAlias);
                        if ((null == aliasInfo.getDimension()) && (null != aliasInfo.getType())) {
                            aliasInfo.setDimension(DimensionUtility.getDimensionByType(aliasInfo.getType()));
                        } //TESTED

                        logger.debug("aliasTable entry: " + aliasInfo.getIndex() + " vs "
                                + Arrays.toString(aliasInfo.getAlias().toArray()));

                        // This is going to collide in an ugly fashion across multiple communities, 
                        // we just have to live with that
                        for (String aliasIndex : aliasInfo.getAlias()) {
                            _aliasTable.put(aliasIndex, aliasInfo);
                        }
                        _aliasTable.put(aliasInfo.getIndex(), aliasInfo);
                        EntityFeaturePojo currAlias = _reverseAliasTable.get(aliasInfo.getIndex());
                        if (null == currAlias) {
                            _reverseAliasTable.put(aliasInfo.getIndex(), aliasInfo);
                        } else { // Collision ... this we can handle a little-bit more elegantly
                            currAlias.getAlias().addAll(aliasInfo.getAlias());
                            _reverseAliasTable.put(aliasInfo.getIndex(), currAlias);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.debug("General Aliasing Error: ", e);

        } // not Json, just carry on...
    }
}

From source file:com.ikanow.infinit.e.api.social.sharing.ShareInterface.java

License:Open Source License

/**
 * //from   w w w .  ja  v a2  s  .co m
 */
@Get
public Representation get() {
    ResponsePojo rp = new ResponsePojo();
    Date startTime = new Date();
    cookieLookup = RESTTools.cookieLookup(cookie);

    // If JSON is != null, check that it is valid JSON
    boolean isValidJson = true;
    if (json != null) {
        try {
            JSON.parse(json);
        } catch (Exception e) {
            rp.setResponse(new ResponseObject("Parsing JSON", false,
                    "The value passed via the json parameter could not be" + " parsed as valid JSON."));
            isValidJson = false;
        }

        try {
            checkForBadCharacters(json);
        } catch (Exception e) {
            rp.setResponse(new ResponseObject("Parsing JSON", false,
                    "The value passed via the json parameter has invalid characters: " + e.getMessage()));
            isValidJson = false;
        }
    }

    if (isValidJson) {
        if (cookieLookup == null) {
            // User is not logged in
            rp.setResponse(new ResponseObject("Cookie Lookup", false,
                    "Cookie session expired or never existed, please login first"));
        } else {
            // UserId which will serve as the OwnerId for transactions below that require it
            personId = cookieLookup;

            if (action.equals("saveJson")) {
                rp = this.shareController.saveJson(personId, id, type, title, description, json);
            } else if (action.equals("addBinaryGET")) {
                rp = new ResponsePojo(
                        new ResponseObject("addBinary", false, "Can only add binary in POST (do not use GET)"));
            } else if (action.equals("addBinaryPOST")) {
                rp = this.shareController.addBinary(personId, "binary", title, description,
                        this.getRequest().getEntity().getMediaType().toString(), binaryData);
            } else if (action.equals("updateBinaryGET")) {
                rp = new ResponsePojo(new ResponseObject("updateBinary", false,
                        "Can only update binary in POST (do not use GET)"));
            } else if (action.equals("updateBinaryPOST")) {
                rp = this.shareController.updateBinary(personId, id, "binary", title, description,
                        this.getRequest().getEntity().getMediaType().toString(), binaryData);
            } else if (action.equals("addRef")) {
                rp = this.shareController.addRef(personId, type, documentLoc, documentId, title, description);
            } else if (action.equals("updateRef")) {
                rp = this.shareController.updateRef(personId, id, type, documentLoc, documentId, title,
                        description);
            } else if (action.equals("removeShare")) {
                rp = this.shareController.removeShare(personId, shareId);
            } else if (action.equals("endorseShare")) {
                rp = this.shareController.endorseShare(personId, communityId, shareId, isEndorsed);
            } else if (action.equals("addCommunity")) {
                rp = this.shareController.addCommunity(personId, shareId, communityId, comment, readWrite);
            } else if (action.equals("removeCommunity")) {
                rp = this.shareController.removeCommunity(personId, shareId, communityId);
            } else if (action.equals("getShare")) {
                rp = this.shareController.getShare(personId, shareId, returnContent);
                SharePojo share = (SharePojo) rp.getData();
                if (null != share) {
                    boolean bBinary = share.getType().equals("binary");
                    if (bBinary && returnContent) {
                        try {
                            ByteArrayOutputRepresentation rep = new ByteArrayOutputRepresentation(
                                    MediaType.valueOf(share.getMediaType()));
                            rep.setOutputBytes(share.getBinaryData());
                            return rep;
                        } catch (Exception ex) {
                            rp = new ResponsePojo(new ResponseObject("get Share", false,
                                    "error converting bytes to output: " + ex.getMessage()));
                        }
                    } else if (!bBinary && jsonOnly) {
                        try {
                            BasicDBObject dbo = (BasicDBObject) com.mongodb.util.JSON.parse(share.getShare());
                            rp.setData(dbo, null);
                        } catch (Exception e) { // Try a list instead
                            BasicDBList dbo = (BasicDBList) com.mongodb.util.JSON.parse(share.getShare());
                            rp.setData(dbo, (BasePojoApiMap<BasicDBList>) null);
                        }
                    }
                }
                //(else error)
            } else if (action.equals("searchShares")) {
                rp = this.shareController.searchShares(personId, searchby, id, type, skip, limit, ignoreAdmin,
                        returnContent, searchParent);
            }
        }
    }

    Date endTime = new Date();
    rp.getResponse().setTime(endTime.getTime() - startTime.getTime());
    if (!rp.getResponse().isSuccess()) {
        if (rp.getResponse().getMessage().contains("ermission")) { // likely to be a permissions error
            RESTTools.logRequest(this);
        }
    } //TOTEST (TODO-2194)
    return new StringRepresentation(rp.toApi(), MediaType.APPLICATION_JSON);
}

From source file:com.ikanow.infinit.e.data_model.driver.InfiniteDriver.java

License:Apache License

public Set<String> updateAliases(Collection<EntityFeaturePojo> aliasesToUpdate, String communityIdStr,
        boolean bUpsert, Map<String, List<SharePojo>> aliasMapping, ResponseObject response) {
    if (null == aliasMapping) {
        aliasMapping = new HashMap<String, List<SharePojo>>();
        this.getAliases(communityIdStr, aliasMapping, response);
        if (!response.isSuccess()) {
            return null;
        }/* w w  w .  j  a v a2  s.co  m*/
    } //TESTED
    Map<ObjectId, BasicDBObject> shareContentCache = new HashMap<ObjectId, BasicDBObject>();
    List<SharePojo> sharesToUpdate = new LinkedList<SharePojo>();
    // Step through the aliases, update the content
    // Loop 1 update
    SharePojo shareForNewAliases = null;
    Set<String> erroredAliases = new HashSet<String>();
    HashMultimap<ObjectId, String> shareToAliasMapping = HashMultimap.create();
    for (EntityFeaturePojo alias : aliasesToUpdate) {
        List<SharePojo> sharesForThisAlias = aliasMapping.get(alias.getIndex());
        if ((null == sharesForThisAlias) && bUpsert) { // This is a new alias and not ignoring upserts
            if (null == shareForNewAliases) { // Haven't yet assigned such a share
                shareForNewAliases = this.upsertSharePrep(communityIdStr, shareContentCache, aliasMapping);
                if (null == shareForNewAliases) {
                    erroredAliases.add(alias.getIndex());
                    continue;
                }
                sharesToUpdate.add(shareForNewAliases);
            }
            BasicDBObject shareContent = shareContentCache.get(shareForNewAliases.get_id()); // (exists by construction)
            shareContent.put(alias.getIndex(), alias.toDb());
            shareToAliasMapping.put(shareForNewAliases.get_id(), alias.getIndex());
        } //TESTED
        else if (null != sharesForThisAlias) {
            for (SharePojo share : sharesForThisAlias) {
                BasicDBObject shareContent = shareContentCache.get(share.get_id());
                if (null == shareContent) {
                    try {
                        String json = share.getShare();
                        shareContent = (BasicDBObject) JSON.parse(json);
                        shareContentCache.put(share.get_id(), shareContent);
                        sharesToUpdate.add(share);
                    } catch (Exception e) {
                        erroredAliases.add(alias.getIndex());
                    }
                } //TESTED
                shareContent.put(alias.getIndex(), alias.toDb());
                shareToAliasMapping.put(share.get_id(), alias.getIndex());
            } //TESTED
        } else {
            erroredAliases.add(alias.getIndex());
        }
        // end loop over updating shares
    } //end loop over aliases

    // Loop 2 now update all the shares
    boolean bSucceededUpdatingSomething = false;
    for (SharePojo share : sharesToUpdate) {
        BasicDBObject shareContent = shareContentCache.get(share.get_id()); // (exists by construction)
        String shareIdStr = share.get_id().toString();
        this.updateShareJSON(shareIdStr, share.getTitle(), share.getDescription(), "infinite-entity-alias",
                shareContent.toString(), response);
        bSucceededUpdatingSomething |= response.isSuccess();
        if (!response.isSuccess()) {
            Set<String> failedAliases = shareToAliasMapping.get(share.get_id());
            if (null != failedAliases) {
                erroredAliases.addAll(failedAliases);
            }
        }
    } //TESTED      

    response.setSuccess(bSucceededUpdatingSomething);
    return erroredAliases;
}