List of usage examples for com.mongodb DBObject containsField
boolean containsField(String s);
From source file:org.datanucleus.store.mongodb.MongoDBSchemaHandler.java
License:Open Source License
private DBObject getIndexObjectForIndex(List<DBObject> indices, String idxName, DBObject idxObj, boolean unique) { if (indices == null || indices.isEmpty()) { return null; }//from w w w .j av a 2 s . c om Iterator<DBObject> idxIter = indices.iterator(); while (idxIter.hasNext()) { DBObject index = idxIter.next(); DBObject obj = null; String name = (String) index.get("name"); if (name.equals(idxName)) { obj = index; if (unique) { boolean flag = (Boolean) index.get("unique"); if (!flag) { continue; } } boolean equal = true; DBObject key = (DBObject) index.get("key"); if (key.toMap().size() != idxObj.toMap().size()) { equal = false; } else { Iterator<String> indicKeyIter = key.keySet().iterator(); while (indicKeyIter.hasNext()) { String fieldKey = indicKeyIter.next(); Object fieldValue = key.get(fieldKey); if (!idxObj.containsField(fieldKey)) { equal = false; } else { Object idxObjValue = idxObj.get(fieldKey); if (!idxObjValue.equals(fieldValue)) { equal = false; } } } } if (equal) { return obj; } } } return null; }
From source file:org.eclipse.birt.data.oda.mongodb.internal.impl.MDbOperation.java
License:Open Source License
static MapReduceOutput callMapReduceCmd(DBCollection dbCollection, QueryProperties queryProps) throws OdaException { if (!queryProps.hasMapReduceCommand()) return null; DBObject command = queryProps.getOperationExprAsParsedObject(false); if (command == null) return null; // check if mapreduce key is already specified in user-defined expression DBObject mapReduceCmd;/*ww w .ja v a2s. c o m*/ if (command.containsField(QueryModel.MAP_REDUCE_CMD_KEY) || command.containsField(QueryModel.MAP_REDUCE_CMD_KEY2)) mapReduceCmd = command; else { // add MapReduce input collection as first entry in command Map mapReduceCmd = new BasicDBObject(QueryModel.MAP_REDUCE_CMD_KEY, dbCollection.getName()); mapReduceCmd.putAll(command); // copy existing command entries } // mapReduce command's optional "limit" parameter applies to the number // of documents in the *input* collection, and thus cannot be used to apply // the searchLimit property defined for data set // execute the mapreduce command MapReduceOutput output; try { output = dbCollection.mapReduce(mapReduceCmd); output.getCommandResult().throwOnError(); return output; } catch (RuntimeException ex) { OdaException odaEx = new OdaException( Messages.bind(Messages.mDbOp_mapReduceCmdFailed, queryProps.getOperationExpression())); odaEx.initCause(ex); throw odaEx; } }
From source file:org.eclipse.birt.data.oda.mongodb.internal.impl.QueryModel.java
License:Open Source License
private static void validateMapReduceCommand(DBObject commandObj) throws OdaException { for (int i = 0; i < REQUIRED_MAPREDUCE_KEYS.length; i++) { String requiredKey = REQUIRED_MAPREDUCE_KEYS[i]; if (!commandObj.containsField(requiredKey)) throw new OdaException(Messages.bind(Messages.queryModel_missingMapReduceKey, requiredKey)); if (commandObj.get(requiredKey) == null) throw new OdaException(Messages.bind(Messages.queryModel_missingMapReduceValue, requiredKey)); }// w ww . ja v a 2 s . co m }
From source file:org.eclipse.birt.data.oda.mongodb.internal.impl.QueryModel.java
License:Open Source License
private static void validateDBCommand(DBObject commandObj) throws OdaException { // check that the db command is one of the supported ones boolean hasSupportedCommand = false; for (int i = 0; i < SUPPORTED_DB_COMMANDS.length; i++) { String supportedCommand = SUPPORTED_DB_COMMANDS[i]; if (commandObj.containsField(supportedCommand) || commandObj.containsField(supportedCommand.toLowerCase())) { hasSupportedCommand = true;//from w w w . jav a 2 s . c om break; } } if (!hasSupportedCommand) throw new OdaException(Messages.bind(Messages.queryModel_nonSupportedDbCmd, commandObj.toString())); // only supports eval command w/ {nolock : true} if (commandObj.containsField(EVAL_KEY)) { boolean noLockValue = getBooleanValueOfKey(commandObj, NOLOCK_KEY, false); if (noLockValue != true) throw new OdaException(Messages.bind(Messages.queryModel_invalidDbCmdKeyValue, EVAL_KEY, "{" + NOLOCK_KEY + " : true}")); //$NON-NLS-1$ //$NON-NLS-2$ } }
From source file:org.eclipselabs.mongoemf.builders.EObjectBuilderImpl.java
License:Open Source License
/** * Builds an attribute value from the DBObject, converting the value if necessary. * Feature maps are delegated to buildFeatureMap() and non-native arrays to * buildAttributeArray(). The converter service is used for value conversion. * Attribute values are expected to be mapped in the DBObject using the attribute * name as the key./*from w w w .ja va2s . c om*/ * * @param collection the MongoDB collection containing the DBObject * @param dbObject the object read from MongoDB * @param resource the resource that will contain the EMF Object * @param eObject the EMF object being built * @param attribute the attribute to set on the EMF object */ @SuppressWarnings("unchecked") protected void buildAttribute(DBCollection collection, DBObject dbObject, Resource resource, EObject eObject, EAttribute attribute) { // Attributes are mapped as key / value pairs with the key being the attribute name. if (!attribute.isTransient() && dbObject.containsField(attribute.getName())) { Object value = dbObject.get(attribute.getName()); if (FeatureMapUtil.isFeatureMap(attribute)) buildFeatureMap(collection, resource, eObject, attribute, (List<DBObject>) value); else if (attribute.isMany()) buildAttributeArray(eObject, attribute, value); else buildAttributeValue(eObject, attribute, value); } }
From source file:org.eclipselabs.mongoemf.builders.EObjectBuilderImpl.java
License:Open Source License
/** * Builds a reference value from the DBObject. References with cardinality greater * than one are expected to be stored as a java.util.List of DBObject. References * with cardinality equal to one are expected to be stored as a DBObject. * Reference values are expected to be mapped in the DBObject using the reference * name as the key. Building of the referenced object is delegated to * buildReferencedObject()./* w w w. ja v a 2 s . c o m*/ * * @param collection the MongoDB collection containing the DBObject * @param dbObject the object read from MongoDB * @param resource the resource that will contain the EMF Object * @param eObject the EMF object being built * @param reference the reference to set on the EMF object */ protected void buildReference(DBCollection collection, DBObject dbObject, Resource resource, EObject eObject, EReference reference) { // References are mapped as key / value pairs with the key being the reference name. if (!reference.isTransient() && dbObject.containsField(reference.getName())) { boolean isResolveProxies = reference.isResolveProxies(); if (reference.isMany()) { // One to many reference @SuppressWarnings("unchecked") List<DBObject> dbReferences = (List<DBObject>) dbObject.get(reference.getName()); @SuppressWarnings("unchecked") EList<EObject> eObjects = (EList<EObject>) eObject.eGet(reference); for (DBObject dbReference : dbReferences) { EObject target = buildReferencedObject(collection, dbReference, resource, isResolveProxies); eObjects.add(target); } } else { // One to one reference DBObject dbReference = (DBObject) dbObject.get(reference.getName()); EObject target = buildReferencedObject(collection, dbReference, resource, isResolveProxies); eObject.eSet(reference, target); } } }
From source file:org.eclipselabs.mongoemf.query.simple.SimpleQueryEngine.java
License:Open Source License
private DBObject buildDBObjectQuery(Expression expression) { final DBObject dbObject = new BasicDBObject(); if (expression != null) { new QuerySwitch<Object>() { Object getValue(Literal literal) { return literal.getValue() == null ? literal.getLiteralValue() : literal.getValue(); }/*from w w w . jav a 2s . c o m*/ @Override public Object caseBinaryOperation(BinaryOperation binaryOperation) { Expression leftOperand = binaryOperation.getLeftOperand(); String operator = binaryOperation.getOperator(); if ("==".equals(operator)) { Expression rightOperand = binaryOperation.getRightOperand(); String property = ExpressionBuilder.toString(leftOperand); if (Keywords.ID_KEY.equals(property)) { dbObject.put(property, new ObjectId(((Literal) rightOperand).getLiteralValue())); } else if (rightOperand instanceof Literal) { dbObject.put(property, getValue((Literal) rightOperand)); } else if ("null".equals(ExpressionBuilder.toString(rightOperand))) { DBObject notExists = new BasicDBObject(); notExists.put("$exists", Boolean.FALSE); dbObject.put(property, notExists); } else { // TODO: What to do? } } else if ("!=".equals(operator)) { Expression rightOperand = binaryOperation.getRightOperand(); String property = ExpressionBuilder.toString(leftOperand); if (rightOperand instanceof Literal) { DBObject notEqual = new BasicDBObject(); notEqual.put("$ne", getValue((Literal) rightOperand)); dbObject.put(property, notEqual); } else if ("null".equals(ExpressionBuilder.toString(rightOperand))) { DBObject exists = new BasicDBObject(); exists.put("$exists", Boolean.TRUE); dbObject.put(property, exists); } else { // TODO: What to do? } } else if ("<".equals(operator) || "<=".equals(operator) || ">".equals(operator) || ">=".equals(operator)) { Expression rightOperand = binaryOperation.getRightOperand(); String property = ExpressionBuilder.toString(leftOperand); if (rightOperand instanceof Literal) { DBObject compare = new BasicDBObject(); compare.put( "<".equals(operator) ? QueryOperators.LT : "<=".equals(operator) ? QueryOperators.LTE : ">".equals(operator) ? QueryOperators.GT : QueryOperators.GTE, getValue((Literal) rightOperand)); dbObject.put(property, compare); } else { // TODO: What to do? } } else if ("||".equals(operator)) { DBObject leftObject = buildDBObjectQuery(leftOperand); DBObject rightObject = buildDBObjectQuery(binaryOperation.getRightOperand()); @SuppressWarnings("unchecked") List<Object> or = (List<Object>) leftObject.get("$or"); if (or != null) { or.add(rightObject); dbObject.putAll(leftObject); } else { or = new ArrayList<Object>(); or.add(leftObject); or.add(rightObject); dbObject.put("$or", or); } } else if ("&&".equals(operator)) { dbObject.putAll(buildDBObjectQuery(leftOperand)); DBObject rightObject = buildDBObjectQuery(binaryOperation.getRightOperand()); for (String field : rightObject.keySet()) { Object rightValue = rightObject.get(field); Object leftValue = dbObject.get(field); if (leftValue instanceof DBObject) { DBObject leftDBObject = (DBObject) leftValue; if (rightValue instanceof DBObject) { DBObject rightDBObject = (DBObject) rightValue; if (leftDBObject.containsField("$nin") && rightDBObject.containsField("$ne")) { @SuppressWarnings("unchecked") List<Object> values = (List<Object>) leftDBObject.get("$nin"); values.add(rightDBObject.get("$ne")); } else if (leftDBObject.containsField("$ne") && rightDBObject.containsField("$ne")) { DBObject nin = new BasicDBObject(); List<Object> values = new ArrayList<Object>(); values.add(leftDBObject.get("$ne")); values.add(rightDBObject.get("$ne")); nin.put("$nin", values); dbObject.put(field, nin); } else { leftDBObject.putAll(rightDBObject); } } else { Object all = leftDBObject.get("$all"); if (all instanceof List<?>) { @SuppressWarnings("unchecked") List<Object> allList = (List<Object>) all; allList.add(rightValue); } else { // What to do? } } } else if (leftValue instanceof List<?>) { @SuppressWarnings("unchecked") List<Object> leftListValue = (List<Object>) leftValue; if (rightValue instanceof List<?>) { leftListValue.addAll((List<?>) rightValue); } else { leftListValue.add(rightValue); } } else if (leftValue != null) { if (rightValue instanceof List<?>) { @SuppressWarnings("unchecked") List<Object> rightListValue = (List<Object>) rightValue; rightListValue.add(0, leftValue); dbObject.put(field, rightListValue); } else { List<Object> listValue = new ArrayList<Object>(); listValue.add(leftValue); listValue.add(rightValue); DBObject in = new BasicDBObject("$all", listValue); dbObject.put(field, in); } } else { dbObject.put(field, rightValue); } } } return null; } }.doSwitch(expression); } return dbObject; }
From source file:org.elasticsearch.river.mongodb.util.MongoDBHelper.java
License:Apache License
public static DBObject applyExcludeFields(DBObject bsonObject, Set<String> excludeFields) { if (excludeFields == null) { return bsonObject; }/* w w w . j av a 2s . c o m*/ DBObject filteredObject = bsonObject; for (String field : excludeFields) { if (field.contains(".")) { String rootObject = field.substring(0, field.indexOf(".")); String childObject = field.substring(field.indexOf(".") + 1); if (filteredObject.containsField(rootObject)) { Object object = filteredObject.get(rootObject); if (object instanceof DBObject) { DBObject object2 = (DBObject) object; object2 = applyExcludeFields(object2, new HashSet<String>(Arrays.asList(childObject))); } } } else { if (filteredObject.containsField(field)) { filteredObject.removeField(field); } } } return filteredObject; }
From source file:org.exoplatform.chat.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 a v a 2 s. 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(","); if (dbo.containsField("lastUpdatedTimestamp")) { sb.append("\"lastUpdatedTimestamp\": ").append(dbo.get("lastUpdatedTimestamp").toString()) .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(StringEscapeUtils.escapeJson(dbo.get("message").toString())) .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.exoplatform.chat.services.mongodb.NotificationServiceImpl.java
License:Open Source License
@Override public List<NotificationBean> getUnreadNotifications(String user, UserService userService, String type, String category, String categoryId) { 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);// w ww . j a v a 2 s . co m 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.setFromFullName(userService.getUser(notificationBean.getFrom()).getFullname()); } notificationBean.setCategory(doc.get("category").toString()); notificationBean.setCategoryId(doc.get("categoryId").toString()); notificationBean.setType(doc.get("type").toString()); notificationBean.setContent(doc.get("content").toString()); if (doc.containsField("options")) { notificationBean.setOptions(doc.get("options").toString()); } RoomBean roomBean = userService.getRoom(user, notificationBean.getCategoryId()); if (roomBean.isSpace() || roomBean.isTeam()) { notificationBean.setRoomDisplayName(roomBean.getFullname()); } notificationBean.setLink(doc.get("link").toString()); notifications.add(notificationBean); } return notifications; }