List of usage examples for com.mongodb MongoClient getDB
@Deprecated public DB getDB(final String dbName)
From source file:com.intellijob.MongoConfiguration.java
License:Apache License
@Autowired @Bean//from ww w . j a v a 2 s .c om public Boolean doImportData(MongoClient mongoClient) throws IOException { DBCollection sys_import_collection = mongoClient.getDB(this.properties.getDatabase()) .getCollection(ApplicationSettings.COLLECTION_NAME); if (isProduction && sys_import_collection.count() == 0) { LOG.info("IMPORT DATA =============================================>"); //Import collection skill_caegories. loadCollectionSkillCategories(mongoClient); //Import languages loadSkillsData(mongoClient, "skill_languages.json", "skill_languages"); //Import knowledges loadSkillsData(mongoClient, "skill_knowledge.json", "skill_knowledges"); //Import personal strength loadSkillsData(mongoClient, "skill_personalstrengths.json", "skill_personalstrengths"); DBObject row = new BasicDBObject(); row.put(ApplicationSettings.FIELD_MONGO_DATA_IMPORTED, true); row.put(ApplicationSettings.FIELD_MONGO_DATA_IMPORTED_DATE, new Date()); row.put(ApplicationSettings.FIELD_ELASTIC_DATA_IMPORTED, false); row.put(ApplicationSettings.FIELD_ELASTIC_DATA_IMPORTED_DATE, null); sys_import_collection.insert(row); LOG.info("IMPORT DATA FINISHED!"); return true; } return false; }
From source file:com.intellijob.MongoConfiguration.java
License:Apache License
/** * Import collection skill_categories./* ww w .j a v a2 s .c o m*/ */ private void loadCollectionSkillCategories(MongoClient mongoClient) { InputStream inputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("imports/skills_categories.json"); String collectionName = "skill_categories"; try { LOG.info("LOAD {} DATA ....................................", collectionName); DBCollection col = mongoClient.getDB(this.properties.getDatabase()).getCollection(collectionName); List<Map<String, Object>> categories = new ObjectMapper().readValue(inputStream, TypeFactory.defaultInstance().constructCollectionType(List.class, HashMap.class)); for (Map<String, Object> category : categories) { DBObject dbObject = new BasicDBObject(category); dbObject.put("_id", new ObjectId(category.get("_id").toString())); col.insert(dbObject); } LOG.info("DONE!"); } catch (Exception e) { LOG.error("Collection (" + collectionName + ") could not be imported successfully!", e); } }
From source file:com.intellijob.MongoConfiguration.java
License:Apache License
/** * Import supported skill data./*from ww w . java 2 s. c o m*/ */ private void loadSkillsData(MongoClient mongoClient, String jsonFile, String collectionName) { try { LOG.info("LOAD {} DATA .........................................", collectionName); InputStream inputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("imports/" + jsonFile); DBCollection col = mongoClient.getDB(this.properties.getDatabase()).getCollection(collectionName); TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() { }; Map<String, Object> mapData = new ObjectMapper().readValue(inputStream, typeRef); setObjectIdRecursive(mapData); DBObject dbObject = new BasicDBObject(mapData); col.insert(dbObject); LOG.info("DONE!"); } catch (Exception e) { LOG.error("Collection (" + collectionName + ") could not be imported successfully!", e); } }
From source file:com.intuit.tweetstest.TweetsController.java
@RequestMapping(value = "/feed", method = RequestMethod.GET) protected String fetchFeeds(HttpServletRequest request, HttpServletResponse response) throws ParseException, ServletException, IOException, Exception { JSONObject result = new JSONObject(); String user = request.getParameter("user"); if (user != null && !user.isEmpty()) { String countStr = request.getParameter("count"); int count; // If count parameter is not sent in request, set it to 100 if (countStr != null && !countStr.isEmpty()) { count = Integer.parseInt(countStr); } else {/*ww w.j a v a2 s .c o m*/ count = 100; } // The access to the MongoDB should itself be a part of a separate // package with all the DB APIs wrapped around and published to the users. // Not doing it here to save some time. MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("tweetsdb"); DBCollection usersCollection = db.getCollection("userscollection"); // Not checking if the user is a valid user or not here. That's a // separate code flow on itself. DBObject query = new BasicDBObject("user", user); // Here I am retrieving the list of users the current user is following DBObject userDocument = usersCollection.findOne(query); if (userDocument == null) { result.put(user, "No such user"); result.put("isSuccess", false); sendResponse(response, result); return null; } JSONObject json = (JSONObject) new JSONParser().parse(userDocument.toString()); JSONArray following = (JSONArray) json.get("following"); // A sample of the following array looks like ["user4", "user3"] List<String> followingList = getFollowingList(following); // Once the following list is retrieved, the tweets of those users are // read from the db. JSONArray tweetsArray = retrieveTweetsFromDB(db, followingList, count); result.put("tweets", tweetsArray); result.put("isSuccess", true); } else { System.out.println("Missing user parameter in the request. Returning error"); result.put("Missing parameter", "user"); result.put("isSuccess", false); } sendResponse(response, result); return null; }
From source file:com.intuit.utils.PopulateTweets.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("tweetscollection"); WriteResult result = collection.remove(new BasicDBObject()); String[] users = { "user1", "user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9", "user10" }; // I am not introducing enough randomness in terms of the insertion of // tweets for users at a random time orders, due to lack of time. for (String user : users) { int tweetIndex = 0; for (int i = 1; i <= 10; i++) { BasicDBObject document = new BasicDBObject(); // This is a way to maintain uniqueness of the tweetid value across the system // Ideally, this should be the "_id" value, but due to lack of time, I am skipping // that part. That would help to partition the tweets across multiple shards in a // large scale system. String tweetId = user + "|tweet" + tweetIndex; document.put("tweetId", tweetId); document.put("user", user); document.put("text", "tweet number" + tweetIndex); document.put("tweetedOn", new Date().toString()); System.out.println("tweet number: " + tweetIndex + " " + document.toString()); collection.insert(document); tweetIndex++;//from ww w .j av a2s .c o m try { // Just introducing some delay between tweets to make the testing a bit easy Thread.sleep(3000); } catch (InterruptedException ex) { Logger.getLogger(PopulateTweets.class.getName()).log(Level.SEVERE, null, ex); } } } BasicDBObject indexObj = new BasicDBObject(); indexObj.put("user", 1); indexObj.put("tweetedOn", -1); collection.createIndex(indexObj); BasicDBObject tweetIdObj = new BasicDBObject(); tweetIdObj.put("tweetId", 1); collection.createIndex(tweetIdObj); }
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; }//from ww w.j a v a 2s . co m 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); // } }
From source file:com.janeluo.jfinalplus.plugin.monogodb.MongoKit.java
License:Apache License
public static void init(MongoClient client, String database) { MongoKit.client = client; MongoKit.defaultDb = client.getDB(database); }
From source file:com.javamongodb.utils.DatabaseUtils.java
public static DBCollection openDBConnection() { try {/*from ww w. j av a 2s . co m*/ MongoClient mongoClient = new MongoClient(HOST_NAME, PORT_NUMBER); //connect to the mongodb server logger.debug("MongoClient object created"); DB database = mongoClient.getDB(DATABASE_NAME); //connect to the database logger.debug("Database achieved"); //boolean auth = db.authenticate(myUserName, myPassword); DBCollection collection = database.getCollection(COLLECTION_NAME); if (collection == null) { collection = database.createCollection(COLLECTION_NAME, null); } logger.debug("Database collection achieved"); return collection; } catch (UnknownHostException | HeadlessException exception) { logger.error("Error opening database connection:\n" + exception.getMessage()); JOptionPane.showMessageDialog(new JFrame(), MessageUtils.MESSAGES.getString("error.while.saving.data"), MessageUtils.MESSAGES.getString("error.message"), JOptionPane.ERROR_MESSAGE); } return null; }
From source file:com.jive.myco.seyren.mongo.MongoStore.java
License:Apache License
@Inject public MongoStore(SeyrenConfig seyrenConfig) { try {//from ww w . j a va 2s . co m String uri = seyrenConfig.getMongoUrl(); MongoClientURI mongoClientUri = new MongoClientURI(uri); MongoClient mongoClient = new MongoClient(mongoClientUri); DB mongo = mongoClient.getDB(mongoClientUri.getDatabase()); mongo.setWriteConcern(WriteConcern.ACKNOWLEDGED); this.mongo = mongo; bootstrapMongo(); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.jjorgemoura.hangmanz.db.MongoDBManager.java
public static DB db() { MongoClient mc = MongoDBManager.engine(); List<String> databaseNames = mc.getDatabaseNames(); return mc.getDB(MONGODB_DB); }