List of usage examples for com.mongodb.client MongoCursor close
@Override
void close();
From source file:org.iotivity.cloud.rdserver.MongoDB.java
License:Open Source License
/** * API for finding resources matched filterValue of filterKey and a * particular device ID in collection/* ww w. j a v a2 s .co m*/ * * @param di * device id * @param filterKey * field name in collection * @param filterValue * field value about field name * @param tablename * collection name * @return ArrayList<PublishPayloadFormat> - array list of resource * information */ public ArrayList<PublishPayloadFormat> readResourceAboutDid(String di, String filterKey, String filterValue, String tablename) { MongoCollection<Document> collection = db.getCollection(tablename); ArrayList<PublishPayloadFormat> resourceFormatList = new ArrayList<PublishPayloadFormat>(); MongoCursor<Document> cursor = collection .find(Filters.and(Filters.eq(Constants.RS_DEVICE_ID, di), Filters.eq(filterKey, filterValue))) .iterator(); try { while (cursor.hasNext()) { Document doc = cursor.next(); resourceFormatList.add(convertDocumentToResourceFormat(doc)); } } finally { cursor.close(); } return resourceFormatList; }
From source file:org.opencb.commons.datastore.mongodb.MongoDBCollection.java
License:Apache License
private <T> QueryResult<T> privateFind(Bson query, Bson projection, Class<T> clazz, ComplexTypeConverter<T, Document> converter, QueryOptions options) { long start = startQuery(); /**/* w w w. j a v a2 s.c om*/ * Getting the cursor and setting the batchSize from options. Default value set to 20. */ FindIterable<Document> findIterable = mongoDBNativeQuery.find(query, projection, options); MongoCursor<Document> cursor = findIterable.iterator(); QueryResult<T> queryResult; List<T> list = new LinkedList<>(); if (cursor != null) { if (queryResultWriter != null) { try { queryResultWriter.open(); while (cursor.hasNext()) { queryResultWriter.write(cursor.next()); } queryResultWriter.close(); } catch (IOException e) { cursor.close(); queryResult = endQuery(null, start); queryResult.setErrorMsg(e.getMessage() + " " + Arrays.toString(e.getStackTrace())); return queryResult; } } else { if (converter != null) { while (cursor.hasNext()) { list.add(converter.convertToDataModelType(cursor.next())); } } else { if (clazz != null && !clazz.equals(Document.class)) { Document document; while (cursor.hasNext()) { document = cursor.next(); try { list.add(objectMapper.readValue(objectWriter.writeValueAsString(document), clazz)); } catch (IOException e) { e.printStackTrace(); } } } else { while (cursor.hasNext()) { list.add((T) cursor.next()); } } } } if (options != null && options.getInt(QueryOptions.SKIP) <= 0 && options.getInt(QueryOptions.LIMIT) > 0) { int numTotalResults; if (options.getBoolean(QueryOptions.SKIP_COUNT)) { numTotalResults = -1; } else { try { // numTotalResults = findIterable.maxTime(options.getInt("countTimeout"), TimeUnit.MILLISECONDS).count(); numTotalResults = (int) mongoDBNativeQuery.count(query); } catch (MongoExecutionTimeoutException e) { numTotalResults = -1; } } queryResult = endQuery(list, numTotalResults, start); } else { queryResult = endQuery(list, start); } cursor.close(); } else { queryResult = endQuery(list, start); } return queryResult; }
From source file:org.radarcns.mongo.data.monitor.application.MongoApplicationStatusWrapper.java
License:Apache License
/** * Returns an {@code ApplicationStatus} initialised with the extracted value. * * @param subject is the subjectID//from w ww. j av a2s. c o m * @param source is the sourceID * @param client is the mongoDb client instance * @return the last seen status update for the given subject and sourceType, otherwise null */ public ApplicationStatus valueByProjectSubjectSource(String project, String subject, String source, ApplicationStatus app, MongoClient client) { MongoCursor<Document> cursor = MongoHelper.findDocumentBySource( MongoHelper.getCollection(client, getCollectionName()), project, subject, source, VALUE + ".time", ASCENDING, 1); if (!cursor.hasNext()) { LOGGER.debug("Empty cursor"); cursor.close(); return null; } Document doc = cursor.next(); cursor.close(); if (app == null) { return getApplication((Document) doc.get(VALUE), new ApplicationStatus()); } return getApplication((Document) doc.get(VALUE), app); }
From source file:org.sead.monitoring.engine.SeadMon.java
License:Apache License
private static List<LogEvent> queryLog(MongoCollection collection, BasicDBObject query, String countStr, int start) { int count = 0; if (countStr != null && !countStr.equals(Constants.INFINITE)) count = Integer.parseInt(countStr); start = start < 0 ? 0 : start;/* w w w . j a v a 2s .co m*/ FindIterable<Document> iter; if (countStr == null || (countStr != null && countStr.equals(Constants.INFINITE))) { iter = collection.find(query).skip(start).sort(new BasicDBObject("date", 1)); } else { iter = collection.find(query).limit(count).skip(start).sort(new BasicDBObject("date", 1)); } List<LogEvent> logEvents = new ArrayList<LogEvent>(); MongoCursor<Document> cursor = iter.iterator(); try { while (cursor.hasNext()) { Document dbobj = cursor.next(); //Converting BasicDBObject to a custom Class(LogEvent) LogEvent logEvent = (new Gson()).fromJson(dbobj.toJson(), LogEvent.class); logEvents.add(logEvent); } } finally { cursor.close(); } return logEvents; }
From source file:org.sead.monitoring.engine.SeadMon.java
License:Apache License
private static List<DataoneLogEvent> queryDataoneLog(MongoCollection collection, BasicDBObject query, String countStr, int start) { int count = 0; if (countStr != null && !countStr.equals(Constants.INFINITE)) count = Integer.parseInt(countStr); start = start < 0 ? 0 : start;/* w w w . j a va 2s . c om*/ FindIterable<Document> iter; if (countStr == null || (countStr != null && countStr.equals(Constants.INFINITE))) { iter = collection.find(query).skip(start).sort(new BasicDBObject("date", 1)); } else { iter = collection.find(query).limit(count).skip(start).sort(new BasicDBObject("date", 1)); } List<DataoneLogEvent> logEvents = new ArrayList<DataoneLogEvent>(); MongoCursor<Document> cursor = iter.iterator(); try { while (cursor.hasNext()) { Document dbobj = cursor.next(); //Converting BasicDBObject to a custom Class(LogEvent) DataoneLogEvent logEvent = (new Gson()).fromJson(dbobj.toJson(), DataoneLogEvent.class); logEvents.add(logEvent); } } finally { cursor.close(); } return logEvents; }
From source file:org.springframework.data.mongodb.core.messaging.CursorReadingTask.java
License:Apache License
/** * Initialize the Task by 1st setting the current state to {@link State#STARTING starting} indicating the * initialization procedure. <br /> * Moving on the underlying {@link MongoCursor} gets {@link #initCursor(MongoTemplate, RequestOptions) created} and is * {@link #isValidCursor(MongoCursor) health checked}. Once a valid {@link MongoCursor} is created the {@link #state} * is set to {@link State#RUNNING running}. If the health check is not passed the {@link MongoCursor} is immediately * {@link MongoCursor#close() closed} and a new {@link MongoCursor} is requested until a valid one is retrieved or the * {@link #state} changes./*from w ww .ja va2 s . c o m*/ */ private void start() { synchronized (lifecycleMonitor) { if (!State.RUNNING.equals(state)) { state = State.STARTING; } } do { boolean valid = false; synchronized (lifecycleMonitor) { if (State.STARTING.equals(state)) { MongoCursor<T> cursor = initCursor(template, request.getRequestOptions(), targetType); valid = isValidCursor(cursor); if (valid) { this.cursor = cursor; state = State.RUNNING; } else { cursor.close(); } } } if (!valid) { try { Thread.sleep(100); } catch (InterruptedException e) { synchronized (lifecycleMonitor) { state = State.CANCELLED; } Thread.interrupted(); } } } while (State.STARTING.equals(getState())); if (awaitStart.getCount() == 1) { awaitStart.countDown(); } }
From source file:service.MongoLanguageService.java
@Override public List<Language> getAll() { // List<Language> languageList = new ArrayList<>(); // /*from w w w . j a va 2 s.c o m*/ // List<Document> resultSet = (List<Document>) collection.find(); // DBCursor cursor = collection.find(); // while(cursor.hasNext()) { // language.setId(resultSet.getInt("ID")); // language.setName(resultSet.getString("NAME")); // System.out.println(cursor.next()); // } // try{ MongoCursor<Document> cursor = collection.find().iterator(); // } catch (UnknownHostException e){ // throw new IllegalArgumentException(e); // } // List<Language> languages = (List<Language>) collection.find().iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } return null; }
From source file:tour.NewQuickTour.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args takes an optional single argument for the connection string *//* ww w .j a va 2s . co m*/ public static void main(final String[] args) { MongoClient mongoClient; if (args.length == 0) { // connect to the local database server mongoClient = new MongoClient(); } else { mongoClient = new MongoClient(new MongoClientURI(args[0])); } // get handle to "mydb" database MongoDatabase database = mongoClient.getDatabase("mydb"); database.drop(); // get a list of the collections in this database and print them out List<String> collectionNames = database.listCollectionNames().into(new ArrayList<String>()); for (final String s : collectionNames) { System.out.println(s); } // get a handle to the "test" collection MongoCollection<Document> collection = database.getCollection("test"); // drop all the data in it collection.drop(); // make a document and insert it Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info", new Document("x", 203).append("y", 102)); collection.insertOne(doc); // get it (since it's the only one in there since we dropped the rest earlier on) Document myDoc = collection.find().first(); System.out.println(myDoc); // now, lets add lots of little documents to the collection so we can explore queries and cursors List<Document> documents = new ArrayList<Document>(); for (int i = 0; i < 100; i++) { documents.add(new Document("i", i)); } collection.insertMany(documents); System.out.println( "total # of documents after inserting 100 small ones (should be 101) " + collection.count()); // lets get all the documents in the collection and print them out MongoCursor<Document> cursor = collection.find().iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } for (Document cur : collection.find()) { System.out.println(cur); } // now use a query to get 1 document out myDoc = collection.find(eq("i", 71)).first(); System.out.println(myDoc); // now use a range query to get a larger subset cursor = collection.find(gt("i", 50)).iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // range query with multiple constraints cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); } // max time collection.find().maxTime(1, TimeUnit.SECONDS).first(); collection.drop(); // ordered bulk writes List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>(); writes.add(new InsertOneModel<Document>(new Document("_id", 4))); writes.add(new InsertOneModel<Document>(new Document("_id", 5))); writes.add(new InsertOneModel<Document>(new Document("_id", 6))); writes.add( new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2)))); writes.add(new DeleteOneModel<Document>(new Document("_id", 2))); writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4))); collection.bulkWrite(writes); collection.drop(); collection.bulkWrite(writes, new BulkWriteOptions().ordered(false)); // getting a list of databases for (String name : mongoClient.listDatabaseNames()) { System.out.println(name); } // drop a database mongoClient.dropDatabase("databaseToBeDropped"); // create a collection database.createCollection("cappedCollection", new CreateCollectionOptions().capped(true).sizeInBytes(0x100000)); for (String name : database.listCollectionNames()) { System.out.println(name); } // create an ascending index on the "i" field collection.createIndex(new Document("i", 1)); // list the indexes on the collection for (final Document index : collection.listIndexes()) { System.out.println(index); } // create a text index on the "content" field collection.createIndex(new Document("content", "text")); collection.insertOne(new Document("_id", 0).append("content", "textual content")); collection.insertOne(new Document("_id", 1).append("content", "additional content")); collection.insertOne(new Document("_id", 2).append("content", "irrelevant content")); // Find using the text index Document search = new Document("$search", "textual content -irrelevant"); Document textSearch = new Document("$text", search); long matchCount = collection.count(textSearch); System.out.println("Text search matches: " + matchCount); // Find using the $language operator textSearch = new Document("$text", search.append("$language", "english")); matchCount = collection.count(textSearch); System.out.println("Text search matches (english): " + matchCount); // Find the highest scoring match Document projection = new Document("score", new Document("$meta", "textScore")); myDoc = collection.find(textSearch).projection(projection).first(); System.out.println("Highest scoring document: " + myDoc); // release resources mongoClient.close(); }