List of usage examples for com.mongodb Mongo getDB
@Deprecated public DB getDB(final String dbName)
From source file:com.ikanow.aleph2.management_db.mongodb.utils.MongoDbCollectionUtils.java
License:Apache License
/** Finds the right database - iterates through DBs until it either finds the collection or not, if not then it finds the first DB with < 200 collections in it * @param client/*from w w w. j a v a2 s. c o m*/ * @param collection_name * @return */ public static DB findDatabase(final Mongo client, String db_name_prefix, String collection_name) { // Does the collection exist? Keep looking until we find an empty DB final Tuple3<Boolean, Boolean, DB> intermediate = IntStream.iterate(1, i -> i + 1).boxed() .map(ii -> db_name_prefix + "_" + ii).map(dbn -> client.getDB(dbn)).map(db -> { final boolean is_empty = db.getCollectionNames().isEmpty(); final boolean contains_names = !is_empty && db.collectionExists(collection_name); return Tuples._3T(is_empty, contains_names, db); }).filter(t3 -> t3._1() || t3._2()).findFirst().get(); //(guaranteed we'll either find an empty DB or one containing our collection) // If the collection doesn't exist, find the first available DB return intermediate._2() ? intermediate._3() : IntStream.iterate(1, i -> i + 1).boxed().map(ii -> db_name_prefix + "_" + ii) .map(dbn -> client.getDB(dbn)) .filter(db -> db.getCollectionNames().size() < MAX_COLLS_PER_DB).findFirst().get(); }
From source file:com.ikanow.infinit.e.data_model.store.MongoDbManager.java
License:Apache License
private static DB initializeFastWriteDB(String dbName, Mongo savedMongo) { DB db = savedMongo.getDB(dbName); //(keep performance in line with 2.4) db.setWriteConcern(WriteConcern.UNACKNOWLEDGED); return db;/*from w w w.j a v a2s . c o m*/ }
From source file:com.ikanow.infinit.e.utility.MongoEntityFeatureTxfer.java
License:Apache License
@SuppressWarnings("unused") private void doUnitTestCode(String sMongoDbHost, String sMongoDbPort, String sElasticHost, String sElasticPort, BasicDBObject query, int nLimit) { Mongo mongoDB = null; ElasticSearchManager elasticManager = null; try {/*ww w . j av a 2 s . c om*/ // Initialize the DB: mongoDB = new Mongo(sMongoDbHost, Integer.parseInt(sMongoDbPort)); DBCollection gazDB = mongoDB.getDB("feature").getCollection("entity"); // Initialize the ES (create the index if it doesn't already): // 1. Set-up the entity feature index String indexName = "entity_index"; //TEST: delete the index: // elasticManager = ElasticSearchManager.getIndex(indexName, sElasticHost + ":" + sElasticPort); // elasticManager.deleteMe(); //TEST: create the index // String sMapping = new Gson().toJson(new GazateerPojo.Mapping(), GazateerPojo.Mapping.class); // Builder localSettings = ImmutableSettings.settingsBuilder(); // localSettings.put("number_of_shards", 1).put("number_of_replicas", 0); q // elasticManager = ElasticSearchManager.createIndex // (indexName, false, // sElasticHost + ":" + sElasticPort, // sMapping, localSettings); //TEST: delete the index: // elasticManager.deleteMe(); //TEST: get the index: // elasticManager = ElasticSearchManager.getIndex(indexName, sElasticHost + ":" + sElasticPort); // Now query the DB: DBCursor dbc = null; if (nLimit > 0) { dbc = gazDB.find(query).limit(nLimit); } else { // Everything! dbc = gazDB.find(query); } Type listType = new TypeToken<ArrayList<EntityFeaturePojo>>() { }.getType(); List<EntityFeaturePojo> entities = new Gson().fromJson(dbc.toArray().toString(), listType); //Debug: List<String> entIds = new LinkedList<String>(); // Loop over array and invoke the cleansing function for each one for (EntityFeaturePojo ent : entities) { if (null != ent.getAlias()) { // (some corrupt gazateer entry) //Debug: //System.out.println("entity=" + ent.getGazateerIndex()); //System.out.println("aliases=" + Arrays.toString(ent.getAlias().toArray())); // Insert into the elasticsearch index //Debug: //System.out.println(new Gson().toJson(ent, GazateerPojo.class)); // Handle groups (system group is: "4c927585d591d31d7b37097a") if (null == ent.getCommunityId()) { ent.setCommunityId(new ObjectId("4c927585d591d31d7b37097a")); } //TEST: index documemt // ent.synchronizeWithIndex(); // boolean b = elasticManager.addDocument(ent, ent.getGazateerIndex(), true); //TEST: remove document //b = elasticManager.removeDocument(ent.getGazateerIndex()); //TEST: (part of get, bulk add/delete) entIds.add(ent.getIndex()); // Debug: // if (!b) { // System.out.println("Didn't add " + ent.getGazateerIndex()); // } } } // End loop over entities //TEST: bulk delete //elasticManager.bulkAddDocuments(entities, "index", null); //elasticManager.bulkDeleteDocuments(entIds); //TEST: get document // elasticManager.getRawClient().admin().indices().refresh(Requests.refreshRequest(indexName)).actionGet(); // for (String id: entIds) { // Map<String, GetField> results = elasticManager.getDocument(id,"doccount", "disambiguated_name"); // System.out.println(id + ": " + results.get("doccount").values().get(0) + " , " + results.get("disambiguated_name").values().get(0)); // } //TEST: search // elasticManager.getRawClient().admin().indices().refresh(Requests.refreshRequest(indexName)).actionGet(); // SearchRequestBuilder searchOptions = elasticManager.getSearchOptions(); // XContentQueryBuilder queryObj = QueryBuilders.matchAllQuery(); // searchOptions.addSort("doccount", SortOrder.DESC); // searchOptions.addFields("doccount", "type"); // SearchResponse rsp = elasticManager.doQuery(queryObj, searchOptions); // SearchHit[] docs = rsp.getHits().getHits(); // for (SearchHit hit: docs) { // String id = hit.getId(); // Long doccount = (Long) hit.field("doccount").value(); // String type = (String) hit.field("type").value(); // System.out.println(id + ": " + doccount + ", " + type); // } } catch (NumberFormatException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } finally { if (null != mongoDB) { mongoDB.close(); } if (null != elasticManager) { //NB not sure when exactly to call this - probably can just not bother? //elasticManager.getRawClient().close(); } } }
From source file:com.imaginea.mongodb.controllers.CollectionController.java
License:Apache License
/** * Maps GET Request to get list of collections inside databases 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. * * @param dbName Name of database * @param selectedCollection Name of selected Collection * @param connectionId Mongo Db Configuration provided by user to connect to. * @param request Get the HTTP request context to extract session parameters * @return String of JSON Format with list of all collections. *///from w w w. j a v a 2 s.co m @GET @Produces(MediaType.APPLICATION_JSON) @Path("/{collectionName}/isCapped") public String isCappedCollection(@PathParam("dbName") final String dbName, @PathParam("collectionName") final String selectedCollection, @QueryParam("connectionId") final String connectionId, @Context final HttpServletRequest request) { String response = new ResponseTemplate().execute(logger, connectionId, request, new ResponseCallback() { public Object execute() throws Exception { Mongo mongoInstance = AuthServiceImpl.getInstance().getMongoInstance(connectionId); return mongoInstance.getDB(dbName).getCollection(selectedCollection).isCapped(); } }); return response; }
From source file:com.imaginea.mongodb.controllers.StatisticsController.java
License:Apache License
/** * Get Statistics of Mongo Server./*from w w w . j av a 2s.co m*/ * * @param connectionId Mongo Db Configuration provided by user to connect to. * @param request Get the HTTP request context to extract session parameters * @return String of JSON Format with server Stats. */ @GET @Produces(MediaType.APPLICATION_JSON) public String getServerStats(@QueryParam("connectionId") final String connectionId, @Context final HttpServletRequest request) throws JSONException { String response = new ResponseTemplate().execute(logger, connectionId, request, new ResponseCallback() { public Object execute() throws Exception { Mongo mongoInstance = authService.getMongoInstance(connectionId); // Get Server Stats try { return mongoInstance.getDB("admin").command("serverStatus"); } catch (MongoException e) { throw new DatabaseException(ErrorCodes.GET_DB_STATS_EXCEPTION, e.getMessage()); } } }); return response; }
From source file:com.imaginea.mongodb.requestdispatchers.DocumentRequestDispatcher.java
License:Apache License
/** * Maps GET Request to get all keys of 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. * //from www .j a va 2 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 all keys in a collection. */ @GET @Path("/keys") @Produces(MediaType.APPLICATION_JSON) public String getKeysRequest(@PathParam("dbName") final String dbName, @PathParam("collectionName") final String collectionName, @QueryParam("dbInfo") final String dbInfo, @Context final HttpServletRequest request) { String response = new ResponseTemplate().execute(logger, dbInfo, request, new ResponseCallback() { public Object execute() throws Exception { // Perform the operation here only. Mongo mongoInstance = UserLogin.mongoConfigToInstanceMapping.get(dbInfo); DBCursor cursor = mongoInstance.getDB(dbName).getCollection(collectionName).find(); DBObject doc = new BasicDBObject(); Set<String> completeSet = new HashSet<String>(); while (cursor.hasNext()) { doc = cursor.next(); getNestedKeys(doc, completeSet, ""); } completeSet.remove("_id"); return completeSet; } }); return response; }
From source file:com.imaginea.mongodb.requestdispatchers.Graphs.java
License:Apache License
/** * Handles the HTTP <code>GET</code> method. * //from w w w.j a v a 2 s . c o m * @param request * servlet request * @param response * servlet response * @throws ServletException * if a servlet-specific error occurs * @throws IOException * if an I/O error occurs */ @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { // Declare Response Objects and PrintWriter response.setContentType("application/x-json"); PrintWriter out = response.getWriter(); final String dbInfo = request.getParameter("dbInfo"); String result = new ResponseTemplate().execute(logger, dbInfo, request, new ResponseCallback() { public Object execute() throws Exception { Mongo mongoInstance = UserLogin.mongoConfigToInstanceMapping.get(dbInfo); // Need a Db to get ServerStats DB db = mongoInstance.getDB("admin"); String uri = request.getRequestURI(); Object result = null; if (uri != null) { if (uri.substring(uri.lastIndexOf('/')).equals("/query")) { result = processQuery(db); } else if (uri.substring(uri.lastIndexOf('/')).equals("/initiate")) { if (request.getParameter("pollingTime") != null) { jump = Integer.parseInt(request.getParameter("pollingTime")); } result = processInitiate(db); } } return result; } }); out.write(result); }
From source file:com.imaginea.mongodb.requestdispatchers.StatisticsRequestDispatcher.java
License:Apache License
/** * Get Statistics of Mongo Server./* www . j a v a2 s. co m*/ * * @param dbInfo * Mongo Db Configuration provided by user to connect to. * @param request * Get the HTTP request context to extract session parameters * @return String of JSON Format with server Stats. */ @GET @Produces(MediaType.APPLICATION_JSON) public String getServerStats(@QueryParam("dbInfo") final String dbInfo, @Context final HttpServletRequest request) throws JSONException { String response = new ResponseTemplate().execute(logger, dbInfo, request, new ResponseCallback() { public Object execute() throws Exception { Mongo mongoInstance = UserLogin.mongoConfigToInstanceMapping.get(dbInfo); // Get Server Stats CommandResult cd = mongoInstance.getDB("admin").command("serverStatus"); return cd; } }); return response; }
From source file:com.imaginea.mongodb.requestdispatchers.UserLogin.java
License:Apache License
/** * Authenticates User by verifying Mongo config details against admin * database and authenticating user to that Db. A facility for guest login * is also allowed when both fields username and password are empty. * <p>/*from ww w .j a v a 2 s . c o m*/ * Also stores a mongo instance based on database configuration. * * @param request * Request made by user for authentication * @param user * Name of user as in admin database in mongo * @param password * password of user as in admin database in mongo * @param host * mongo host to connect to * @param mongoPort * mongo Port to connect to * * * */ @POST @Produces(MediaType.APPLICATION_JSON) public String authenticateUser(@FormParam("username") String user, @FormParam("password") final String password, @FormParam("host") String host, @FormParam("port") final String mongoPort, @Context final HttpServletRequest request) { // Reassign username for guest user in case of empty username and // password fields if ("".equals(user) && "".equals(password)) { user = "guest"; } if ("127.0.0.1".equals(host)) { host = "localhost"; // 1 key for both in map } final String mongoHost = host; final String username = user; String response = ErrorTemplate.execute(logger, new ResponseCallback() { public Object execute() throws Exception { if ("".equals(mongoHost) || "".equals(mongoPort)) { ApplicationException e = new ApplicationException(ErrorCodes.MISSING_LOGIN_FIELDS, "Missing Login Fields"); return formErrorResponse(logger, e); } Mongo m = new Mongo(mongoHost, Integer.parseInt(mongoPort)); boolean loginStatus = false; if ("guest".equals(username) && "".equals(password)) { loginStatus = true; } else { // Authorize User using <admin> Db DB db = m.getDB("admin"); loginStatus = db.authenticate(username, password.toCharArray()); } if (!loginStatus) { ApplicationException e = new ApplicationException(ErrorCodes.INVALID_USERNAME, "Invalid UserName or Password"); return formErrorResponse(logger, e); } // Add mongo Configuration Key to key dbInfo in session String mongoConfigKey = mongoHost + "_" + mongoPort; HttpSession session = request.getSession(); Object dbInfo = session.getAttribute("dbInfo"); if (dbInfo == null) { List<String> mongosInSession = new ArrayList<String>(); mongosInSession.add(mongoConfigKey); session.setAttribute("dbInfo", mongosInSession); } else { @SuppressWarnings("unchecked") List<String> mongosInSession = (List<String>) dbInfo; mongosInSession.add(mongoConfigKey); session.setAttribute("dbInfo", mongosInSession); } // Store a MongoInstance if (!mongoConfigToInstanceMapping.containsKey(mongoConfigKey)) { Mongo mongoInstance = new Mongo(mongoHost, Integer.parseInt(mongoPort)); mongoConfigToInstanceMapping.put(mongoConfigKey, mongoInstance); } Object usersPresent = mongoConfigToUsersMapping.get(mongoConfigKey); int noOfUsers = 0; if (usersPresent == null) { mongoConfigToUsersMapping.put(mongoConfigKey, noOfUsers); } noOfUsers = mongoConfigToUsersMapping.get(mongoConfigKey) + 1; mongoConfigToUsersMapping.put(mongoConfigKey, noOfUsers); String status = "Login Success"; return status; } }); return response; }
From source file:com.ineunet.knife.persist.mongo.MongoDBTemplate.java
License:Apache License
public MongoDBTemplate(String name) throws Exception { Mongo mongo = MongoManager.getMongoDBServer().getMongo(); Jongo jongo = new Jongo(mongo.getDB(MongoManager.getMongoDBServer().getDefaultDbName())); this.mc = jongo.getCollection(name); }