List of usage examples for com.mongodb.client MongoCursor hasNext
@Override
boolean hasNext();
From source file:com.imaginea.mongodb.controllers.DocumentController.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.// w w w . j a v a2 s. c o m * * @param dbName Name of Database * @param collectionName Name of Collection * @param connectionId 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("allKeys") final Boolean allKeys, @QueryParam("connectionId") final String connectionId, @Context final HttpServletRequest request) { String response = new ResponseTemplate().execute(logger, connectionId, request, new ResponseCallback() { public Object execute() throws Exception { // Perform the operation here only. MongoClient mongoInstance = authService.getMongoInstance(connectionId); long count = mongoInstance.getDatabase(dbName).getCollection(collectionName).count(); FindIterable<Document> findIterable = mongoInstance.getDatabase(dbName) .getCollection(collectionName).find(); if (!allKeys) { findIterable.limit(10); } MongoCursor<Document> cursor = findIterable.iterator(); Set<String> completeSet = new HashSet<String>(); if (cursor.hasNext()) { while (cursor.hasNext()) { Document doc = cursor.next(); getNestedKeys(doc, completeSet, ""); } } completeSet.remove("_id"); JSONObject result = new JSONObject(); result.put("keys", completeSet); result.put("count", count); return result; } }); return response; }
From source file:com.imaginea.mongodb.services.impl.CollectionServiceImpl.java
License:Apache License
/** * Gets the list of collections present in a database in mongo to which user is connected to. * * @param dbName Name of database/*from w w w .j a va 2 s . co m*/ * @return List of All Collections present in MongoDb * @throws DatabaseException throw super type of UndefinedDatabaseException * @throws CollectionException exception while performing get list operation on collection */ public Set<String> getCollList(String dbName) throws DatabaseException, CollectionException { if (dbName == null || dbName.equals("")) { throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Invalid Database name"); } try { // List<String> dbList = databaseService.getDbList(); // if (!dbList.contains(dbName)) { // throw new DatabaseException(ErrorCodes.DB_DOES_NOT_EXISTS, // "Database with dbName [ " + dbName + "] does not exist"); // } MongoIterable<String> listCollectionNames = mongoInstance.getDatabase(dbName).listCollectionNames(); Set<String> collectionList = new HashSet<>(); MongoCursor<String> iterator = listCollectionNames.iterator(); while (iterator.hasNext()) { String colName = iterator.next(); if (colName.contains(".files") || colName.contains(".chunks")) { continue; } collectionList.add(colName); } // For a newly added database there will be no system.users, So we // are manually creating the system.users if (collectionList.contains("system.indexes") && !collectionList.contains("system.users")) { mongoInstance.getDatabase(dbName).createCollection("system.users"); collectionList.add("system.users"); } return collectionList; } catch (MongoException m) { throw new CollectionException(ErrorCodes.GET_COLLECTION_LIST_EXCEPTION, m.getMessage()); } }
From source file:com.imaginea.mongodb.services.impl.CollectionServiceImpl.java
License:Apache License
/** * Deletes a collection inside a database in mongo to which user is connected to. * * @param dbName Name of Database in which to insert a collection * @param collectionName Name of Collection to be inserted * @return Success if deletion is successful else throw exception * @throws DatabaseException throw super type of UndefinedDatabaseException * @throws ValidationException throw super type of * EmptyDatabaseNameException,EmptyCollectionNameException * @throws CollectionException throw super type of * UndefinedCollectionException,DeleteCollectionException *//* ww w . j a v a 2 s .com*/ private void createCollection(CreateCollectionOptions options, MongoCollection<Document> selectedCollection, String selectedCollectionName, MongoDatabase db) { db.createCollection(selectedCollectionName + "_temp", options); MongoCollection<Document> tempCollection = db.getCollection(selectedCollectionName + "_temp"); MongoCursor<Document> cur = selectedCollection.find().iterator(); while (cur.hasNext()) { Document obj = cur.next(); tempCollection.insertOne(obj); } MongoNamespace namespace = selectedCollection.getNamespace(); selectedCollection.drop(); tempCollection.renameCollection(namespace); }
From source file:com.imaginea.mongodb.services.impl.DatabaseServiceImpl.java
License:Apache License
/** * Gets the list of databases present in mongo database to which user is connected to. * * @return List of All Databases present in MongoDb * @throws DatabaseException If any error while getting database list. *//*from w ww.j a v a 2s. c o m*/ public List<String> getDbList() throws DatabaseException { try { Set<String> authenticatedDbNames = connectionDetails.getAuthenticatedDbNames(); if (!connectionDetails.isAdminLogin()) { return new ArrayList<String>(authenticatedDbNames); } List<String> dbs = new ArrayList<String>(); MongoCursor<String> dbsCursor = mongoInstance.listDatabaseNames().iterator(); while (dbsCursor.hasNext()) { dbs.add(dbsCursor.next()); } return dbs; } catch (MongoException m) { throw new DatabaseException(ErrorCodes.GET_DB_LIST_EXCEPTION, m.getMessage()); } }
From source file:com.imaginea.mongodb.services.impl.DocumentServiceImpl.java
License:Apache License
/** * Insert a document inside a collection in a database in mongo to which user is connected to. * * @param dbName Name of Database//from ww w . java2 s . com * @param collectionName Name of Collection from which to get all Documents * @param document : Document data to be inserted * @return : Insertion Status * @throws DatabaseException throw super type of UndefinedDatabaseException * @throws ValidationException throw super type of * EmptyDatabaseNameException,EmptyCollectionNameException ,EmptyDocumentDataException * @throws CollectionException throw super type of UndefinedCollectionException * @throws DocumentException throw super type of InsertDocumentException */ public String insertDocument(String dbName, String collectionName, Document document) throws DatabaseException, CollectionException, DocumentException, ValidationException { if (dbName == null) { throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database name is null"); } if (dbName.equals("")) { throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database Name Empty"); } if (collectionName == null) { throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Collection name is null"); } if (collectionName.equals("")) { throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Collection Name Empty"); } String result = null; try { // if (!databaseService.getDbList().contains(dbName)) { // throw new DatabaseException(ErrorCodes.DB_DOES_NOT_EXISTS, // "DB [" + dbName + "] DOES NOT EXIST"); // } MongoCursor<String> iterator = mongoInstance.getDatabase(dbName).listCollectionNames().iterator(); Set<String> collectionNames = null; if (iterator.hasNext()) { collectionNames = new HashSet<>(); while (iterator.hasNext()) { collectionNames.add(iterator.next()); } } if (!collectionNames.contains(collectionName)) { throw new CollectionException(ErrorCodes.COLLECTION_DOES_NOT_EXIST, "COLLECTION [ " + collectionName + "] _DOES_NOT_EXIST in Db [ " + dbName + "]"); } // MongoDb permits Duplicate document Insert mongoInstance.getDatabase(dbName).getCollection(collectionName).insertOne(document); result = "Inserted Document with Data : [" + document + "]"; } catch (MongoException e) { throw new DocumentException(ErrorCodes.DOCUMENT_CREATION_EXCEPTION, e.getMessage()); } return result; }
From source file:com.imaginea.mongodb.services.impl.GridFSServiceImpl.java
License:Apache License
private JSONObject executeFind(GridFSBucket gridFS, String query, String sortBy, String limit, String skip) throws JSONException { Document queryObj = Document.parse(query); Document sortObj = Document.parse(sortBy); int filesLimit = Integer.parseInt(limit); int filesSkip = Integer.parseInt(skip); // Partial Keys cant be fetched for a file MongoCursor<GridFSFile> it = gridFS.find(queryObj).sort(sortObj).skip(filesSkip).limit(filesLimit) .iterator();//from www .jav a2s . co m JSONArray fileList = new JSONArray(); while (it.hasNext()) { GridFSFile fsFile = it.next(); JSONObject file = new JSONObject(); file.put("_id", fsFile.getId().asObjectId().getValue()); file.put("fileName", fsFile.getFilename()); file.put("length", fsFile.getLength()); file.put("chunkSize", fsFile.getChunkSize()); file.put("uploadDate", fsFile.getUploadDate()); file.put("md5", fsFile.getMD5()); if (fsFile.getMetadata() != null) { file.put("metadata", fsFile.getMetadata()); } fileList.put(file); } JSONObject result = new JSONObject(); long count = fileList.length(); result.put("documents", fileList); result.put("editable", true); result.put("count", count); return result; }
From source file:com.imaginea.mongodb.services.impl.GridFSServiceImpl.java
License:Apache License
@Override public Set<String> getAllBuckets(String dbName) throws DatabaseException, CollectionException { if (dbName == null) { throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database name is null"); }//from w w w . j av a2 s . c om if (dbName.equals("")) { throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database Name Empty"); } // if (!databaseService.getDbList().contains(dbName)) { // throw new DatabaseException(ErrorCodes.DB_DOES_NOT_EXISTS, // "DB [" + dbName + "] DOES NOT EXIST"); // } MongoCursor<String> iterator = mongoInstance.getDatabase(dbName).listCollectionNames().iterator(); Set<String> bucketsList = new HashSet<String>(); if (iterator.hasNext()) { while (iterator.hasNext()) { String collection = iterator.next(); int pos = collection.lastIndexOf(".files"); if (pos > 0) { bucketsList.add(collection.substring(0, pos)); } } } return bucketsList; }
From source file:com.imaginea.mongodb.services.impl.SystemCollectionServiceImpl.java
License:Apache License
/** * Drops all the users from the given mongo db * * @param dbName Name of the database// w w w. j a v a 2 s . c om * @return Returns the success message that shown to the user * @throws DatabaseException throw super type of UndefinedDatabaseException */ @Override public String removeAllUsers(String dbName) throws ApplicationException { if (dbName == null) { throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database name is null"); } if (dbName.equals("")) { throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database Name Empty"); } MongoCursor<Document> users = mongoInstance.getDatabase(dbName).getCollection("system.users").find() .iterator(); if (users.hasNext()) { while (users.hasNext()) { try { Document user = users.next(); mongoInstance.getDatabase(dbName).getCollection("system.users").findOneAndDelete(user); } catch (MongoException e) { throw new ApplicationException(ErrorCodes.USER_DELETION_EXCEPTION, e.getMessage()); } } return "All users are dropped from the DB: " + dbName; } else { return "The DB:" + dbName + "does not have any users"; } }
From source file:com.imaginea.mongodb.services.impl.SystemCollectionServiceImpl.java
License:Apache License
/** * Gets indexes for a given collection in a mongo db * * @param dbName Name of the database the indexes should be listed * @param collectionName Name of the collection to which the index is to be listed * @return Returns the success message that shown to the user * @throws DatabaseException throw super type of UndefinedDatabaseException *///w w w . ja v a 2s .co m @Override public JSONObject getIndex(String dbName, String collectionName) throws ApplicationException { if (dbName == null) { throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database name is null"); } if (dbName.equals("")) { throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database Name Empty"); } if (collectionName == null) { throw new DatabaseException(ErrorCodes.COLLECTION_NAME_EMPTY, "Collection name is null"); } if (collectionName.equals("")) { throw new DatabaseException(ErrorCodes.COLLECTION_NAME_EMPTY, "Collection name is Empty"); } try { ListIndexesIterable<Document> result = mongoInstance.getDatabase(dbName).getCollection(collectionName) .listIndexes(); MongoCursor<Document> iterator = result.iterator(); List<Document> listOfIndexes = null; if (iterator.hasNext()) { listOfIndexes = new ArrayList<Document>(); while (iterator.hasNext()) { Document doc = iterator.next(); Document resultDoc = (Document) doc.get("key"); listOfIndexes.add(resultDoc); } } return ApplicationUtils.constructResponse(false, listOfIndexes.size(), listOfIndexes); } catch (MongoException e) { throw new ApplicationException(ErrorCodes.INDEX_ADDITION_EXCEPTION, e.getMessage()); } }
From source file:com.imaginea.mongodb.services.impl.SystemCollectionServiceImpl.java
License:Apache License
/** * Removes all the indexes from all the collections in a given mongo db * * @param dbName Name of the database/*w ww . j a v a 2s .c o m*/ * @return Returns the success message that shown to the user * @throws DatabaseException throw super type of UndefinedDatabaseException */ @Override public String removeIndexes(String dbName) throws ApplicationException { if (dbName == null) { throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database name is null"); } if (dbName.equals("")) { throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database Name Empty"); } MongoCursor<String> iterator = mongoInstance.getDatabase(dbName).listCollectionNames().iterator(); if (iterator.hasNext()) { while (iterator.hasNext()) { String collection = iterator.next(); try { mongoInstance.getDatabase(dbName).getCollection(collection).dropIndexes(); } catch (MongoException e) { throw new ApplicationException(ErrorCodes.INDEX_REMOVE_EXCEPTION, e.getMessage()); } } } return "All indexes are dropped from DB: " + dbName; }