List of usage examples for com.mongodb DBCursor close
@Override public void close()
From source file:org.exist.mongodb.xquery.mongodb.collection.Find.java
License:Open Source License
@Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { try {//from w w w. ja v a 2 s. com // Verify clientid and get client String mongodbClientId = args[0].itemAt(0).getStringValue(); MongodbClientStore.getInstance().validate(mongodbClientId); MongoClient client = MongodbClientStore.getInstance().get(mongodbClientId); // Get parameters String dbname = args[1].itemAt(0).getStringValue(); String collection = args[2].itemAt(0).getStringValue(); String query = (args.length >= 4) ? args[3].itemAt(0).getStringValue() : null; String keys = (args.length >= 5) ? args[4].itemAt(0).getStringValue() : null; // Get database DB db = client.getDB(dbname); DBCollection dbcol = db.getCollection(collection); // PLace holder result cursor DBCursor cursor; if (query == null) { // No query cursor = dbcol.find(); } else { // Parse query BasicDBObject mongoQuery = (BasicDBObject) JSON.parse(query); // Parse keys when available BasicDBObject mongoKeys = (keys == null) ? null : (BasicDBObject) JSON.parse(keys); // Call correct method cursor = (mongoKeys == null) ? dbcol.find(mongoQuery) : dbcol.find(mongoQuery, mongoKeys); } // Execute query Sequence retVal = new ValueSequence(); // Harvest results try { while (cursor.hasNext()) { retVal.add(new StringValue(cursor.next().toString())); } } finally { cursor.close(); } return retVal; } catch (JSONParseException ex) { LOG.error(ex.getMessage()); throw new XPathException(this, MongodbModule.MONG0004, ex.getMessage()); } catch (XPathException ex) { LOG.error(ex.getMessage(), ex); throw new XPathException(this, ex.getMessage(), ex); } catch (MongoException ex) { LOG.error(ex.getMessage(), ex); throw new XPathException(this, MongodbModule.MONG0002, ex.getMessage()); } catch (Throwable ex) { LOG.error(ex.getMessage(), ex); throw new XPathException(this, MongodbModule.MONG0003, ex.getMessage()); } }
From source file:org.flinkmon.mongo.conn.ShardSetFinder.java
License:Open Source License
public Map<String, List<MongoClientWrapper>> findShardSets(MongoClient mongoS) { // TODO figure out how to do this with the new driver syntax. Does not // appear to support sisterDB DBCursor find = mongoS.getDB("admin").getSisterDB("config").getCollection("shards").find(); Map<String, List<MongoClientWrapper>> shardSets = new HashMap<>(); while (find.hasNext()) { DBObject next = find.next();/* ww w . j a va 2s .c o m*/ String key = (String) next.get("_id"); shardSets.put(key, getMongoClient(buildServerAddressList(next))); } find.close(); return shardSets; }
From source file:org.forgerock.openidm.repo.mongodb.impl.query.Queries.java
License:Open Source License
protected List<DBObject> executeQuery(QueryInfo queryInfo, Map<String, Object> params, DBCollection collection) throws BadRequestException { List<DBObject> result = null; if (queryInfo.isGroupQuery()) { String resultKey = ""; List<String> list = queryInfo.getAggregationParams(); List<DBObject> dboList = new ArrayList<DBObject>(); DBObject firstParam = new BasicDBObject(); boolean first = true; for (String s : list) { DBObject query = resolveQuery(s, params); if (first) { firstParam = query;//from w w w .j a va2s .co m first = !first; } else { dboList.add(query); } } AggregationOutput output = collection.aggregate(firstParam, (DBObject[]) dboList.toArray(new BasicDBObject[0])); if (output.results().iterator().hasNext()) { result = new ArrayList<DBObject>(); } for (DBObject obj : output.results()) { result.add(obj); } } else { String q = (queryInfo.getQuery() == null) ? "{}" : queryInfo.getQuery(); DBObject query = resolveQuery(q, params); String f = (queryInfo.getFileds() == null) ? "{}" : queryInfo.getFileds(); DBObject fields = resolveQuery(f, params); String s = (queryInfo.getSort() == null) ? "{}" : queryInfo.getSort(); DBObject sort = resolveQuery(s, params); DBCursor cur = null; try { cur = collection.find(query, fields).sort(sort); result = cur.toArray(); } catch (Exception ex) { throw new BadRequestException(ex.getMessage()); } finally { cur.close(); } } return result; }
From source file:org.geotools.data.mongodb.MongoLayer.java
License:LGPL
/** * Get mapping of field names and types, and counts for different types * /*from w ww .j a v a 2 s . com*/ * @param collection where metadata from map-reduce job stored, in format: { "_id" : { * "fieldname" : "geometry.type", "type" : "Point"}, "value" : 2 } { "_id" : { * "fieldname" : "properties.ActivityDescription", "type" : "number" }, "value" : 1 } * { "_id" : { "fieldname" : "properties.ActivityDescription", "type" : "string" }, * "value" : 3 } where value is number of occurrences for given type * @return mapping of field names to ClassCount holding type and count info */ private HashMap<String, ClassCount> getFieldMap(DBCollection metaResultsColl) { // cursor over collection BasicDBObject query = new BasicDBObject(); DBCursor cursor = metaResultsColl.find(query); // avoid cursor timeout cursor.addOption(Bytes.QUERYOPTION_NOTIMEOUT); // map to store fieldname and ClasCount object holding type and type-count info HashMap<String, ClassCount> fieldMap = new HashMap<String, ClassCount>(); try { // iterate over each record while (cursor.hasNext()) { // check type found for current field DBObject currRec = cursor.next(); DBObject currField = (DBObject) currRec.get("_id"); String fieldName = (String) currField.get("fieldname"); String fieldType = (String) currField.get("type"); int typeCount = ((Double) currRec.get("value")).intValue(); // if first occurrence of field name instantiate counter if (!fieldMap.containsKey(fieldName)) { fieldMap.put(fieldName, new ClassCount(fieldType, typeCount)); } // else increment count for given type else { ClassCount currCount = fieldMap.get(fieldName); currCount.add(fieldType, typeCount); fieldMap.put(fieldName, currCount); } } } finally { // need to explicitly release cursor since notimeout option set cursor.close(); } return fieldMap; }
From source file:org.graylog2.database.PersistedServiceImpl.java
License:Open Source License
protected List<DBObject> cursorToList(DBCursor cursor) { List<DBObject> results = Lists.newArrayList(); if (cursor == null) { return results; }/*from www. ja v a2s . c o m*/ try { while (cursor.hasNext()) { results.add(cursor.next()); } } finally { cursor.close(); } return results; }
From source file:org.greenmongoquery.db.service.impl.MongoServiceImpl.java
License:Open Source License
@Override public MongoCollectionModel getAllDocuments(Mongo mongo, String dbname, String collectionName) { Gson gson = new GsonBuilder().create(); MongoCollectionModel model = new MongoCollectionModel(); StringBuilder bsonData = new StringBuilder(); List<Map> result = new ArrayList<Map>(); model.setQuery("db." + collectionName + ".find();"); Map data = new TreeMap(); DB db = mongo.getDB(dbname);//from w ww . j a v a 2 s . co m DBCollection coll = db.getCollection(collectionName); DBCursor cursor = coll.find(); String output = null; try { while (cursor.hasNext()) { output = cursor.next().toString(); bsonData.append(output + "\n"); data = gson.fromJson(output, Map.class); result.add(data); } } finally { cursor.close(); } model.setBsonData(bsonData); model.setResult(result); return model; }
From source file:org.greenmongoquery.db.service.impl.MongoServiceImpl.java
License:Open Source License
@Override public MongoCollectionModel getDocumentsByQuery(Mongo mongo, String db, String collection, String query) { Map<String, String> queryDelimit = org.greenmongoquery.util.Util.getQuerySeperate(query); collection = (String) queryDelimit.get("coll"); query = queryDelimit.get("query"); logger.info("Query " + query); Gson gson = new GsonBuilder().create(); MongoCollectionModel model = new MongoCollectionModel(); StringBuilder bsonData = new StringBuilder(); List<Map> result = new ArrayList<Map>(); DBObject object = (DBObject) JSON.parse(query); DB dbs = mongo.getDB(db);// w w w.j a v a 2 s .c om DBCollection coll = dbs.getCollection(collection); DBCursor cursor = coll.find(object); Map data = new TreeMap(); String output = null; try { while (cursor.hasNext()) { output = cursor.next().toString(); bsonData.append(output + "\n"); data = gson.fromJson(output, Map.class); result.add(data); } } finally { cursor.close(); } model.setBsonData(bsonData); model.setResult(result); return model; }
From source file:org.helios.dashkuj.core.Dashkuj.java
License:Open Source License
/** * Synchronizes the api keys from mongoDB to redis for cases when redis loses them * @param redisHost The redis host// w ww .ja v a2s .c om * @param redisPort The redis port * @param mongoHost The mongodb host * @param mongoPort The mongodb port * FIXME: Need to support credentials */ public void synchRedisApiKeys(String redisHost, int redisPort, String mongoHost, int mongoPort) { Mongo mongo = null; DBCursor cursor = null; Jedis jedis = null; try { mongo = new Mongo(mongoHost, mongoPort); jedis = new Jedis(redisHost, redisPort); log.info("Synchronizing APIKeys between mongo [{}:{}] and redis [{}:{}]", mongoHost, mongoPort, redisHost, redisPort); Map<String, String> apiKeys = jedis.hgetAll("apiKeys"); DB db = mongo.getDB("dashku_development"); DBCollection dbColl = db.getCollection("users"); cursor = dbColl.find(); while (cursor.hasNext()) { DBObject dbo = cursor.next(); String apiKey = dbo.get("apiKey").toString(); String id = dbo.get("_id").toString(); String user = dbo.get("username").toString(); log.debug("Inspecting user [" + user + "]"); if (!apiKeys.containsKey(apiKey)) { jedis.hmset("apiKeys", Collections.singletonMap(apiKey, id)); log.info("Added missing redis entry [" + apiKey + "] for user [" + user + "]"); } } log.info("Redis Synch Complete"); } catch (Exception ex) { log.error("Redis Synch Failed", ex); throw new RuntimeException("Redis Synch Failed", ex); } finally { if (cursor != null) try { cursor.close(); } catch (Exception e) { } if (mongo != null) try { mongo.close(); } catch (Exception e) { } if (jedis != null) try { jedis.disconnect(); } catch (Exception e) { } } }
From source file:org.helios.dashkuj.domain.Dashboard.java
License:Open Source License
public static void main(String[] args) { Jedis jedis = null;/*ww w . j av a 2s .com*/ Mongo mongo = null; DBCursor cursor = null; Morphia morphia = null; Datastore mongoDs = null; try { jedis = new Jedis("dashku"); Map<String, String> apiKeys = jedis.hgetAll("apiKeys"); log(apiKeys); mongo = new Mongo("dashku"); morphia = new Morphia(); mongoDs = morphia.createDatastore(mongo, "dashku_development"); DB db = mongo.getDB("dashku_development"); DBCollection dbColl = db.getCollection("users"); cursor = dbColl.find(); while (cursor.hasNext()) { DBObject dbo = cursor.next(); String apiKey = dbo.get("apiKey").toString(); String id = dbo.get("_id").toString(); String user = dbo.get("username").toString(); log("Inspecting user [" + user + "]"); if (!apiKeys.containsKey(apiKey)) { jedis.hmset("apiKeys", Collections.singletonMap(apiKey, id)); log("Added missing redis entry [" + apiKey + "] for user [" + user + "]"); } } cursor.close(); // CommandResult cr = db.command("serverStatus"); // Date date = cr.getDate("localTime"); // // JsonElement je = new JsonParser().parse(cr.toString()); // String jsDate = je.getAsJsonObject().get("localTime").getAsJsonObject().getAsJsonPrimitive("$date").toString(); // //log(GsonFactory.getInstance().printer().toJson(je)); // log("Date:[" + date + "]"); // log("JS-Date:[" + jsDate + "]"); } catch (Exception ex) { ex.printStackTrace(System.err); } finally { if (jedis != null) try { jedis.disconnect(); } catch (Exception ex) { } if (cursor != null) try { cursor.close(); } catch (Exception ex) { } if (mongo != null) try { mongo.close(); } catch (Exception ex) { } } }
From source file:org.jboss.aerogear.push.registration.DeviceRegistrationService.java
License:Apache License
public Set<String> allTokensForOS(String os) { Set<String> tokens = new HashSet<String>(); DBCollection collection = database.getCollection(os); // interate:/*from w ww .j a v a2 s . c om*/ DBCursor cursor = collection.find(); try { while (cursor.hasNext()) { tokens.add((String) cursor.next().get("token")); } } finally { cursor.close(); } return tokens; }