List of usage examples for com.mongodb BasicDBObject getDouble
public double getDouble(final String key)
From source file:org.knowrob.knowrob_sim_games.MongoSimGames.java
License:Open Source License
/** * Query the trajectory of the given link of the given model with double timestamps * save result in MongoDB/*from w w w. j av a 2 s . com*/ */ public void ViewLinkTrajectory(double start_ts, double end_ts, String model_name, String link_name, String markerID, String markerType, String color, float scale, double deltaT) { // create the pipeline operations, first with the $match check the times DBObject match_time = new BasicDBObject("$match", new BasicDBObject("timestamp", new BasicDBObject("$gte", start_ts).append("$lte", end_ts))); // $unwind the models DBObject unwind_models = new BasicDBObject("$unwind", "$models"); // $match for the given model name from the unwinded models DBObject match_model = new BasicDBObject("$match", new BasicDBObject("models.name", model_name)); // build the $projection operation DBObject proj_links_fields = new BasicDBObject("_id", 0); proj_links_fields.put("timestamp", 1); proj_links_fields.put("models.links", 1); DBObject project_links = new BasicDBObject("$project", proj_links_fields); // $unwind the links DBObject unwind_links = new BasicDBObject("$unwind", "$models.links"); // $match for the given link name from the unwinded links DBObject match_link = new BasicDBObject("$match", new BasicDBObject("models.links.name", link_name)); // build the final $projection operation DBObject proj_fields = new BasicDBObject("timestamp", 1); proj_fields.put("pos", "$models.links.pos"); proj_fields.put("rot", "$models.links.rot"); DBObject project = new BasicDBObject("$project", proj_fields); // run aggregation List<DBObject> pipeline = Arrays.asList(match_time, unwind_models, match_model, project_links, unwind_links, match_link, project); AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); Cursor cursor = this.coll.aggregate(pipeline, aggregationOptions); // Traj as dynamic array ArrayList<Vector3d> traj = new ArrayList<Vector3d>(); // timestamp used for deltaT double prev_ts = 0; // if cursor not empty, append matadata to the first doc if (cursor.hasNext()) { // get the first document as the next cursor BasicDBObject first_doc = (BasicDBObject) cursor.next(); traj.add(new Vector3d(((BasicDBObject) first_doc.get("pos")).getDouble("x"), ((BasicDBObject) first_doc.get("pos")).getDouble("y"), ((BasicDBObject) first_doc.get("pos")).getDouble("z"))); // set the timestamp prev_ts = first_doc.getDouble("timestamp"); } // if query returned no values for these timestamps, get the pose at the nearest timestamp else { // write the pose to the given db and coll this.ViewLinkPoseAt(start_ts, model_name, link_name, markerID, markerType, color, scale); } // insert rest of trajectory while (cursor.hasNext()) { // get the current document BasicDBObject curr_doc = (BasicDBObject) cursor.next(); double curr_ts = curr_doc.getDouble("timestamp"); // if time diff > then deltaT add position to trajectory if (curr_ts - prev_ts > deltaT) { traj.add(new Vector3d(((BasicDBObject) curr_doc.get("pos")).getDouble("x"), ((BasicDBObject) curr_doc.get("pos")).getDouble("y"), ((BasicDBObject) curr_doc.get("pos")).getDouble("z"))); prev_ts = curr_ts; } } // create the markers this.CreateMarkers(traj, markerID, markerType, color, scale); }
From source file:org.knowrob.knowrob_sim_games.MongoSimGames.java
License:Open Source License
/** * Query the trajectory of the given collision of the given link of the given model from double timestamps * view results as rviz markers//from www.ja v a2 s .co m */ public void ViewCollisionTrajectory(double start_ts, double end_ts, String model_name, String link_name, String collision_name, String markerID, String markerType, String color, float scale, double deltaT) { // create the pipeline operations, first with the $match check the times DBObject match_time = new BasicDBObject("$match", new BasicDBObject("timestamp", new BasicDBObject("$gte", start_ts).append("$lte", end_ts))); // $unwind the models DBObject unwind_models = new BasicDBObject("$unwind", "$models"); // $match for the given model name from the unwinded models DBObject match_model = new BasicDBObject("$match", new BasicDBObject("models.name", model_name)); // build the $projection operation DBObject proj_links_fields = new BasicDBObject("_id", 0); proj_links_fields.put("timestamp", 1); proj_links_fields.put("models.links", 1); DBObject project_links = new BasicDBObject("$project", proj_links_fields); // $unwind the links DBObject unwind_links = new BasicDBObject("$unwind", "$models.links"); // $match for the given link name from the unwinded links DBObject match_link = new BasicDBObject("$match", new BasicDBObject("models.links.name", link_name)); // build the final $projection operation DBObject proj_collision_fields = new BasicDBObject("timestamp", 1); proj_collision_fields.put("models.links.collisions", 1); DBObject project_collisions = new BasicDBObject("$project", proj_collision_fields); // $unwind the collisions DBObject unwind_collisions = new BasicDBObject("$unwind", "$models.links.collisions"); // $match for the given collision name from the unwinded collisions DBObject match_collision = new BasicDBObject("$match", new BasicDBObject("models.links.collisions.name", collision_name)); // build the final $projection operation DBObject proj_fields = new BasicDBObject("timestamp", 1); proj_fields.put("pos", "$models.links.collisions.pos"); proj_fields.put("rot", "$models.links.collisions.rot"); DBObject project = new BasicDBObject("$project", proj_fields); // run aggregation List<DBObject> pipeline = Arrays.asList(match_time, unwind_models, match_model, project_links, unwind_links, match_link, project_collisions, unwind_collisions, match_collision, project); AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); Cursor cursor = this.coll.aggregate(pipeline, aggregationOptions); // Traj as dynamic array ArrayList<Vector3d> traj = new ArrayList<Vector3d>(); // timestamp used for deltaT double prev_ts = 0; // if cursor not empty, append matadata to the first doc if (cursor.hasNext()) { // get the first document as the next cursor BasicDBObject first_doc = (BasicDBObject) cursor.next(); traj.add(new Vector3d(((BasicDBObject) first_doc.get("pos")).getDouble("x"), ((BasicDBObject) first_doc.get("pos")).getDouble("y"), ((BasicDBObject) first_doc.get("pos")).getDouble("z"))); // set the timestamp prev_ts = first_doc.getDouble("timestamp"); } // if query returned no values for these timestamps, get the pose at the nearest timestamp else { // write the pose to the given db and coll this.ViewCollisionPoseAt(start_ts, model_name, link_name, collision_name, markerID, markerType, color, scale); } // insert rest of trajectory while (cursor.hasNext()) { // get the current document BasicDBObject curr_doc = (BasicDBObject) cursor.next(); double curr_ts = curr_doc.getDouble("timestamp"); // if time diff > then deltaT add position to trajectory if (curr_ts - prev_ts > deltaT) { traj.add(new Vector3d(((BasicDBObject) curr_doc.get("pos")).getDouble("x"), ((BasicDBObject) curr_doc.get("pos")).getDouble("y"), ((BasicDBObject) curr_doc.get("pos")).getDouble("z"))); prev_ts = curr_ts; } } // create the markers this.CreateMarkers(traj, markerID, markerType, color, scale); }
From source file:org.knowrob.knowrob_sim_games.MongoSimGames.java
License:Open Source License
/** * Get the positions of the model links at the given timestamp * view as rviz markers//from ww w.j av a 2 s .c o m */ public void ViewLinksTrajs(String start_str, String end_str, String model_name, String markerID, String markerType, String color, float scale, double deltaT) { // transform the knowrob time to double with 3 decimal precision double start_ts = (double) Math.round((parseTime_d(start_str) - TIME_OFFSET) * 1000) / 1000; double end_ts = (double) Math.round((parseTime_d(end_str) - TIME_OFFSET) * 1000) / 1000; // create the pipeline operations, first with the $match check the times DBObject match_time = new BasicDBObject("$match", new BasicDBObject("timestamp", new BasicDBObject("$gte", start_ts).append("$lte", end_ts))); // $unwind models in order to output only the queried model DBObject unwind_models = new BasicDBObject("$unwind", "$models"); // $match for the given model name from the unwinded models DBObject match_model = new BasicDBObject("$match", new BasicDBObject("models.name", model_name)); // build the $projection operation DBObject proj_fields = new BasicDBObject("_id", 0); proj_fields.put("timestamp", 1); proj_fields.put("links_pos", "$models.links.pos"); DBObject project = new BasicDBObject("$project", proj_fields); // run aggregation List<DBObject> pipeline = Arrays.asList(match_time, unwind_models, match_model, project); AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); Cursor cursor = this.coll.aggregate(pipeline, aggregationOptions); // Traj as dynamic array ArrayList<Vector3d> trajs = new ArrayList<Vector3d>(); double prev_ts = 0; // if cursor not empty, append matadata to the first doc if (cursor.hasNext()) { // get the first document as the next cursor BasicDBObject first_doc = (BasicDBObject) cursor.next(); // get the list of links pos BasicDBList pos_list = (BasicDBList) first_doc.get("links_pos"); // get the timestamp prev_ts = first_doc.getDouble("timestamp"); // pos_list and rot_list length should be always the same for (int i = 0; i < pos_list.size(); ++i) { trajs.add(new Vector3d(((BasicDBObject) pos_list.get(i)).getDouble("x"), ((BasicDBObject) pos_list.get(i)).getDouble("y"), ((BasicDBObject) pos_list.get(i)).getDouble("z"))); } } // if query returned no values for these timestamps, get the pose at the nearest timestamp else { this.ViewLinksPositionsAt(start_str, model_name, markerID, markerType, color, scale); } // insert rest of trajectory while (cursor.hasNext()) { // get the current document BasicDBObject curr_doc = (BasicDBObject) cursor.next(); // get the list of links pos BasicDBList pos_list = (BasicDBList) curr_doc.get("links_pos"); double curr_ts = curr_doc.getDouble("timestamp"); // if time diff > then deltaT add position to trajectory if (curr_ts - prev_ts > deltaT) { // pos_list and rot_list length should be always the same for (int i = 0; i < pos_list.size(); ++i) { trajs.add(new Vector3d(((BasicDBObject) pos_list.get(i)).getDouble("x"), ((BasicDBObject) pos_list.get(i)).getDouble("y"), ((BasicDBObject) pos_list.get(i)).getDouble("z"))); } prev_ts = curr_ts; } } // create the markers this.CreateMarkers(trajs, markerID, markerType, color, scale); }
From source file:org.openhab.persistence.mongodb.internal.MongoDBPersistenceService.java
License:Open Source License
@Override public Iterable<HistoricItem> query(FilterCriteria filter) { if (!initialized) { return Collections.emptyList(); }/*from ww w. j a v a2 s. com*/ if (!isConnected()) { connectToDatabase(); } if (!isConnected()) { return Collections.emptyList(); } String name = filter.getItemName(); Item item = getItem(name); List<HistoricItem> items = new ArrayList<HistoricItem>(); DBObject query = new BasicDBObject(); if (filter.getItemName() != null) { query.put(FIELD_ITEM, filter.getItemName()); } if (filter.getState() != null && filter.getOperator() != null) { String op = convertOperator(filter.getOperator()); Object value = convertValue(filter.getState()); query.put(FIELD_VALUE, new BasicDBObject(op, value)); } if (filter.getBeginDate() != null) { query.put(FIELD_TIMESTAMP, new BasicDBObject("$gte", filter.getBeginDate())); } if (filter.getEndDate() != null) { query.put(FIELD_TIMESTAMP, new BasicDBObject("$lte", filter.getEndDate())); } Integer sortDir = (filter.getOrdering() == Ordering.ASCENDING) ? 1 : -1; DBCursor cursor = this.mongoCollection.find(query).sort(new BasicDBObject(FIELD_TIMESTAMP, sortDir)) .skip(filter.getPageNumber() * filter.getPageSize()).limit(filter.getPageSize()); while (cursor.hasNext()) { BasicDBObject obj = (BasicDBObject) cursor.next(); final State state; if (item instanceof NumberItem) { state = new DecimalType(obj.getDouble(FIELD_VALUE)); } else if (item instanceof DimmerItem) { state = new PercentType(obj.getInt(FIELD_VALUE)); } else if (item instanceof SwitchItem) { state = OnOffType.valueOf(obj.getString(FIELD_VALUE)); } else if (item instanceof ContactItem) { state = OpenClosedType.valueOf(obj.getString(FIELD_VALUE)); } else if (item instanceof RollershutterItem) { state = new PercentType(obj.getInt(FIELD_VALUE)); } else if (item instanceof ColorItem) { state = new HSBType(obj.getString(FIELD_VALUE)); } else if (item instanceof DateTimeItem) { Calendar cal = Calendar.getInstance(); cal.setTime(obj.getDate(FIELD_VALUE)); state = new DateTimeType(cal); } else { state = new StringType(obj.getString(FIELD_VALUE)); } items.add(new MongoDBItem(name, state, obj.getDate(FIELD_TIMESTAMP))); } return items; }
From source file:org.sdsai.dsds.mongo.MongoUtils.java
License:Open Source License
public static Object getPrimitive(final BasicDBObject dbo, final String fieldName, final Class<?> returnType) throws Exception { final boolean contained = dbo.containsField(fieldName); if (Boolean.TYPE.equals(returnType)) return contained ? dbo.getBoolean(fieldName) : Boolean.FALSE; if (Short.TYPE.equals(returnType) || Byte.TYPE.equals(returnType) || Integer.TYPE.equals(returnType)) return (Integer) (contained ? dbo.getInt(fieldName) : 0); if (Character.TYPE.equals(returnType)) return (Character) ((dbo.get(fieldName) + "").charAt(0)); if (Long.TYPE.equals(returnType)) return (Long) (contained ? dbo.getLong(fieldName) : 0L); if (Float.TYPE.equals(returnType)) return (Float) (contained ? Float.valueOf(dbo.get(fieldName) + "") : 0F); if (Double.TYPE.equals(returnType)) return (Double) (contained ? dbo.getDouble(fieldName) : 0D); return null;//from w w w . j a v a2s. c o m }
From source file:pt.tiago.mongodbteste.MongoDB.java
private void queries() { DBCollection coll = db.getCollection("Purchase"); //find the sum group by category DBObject group = new BasicDBObject("$group", new BasicDBObject("_id", "$categoryID").append("total", new BasicDBObject("$sum", "$price"))); DBObject sort = new BasicDBObject("$sort", new BasicDBObject("price", 1)); AggregationOutput output = coll.aggregate(group, sort); for (DBObject result : output.results()) { System.out.println(result); }//from ww w .j a v a 2 s . co m System.out.println("////////////////////////////////"); //find the year of date //SELECT DISTINCT(YEAR(DateOfPurchase)) AS ano FROM Purchase // $group : {_id : { year : {$year : "$birth_date"}}, total : {$sum : 1} System.out.println("SELECT DISTINCT(YEAR(DateOfPurchase)) AS ano FROM Purchase"); DBCollection collection2 = db.getCollection("Purchase"); group = new BasicDBObject("$group", new BasicDBObject("_id", new BasicDBObject("year", new BasicDBObject("$year", "$dateOfPurchase"))) .append("total", new BasicDBObject("$sum", 1))); output = collection2.aggregate(group); BasicDBObject basicObj; for (DBObject result : output.results()) { basicObj = (BasicDBObject) result; basicObj = (BasicDBObject) basicObj.get("_id"); System.out.println(basicObj.get("year")); ; } System.out.println("////////////////////////////////"); //find the sum with year and categoryID // SELECT SUM(Price) AS Sumatorio FROM Purchase WHERE CategoryID = ? AND Year(DateOfPurchase) = ? System.out.println( "SELECT SUM(Price) AS Sumatorio FROM Purchase WHERE CategoryID = ? AND Year(DateOfPurchase) = ?"); int year = 2014; Calendar cal = Calendar.getInstance(); cal.set(year, 0, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(year, 11, 31); BasicDBObject match = new BasicDBObject("$match", new BasicDBObject("categoryID", new ObjectId("548089fc46e68338719aa1f8"))); match.put("$match", new BasicDBObject("dateOfPurchase", new BasicDBObject("$gte", cal.getTime()).append("$lt", cal2.getTime()))); group = new BasicDBObject("$group", new BasicDBObject("_id", null).append("total", new BasicDBObject("$sum", "$price"))); output = coll.aggregate(match, group); for (DBObject result : output.results()) { basicObj = (BasicDBObject) result; System.out.println(basicObj.getDouble("total")); } System.out.println("////////////////////////////////"); System.out.println("SELECT SUM(Price) , MONTH(DateOfPurchase)" + " FROM Purchase WHERE PersonID = ? AND CategoryID = ? " + "AND Price <= ? GROUP BY MONTH(DateOfPurchase)"); coll = db.getCollection("Purchase"); BasicDBObject cateObj = new BasicDBObject("categoryID", new ObjectId("548089fc46e68338719aa1f8")); BasicDBObject personObj = new BasicDBObject("personID", new ObjectId("548079fa46e68338719aa1f6")); BasicDBList and = new BasicDBList(); and.add(cateObj); and.add(personObj); DBObject andCriteria = new BasicDBObject("$and", and); DBObject matchCriteria = new BasicDBObject("$match", andCriteria); group = new BasicDBObject("$group", new BasicDBObject("_id", null).append("total", new BasicDBObject("$sum", "$price"))); group.put("$group", new BasicDBObject("_id", new BasicDBObject("month", new BasicDBObject("$month", "$dateOfPurchase"))) .append("total", new BasicDBObject("$sum", "$price"))); output = coll.aggregate(matchCriteria, group); for (DBObject result : output.results()) { basicObj = (BasicDBObject) result; System.out.println(basicObj.toString()); } System.out.println("////////////////////////////////"); System.out.println("SELECT SUM(Price) , PersonID FROM Purchase WHERE " + "YEAR(DateOfPurchase) = ? AND Price <= ? GROUP BY PersonID"); coll = db.getCollection("Purchase"); year = 2014; cal = Calendar.getInstance(); cal.set(year, 0, 0); cal2 = Calendar.getInstance(); cal2.set(year, 11, 31); BasicDBObject priceObj = new BasicDBObject("price", new BasicDBObject("$lte", 2000)); BasicDBObject dateObj = new BasicDBObject("dateOfPurchase", new BasicDBObject("$gte", cal.getTime()).append("$lt", cal2.getTime())); and = new BasicDBList(); and.add(priceObj); and.add(dateObj); andCriteria = new BasicDBObject("$and", and); matchCriteria = new BasicDBObject("$match", andCriteria); group = new BasicDBObject("$group", new BasicDBObject("_id", "$personID").append("total", new BasicDBObject("$sum", "$price"))); output = coll.aggregate(matchCriteria, group); for (DBObject result : output.results()) { basicObj = (BasicDBObject) result; System.out.println(basicObj.toString()); } }
From source file:tad.grupo7.ccamistadeslargas.DAO.GastoDAO.java
/** * Obtiene todos los gastos pertenecientes a un evento. * @param idEvento ObjectId del evento./* w w w.ja v a2s. com*/ * @return List */ public static List<Gasto> readAll(ObjectId idEvento) { BasicDBObject whereQuery = new BasicDBObject(); whereQuery.put("idEvento", idEvento); DBCursor cursor = gastos.find(whereQuery); List<Gasto> gastos = new ArrayList<>(); while (cursor.hasNext()) { BasicDBObject g = (BasicDBObject) cursor.next(); ObjectId id = g.getObjectId("_id"); String nombre = g.getString("nombre"); Double precio = g.getDouble("precio"); ObjectId idPagador = g.getObjectId("idPagador"); List<Participante> deudores = ParticipanteDAO.readAllDeudoresFromPago(id); gastos.add(new Gasto(id, nombre, precio, idEvento, idPagador, deudores)); } return gastos; }
From source file:tango.gui.CellManager.java
License:Open Source License
private void sort(String key, ArrayList<Cell> cells) { if (key.equals("idx")) return;/*from w ww . j a v a 2s . c o m*/ ij.IJ.log("sort by:" + key); Cell.setAscendingOrger(layout.getAscendingOrder()); boolean notFound = false; HashMap<ObjectId, BasicDBObject> objects = null; if (!key.equals("tag")) objects = Core.getExperiment().getConnector().getNucleiObjects(Core.getExperiment().getId()); for (Cell c : cells) { if (key.equals("tag")) c.setValue(c.getTag().getTag()); else { //HashMap<Integer, BasicDBObject> objects = Core.getExperiment().getConnector().getObjects(c.getId(), 0); //ij.IJ.log("nb of objects:"+objects.size()); //BasicDBObject dbo = objects.get(1); BasicDBObject dbo = objects.get(c.getId()); if (dbo != null) { if (dbo.containsField(key)) c.setValue(dbo.getDouble(key)); else { c.setValue(-1); notFound = true; } } } } if (notFound) ij.IJ.log("Warning measurement: " + key + " not found for one or several nuclei"); Collections.sort(cells); }
From source file:tango.gui.ObjectManager.java
License:Open Source License
private void sort(String key, Object3DGui[] objectsGui, int structureIdx) { Object3DGui.setAscendingOrger(((ObjectManagerLayout) layout).getAscendingOrder()); HashMap<Integer, BasicDBObject> objects = Core.getExperiment().getConnector().getObjects(currentNucId, structureIdx);/*w w w . j av a 2 s . com*/ boolean notFound = false; for (Object3DGui o : objectsGui) { BasicDBObject dbo = objects.get(o.getLabel()); if (dbo != null) { if (dbo.containsField(key)) { o.setValue(dbo.getDouble(key)); } else { o.setValue(-1); notFound = true; } } } if (notFound) { ij.IJ.log("Warning measurement: " + key + " not found for one or several objects"); } Arrays.sort(objectsGui); }
From source file:tango.mongo.MongoUtils.java
License:Open Source License
public static float[] getFloatArray(DBCursor cur, String key) { List<DBObject> list = cur.toArray(); float[] res = new float[list.size()]; boolean field = false; for (int i = 0; i < list.size(); i++) { BasicDBObject o = ((BasicDBObject) list.get(i)); if (o.containsField(key)) { field = true;/* w w w . j a v a2s . c o m*/ res[i] = (float) o.getDouble(key); } } return field ? res : null; }