List of usage examples for com.mongodb.util JSON parse
public static Object parse(final String jsonString)
Parses a JSON string and returns a corresponding Java object.
From source file:com.ikanow.infinit.e.data_model.driver.InfiniteDriver.java
License:Apache License
public Set<String> removeAliases(Collection<String> aliasesToRemove, String communityIdStr, 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 a 2 s.c o 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 Set<String> erroredAliases = new HashSet<String>(); HashMultimap<ObjectId, String> shareToAliasMapping = HashMultimap.create(); for (String alias : aliasesToRemove) { List<SharePojo> sharesForThisAlias = aliasMapping.get(alias); 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); } } //TESTED shareContent.remove(alias); shareToAliasMapping.put(share.get_id(), alias); } //TESTED } // 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(); if (shareContent.isEmpty()) { // Remove the share this.removeShare(shareIdStr, response); if (!response.isSuccess()) { Set<String> failedAliases = shareToAliasMapping.get(share.get_id()); if (null != failedAliases) { erroredAliases.addAll(failedAliases); } } } //TESTED else { 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 } //TESTED response.setSuccess(bSucceededUpdatingSomething); return erroredAliases; }
From source file:com.ikanow.infinit.e.data_model.driver.InfiniteDriver.java
License:Apache License
private SharePojo upsertSharePrep(String communityIdStr, Map<ObjectId, BasicDBObject> shareContentCache, Map<String, List<SharePojo>> aliasMapping) { SharePojo shareForNewAliases = null; BasicDBObject contentForNewAliases = null; for (List<SharePojo> shares : aliasMapping.values()) { if (!shares.isEmpty()) { shareForNewAliases = shares.iterator().next(); try { String json = shareForNewAliases.getShare(); contentForNewAliases = (BasicDBObject) JSON.parse(json); shareContentCache.put(shareForNewAliases.get_id(), contentForNewAliases); break; } catch (Exception e) { } // Try a different share }/*from w ww .j a v a 2s .c o m*/ } //TESTED if (null == shareForNewAliases) { // Didn't find one, so going to have to create something EntityFeaturePojo discard = new EntityFeaturePojo(); discard.setDisambiguatedName("DISCARD"); discard.setType("SPECIAL"); discard.setIndex("DISCARD"); EntityFeaturePojo docDiscard = new EntityFeaturePojo(); docDiscard.setDisambiguatedName("DOCUMENT_DISCARD"); docDiscard.setType("SPECIAL"); docDiscard.setIndex("DOCUMENT_DISCARD"); contentForNewAliases = new BasicDBObject("DISCARD", discard.toDb()); contentForNewAliases.put("DOCUMENT_DISCARD", docDiscard); ResponseObject response = new ResponseObject(); shareForNewAliases = this.addShareJSON("Alias Share: " + communityIdStr, "An alias share for a specific community", "infinite-entity-alias", "{}", response); if ((null == shareForNewAliases) || !response.isSuccess()) { return null; } //TESTED // Remove share from personal community try { ShareCommunityPojo currCommunity = shareForNewAliases.getCommunities().iterator().next(); String removeCommunityIdStr = currCommunity.get_id().toString(); if (!communityIdStr.equals(removeCommunityIdStr)) { // (obv not if this is my community somehow, don't think that's possible) this.removeShareFromCommunity(shareForNewAliases.get_id().toString(), removeCommunityIdStr, response); if (!response.isSuccess()) { return null; } } } catch (Exception e) { } // do nothing I guess, not in any communities? this.addShareToCommunity(shareForNewAliases.get_id().toString(), "aliasComm", communityIdStr, response); if (!response.isSuccess()) { return null; } } //TESTED shareContentCache.put(shareForNewAliases.get_id(), contentForNewAliases); return shareForNewAliases; }
From source file:com.ikanow.infinit.e.data_model.driver.InfiniteDriver.java
License:Apache License
private void populateAliasTableFromShare(SharePojo share, HashMap<String, EntityFeaturePojo> masterAliases, Map<String, List<SharePojo>> aliasMapping) { String json = share.getShare(); if (null != json) { try {//from w w w .ja v a 2 s. c o m 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(); BasicDBObject entityFeatureObj = (BasicDBObject) entry.getValue(); EntityFeaturePojo aliasInfo = null; try { aliasInfo = EntityFeaturePojo.fromDb(entityFeatureObj, EntityFeaturePojo.class); } catch (Exception e) { continue; } if (null == aliasInfo.getIndex()) { aliasInfo.setIndex(masterAlias); } if (null != aliasInfo) { // (allow getAlias to be null/empty) //(overwrite duplicates) masterAliases.put(aliasInfo.getIndex(), aliasInfo); if (null != aliasMapping) { List<SharePojo> shareList = aliasMapping.get(aliasInfo.getIndex()); if (null == shareList) { shareList = new LinkedList<SharePojo>(); aliasMapping.put(aliasInfo.getIndex(), shareList); } shareList.add(share); } } } } } catch (Exception e) { } // not Json, just carry on... } }
From source file:com.imaginea.mongodb.requestdispatchers.DocumentRequestDispatcher.java
License:Apache License
/** * Maps GET Request to get list of documents inside a collection inside a * database present in mongo db to a service function that returns the list. * Also forms the JSON response for this request and sent it to client. In * case of any exception from the service files an error object if formed. * /*from w ww .j a v a2 s .c om*/ * @param dbName * Name of Database * @param collectionName * Name of Collection * @param dbInfo * Mongo Db Configuration provided by user to connect to. * @param request * Get the HTTP request context to extract session parameters * @return A String of JSON format with list of All Documents in a * collection. */ @GET @Produces(MediaType.APPLICATION_JSON) public String getQueriedDocsList(@PathParam("dbName") final String dbName, @PathParam("collectionName") final String collectionName, @QueryParam("query") final String query, @QueryParam("dbInfo") final String dbInfo, @QueryParam("fields") String keys, @QueryParam("limit") final String limit, @QueryParam("skip") final String skip, @Context final HttpServletRequest request) throws JSONException { // Get all fields with "_id" in case of keys = null if (keys == null) { keys = ""; } final String fields = keys; String response = new ResponseTemplate().execute(logger, dbInfo, request, new ResponseCallback() { public Object execute() throws Exception { DocumentService documentService = new DocumentServiceImpl(dbInfo); // Get query DBObject queryObj = (DBObject) JSON.parse(query); StringTokenizer strtok = new StringTokenizer(fields, ","); DBObject keyObj = new BasicDBObject(); while (strtok.hasMoreElements()) { keyObj.put(strtok.nextToken(), 1); } int docsLimit = Integer.parseInt(limit); int docsSkip = Integer.parseInt(skip); ArrayList<DBObject> documentList = documentService.getQueriedDocsList(dbName, collectionName, queryObj, keyObj, docsLimit, docsSkip); return documentList; } }); return response; }
From source file:com.imaginea.mongodb.requestdispatchers.DocumentRequestDispatcher.java
License:Apache License
/** * Maps POST Request to perform operations like update/delete/insert * document inside a collection inside a database present in mongo db to a * service function that returns the list. Also forms the JSON response for * this request and sent it to client. In case of any exception from the * service files an error object if formed. * // ww w.j ava2s . c o m * @param dbName * Name of Database * @param collectionName * Name of Collection * @param documentData * Contains the document to be inserted * @param _id * Object id of document to delete or update * @param keys * new Document values in case of update * @param action * Query Paramater with value PUT for identifying a create * database request and value DELETE for dropping a database. * @param dbInfo * Mongo Db Configuration provided by user to connect to. * @param request * Get the HTTP request context to extract session parameters * @return String with Status of operation performed. */ @POST @Produces(MediaType.APPLICATION_JSON) public String postDocsRequest(@PathParam("dbName") final String dbName, @PathParam("collectionName") final String collectionName, @DefaultValue("POST") @QueryParam("action") final String action, @FormParam("document") final String documentData, @FormParam("_id") final String _id, @FormParam("keys") final String keys, @QueryParam("dbInfo") final String dbInfo, @Context final HttpServletRequest request) { String response = new ResponseTemplate().execute(logger, dbInfo, request, new ResponseCallback() { public Object execute() throws Exception { DocumentService documentService = new DocumentServiceImpl(dbInfo); String result = null; RequestMethod method = null; for (RequestMethod m : RequestMethod.values()) { if ((m.toString()).equals(action)) { method = m; break; } } switch (method) { case PUT: { if ("".equals(documentData)) { UndefinedDocumentException e = new UndefinedDocumentException( "Document Data Missing in Request Body"); result = formErrorResponse(logger, e); } else { DBObject document = (DBObject) JSON.parse(documentData); result = documentService.insertDocument(dbName, collectionName, document); } break; } case DELETE: { if ("".equals(_id)) { UndefinedDocumentException e = new UndefinedDocumentException( "Document Data Missing in Request Body"); result = formErrorResponse(logger, e); } else { ObjectId id = new ObjectId(_id); result = documentService.deleteDocument(dbName, collectionName, id); } break; } case POST: { if ("".equals(_id) || "".equals(keys)) { UndefinedDocumentException e = new UndefinedDocumentException( "Document Data Missing in Request Body"); formErrorResponse(logger, e); } else { // Id of Document to update ObjectId id = new ObjectId(_id); // New Document Keys DBObject newDoc = (DBObject) JSON.parse(keys); result = documentService.updateDocument(dbName, collectionName, id, newDoc); } break; } default: { result = "Action parameter value is wrong"; break; } } return result; } }); return response; }
From source file:com.impetus.client.mongodb.MongoDBClient.java
License:Apache License
/** * Parses the map reduce command.//from ww w.ja va 2 s . co m * * @param jsonClause * the json clause * @return the map reduce command */ private MapReduceCommand parseMapReduceCommand(String jsonClause) { String collectionName = jsonClause.replaceFirst("(?ms).*?\\.\\s*(.+?)\\s*\\.\\s*mapReduce\\s*\\(.*", "$1"); if (collectionName.contains("getCollection")) { collectionName = collectionName.replaceFirst(".*getCollection\\s*\\(\\s*(['\"])([^'\"]+)\\1\\s*\\).*", "$2"); } DBCollection collection = mongoDb.getCollection(collectionName); String body = jsonClause.replaceFirst("^(?ms).*?mapReduce\\s*\\(\\s*(.*)\\s*\\)\\s*;?\\s*$", "$1"); String mapFunction = findCommaSeparatedArgument(body, 0).trim(); String reduceFunction = findCommaSeparatedArgument(body, 1).trim(); String query = findCommaSeparatedArgument(body, 2).trim(); DBObject parameters = (DBObject) JSON.parse(query); DBObject mongoQuery; if (parameters.containsField("query")) { mongoQuery = (DBObject) parameters.get("query"); } else { mongoQuery = new BasicDBObject(); } return new MapReduceCommand(collection, mapFunction, reduceFunction, null, MapReduceCommand.OutputType.INLINE, mongoQuery); }
From source file:com.impetus.client.mongodb.MongoDBClient.java
License:Apache License
/** * Parses the and scroll./*from ww w. j a v a2 s. co m*/ * * @param jsonClause * the json clause * @param collectionName * the collection name * @return the DB cursor * @throws JSONParseException * the JSON parse exception */ private DBCursor parseAndScroll(String jsonClause, String collectionName) throws JSONParseException { BasicDBObject clause = (BasicDBObject) JSON.parse(jsonClause); DBCursor cursor = mongoDb.getCollection(collectionName).find(clause); return cursor; }
From source file:com.impetus.spark.client.MongoSparkClient.java
License:Apache License
/** * Generate bson from java object.//w w w . j a v a 2s . co m * * @param obj * the obj * @return the BSON object */ protected BSONObject generateBSONFromJavaObject(Object obj) { ObjectWriter ow = new ObjectMapper().writer(); String json = null; try { json = ow.writeValueAsString(obj); return (BSONObject) JSON.parse(json); } catch (JsonGenerationException | JsonMappingException e) { throw new KunderaException( "Error in converting BSON Object from Java Object due to error in JSON generation/mapping. Caused BY:", e); } catch (IOException e) { throw new KunderaException("Error in converting BSON Object from Java Object. Caused BY:", e); } }
From source file:com.indeed.iupload.core.authentification.FileBasedUserPermissionProvider.java
License:Apache License
@Override @Scheduled(cron = "* */5 * * * *") public void reload() throws IOException { InputStream is = userPermissionConfigLoader.getConfigJsonStream(); try {//from w w w .jav a 2s . co m DBObject configRoot = (DBObject) JSON.parse(getContent(is)); setUp(configRoot); } finally { Closeables2.closeQuietly(is, logger); } logger.info("Reloaded auth configuration."); }
From source file:com.intuit.utils.PopulateUsers.java
public static void main(String[] args) { Date now = new Date(); System.out.println("Current date is: " + now.toString()); MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("tweetsdb"); DBCollection collection = db.getCollection("userscollection"); WriteResult result = collection.remove(new BasicDBObject()); int userIndex = 1; for (int i = 1; i <= 10; i++) { JSONObject userDocument = new JSONObject(); String user = "user" + userIndex; userDocument.put("user", user); JSONArray followerList = new JSONArray(); Random randomGenerator = new Random(); for (int j = 0; j < 3; j++) { int followerId = randomGenerator.nextInt(10) + 1; // Assumption here is, a user will not be a follower on himself while (followerId == userIndex) { followerId = randomGenerator.nextInt(10) + 1; }/* w ww . j av a 2 s .c om*/ String follower = "user" + followerId; if (!followerList.contains(follower)) { followerList.add(follower); } } userDocument.put("followers", followerList); JSONArray followingList = new JSONArray(); for (int k = 0; k < 3; k++) { int followingId = randomGenerator.nextInt(10) + 1; // Assumption here is, a user will not be following his own tweets while (followingId == userIndex) { followingId = randomGenerator.nextInt(10) + 1; } String followingUser = "user" + followingId; if (!followingList.contains(followingUser)) { followingList.add(followingUser); } } userDocument.put("following", followingList); System.out.println("Json string is: " + userDocument.toString()); DBObject userDBObject = (DBObject) JSON.parse(userDocument.toString()); collection.insert(userDBObject); userIndex++; } // try { // FileWriter file = new FileWriter("/Users/dmurty/Documents/MongoData/usersCollection.js"); // file.write(usersArray.toJSONString()); // file.flush(); // file.close(); // } catch (IOException ex) { // Logger.getLogger(PopulateUsers.class.getName()).log(Level.SEVERE, null, ex); // } }