List of usage examples for com.mongodb DBObject containsField
boolean containsField(String s);
From source file:org.atlasapi.persistence.content.mongo.MongoDBQueryBuilder.java
License:Apache License
private DBObject buildQueryForSingleLevelEntity(Collection<ConstrainedAttribute> contraints) { DBObject rhs = new BasicDBObject(); for (ConstrainedAttribute constrainedAttribute : contraints) { String name = attributeName(constrainedAttribute.attribute); if (rhs.containsField(name)) { ((DBObject) rhs.get(name)).putAll((DBObject) constrainedAttribute.queryOrValue()); } else {/*from w w w . ja v a 2 s .co m*/ rhs.put(name, constrainedAttribute.queryOrValue()); } } return rhs; }
From source file:org.aw20.mongoworkbench.command.MapReduceMongoCommand.java
License:Open Source License
@SuppressWarnings("deprecation") @Override/*w ww . j a v a2 s.c o m*/ public void execute() throws Exception { MongoClient mdb = MongoFactory.getInst().getMongo(sName); if (mdb == null) throw new Exception("no server selected"); if (sDb == null) throw new Exception("no database selected"); MongoFactory.getInst().setActiveDB(sDb); DB db = mdb.getDB(sDb); BasicDBObject cmdMap = parseMongoCommandString(db, cmd); if (!cmdMap.containsField("mapreduceArgs")) throw new Exception("no mapReduce document"); DBCollection collection = db.getCollection(sColl); // Build the Map BasicDBObject options = (BasicDBObject) ((BasicDBList) cmdMap.get("mapreduceArgs")).get(2); String outputCollection = null; String outputDB = null; MapReduceCommand.OutputType outputType = MapReduceCommand.OutputType.INLINE; if (options.get("out") instanceof String) { outputCollection = (String) options.get("out"); outputType = MapReduceCommand.OutputType.REPLACE; } else if (options.get("out") instanceof BasicDBObject) { BasicDBObject out = (BasicDBObject) options.get("out"); if (out.containsField("inline")) { outputCollection = null; } else if (out.containsField("replace")) { outputCollection = (String) out.get("replace"); outputType = MapReduceCommand.OutputType.REPLACE; } else if (out.containsField("merge")) { outputCollection = (String) out.get("merge"); outputType = MapReduceCommand.OutputType.MERGE; } else if (out.containsField("reduce")) { outputCollection = (String) out.get("reduce"); outputType = MapReduceCommand.OutputType.REDUCE; } if (out.containsField("db")) outputDB = (String) out.get("db"); } MapReduceCommand mrc = new MapReduceCommand(collection, ((Code) ((BasicDBList) cmdMap.get("mapreduceArgs")).get(0)).getCode(), ((Code) ((BasicDBList) cmdMap.get("mapreduceArgs")).get(1)).getCode(), outputCollection, outputType, (BasicDBObject) options.get("query")); if (outputDB != null) mrc.setOutputDB(outputDB); if (options.containsField("sort") && options.get("sort") instanceof DBObject) mrc.setSort((DBObject) options.get("sort")); if (options.containsField("scope") && options.get("scope") instanceof DBObject) mrc.setScope(((DBObject) options.get("scope")).toMap()); if (options.containsField("finalize") && options.get("scope") instanceof Code) mrc.setFinalize(((Code) options.get("scope")).getCode()); if (options.containsField("limit")) mrc.setLimit(StringUtil.toInteger(options.get("limit"), -1)); mrc.addExtraOption("jsMode", StringUtil.toBoolean(options.get("jsMode"), false)); mrc.setVerbose(StringUtil.toBoolean(options.get("verbose"), false)); // Run the actual mapreduce function MapReduceOutput mro = collection.mapReduce(mrc); // Pull the inline results if (mro.getOutputCollection() == null) { dbListResult = new BasicDBList(); Iterable<DBObject> it = mro.results(); for (DBObject dbo : it) { dbListResult.add(dbo); } } BasicDBObject dbo = mro.getRaw(); StringBuilder sb = new StringBuilder(); if (dbo.containsField("timeMillis")) sb.append("Time=").append(dbo.get("timeMillis")).append("ms; "); if (dbo.containsField("counts")) { BasicDBObject counts = (BasicDBObject) dbo.get("counts"); sb.append("Counts: input=" + counts.get("input")); sb.append("; emit=" + counts.get("emit")); sb.append("; reduce=" + counts.get("reduce")); sb.append("; output=" + counts.get("output")); } setMessage(sb.toString()); }
From source file:org.aw20.mongoworkbench.command.SystemJavaScriptReadCommand.java
License:Open Source License
@Override public void execute() throws Exception { MongoClient mdb = MongoFactory.getInst().getMongo(sName); if (mdb == null) throw new Exception("no server selected"); if (sDb == null) throw new Exception("no database selected"); MongoFactory.getInst().setActiveDB(sDb); DB db = mdb.getDB(sDb);/*w w w . j a v a 2s . c o m*/ DBCollection coll = db.getCollection("system.js"); DBObject dbo = coll.findOne(new BasicDBObject("_id", jsName)); if (dbo.containsField("value")) { jsCode = ((Code) dbo.get("value")).getCode(); } setMessage("System JavaScript loaded=" + jsName); }
From source file:org.aw20.mongoworkbench.eclipse.view.wizard.GroupWizard.java
License:Open Source License
@Override public boolean onWizardCommand(MongoCommand cmd, BasicDBObject dbo) { if (!cmd.getClass().getName().equals(GroupMongoCommand.class.getName())) return false; if (!dbo.containsField("groupArg")) return false; DBObject gmap = (DBObject) dbo.get("groupArg"); if (gmap.containsField("cond")) { textGroupCondition.setText(JSONFormatter.format(gmap.get("cond"))); } else {/*from w ww . jav a 2 s. c o m*/ textGroupCondition.setText(""); } if (gmap.containsField("initial")) { textGroupInitial.setText(JSONFormatter.format(gmap.get("initial"))); } else { textGroupInitial.setText(""); } if (gmap.containsField("key")) { textGroupKey.setText(JSONFormatter.format(gmap.get("key"))); } else { textGroupKey.setText(""); } if (gmap.containsField("keyf")) { org.bson.types.Code c = (org.bson.types.Code) gmap.get("key"); textGroupKeyF.setText(c.toString()); } else { textGroupKeyF.setText(""); } if (gmap.containsField("reduce")) { org.bson.types.Code c = (org.bson.types.Code) gmap.get("reduce"); textGroupReduce.setText(c.toString()); } else { textGroupReduce.setText(""); } if (gmap.containsField("finalize")) { org.bson.types.Code c = (org.bson.types.Code) gmap.get("finalize"); textGroupFinalize.setText(c.toString()); } else { textGroupFinalize.setText(""); } return true; }
From source file:org.axonframework.mongo.serialization.BSONNode.java
License:Apache License
/** * Constructrs a BSONNode structure from the given DBObject structure. The node returned is the root node. * * @param node The root DBObject node containing the BSON Structure * @return The BSONNode representing the root of the BSON structure *//*from w w w .ja va 2 s . co m*/ public static BSONNode fromDBObject(DBObject node) { if (node.keySet().size() != 1) { throw new IllegalArgumentException("Given node should have exactly one attribute"); } String rootName = node.keySet().iterator().next(); BSONNode rootNode = new BSONNode(decode(rootName)); Object rootContents = node.get(rootName); if (rootContents instanceof List) { ((List<?>) rootContents).stream().filter(childElement -> childElement instanceof DBObject) .forEach(childElement -> { DBObject dbChild = (DBObject) childElement; if (dbChild.containsField(VALUE_KEY)) { rootNode.setValue((String) dbChild.get(VALUE_KEY)); } else { rootNode.addChildNode(fromDBObject(dbChild)); } }); } else if (rootContents instanceof DBObject) { rootNode.addChildNode(fromDBObject((DBObject) rootContents)); } else if (rootContents instanceof String) { rootNode.setValue((String) rootContents); } else { throw new IllegalArgumentException( "Node in " + rootName + " contains child " + rootContents + " which cannot be parsed"); } return rootNode; }
From source file:org.axonframework.serialization.bson.BSONNode.java
License:Apache License
/** * Constructrs a BSONNode structure from the given DBObject structure. The node returned is the root node. * * @param node The root DBObject node containing the BSON Structure * @return The BSONNode representing the root of the BSON structure */// ww w .j a va2 s .c om public static BSONNode fromDBObject(DBObject node) { if (node.keySet().size() != 1) { throw new IllegalArgumentException("Given node should have exactly one attribute"); } String rootName = node.keySet().iterator().next(); BSONNode rootNode = new BSONNode(decode(rootName)); Object rootContents = node.get(rootName); if (rootContents instanceof List) { for (Object childElement : (List) rootContents) { if (childElement instanceof DBObject) { DBObject dbChild = (DBObject) childElement; if (dbChild.containsField(VALUE_KEY)) { rootNode.setValue((String) dbChild.get(VALUE_KEY)); } else { rootNode.addChildNode(fromDBObject(dbChild)); } } } } else if (rootContents instanceof DBObject) { rootNode.addChildNode(fromDBObject((DBObject) rootContents)); } else if (rootContents instanceof String) { rootNode.setValue((String) rootContents); } else { throw new IllegalArgumentException( "Node in " + rootName + " contains child " + rootContents + " which cannot be parsed"); } return rootNode; }
From source file:org.benjp.services.mongodb.ChatServiceImpl.java
License:Open Source License
public String read(String room, UserService userService, boolean isTextOnly, Long fromTimestamp, Long toTimestamp) {/*from ww w. j ava 2s. co m*/ StringBuilder sb = new StringBuilder(); SimpleDateFormat formatter = new SimpleDateFormat("hh:mm aaa"); SimpleDateFormat formatterDate = new SimpleDateFormat("dd/MM/yyyy hh:mm aaa"); // formatter.format(); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); Date today = calendar.getTime(); DBCollection coll = db().getCollection(M_ROOM_PREFIX + room); BasicDBObject query = new BasicDBObject(); long from = (fromTimestamp != null) ? fromTimestamp : System.currentTimeMillis() - readMillis; BasicDBObject tsobj = new BasicDBObject("$gt", from); if (toTimestamp != null) { tsobj.append("$lt", toTimestamp); } query.put("timestamp", tsobj); BasicDBObject sort = new BasicDBObject(); sort.put("timestamp", -1); int limit = (isTextOnly) ? readTotalTxt : readTotalJson; DBCursor cursor = coll.find(query).sort(sort).limit(limit); if (!cursor.hasNext()) { if (isTextOnly) sb.append("no messages"); else sb.append("{\"messages\": []}"); } else { Map<String, UserBean> users = new HashMap<String, UserBean>(); String timestamp, user, fullname, email, msgId, date; boolean first = true; while (cursor.hasNext()) { DBObject dbo = cursor.next(); timestamp = dbo.get("timestamp").toString(); if (first) //first element (most recent one) { if (!isTextOnly) { sb.append("{\"room\": \"").append(room).append("\","); sb.append("\"timestamp\": \"").append(timestamp).append("\","); sb.append("\"messages\": ["); } } user = dbo.get("user").toString(); msgId = dbo.get("_id").toString(); UserBean userBean = users.get(user); if (userBean == null) { userBean = userService.getUser(user); users.put(user, userBean); } fullname = userBean.getFullname(); email = userBean.getEmail(); date = ""; try { if (dbo.containsField("time")) { Date date1 = (Date) dbo.get("time"); if (date1.before(today) || isTextOnly) date = formatterDate.format(date1); else date = formatter.format(date1); } } catch (Exception e) { log.info("Message Date Format Error : " + e.getMessage()); } if (isTextOnly) { StringBuilder line = new StringBuilder(); line.append("[").append(date).append("] "); String message = dbo.get("message").toString(); if (TYPE_DELETED.equals(message)) message = TYPE_DELETED; if ("true".equals(dbo.get("isSystem"))) { line.append("System Message: "); if (message.endsWith("<br/>")) message = message.substring(0, message.length() - 5); line.append(message).append("\n"); } else { line.append(fullname).append(": "); message = message.replaceAll("<br/>", "\n"); line.append(message).append("\n"); } sb.insert(0, line); } else { if (!first) sb.append(","); sb.append("{\"id\": \"").append(msgId).append("\","); sb.append("\"timestamp\": ").append(timestamp).append(","); sb.append("\"user\": \"").append(user).append("\","); sb.append("\"fullname\": \"").append(fullname).append("\","); sb.append("\"email\": \"").append(email).append("\","); sb.append("\"date\": \"").append(date).append("\","); sb.append("\"message\": \"").append(dbo.get("message")).append("\","); if (dbo.containsField("options")) { String options = dbo.get("options").toString(); if (options.startsWith("{")) sb.append("\"options\": ").append(options).append(","); else sb.append("\"options\": \"").append(options).append("\","); } else { sb.append("\"options\": \"\","); } sb.append("\"type\": \"").append(dbo.get("type")).append("\","); sb.append("\"isSystem\": \"").append(dbo.get("isSystem")).append("\"}"); } first = false; } if (!isTextOnly) { sb.append("]}"); } } return sb.toString(); }
From source file:org.benjp.services.mongodb.ChatServiceImpl.java
License:Open Source License
public List<RoomBean> getExistingRooms(String user, boolean withPublic, boolean isAdmin, NotificationService notificationService, TokenService tokenService) { List<RoomBean> rooms = new ArrayList<RoomBean>(); String roomId = null;/* ww w .ja va 2s . c o m*/ DBCollection coll = db().getCollection(M_ROOM_PREFIX + M_ROOMS_COLLECTION); BasicDBObject basicDBObject = new BasicDBObject(); basicDBObject.put("users", user); DBCursor cursor = coll.find(basicDBObject); while (cursor.hasNext()) { DBObject dbo = cursor.next(); roomId = dbo.get("_id").toString(); long timestamp = -1; if (dbo.containsField("timestamp")) { timestamp = ((Long) dbo.get("timestamp")).longValue(); } List<String> users = ((List<String>) dbo.get("users")); users.remove(user); if (users.size() > 0 && !user.equals(users.get(0))) { String targetUser = users.get(0); boolean isDemoUser = tokenService.isDemoUser(targetUser); if (!isAdmin || (isAdmin && ((!withPublic && !isDemoUser) || (withPublic && isDemoUser)))) { RoomBean roomBean = new RoomBean(); roomBean.setRoom(roomId); roomBean.setUnreadTotal( notificationService.getUnreadNotificationsTotal(user, "chat", "room", roomId)); roomBean.setUser(users.get(0)); roomBean.setTimestamp(timestamp); rooms.add(roomBean); } } } return rooms; }
From source file:org.benjp.services.mongodb.NotificationServiceImpl.java
License:Open Source License
@Override public List<NotificationBean> getUnreadNotifications(String user, String type, String category, String categoryId) {//from ww w.j av a2 s. c o m List<NotificationBean> notifications = new ArrayList<NotificationBean>(); DBCollection coll = db().getCollection(M_NOTIFICATIONS); BasicDBObject query = new BasicDBObject(); query.put("user", user); // query.put("isRead", false); if (type != null) query.put("type", type); if (category != null) query.put("category", category); if (categoryId != null) query.put("categoryId", categoryId); DBCursor cursor = coll.find(query); while (cursor.hasNext()) { DBObject doc = cursor.next(); NotificationBean notificationBean = new NotificationBean(); notificationBean.setTimestamp((Long) doc.get("timestamp")); notificationBean.setUser(user); if (doc.containsField("from")) notificationBean.setFrom(doc.get("from").toString()); notificationBean.setCategory(doc.get("category").toString()); notificationBean.setCategoryId(doc.get("categoryId").toString()); notificationBean.setType(doc.get("type").toString()); notificationBean.setContent(doc.get("content").toString()); notificationBean.setLink(doc.get("link").toString()); notifications.add(notificationBean); } return notifications; }
From source file:org.benjp.services.mongodb.UserServiceImpl.java
License:Open Source License
public void toggleFavorite(String user, String targetUser) { DBCollection coll = db().getCollection(M_USERS_COLLECTION); BasicDBObject query = new BasicDBObject(); query.put("user", user); DBCursor cursor = coll.find(query);/* ww w. j a va 2 s.co m*/ if (cursor.hasNext()) { DBObject doc = cursor.next(); List<String> favorites = new ArrayList<String>(); if (doc.containsField("favorites")) { favorites = (List<String>) doc.get("favorites"); } if (favorites.contains(targetUser)) favorites.remove(targetUser); else favorites.add(targetUser); doc.put("favorites", favorites); coll.save(doc, WriteConcern.SAFE); } }