List of usage examples for com.mongodb BasicDBObject get
public Object get(final String key)
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 w ww. j a v a2 s . co 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.knowrob.knowrob_sim_games.MongoSimGames.java
License:Open Source License
/** * Get the positions of the model links at the given timestamp */// www. j a v a 2s .c o m public List<Point3d> GetLinksPositions(String ts_str, String model_name) { // list of all the links positions List<Point3d> links_positions = new ArrayList<Point3d>(); // transform the knowrob time to double with 3 decimal precision double timestamp = (double) Math.round((parseTime_d(ts_str) - TIME_OFFSET) * 1000) / 1000; // remove the knowrob namespace (http://knowrob.org/kb/knowrob.owl#) form the model // String model_name = kr_model_name.split("#")[1]; //System.out.println("Java - timestamp: " + timestamp + " model name: " + model_name); // $and list for querying the $match in the aggregation BasicDBList time_and_name = new BasicDBList(); // add the timestamp and the model name time_and_name.add(new BasicDBObject("timestamp", new BasicDBObject("$lte", timestamp))); time_and_name.add(new BasicDBObject("models.name", model_name)); // create the pipeline operations, first the $match DBObject match_time_and_name = new BasicDBObject("$match", new BasicDBObject("$and", time_and_name)); // sort the results in descending order on the timestamp (keep most recent result first) DBObject sort_desc = new BasicDBObject("$sort", new BasicDBObject("timestamp", -1)); // $limit the result to 1, we only need one pose DBObject limit_result = new BasicDBObject("$limit", 1); // $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_and_name, sort_desc, limit_result, 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); // if query has a response, append metadata to it if (cursor.hasNext()) { // get the first doc BasicDBObject first_doc = (BasicDBObject) cursor.next(); // get the positions array BasicDBList links_pos_arr = (BasicDBList) first_doc.get("links_pos"); // iterate the results for (int i = 0; i < links_pos_arr.size(); i++) { // current position Point3d pos = new Point3d(); // set the positions pos.x = ((BasicDBObject) links_pos_arr.get(i)).getDouble("x"); pos.y = ((BasicDBObject) links_pos_arr.get(i)).getDouble("y"); pos.z = ((BasicDBObject) links_pos_arr.get(i)).getDouble("z"); // add position to the list links_positions.add(pos); } } return links_positions; }
From source file:org.mephi.griffin.actorcloud.storage.Entity.java
License:Apache License
public Entity(BasicDBObject doc) { properties = new HashMap<>(); Set<String> keys = doc.keySet(); for (String key : keys) { if (doc.get(key) instanceof BasicDBObject) properties.put(key, new Entity((BasicDBObject) doc.get(key))); else if (doc.get(key) instanceof BasicDBObject[]) { ArrayList<Entity> entities = new ArrayList<>(); for (BasicDBObject item : ((BasicDBObject[]) doc.get(key))) { entities.add(new Entity(item)); }/*ww w . ja va2s . c o m*/ properties.put(key, entities); } else if (doc.get(key) instanceof List && ((List) doc.get(key)).size() > 0 && ((List) doc.get(key)).get(0) instanceof BasicDBObject) { ArrayList<Entity> entities = new ArrayList<>(); for (BasicDBObject item : (List<BasicDBObject>) doc.get(key)) entities.add(new Entity(item)); properties.put(key, entities); } else { properties.put(key, doc.get(key)); } } }
From source file:org.mongoste.core.impl.mongodb.MongoStatsEngine.java
License:Open Source License
@Override public List<StatCounter> getTopTargets(Query query) throws StatsEngineException { List<StatCounter> result = new ArrayList<StatCounter>(); try {/*w w w .j ava 2s .com*/ DBCollection counters = getCounterCollection(); DBObject queryDoc = MongoUtil.createDoc(EVENT_CLIENT_ID, getQueryValue(query, QueryField.CLIENT_ID), EVENT_TARGET_TYPE, getQueryValue(query, QueryField.TARGET_TYPE)); String actionCountPath = createDotPath(EVENT_ACTION, getQueryValue(query, QueryField.ACTION), FIELD_COUNT); DBObject order = MongoUtil.createDoc(actionCountPath, getQueryOrder(query)); log.debug("Ensuring index for {}", order); counters.ensureIndex(order); log.debug("Querying counters"); DBCursor dbc = counters.find(queryDoc, MongoUtil.createDoc(EVENT_TARGET, 1, EVENT_ACTION, 1)); Integer limit = query.getMaxResults(); dbc = dbc.sort(order).limit(limit == null ? 10 : limit); BasicDBObject counter; String target; Long count; while (dbc.hasNext()) { counter = (BasicDBObject) dbc.next(); target = String.valueOf(counter.get(EVENT_TARGET)); count = MongoUtil.getChildDBObject(counter, actionCountPath, 2).getLong(FIELD_COUNT); result.add(new StatCounter(target, count)); } } catch (Exception ex) { log.error("getTopTargets", ex); throw new StatsEngineException("getTopTargets", ex); } return result; }
From source file:org.mongoste.core.impl.mongodb.MongoStatsEngine.java
License:Open Source License
private List<StatAction> getTargetStats(DBObject query) throws StatsEngineException { List<StatAction> result = new ArrayList<StatAction>(); DBCursor dbc = null;//from w ww . jav a 2 s. c om try { log.debug("Querying targets"); DBCollection targets = getTargetCollection(); long t = System.currentTimeMillis(); DBObject fields = MongoUtil.createDoc(EVENT_ACTION, 1, FIELD_COUNT, 1, EVENT_DATE, 1); dbc = targets.find(query, fields); t = System.currentTimeMillis() - t; if (t > 1000) { log.warn("getTargetStats query: {}\n took {}s", debugTrim(query), t / 1000.0); } BasicDBObject resultDoc; Map<String, StatAction> actions = new HashMap<String, StatAction>(); Map<String, Map<DateTime, StatCounter>> actionsDate = new HashMap<String, Map<DateTime, StatCounter>>(); Map<DateTime, StatCounter> dateCount; StatAction action; StatCounter dateCounter; String actionName; Long count; MutableDateTime dateTime = DateUtil.getDateTimeUTC(true).toMutableDateTime(); DateTime date; Date eventYearMonthTargetDate; int processed = 0; t = System.currentTimeMillis(); while (dbc.hasNext()) { resultDoc = (BasicDBObject) dbc.next(); actionName = resultDoc.getString(EVENT_ACTION); count = resultDoc.getLong(FIELD_COUNT); eventYearMonthTargetDate = (Date) resultDoc.get(EVENT_DATE); dateTime.setDate(eventYearMonthTargetDate.getTime()); date = dateTime.toDateTime(); action = actions.get(actionName); if (action == null) { actions.put(actionName, action = new StatAction(actionName, 0)); } action.add(count); dateCount = actionsDate.get(actionName); if (dateCount == null) { dateCount = new TreeMap<DateTime, StatCounter>(); actionsDate.put(actionName, dateCount); } dateCounter = dateCount.get(date); if (dateCounter == null) { dateCount.put(date, dateCounter = new StatCounter(actionName, 0, date.toDate())); } dateCounter.add(count); processed++; } //Build result list for (Entry<String, StatAction> entry : actions.entrySet()) { action = entry.getValue(); dateCount = actionsDate.get(action.getName()); List<StatCounter> targetList = action.getTargets(); for (Entry<DateTime, StatCounter> entryDate : dateCount.entrySet()) { StatCounter counter = entryDate.getValue(); targetList.add(counter); } result.add(action); } t = System.currentTimeMillis() - t; //TODO add warning level to X ms: if (t > 1000) { log.warn("getTargetStats query fetch: {}\n took {}s", debugTrim(query), t / 1000.0); } else { log.info("getTargetStats processed {} results in {}ms", processed, t); } } catch (Exception ex) { log.error("getTargetStats", ex); if (ex instanceof StatsEngineException) { throw (StatsEngineException) ex; } throw new StatsEngineException("getTargetStats", ex); } finally { MongoUtil.close(dbc); } return result; }
From source file:org.mongoste.core.impl.mongodb.MongoStatsEngine.java
License:Open Source License
private Map<String, Long> getActionCount(DBObject query) throws StatsEngineException { Map<String, Long> result = new HashMap<String, Long>(); DBCursor dbc = null;//from ww w . ja v a 2s. co m try { log.debug("Querying counters"); DBCollection counters = getCounterCollection(); long t = System.currentTimeMillis(); dbc = counters.find(query, MongoUtil.createDoc(EVENT_ACTION, 1)); t = System.currentTimeMillis() - t; if (t > 1000) { log.warn("getActionCount query: {}\n took {}s", debugTrim(query), t / 1000.0); } BasicDBObject actionCounters, counter; String action; Long count; int processed = 0; t = System.currentTimeMillis(); while (dbc.hasNext()) { actionCounters = (BasicDBObject) dbc.next(); actionCounters = (BasicDBObject) actionCounters.get(EVENT_ACTION); for (Map.Entry entry : actionCounters.entrySet()) { action = entry.getKey().toString(); count = result.get(action); if (count == null) { count = 0L; } counter = (BasicDBObject) entry.getValue(); count += counter.getLong(FIELD_COUNT); result.put(action, count); } processed++; } t = System.currentTimeMillis() - t; if (t > 1000) { log.warn("getActionCount query fetch: {}\n took {}s", debugTrim(query), t / 1000.0); } else { log.info("getActionCount processed {} results in {}ms", processed, t); } } catch (Exception ex) { log.error("getActionCount", ex); if (ex instanceof StatsEngineException) { throw (StatsEngineException) ex; } throw new StatsEngineException("getActionCount", ex); } finally { MongoUtil.close(dbc); } return result; }
From source file:org.mongoste.core.impl.mongodb.MongoUtil.java
License:Open Source License
public static BasicDBObject getChildDBObject(BasicDBObject source, String dotPath, int maxDepth) { String[] path = dotPath.split("\\."); BasicDBObject result = source; for (String key : path) { if (result == null) { break; }/* ww w . j a v a 2 s . com*/ result = (BasicDBObject) result.get(key); if (--maxDepth == 0) { break; } } return result; }
From source file:org.mule.transport.mongodb.MongoDBMessageDispatcher.java
License:Open Source License
protected Object doDispatchToCollection(MuleEvent event, String collection) throws Exception { Object payload = event.getMessage().getPayload(); DB db;//from w w w .j a v a 2 s . co m db = connector.getMongo().getDB(connector.getMongoURI().getDatabase()); db.requestStart(); if (payload instanceof List) { List list = (List) payload; for (Object o : list) { performOperation(event, o, db, collection); } db.requestDone(); return payload; } else { MuleMessage message = event.getMessage(); BasicDBObject result = performOperation(event, message.getPayload(), db, collection); Object id = getObjectIdAsString(result.get("_id")); if (id == null) { logger.warn("_id is null, cannot set " + MongoDBConnector.PROPERTY_OBJECT_ID); } else { event.getMessage().setOutboundProperty(MongoDBConnector.PROPERTY_OBJECT_ID, id); } db.requestDone(); return result.toMap(); } }
From source file:org.mule.transport.mongodb.MongoDBMessageDispatcher.java
License:Open Source License
protected BasicDBObject update(BasicDBObject object, DB db, String collection, MuleEvent event) throws Exception { logger.debug(String.format("Updating collection %s in DB %s: %s", collection, db, object)); boolean upsert = false; boolean multi = false; MuleMessage message = event.getMessage(); if (message.getOutboundPropertyNames().contains(MongoDBConnector.MULE_MONGO_UPDATE_UPSERT)) { if (message.getOutboundProperty(MongoDBConnector.MULE_MONGO_UPDATE_UPSERT).equals("true")) upsert = true;/*from ww w. j a v a2 s . co m*/ } if (event.getEndpoint().getProperties().containsKey("upsert")) { if (event.getEndpoint().getProperty("upsert").equals("true")) upsert = true; } if (message.getOutboundPropertyNames().contains(MongoDBConnector.MULE_MONGO_UPDATE_MULTI)) { if (message.getOutboundProperty(MongoDBConnector.MULE_MONGO_UPDATE_MULTI).equals("true")) multi = true; } if (event.getEndpoint().getProperties().containsKey("multi")) { if (event.getEndpoint().getProperty("multi").equals("true")) multi = true; } DBObject objectToUpdate; if (!message.getOutboundPropertyNames().contains(MongoDBConnector.MULE_MONGO_UPDATE_QUERY) && !event.getEndpoint().getProperties().containsKey("updateQuery")) { logger.debug(String.format("%s property is not set, updating object using _id value of payload", MongoDBConnector.MULE_MONGO_UPDATE_QUERY)); objectToUpdate = db.getCollection(collection) .findOne(new BasicDBObject("_id", new ObjectId(object.get("_id").toString()))); if (!upsert) { throw new MongoException("Object not found from update query and upsert is false"); } } else { String updateQuery = message.getOutboundProperty(MongoDBConnector.MULE_MONGO_UPDATE_QUERY); if (updateQuery == null) { updateQuery = (String) event.getEndpoint().getProperty("updateQuery"); } String evaluatedQuery = message.getMuleContext().getExpressionManager().parse(updateQuery, message); logger.debug(String.format("%s property is set, building query from %s", MongoDBConnector.MULE_MONGO_UPDATE_QUERY, evaluatedQuery)); objectToUpdate = (DBObject) JSON.parse(evaluatedQuery); if (objectToUpdate == null) throw new MongoException("Could not find create update query from: " + updateQuery); } WriteConcern writeConcern = WriteConcernFactory.getWriteConcern(event); if (writeConcern == null) { db.getCollection(collection).update(objectToUpdate, object, upsert, multi); } else { logger.debug("Using WriteConcern value " + writeConcern); db.getCollection(collection).update(objectToUpdate, object, upsert, multi, writeConcern); } return object; }
From source file:org.mybatis.jpetstore.domain.Item.java
License:Apache License
public static Item fromDBObject(@Nonnull final DBObject dbObj) { checkNotNull(dbObj, "Argument[dbObj] must not be null"); BasicDBObject itemObj = (BasicDBObject) dbObj; DBObject productObj = (DBObject) itemObj.get("product"); ItemBuilder builder = new ItemBuilder(itemObj.getString("item_id"), Product.fromDBObject(productObj)); if (itemObj.get("supplier_id") != null) { builder.supplierId(itemObj.getInt("supplier_id")); }/*from w w w .j a va 2 s . c o m*/ String listPrice = itemObj.getString("list_price"); if (!isNullOrEmpty(listPrice)) { builder.listPrice(decodeRealNumber(listPrice)); } String unitCost = itemObj.getString("unit_cost"); if (!isNullOrEmpty(unitCost)) { builder.unitCost(decodeRealNumber(unitCost)); } builder.status(itemObj.getString("status")).quantity(itemObj.getInt("quantity")) .attribute1(itemObj.getString("attribute_1")).attribute2(itemObj.getString("attribute_2")) .attribute3(itemObj.getString("attribute_3")).attribute4(itemObj.getString("attribute_4")) .attribute5(itemObj.getString("attribute_5")); return builder.build(); }