List of usage examples for com.mongodb DBCursor close
@Override public void close()
From source file:hsenid.webapp.Login.java
/** * @param user// w w w. j av a 2 s . com * Passing a user to validate username and password * @return status * Returns whether user passed the validation or not */ public static boolean ValidateByDB(User user) { boolean status = false; DBCursor cursor = null; try { DB userdata = DBCon.getConnection(); DBCollection user_cred = (DBCollection) userdata.getCollection("user_cred"); BasicDBObject query = new BasicDBObject(); query.put("Name", user.getUsername()); query.append("Pass", user.getPassword()); BasicDBObject fields = new BasicDBObject("Pass", 0).append("_id", 0); cursor = user_cred.find(query, fields); status = cursor.hasNext(); } catch (Exception e) { error = "Something bad happened. Try again later."; } finally { if (cursor != null) { cursor.close(); } } return status; }
From source file:in.mtap.iincube.mongoapi.MongoReader.java
License:Apache License
public List<DBObject> execute() { DBCursor cursor = getCursor(); List<DBObject> result = new LinkedList<DBObject>(); while (cursor.hasNext()) { result.add(cursor.next());/*from w ww .j a va2 s .com*/ } cursor.close(); return result; }
From source file:in.mtap.iincube.mongoapi.MongoReader.java
License:Apache License
public <T> T execute(DBObjectEncoder<T> encoder) { DBCursor cursor = getCursor(); try {//from w w w. j a v a 2 s . c om assertNotNull(encoder, "encoder == null"); return encoder.encode(cursor); } finally { cursor.close(); } }
From source file:it.wami.map.mongodeploy.thread.WayRunnable.java
License:Apache License
/** * /*ww w. j a va 2 s. c o m*/ * @param cursor {@link Cursor} the cursor of the response from the server * @param way {@link Way} the way object * @param nodes {@link BasicBSONList} the list containings the way's nodes * @return */ private Way updateWay(DBCursor cursor, Way way, BasicBSONList nodes) { boolean isCircularId = nodes.get(0) == nodes.get(nodes.size() - 1); double[][] coords = new double[nodes.size()][2]; BasicDBObject loc; if (way.containsField("loc")) { loc = (BasicDBObject) way.get("loc"); } else { loc = new BasicDBObject(); } // for better performance List<DBObject> list = new ArrayList<DBObject>(); while (cursor.hasNext()) { list.add(cursor.next()); } cursor.close(); // worst code ever n^2. for order the list as nodes int i = 0; for (Object nodeID : nodes) {// array to match to for (DBObject node : list) {// array being matched if (node != null && node.get("_id").equals(nodeID)) { BasicDBObject nodeLoc = (BasicDBObject) node.get("loc"); BasicBSONList coordinates = (BasicBSONList) nodeLoc.get("coordinates"); coords[i] = new double[] { (Double) coordinates.get(0), (Double) coordinates.get(1) }; i++; } } } // if the lat and the lng are the same boolean isCircularLtLng = (coords[0][0] == coords[coords.length - 1][0]) && (coords[0][1] == coords[coords.length - 1][1]); way.append("loc", loc); // fix if (isCircularId || isCircularLtLng) { if (coords.length > 3) { loc.append("type", "Polygon"); double[][][] o = new double[1][][]; o[0] = coords; loc.append("coordinates", o); } else { coords = Arrays.copyOf(coords, coords.length - 1); if (coords.length < 2) { way.remove("loc"); } else { loc.append("type", "LineString"); loc.append("coordinates", coords); } } } else { loc.append("type", "LineString"); loc.append("coordinates", coords); } return way; }
From source file:javaapplication15.JavaApplication15.java
/** * @param args the command line arguments * @throws java.net.UnknownHostException */// ww w.ja v a 2 s .co m public static void main(String[] args) throws UnknownHostException { MongoClient client = new MongoClient("localhost", 27017); DB myDB = client.getDB("m101"); DBCollection collection = myDB.getCollection("Sample2"); collection.drop(); BasicDBObject query = new BasicDBObject("x", new BasicDBObject("$gt", 10).append("$lt", 50)).append("y", new BasicDBObject("$gt", 10).append("$lt", 50)); for (int i = 0; i < 10; i++) { collection.insert( new BasicDBObject("x", new Random().nextInt(100)).append("y", new Random().nextInt(100))); } // DBObject one = collection.findOne(query); // System.out.println(one); DBCursor cursor = collection.find(query); try { while (cursor.hasNext()) { DBObject dBObject = cursor.next(); System.out.println(dBObject); } } finally { cursor.close(); } }
From source file:jc.mongodb.command.DefaultQueuePeekCommand.java
License:Apache License
@Override public T peek(MongoContext<T> ctx) { DBCursor cursor; if (isEmptyCommand.isEmpty(ctx)) { return null; }//from w w w. ja v a 2 s . c o m cursor = ctx.getCollection().find().sort(asc ? ORDER_BY_ASC : ORDER_BY_DESC); try { if (cursor.hasNext()) { return ctx.getSerializer().toElement(cursor.next()); } return null; } finally { cursor.close(); } }
From source file:lucenetools.DocIndexerMongo.java
License:Apache License
/** * Indexes the given Mongo collection using the given writer. Each tweet * will be indexed as a separate document. * * @param writer writer to use for indexing documents * @param opts options object * @param analyzer analyzer specified from config file * @throws MongoTimeoutException if the mongo instance cannot be connected to * @throws IOException if there is an issue with the document * @throws NoSuchMethodException if method not found * @throws IllegalAccessException cannot access class * @throws IllegalArgumentException wrong set of arguments * @throws InvocationTargetException instantiated class has a problem *//*from w w w . jav a2s . c o m*/ static void indexDocs(IndexWriter writer, Options opts, Analyzer analyzer) throws MongoTimeoutException, IOException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { DBCursor cursor = getCursor(opts); boolean noLimit = false; int origLimit = opts.limit; if (-1 == opts.limit) { noLimit = true; opts.limit = 1; } ArrayList<String> include = getKeywords(opts.include); ArrayList<String> exclude = getKeywords(opts.exclude); String tweet, tweetLower, tweetIndex; try { if (cursor.size() == 0) { throw new UnsupportedOperationException(); } else { for (int i = 0; i < opts.limit; i++) { if (cursor.hasNext()) { // read the next tweet from mongo DBObject tweetJSON = cursor.next(); tweet = tweetJSON.get("text").toString(); tweetLower = tweet.toLowerCase(); if (eval(tweetLower, include, exclude)) { // the tweet index is the MongoID associated with that tweet tweetIndex = tweetJSON.get("_id").toString(); // identify the db path to retrieve the tweet String path = getPath(opts) + "_" + tweetIndex; // use the analyzer's package name to find out if there is a custom // implementation of the Utils class with the addDocument function String packageName = opts.analyzerName.split("\\.")[0]; try { Class<?> cla = Class.forName(packageName + ".Utils"); Method method = cla.getMethod("addDocument", String.class, String.class, IndexWriter.class); method.invoke(null, tweetJSON.toString(), path, writer); // use the default Utils implementaiton } catch (ClassNotFoundException | NoSuchMethodException cnfe) { Utils.addDocument(tweetJSON.toString(), path, writer); } ++docsIndexed; if (0 == (docsIndexed % 1000)) { System.out.print("Docs analyzed and indexed: " + docsIndexed + "\r"); System.out.flush(); } // increment limit to emulate no limit being used if (noLimit) { ++opts.limit; } } else { //ensure that the limit is reached ++opts.limit; } } else { if (origLimit != -1) System.out.println("Maximum available documents is " + (i + 1) + "; unable to reach desired limit of " + origLimit + "."); break; } } } if (origLimit != -1) System.out.printf("Searched %d tweets to find %d that met the filter requirements.\n", opts.limit - 1, origLimit); } catch (MongoTimeoutException mte) { System.out.println( "Timed out while waiting to connect." + "\nEnsure that the host/port/database/collection " + "configuration in your YAML file is correct."); } catch (UnsupportedOperationException uoe) { System.out.println("\nWARNING: Cursor returned with 0 documents - " + "ensure that the database/collection \n" + "configuration in your YAML file is correct."); } finally { cursor.close(); } }
From source file:lucenetools.DocIndexerMongo.java
License:Apache License
/** * Show analysis for tweets// w ww .ja va 2s . c o m * * @param n number of tweets to show the analysis for * @param opts options object * @param analyzer analyzer specified from config file * @throws IOException if there is an issue with the document */ public static void showTweetAnalysis(int n, Options opts, Analyzer analyzer) throws IOException { DBCursor cursor = getCursor(opts); boolean noLimit = false; if (-1 == opts.limit) { noLimit = true; opts.limit = 1; } ArrayList<String> include = getKeywords(opts.include); ArrayList<String> exclude = getKeywords(opts.exclude); System.out.println("Analysis results for Mongo client" + ", " + n + " tweets max:\n"); int count = 0; String tweet, tweetLower; try { if (cursor.size() == 0) { throw new UnsupportedOperationException(); } else { for (int i = 0; i < opts.limit; i++) { if (cursor.hasNext()) { // read the next tweet from mongo DBObject tweetJSON = cursor.next(); tweet = tweetJSON.get("text").toString(); tweetLower = tweet.toLowerCase(); //check for keywords if (eval(tweetLower, include, exclude)) { System.out.println(tweet); DebugAnalyzer.showAnalysisFromStream(new StringReader(tweet), analyzer); System.out.println(); ++count; if (count >= n) { System.out.printf( "Searched %d tweets to find %d that met the filter requirements.\n", i + 1, n); break; } if (noLimit) ++opts.limit; } else { ++opts.limit; } } } } } catch (MongoTimeoutException mte) { System.out.println( "Timed out while waiting to connect." + "\nEnsure that the host/port/database/collection " + "configuration in your YAML file is correct."); } catch (UnsupportedOperationException uoe) { System.out.println("\nWARNING: Cursor returned with 0 documents - " + "ensure that the database/collection \n" + "configuration in your YAML file is correct."); } finally { cursor.close(); } }
From source file:me.carbou.mathieu.tictactoe.db.DBCollection.java
License:Apache License
public Stream<Map<String, Object>> find(Map where, Map fields, Map sort, Function<Map, Map> transform, int limit, int skip) { final DBCursor cursor = getCollection().find(new BasicDBObject(addWhere(where)), new BasicDBObject(preFind(fields))); if (!sort.isEmpty()) cursor.sort(new BasicDBObject(sort)); if (skip > 0) cursor.skip(skip);/*from w w w . j a v a2 s .co m*/ if (limit > DB.NO_LIMIT) cursor.limit(limit); int est = cursor.size(); Spliterator<Map<String, Object>> spliterator = new Spliterators.AbstractSpliterator<Map<String, Object>>( est, NONNULL | ORDERED | SIZED | IMMUTABLE) { @Override public boolean tryAdvance(Consumer<? super Map<String, Object>> action) { if (cursor.hasNext()) { action.accept(postFind(where, cursor.next(), transform)); return true; } else { cursor.close(); return false; } } }; return StreamSupport.stream(spliterator, false); }
From source file:me.lightspeed7.mongofs.gridfs.GridFS.java
License:Apache License
/** * Finds a list of files matching the given query. * /*from w ww. jav a 2 s . c om*/ * @param query * the filter to apply * @param sort * the fields to sort with * @return list of gridfs files * @throws com.mongodb.MongoException */ public List<GridFSDBFile> find(final DBObject query, final DBObject sort) { List<GridFSDBFile> files = new ArrayList<GridFSDBFile>(); DBCursor cursor = filesCollection.find(query); if (sort != null) { cursor.sort(sort); } try { while (cursor.hasNext()) { files.add(injectGridFSInstance(cursor.next())); } } finally { cursor.close(); } return Collections.unmodifiableList(files); }