List of usage examples for com.mongodb DBCursor close
@Override public void close()
From source file:org.jenkinsci.plugins.compatibilityaction.MongoProviderImpl.java
public <T> List<T> readMany(BasicDBObject query, Class<T> clazz) throws CompatibilityDataException { List<T> list = new ArrayList<T>(); org.mongojack.DBCursor cursor = null; MongoClient client = null;//w w w . j ava 2 s. c o m try { client = getService().createClient(); JacksonDBCollection coll = JacksonDBCollection.wrap(client.getDB(database).getCollection(collection), clazz); cursor = coll.find(query); while (cursor.hasNext()) { list.add((T) cursor.next()); } } catch (Exception ex) { throw new CompatibilityDataException(String.format("Failed to fetch object with query %s", query), ex); } finally { if (cursor != null) { cursor.close(); } if (client != null) { client.close(); } } return list; }
From source file:org.jenkinsci.plugins.compatibilityaction.MongoProviderImpl.java
public List<DBObject> listAndSort(DBObject query, BasicDBObject sorter) throws CompatibilityDataException { List<DBObject> objects = new ArrayList<DBObject>(); DBCursor cursor = null; MongoClient client = null;/* ww w . ja v a2 s . c om*/ try { client = getService().createClient(); cursor = client.getDB(database).getCollection(collection).find(query).sort(sorter); while (cursor.hasNext()) { objects.add(cursor.next()); } } catch (Exception ex) { throw new CompatibilityDataException( String.format("(Unknown Host) Failed to fetch object with query %s", query), ex); } finally { if (cursor != null) { cursor.close(); } if (client != null) { client.close(); } } return objects; }
From source file:org.keycloak.connections.mongo.updater.impl.updates.Update1_7_0.java
License:Apache License
@Override public void update(KeycloakSession session) throws ClassNotFoundException { DBCollection clients = db.getCollection("clients"); DBCursor clientsCursor = clients.find(); try {/*from w ww .j av a2 s. co m*/ while (clientsCursor.hasNext()) { BasicDBObject client = (BasicDBObject) clientsCursor.next(); boolean directGrantsOnly = client.getBoolean("directGrantsOnly", false); client.append("standardFlowEnabled", !directGrantsOnly); client.append("implicitFlowEnabled", false); client.append("directAccessGrantsEnabled", directGrantsOnly); client.removeField("directGrantsOnly"); clients.save(client); } } finally { clientsCursor.close(); } }
From source file:org.mandar.analysis.recsys2014.recsysMain.java
License:Open Source License
public void run() { // We first need to configure the data access. LenskitConfiguration dataConfig = this.configureDAO(DBSettings.TRAINING_COLLECTION); // Now we create the LensKit configuration... LenskitConfiguration config = new LenskitConfiguration(); if (algo.equals("svd")) { config = this.configureSVDRecommender(numFeatures, numIterations, regularizationParam, stoppingCondition, threshold); } else if (algo.equals("ii")) { config = this.configureIIRecommender(numNeighbours, similarityModel); } else if (algo.equals("uu")) { config = this.configureUURecommender(numNeighbours); } else if (algo.equals("so")) { config = this.configureSORecommender(damping); } else if (algo.equals("tfidf")) { config = this.configureTFIDFRecommender(); }/*from w ww.ja va2 s .c om*/ // There are more parameters, roles, and components that can be set. See the // JavaDoc for each recommender algorithm for more information. // Now that we have a factory, build a recommender from the configuration // and data source. This will compute the similarity matrix and return a recommender // that uses it. LenskitRecommender rec = null; try { LenskitRecommenderEngine engine = LenskitRecommenderEngine.newBuilder().addConfiguration(config) .addConfiguration(dataConfig).build(); rec = engine.createRecommender(dataConfig); } catch (RecommenderBuildException e) { e.printStackTrace(); System.exit(1); } // we want to recommend items if ("training".equals(this.goal)) { ItemRecommender irec = rec.getItemRecommender(); assert irec != null; // not null because we configured one // for users try { MongoClient mongoClient = new MongoClient(DBSettings.DBHOST); DB db = mongoClient.getDB(DBSettings.DATABASE); DBCollection collection = db.getCollection(DBSettings.MOVIES_COLLECTION); for (long user : users) { // get 10 recommendation for the user List<ScoredId> recs = irec.recommend(user, 10); System.out.format("Recommendations for %d:\n", user); for (ScoredId item : recs) { DBObject obj = collection.findOne(new BasicDBObject(DBSettings.FIELDS.movie, item.getId())); String recTitle = obj.get("title").toString(); String recDirector = obj.get("director").toString(); String recRel = obj.get("release_date").toString(); String recStars = obj.get("stars").toString(); System.out.format("\tID:%d, %s, %s Directed By: %s Starring: %s\n", item.getId(), recTitle, recRel, recDirector, recStars); } } mongoClient.close(); } catch (UnknownHostException u) { u.printStackTrace(); } } else if ("eval".equals(this.goal)) { //ItemScorer iscorer = rec.getItemScorer(); RatingPredictor rat = rec.getRatingPredictor(); File outFile = new File("data/participant_solution_" + algo + ".dat"); String line = ""; //String cvsSplitBy = ","; long eng = 0; int count = 0; try { long lines = Utils.countLines("data/test_solution.dat"); //outFile.delete(); BufferedWriter brout = new BufferedWriter((new FileWriter(outFile, false))); //BufferedReader br = new BufferedReader(new FileReader(csvData)); long progress = 0; //br.readLine(); System.out.println( "Reading from Test Set and writing result " + "data/participant_solution_" + algo + ".dat"); MongoClient mongoClient = new MongoClient(DBSettings.DBHOST); DB db = mongoClient.getDB(DBSettings.DATABASE); DBCollection collection = db.getCollection(DBSettings.TEST_COLLECTION_EMPTY); DBCursor cur = collection.find(); ArrayList<DBObject> arr = new ArrayList<DBObject>(cur.size()); System.out.println("Making ObjectArrayList out of test collection result"); while (cur.hasNext()) { DBObject buff = cur.next(); eng = (long) Math.abs(rat.predict(Long.parseLong(buff.get("uID").toString()), Long.parseLong(buff.get("movieID").toString()))); buff.put("engagement", eng); arr.add(buff); count++; } cur.close(); //Now sort this by uID (desc), engagement (desc) and tweetID (desc) System.out.println("Sorting ObjectArrayList"); Collections.sort(arr, new MongoComparator()); for (int i = 0; i < arr.size(); i++) { brout.write(arr.get(i).get("uID") + "," + arr.get(i).get("tweetID") + "," + arr.get(i).get("engagement")); brout.newLine(); progress++; if ((progress * 100 / lines) % 10 >= 0 && (progress * 100 / lines) % 10 <= 1) { System.out.println("File write Progress: " + (progress * 100 / lines) + " %"); } } brout.close(); ProcessBuilder pbr = new ProcessBuilder("java", "-jar", "rscevaluator-0.1-jar-with-dependencies.jar", "data/test_solution.dat", "data/participant_solution_" + algo + ".dat"); Process p = pbr.start(); BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream())); double resultbuff = 0.0d; while ((line = is.readLine()) != null) { if (line.contains("nDCG@10:")) { resultbuff = Double.parseDouble(line.substring(9)); } System.out.println(line); } System.out.println("Writing evaluation results to MongoDB"); this.writeAlgoTestResults(resultbuff, db); mongoClient.close(); p.waitFor(); } catch (FileNotFoundException f) { f.printStackTrace(); } catch (IOException f) { f.printStackTrace(); } catch (InterruptedException i) { i.printStackTrace(); } catch (NullPointerException n) { n.printStackTrace(); } } }
From source file:org.mongolink.domain.query.QueryExecutor.java
License:Open Source License
public List<T> execute(DBObject query, CursorParameter cursorParameter) { final List<T> result = Lists.newArrayList(); DBCollection collection = db.getCollection(mapper.collectionName()); DBCursor cursor = collection.find(query); cursor = cursorParameter.apply(cursor); try {//from w ww. j a v a 2s .c o m while (cursor.hasNext()) { result.add(loadEntity(cursor.next())); } return result; } finally { cursor.close(); } }
From source file:org.mongoste.core.impl.mongodb.MongoUtil.java
License:Open Source License
public static void close(DBCursor dbc) { if (dbc != null) { dbc.close(); } }
From source file:org.onebusaway.gtfs_realtime.producer_demo.GtfsRealtimeProviderImpl.java
License:Apache License
/** * @return a DBObject array of recent entries in MongoDB collection. *//*from w ww .ja v a 2 s .c o m*/ private ArrayList<DBObject> downloadLocations() throws IOException { // get list of distinct bus ids: // _log.info("getting distinct bus IDs"); // List busIDs = _coll.distinct("entity.id"); // _log.info("success: bus IDs"); // System.out.println(busIDs); ArrayList<DBObject> myList = new ArrayList<DBObject>(); ArrayList<Object> busIDs = locationList.getBusIDs(); // Loop over bus ids; get most recent timestamp for each for (Object busID : busIDs) { ArrayList queryList = new ArrayList(); // most recent timestamp: queryList.add(new BasicDBObject("entity.vehicle.timestamp", new BasicDBObject("$gt", _currtime))); // match on bus ID: queryList.add(new BasicDBObject("entity.id", busID.toString())); // build full query BasicDBObject query = new BasicDBObject("$and", queryList); _log.info("query on busID " + busID.toString()); DBCursor cursor2 = _coll.find(query).sort(new BasicDBObject("entity.vehicle.timestamp", -1)).limit(1); try { while (cursor2.hasNext()) { DBObject myDoc = cursor2.next(); myList.add(myDoc); } } finally { cursor2.close(); } } return myList; }
From source file:org.onebusaway.gtfs_realtime.trip_updates.GtfsRealtimeProviderImpl.java
License:Apache License
/** * @return a DBObject array of recent entries in MongoDB collection. *//* www.j ava 2 s .c om*/ private ArrayList<DBObject> downloadUpdates() throws IOException { // get list of distinct bus ids: // _log.info("getting distinct bus IDs"); // List busIDs = _locationsColl.distinct("entity.id"); // _log.info("success: bus IDs"); // System.out.println(busIDs); ArrayList<DBObject> myList = new ArrayList<DBObject>(); ArrayList<Object> busIDs = updateList.getBusIDs(); // Loop over bus ids; get most recent timestamp for each for (Object busID : busIDs) { List<BasicDBObject> queryList = new ArrayList<BasicDBObject>(); // match on bus ID: queryList.add(new BasicDBObject("device_id", busID.toString())); // look for departures only: queryList.add(new BasicDBObject("type", 1)); // build full query BasicDBObject query = new BasicDBObject("$and", queryList); _log.info("query on busID " + busID.toString()); DBCursor cursor2 = _coll.find(query).sort(new BasicDBObject("time", -1)).limit(1); try { while (cursor2.hasNext()) { DBObject myDoc = cursor2.next(); myList.add(myDoc); } } finally { cursor2.close(); } } return myList; }
From source file:org.opencb.cellbase.mongodb.db.ExonMongoDBAdaptor.java
License:Apache License
private List<Gene> executeQuery(DBObject query, List<String> excludeFields) { List<Gene> result = null; DBCursor cursor = null; if (excludeFields != null && excludeFields.size() > 0) { BasicDBObject returnFields = new BasicDBObject("_id", 0); for (String field : excludeFields) { returnFields.put(field, 0);/*from w ww . ja va 2 s. co m*/ } cursor = mongoDBCollection.find(query, returnFields); } else { cursor = mongoDBCollection.find(query); } try { if (cursor != null) { result = new ArrayList<Gene>(cursor.size()); // Gson jsonObjectMapper = new Gson(); Gene gene = null; while (cursor.hasNext()) { // gene = (Gene) jsonObjectMapper.fromJson(cursor.next().toString(), Gene.class); result.add(gene); } } } finally { cursor.close(); } return result; }
From source file:org.opencb.cellbase.mongodb.db.network.PathwayMongoDBAdaptor.java
License:Apache License
@Override public String getPathways() { BasicDBObject query = new BasicDBObject(); BasicDBObject returnFields = new BasicDBObject(); returnFields.put("_id", 0); returnFields.put("name", 1); returnFields.put("displayName", 1); returnFields.put("subPathways", 1); returnFields.put("parentPathway", 1); BasicDBObject orderBy = new BasicDBObject(); orderBy.put("name", 1); DBCursor cursor = coll.find(query, returnFields).sort(orderBy); String result = cursor.toArray().toString(); cursor.close(); return result; }