List of usage examples for com.mongodb DBCursor hasNext
@Override public boolean hasNext()
From source file:ch.agent.crnickl.mongodb.ReadMethodsForSchema.java
License:Apache License
/** * Find a collection of schema surrogates with labels matching a pattern. * /* w w w . j av a 2s. c om*/ * @param db a database * @param pattern a simple pattern where "*" stands for zero or more characters * @return a collection of schema surrogates * @throws T2DBException */ public Collection<Surrogate> getSchemaSurrogateList(Database db, String pattern) throws T2DBException { try { Collection<Surrogate> result = new ArrayList<Surrogate>(); DBCollection coll = getMongoDB(db).getSchemas(); DBObject query = null; if (pattern != null && pattern.length() > 0) { String regexp = extractRegexp(pattern); if (regexp == null) { regexp = pattern.replace("*", ".*"); if (regexp.equals(pattern)) regexp = null; } query = mongoObject(MongoDatabase.FLD_SCHEMA_NAME, regexp == null ? pattern : Pattern.compile(regexp)); } DBCursor cursor = coll.find(query); try { while (cursor.hasNext()) { ObjectId id = (ObjectId) cursor.next().get(MongoDatabase.FLD_ID); Surrogate s = makeSurrogate(db, DBObjectType.SCHEMA, new MongoDBObjectId(id)); result.add(s); } } finally { cursor.close(); } return result; } catch (Exception e) { throw T2DBMsg.exception(e, E.E30105, pattern); } }
From source file:ch.agent.crnickl.mongodb.ReadMethodsForValueType.java
License:Apache License
/** * Find a collection of value types with names matching a pattern. * If the pattern is enclosed in slashes it is taken as a standard * regexp pattern; the slashes will be removed. If it is not enclosed * in slashes, it is taken as a minimal pattern and all occurrences of * "*" will be replaced with ".*" (zero or more arbitrary characters). * // w w w .j av a 2 s. co m * @param database a database * @param pattern a simple pattern or a regexp pattern * @return a collection of value types, possibly empty, never null * @throws T2DBException */ public Collection<ValueType<?>> getValueTypes(Database database, String pattern) throws T2DBException { try { DBObject query = null; if (pattern != null && pattern.length() > 0) { String regexp = extractRegexp(pattern); if (regexp == null) pattern = pattern.replace("*", ".*"); else pattern = regexp; query = mongoObject(MongoDatabase.FLD_VT_NAME, Pattern.compile(pattern)); } DBCursor cursor = getMongoDB(database).getValueTypes().find(query); Collection<ValueType<?>> result = new ArrayList<ValueType<?>>(); try { while (cursor.hasNext()) { result.add(unpack(database, (BasicDBObject) cursor.next())); } } finally { cursor.close(); } return result; } catch (Exception e) { throw T2DBMsg.exception(e, E.E10106, pattern); } }
From source file:ch.agent.crnickl.mongodb.WriteMethodsForSchema.java
License:Apache License
/** * Find a chronicle with an explicit attribute value for a given property and schemas. * This looks like a "reading" method but is used in the context of schema updating. * // www .j a v a2 s . c o m * @param property a property * @param schema a schema * @return a surrogate or null * @throws T2DBException */ public Surrogate findChronicle(Property<?> property, Schema schema) throws T2DBException { Surrogate result = null; DBCursor cursor = null; try { Database db = schema.getDatabase(); cursor = getMongoDB(db).getAttributes().find(mongoObject(MongoDatabase.FLD_ATTR_PROP, getId(property))); while (cursor.hasNext()) { ObjectId chrOid = ((BasicDBObject) cursor.next()).getObjectId(MongoDatabase.FLD_ATTR_CHRON); Surrogate entityKey = makeSurrogate(db, DBObjectType.CHRONICLE, chrOid); Schema s = db.getChronicle(entityKey).getSchema(true); if (s.dependsOnSchema(schema)) { result = entityKey; break; } } } catch (Exception e) { throw T2DBMsg.exception(e, E.E30117); } finally { if (cursor != null) cursor.close(); } return result; }
From source file:ch.agent.crnickl.mongodb.WriteMethodsForSchema.java
License:Apache License
/** * Find a chronicle with a given series in a collection of schemas. * This looks like a "reading" method but is used in the context of schema updating. * // w ww . j a v a 2s .co m * @param ss a series definition * @param schema a schema * @return a surrogate or null * @throws T2DBException */ public Surrogate findChronicle(SeriesDefinition ss, Schema schema) throws T2DBException { Surrogate result = null; DBCursor cursor1 = null; DBCursor cursor2 = null; try { Database db = schema.getDatabase(); cursor1 = getMongoDB(db).getChronicles() .find(mongoObject(MongoDatabase.FLD_CHRON_SCHEMA, getId(schema))); OUTER: while (cursor1.hasNext()) { ObjectId chronicleOid = getObjectId((BasicDBObject) cursor1.next()); cursor2 = getMongoDB(db).getSeries().find(mongoObject(MongoDatabase.FLD_SER_CHRON, chronicleOid, MongoDatabase.FLD_SER_NUM, ss.getNumber())); while (cursor2.hasNext()) { Surrogate entityKey = makeSurrogate(db, DBObjectType.CHRONICLE, chronicleOid); Schema s = db.getChronicle(entityKey).getSchema(true); if (s.dependsOnSchema(schema)) { result = entityKey; break OUTER; } } } } catch (Exception e) { throw T2DBMsg.exception(e, E.E30117); } finally { if (cursor1 != null) cursor1.close(); if (cursor2 != null) cursor2.close(); } return result; }
From source file:ch.bfh.uniboard.persistence.mongodb.PersistenceService.java
License:GNU General Public License
@Override public ResultContainer get(Query query) { try {/*from w w w . j a v a 2s.c o m*/ //Check Database connection if (!this.connectionManager.isConnected()) { Attributes gamma = new Attributes(); gamma.add(Attributes.ERROR, new StringValue("Internal Server Error. Service not available")); logger.log(Level.WARNING, "Database error: unable to connect to database"); return new ResultContainer(new ArrayList<Post>(), gamma); } //TODO Remove this block and its tests //check basic wellformedness of query if (query == null || query.getConstraints() == null || query.getConstraints().isEmpty() || query.getConstraints().contains(null)) { Attributes gamma = new Attributes(); gamma.add(Attributes.REJECTED, new StringValue("Syntax error: Incomplete query")); logger.log(Level.WARNING, "Syntax error: Incomplete query"); return new ResultContainer(new ArrayList<Post>(), gamma); } List<DBObject> constraintsList = new ArrayList<>(); //iterates over the constraints and constructs the corresponding query string for (Constraint c : query.getConstraints()) { //constructs the key String keyString = ""; if (c.getIdentifier() instanceof MessageIdentifier) { //TODO constraint that wants to compare the raw byte[] keyString += "searchable-message"; } else if (c.getIdentifier() instanceof AlphaIdentifier) { keyString += "alpha"; } else if (c.getIdentifier() instanceof BetaIdentifier) { keyString += "beta"; } else { Attributes gamma = new Attributes(); gamma.add(Attributes.REJECTED, new StringValue("Syntax error: Unknown identifier")); logger.log(Level.WARNING, "Syntax error: Unknown identifier"); return new ResultContainer(new ArrayList<Post>(), gamma); } //constructs the hierarchy of the keys for (String key : c.getIdentifier().getParts()) { keyString += "." + key; } //constructs the researched value string by checking the type of constraints and getting the searched values DBObject actualConstraint = new BasicDBObject(); if (c instanceof Equal) { Equal op = (Equal) c; actualConstraint.put(keyString, op.getValue().getValue()); } else if (c instanceof NotEqual) { NotEqual op = (NotEqual) c; actualConstraint.put(keyString, new BasicDBObject("$ne", op.getValue().getValue())); } else if (c instanceof In) { In op = (In) c; List<Object> values = new ArrayList<>(); Class valueClass = op.getSet().get(0).getClass(); for (Value v : op.getSet()) { if (!(v.getClass().equals(valueClass))) { Attributes gamma = new Attributes(); gamma.add(Attributes.REJECTED, new StringValue("Syntax error: not same value type for IN constraint")); logger.log(Level.WARNING, "Syntax error: not same value type for IN constraint"); return new ResultContainer(new ArrayList<Post>(), gamma); } values.add(v.getValue()); } actualConstraint.put(keyString, new BasicDBObject("$in", values)); } else if (c instanceof Between) { Between op = (Between) c; if (!(op.getStart().getClass().equals(op.getEnd().getClass()))) { Attributes gamma = new Attributes(); gamma.add(Attributes.REJECTED, new StringValue("Syntax error: not same value type for BETWEEN constraint")); logger.log(Level.WARNING, "Syntax error: not same value type for BETWEEN constraint"); return new ResultContainer(new ArrayList<Post>(), gamma); } actualConstraint.put(keyString, new BasicDBObject("$gt", op.getStart().getValue()).append("$lt", op.getEnd().getValue())); } else if (c instanceof Greater) { Greater op = (Greater) c; actualConstraint.put(keyString, new BasicDBObject("$gt", op.getValue().getValue())); } else if (c instanceof GreaterEqual) { GreaterEqual op = (GreaterEqual) c; actualConstraint.put(keyString, new BasicDBObject("$gte", op.getValue().getValue())); } else if (c instanceof Less) { Less op = (Less) c; actualConstraint.put(keyString, new BasicDBObject("$lt", op.getValue().getValue())); } else if (c instanceof LessEqual) { LessEqual op = (LessEqual) c; actualConstraint.put(keyString, new BasicDBObject("$lte", op.getValue().getValue())); } else { Attributes gamma = new Attributes(); gamma.add(Attributes.REJECTED, new StringValue("Syntax error: Unknown type of constraint")); logger.log(Level.WARNING, "Syntax error: Unknown type of constraint"); return new ResultContainer(new ArrayList<Post>(), gamma); } constraintsList.add(actualConstraint); } //combine the different constrainst in an AND query DBObject completeQuery = new BasicDBObject(); completeQuery.put("$and", constraintsList); DBCursor cursor; if (query.getOrder().size() > 0) { //Create orderBy BasicDBObject orderBy = new BasicDBObject(); for (Order order : query.getOrder()) { String identifier; if (order.getIdentifier() instanceof MessageIdentifier) { identifier = "message"; } else if (order.getIdentifier() instanceof AlphaIdentifier) { identifier = "alpha"; } else if (order.getIdentifier() instanceof BetaIdentifier) { identifier = "beta"; } else { Attributes gamma = new Attributes(); gamma.add(Attributes.REJECTED, new StringValue("Syntax error: Unknown identifier")); logger.log(Level.WARNING, "Syntax error: Unknown identifier"); return new ResultContainer(new ArrayList<Post>(), gamma); } for (String key : order.getIdentifier().getParts()) { identifier += "." + key; } int ascDesc; if (order.isAscDesc()) { ascDesc = 1; } else { ascDesc = -1; } orderBy.append(identifier, ascDesc); } cursor = this.connectionManager.getCollection().find(completeQuery).sort(orderBy) .limit(query.getLimit()); } else { //apply query on database cursor = this.connectionManager.getCollection().find(completeQuery).limit(query.getLimit()); } //creates the result container with the db result List<Post> list = new ArrayList<>(); while (cursor.hasNext()) { DBObject object = cursor.next(); //convert to PersistedPost list.add(PersistedPost.fromDBObject(object)); } return new ResultContainer(list, new Attributes()); } catch (Exception e) { Attributes gamma = new Attributes(); gamma.add(Attributes.ERROR, new StringValue("General error: " + e.getMessage())); logger.log(Level.WARNING, "General Get error", e); return new ResultContainer(new ArrayList<Post>(), gamma); } }
From source file:ch.windmobile.server.mongo.MongoDataSource.java
License:Open Source License
private List<BasicDBObject> getHistoricData(String stationId, DateTime lastUpdate, int duration) { DBCollection dataCollection = database.getCollection(getDataCollectionName(stationId)); long startTime = lastUpdate.getMillis() - duration * 1000; DBObject query = BasicDBObjectBuilder .start("_id", BasicDBObjectBuilder.start("$gte", startTime / 1000).get()).get(); List<BasicDBObject> datas = new ArrayList<BasicDBObject>(); DBCursor cursor = dataCollection.find(query); while (cursor.hasNext()) { datas.add((BasicDBObject) cursor.next()); }//from www . j a va2 s . c om return datas; }
From source file:ch.windmobile.server.mongo.MongoDataSource.java
License:Open Source License
@Override public List<StationInfo> getStationInfoList(boolean allStation) throws DataSourceException { try {/*from w ww.j av a2s . c o m*/ DBCollection stations = database.getCollection(getStationsCollectionName()); List<String> list = new ArrayList<String>(); if (allStation == true) { list.add(Status.RED.value()); list.add(Status.ORANGE.value()); list.add(Status.GREEN.value()); } else { list.add(Status.GREEN.value()); } DBObject query = BasicDBObjectBuilder.start("prov", getProvider()) .add("status", new BasicDBObject("$in", list)).get(); DBCursor cursor = stations.find(query); List<StationInfo> stationInfoList = new ArrayList<StationInfo>(); while (cursor.hasNext()) { try { BasicDBObject stationJson = (BasicDBObject) cursor.next(); if (getStationsFilter() != null) { String stationId = stationJson.getString("_id"); if (getStationsFilter().contains(stationId)) { stationInfoList.add(createStationInfo(stationJson)); } } else { stationInfoList.add(createStationInfo(stationJson)); } } catch (Exception e) { log.warn("Station was ignored because:", e); } } return stationInfoList; } catch (Exception e) { throw exceptionHandler(e); } }
From source file:cl.wsconsulta.consulta.Consulta.java
@WebMethod(operationName = "consultar") public String realizarConsulta(@WebParam(name = "consulta") BasicDBList privileges) throws IOException { DB database;/* w w w . j a va2 s . c om*/ try (BufferedReader entrada = new BufferedReader(new FileReader("datos.ini"))) { database = null; try { dataBase = entrada.readLine(); indiceInvertido = entrada.readLine(); coleccionDocumentos = entrada.readLine(); coleccionIndice = entrada.readLine(); MongoClient mongoClient = new MongoClient(); database = mongoClient.getDB(dataBase); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } entrada.close(); } DBCollection indiceInvertido = database.getCollection(coleccionIndice); DBCollection documento = database.getCollection(coleccionDocumentos); while (true) { BufferedReader lector = new BufferedReader(new InputStreamReader(System.in)); String consulta = lector.readLine().toUpperCase(); BasicDBObject query = new BasicDBObject("palabra", consulta); DBCursor cursor = indiceInvertido.find(query); if (cursor.count() == 0) { System.out.println("Busqueda sin resultados: " + consulta); } else { while (cursor.hasNext()) { privileges = (BasicDBList) cursor.next().get("documento"); //DBObject obj = cursor.next(); //Object value = obj.get("documento"); //System.out.println(value); } System.out.println(privileges); } } }
From source file:cl.wsconsulta.servlet.ConsultaServlet.java
public static String consultar(String consulta) throws FileNotFoundException, IOException { DB database;/* w w w . jav a2s . c o m*/ database = null; dataBase = "labsd"; indiceInvertido = "prueba.xml"; coleccionDocumentos = "documentos"; coleccionIndice = "indiceInvertido"; MongoClient mongoClient = new MongoClient(); database = mongoClient.getDB(dataBase); DBCollection indiceInvertido = database.getCollection(coleccionIndice); DBCollection documento = database.getCollection(coleccionDocumentos); BasicDBList privileges = new BasicDBList(); BasicDBObject query = new BasicDBObject("palabra", consulta); DBCursor cursor = indiceInvertido.find(query); if (cursor.count() == 0) { System.out.println("Busqueda sin resultados: " + consulta); } else { while (cursor.hasNext()) { privileges = (BasicDBList) cursor.next().get("documento"); //DBObject obj = cursor.next(); //Object value = obj.get("documento"); //System.out.println(value); } } String lista = privileges.toString(); return lista; }
From source file:clustering.ClusteringArtists.java
public static void main(String[] args) throws UnknownHostException { ArrayList<Artist> artArr = new ArrayList<Artist>(); DBHelper dbHelper = DBHelper.getInstance(); DBCursor artists = dbHelper.findAllArtistsWithFB(); while (artists.hasNext()) { DBObject currentArtist = artists.next(); artArr.add(/*from w ww .j a v a 2s. co m*/ new Artist((ObjectId) currentArtist.get("_id"), (Integer) currentArtist.get("facebook_likes"))); } Collections.sort(artArr); parse(artArr, 1); merge_clusters(5); print_clusters(); }