List of usage examples for com.mongodb DBCursor next
@Override
public DBObject next()
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. * /*from ww w. ja 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. * /*from ww w . ja v a2s . c o 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 . co 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()); }// ww w .jav a 2 s.co m 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 www. j a v a 2 s .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;//from w w w .ja v a 2 s . com 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 .j av a 2 s.c om*/ 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(/* w w w . j a v a 2s . c om*/ new Artist((ObjectId) currentArtist.get("_id"), (Integer) currentArtist.get("facebook_likes"))); } Collections.sort(artArr); parse(artArr, 1); merge_clusters(5); print_clusters(); }
From source file:clustering.ClusteringArtistsTW.java
public static void main(String[] args) throws UnknownHostException { new Integer(5).doubleValue(); ArrayList<ArtistTW> artArr = new ArrayList<ArtistTW>(); DBHelper dbHelper = DBHelper.getInstance(); DBCursor artists = dbHelper.findAllArtistsWithTW(); while (artists.hasNext()) { DBObject currentArtist = artists.next(); //System.out.println(currentArtist); String twf = currentArtist.get("twitter_followers").toString(); StringTokenizer st = new StringTokenizer(twf, "."); int twfint = Integer.parseInt(st.nextToken()); System.out.println(twfint); ArtistTW artist = new ArtistTW((ObjectId) currentArtist.get("_id"), twfint); artArr.add(artist);//from w ww . j a va 2 s.com } Collections.sort(artArr); parse(artArr, 1); merge_clusters(6); print_clusters(); }
From source file:clustering.KMeans.java
public static void main(String[] args) throws UnknownHostException { if (args.length != 1) { System.out.println("Usage : KMeans <nrClusters>"); System.exit(-1);/*from w ww .j a va 2 s . c om*/ } int kClusters = Integer.parseInt(args[0]); ArrayList<Artist> artists = new ArrayList<Artist>(); DBHelper dbHelper = DBHelper.getInstance(); DBCursor result = dbHelper.findArtistsWithFBandTW(); while (result.hasNext()) { DBObject currentArtist = result.next(); artists.add(Artist.fromDBObject(currentArtist)); } //System.out.println(artists.size()); KMeansPlusPlusClusterer<Artist> clusterer = new KMeansPlusPlusClusterer<Artist>(kClusters); List<CentroidCluster<Artist>> clusters = clusterer.cluster(artists); //System.out.println(clusters.size()); dbHelper.emptyClusterCenters(); for (CentroidCluster<Artist> cluster : clusters) { double[] center = cluster.getCenter().getPoint(); ObjectId centerId = dbHelper.insertClusterCenter(center[0], center[1], center[2]); List<Artist> artC = cluster.getPoints(); for (Artist artist : artC) { dbHelper.updateMatrixRowCluster(artist.getDBObject(), centerId); //System.out.print("("+artist.fb_likes+","+artist.twitter_followers+","+artist.album_count+") "); } } }