List of usage examples for com.mongodb BasicDBObject append
@Override public BasicDBObject append(final String key, final Object val)
From source file:com.opengamma.livedata.server.MongoDBPersistentSubscriptionManager.java
License:Open Source License
@Override public void saveToStorage(Set<PersistentSubscription> newState) { clean();/* w w w. j a v a 2 s.co m*/ FudgeSerializer serializer = new FudgeSerializer(OpenGammaFudgeContext.getInstance()); FudgeDeserializer deserializer = new FudgeDeserializer(OpenGammaFudgeContext.getInstance()); List<DBObject> objects = new ArrayList<DBObject>(); for (PersistentSubscription sub : newState) { FudgeMsg msg = LiveDataSpecificationFudgeBuilder.toFudgeMsg(serializer, sub.getFullyQualifiedSpec()); DBObject fieldData = deserializer.fudgeMsgToObject(DBObject.class, msg); BasicDBObject mainObject = new BasicDBObject(); mainObject.append("fieldData", fieldData); objects.add(mainObject); } _mongoCollection.insert(objects); }
From source file:com.querydsl.mongodb.MongodbSerializer.java
License:Apache License
@SuppressWarnings("unchecked") @Override/*from w ww . j a v a2 s . c om*/ public Object visit(Operation<?> expr, Void context) { Operator op = expr.getOperator(); if (op == Ops.EQ) { if (expr.getArg(0) instanceof Operation) { Operation<?> lhs = (Operation<?>) expr.getArg(0); if (lhs.getOperator() == Ops.COL_SIZE || lhs.getOperator() == Ops.ARRAY_SIZE) { return asDBObject(asDBKey(lhs, 0), asDBObject("$size", asDBValue(expr, 1))); } else { throw new UnsupportedOperationException("Illegal operation " + expr); } } else if (expr.getArg(0) instanceof Path) { Path<?> path = (Path<?>) expr.getArg(0); Constant<?> constant = (Constant<?>) expr.getArg(1); return asDBObject(asDBKey(expr, 0), convert(path, constant)); } } else if (op == Ops.STRING_IS_EMPTY) { return asDBObject(asDBKey(expr, 0), ""); } else if (op == Ops.AND) { BSONObject lhs = (BSONObject) handle(expr.getArg(0)); BSONObject rhs = (BSONObject) handle(expr.getArg(1)); if (Sets.intersection(lhs.keySet(), rhs.keySet()).isEmpty()) { lhs.putAll(rhs); return lhs; } else { BasicDBList list = new BasicDBList(); list.add(handle(expr.getArg(0))); list.add(handle(expr.getArg(1))); return asDBObject("$and", list); } } else if (op == Ops.NOT) { //Handle the not's child Operation<?> subOperation = (Operation<?>) expr.getArg(0); Operator subOp = subOperation.getOperator(); if (subOp == Ops.IN) { return visit(ExpressionUtils.operation(Boolean.class, Ops.NOT_IN, subOperation.getArg(0), subOperation.getArg(1)), context); } else { BasicDBObject arg = (BasicDBObject) handle(expr.getArg(0)); return negate(arg); } } else if (op == Ops.OR) { BasicDBList list = new BasicDBList(); list.add(handle(expr.getArg(0))); list.add(handle(expr.getArg(1))); return asDBObject("$or", list); } else if (op == Ops.NE) { Path<?> path = (Path<?>) expr.getArg(0); Constant<?> constant = (Constant<?>) expr.getArg(1); return asDBObject(asDBKey(expr, 0), asDBObject("$ne", convert(path, constant))); } else if (op == Ops.STARTS_WITH) { return asDBObject(asDBKey(expr, 0), Pattern.compile("^" + regexValue(expr, 1))); } else if (op == Ops.STARTS_WITH_IC) { return asDBObject(asDBKey(expr, 0), Pattern.compile("^" + regexValue(expr, 1), Pattern.CASE_INSENSITIVE)); } else if (op == Ops.ENDS_WITH) { return asDBObject(asDBKey(expr, 0), Pattern.compile(regexValue(expr, 1) + "$")); } else if (op == Ops.ENDS_WITH_IC) { return asDBObject(asDBKey(expr, 0), Pattern.compile(regexValue(expr, 1) + "$", Pattern.CASE_INSENSITIVE)); } else if (op == Ops.EQ_IGNORE_CASE) { return asDBObject(asDBKey(expr, 0), Pattern.compile("^" + regexValue(expr, 1) + "$", Pattern.CASE_INSENSITIVE)); } else if (op == Ops.STRING_CONTAINS) { return asDBObject(asDBKey(expr, 0), Pattern.compile(".*" + regexValue(expr, 1) + ".*")); } else if (op == Ops.STRING_CONTAINS_IC) { return asDBObject(asDBKey(expr, 0), Pattern.compile(".*" + regexValue(expr, 1) + ".*", Pattern.CASE_INSENSITIVE)); } else if (op == Ops.MATCHES) { return asDBObject(asDBKey(expr, 0), Pattern.compile(asDBValue(expr, 1).toString())); } else if (op == Ops.MATCHES_IC) { return asDBObject(asDBKey(expr, 0), Pattern.compile(asDBValue(expr, 1).toString(), Pattern.CASE_INSENSITIVE)); } else if (op == Ops.LIKE) { String regex = ExpressionUtils.likeToRegex((Expression) expr.getArg(1)).toString(); return asDBObject(asDBKey(expr, 0), Pattern.compile(regex)); } else if (op == Ops.BETWEEN) { BasicDBObject value = new BasicDBObject("$gte", asDBValue(expr, 1)); value.append("$lte", asDBValue(expr, 2)); return asDBObject(asDBKey(expr, 0), value); } else if (op == Ops.IN) { int constIndex = 0; int exprIndex = 1; if (expr.getArg(1) instanceof Constant<?>) { constIndex = 1; exprIndex = 0; } if (Collection.class.isAssignableFrom(expr.getArg(constIndex).getType())) { @SuppressWarnings("unchecked") //guarded by previous check Collection<?> values = ((Constant<? extends Collection<?>>) expr.getArg(constIndex)).getConstant(); return asDBObject(asDBKey(expr, exprIndex), asDBObject("$in", values.toArray())); } else { Path<?> path = (Path<?>) expr.getArg(exprIndex); Constant<?> constant = (Constant<?>) expr.getArg(constIndex); return asDBObject(asDBKey(expr, exprIndex), convert(path, constant)); } } else if (op == Ops.NOT_IN) { int constIndex = 0; int exprIndex = 1; if (expr.getArg(1) instanceof Constant<?>) { constIndex = 1; exprIndex = 0; } if (Collection.class.isAssignableFrom(expr.getArg(constIndex).getType())) { @SuppressWarnings("unchecked") //guarded by previous check Collection<?> values = ((Constant<? extends Collection<?>>) expr.getArg(constIndex)).getConstant(); return asDBObject(asDBKey(expr, exprIndex), asDBObject("$nin", values.toArray())); } else { Path<?> path = (Path<?>) expr.getArg(exprIndex); Constant<?> constant = (Constant<?>) expr.getArg(constIndex); return asDBObject(asDBKey(expr, exprIndex), asDBObject("$ne", convert(path, constant))); } } else if (op == Ops.COL_IS_EMPTY) { BasicDBList list = new BasicDBList(); list.add(asDBObject(asDBKey(expr, 0), new BasicDBList())); list.add(asDBObject(asDBKey(expr, 0), asDBObject("$exists", false))); return asDBObject("$or", list); } else if (op == Ops.LT) { return asDBObject(asDBKey(expr, 0), asDBObject("$lt", asDBValue(expr, 1))); } else if (op == Ops.GT) { return asDBObject(asDBKey(expr, 0), asDBObject("$gt", asDBValue(expr, 1))); } else if (op == Ops.LOE) { return asDBObject(asDBKey(expr, 0), asDBObject("$lte", asDBValue(expr, 1))); } else if (op == Ops.GOE) { return asDBObject(asDBKey(expr, 0), asDBObject("$gte", asDBValue(expr, 1))); } else if (op == Ops.IS_NULL) { return asDBObject(asDBKey(expr, 0), asDBObject("$exists", false)); } else if (op == Ops.IS_NOT_NULL) { return asDBObject(asDBKey(expr, 0), asDBObject("$exists", true)); } else if (op == Ops.CONTAINS_KEY) { Path<?> path = (Path<?>) expr.getArg(0); Expression<?> key = expr.getArg(1); return asDBObject(visit(path, context) + "." + key.toString(), asDBObject("$exists", true)); } else if (op == MongodbOps.NEAR) { return asDBObject(asDBKey(expr, 0), asDBObject("$near", asDBValue(expr, 1))); } else if (op == MongodbOps.NEAR_SPHERE) { return asDBObject(asDBKey(expr, 0), asDBObject("$nearSphere", asDBValue(expr, 1))); } else if (op == MongodbOps.ELEM_MATCH) { return asDBObject(asDBKey(expr, 0), asDBObject("$elemMatch", asDBValue(expr, 1))); } throw new UnsupportedOperationException("Illegal operation " + expr); }
From source file:com.redhat.jielicious.storage.mongo.handler.MongoStorageHandler.java
License:Open Source License
private Bson createSortObject(String sort) { BasicDBObject sortObject = new BasicDBObject(); if (sort != null) { String[] items = sort.split(","); for (String item : items) { if (item.charAt(0) == '+') { sortObject.append("obj." + item.substring(1), 1); } else if (item.charAt(0) == '-') { sortObject.append("obj." + item.substring(1), -1); }/*from w w w . j a v a 2s . c o m*/ } } return sortObject; }
From source file:com.redhat.lightblue.crud.mongo.MongoLocking.java
License:Open Source License
public void ping(String callerId, String resourceId) { Date now = new Date(); BasicDBObject q = new BasicDBObject().append(CALLERID, callerId).append(RESOURCEID, resourceId) .append(EXPIRATION, new BasicDBObject("$gt", now)).append(COUNT, new BasicDBObject("$gt", 0)); DBObject lock = coll.findOne(q);/*w ww.j a v a 2s .c om*/ if (lock != null) { Date expiration = new Date(now.getTime() + ((Number) lock.get(TTL)).longValue()); int ver = ((Number) lock.get(VERSION)).intValue(); BasicDBObject update = new BasicDBObject() .append("$set", new BasicDBObject(TIMESTAMP, now).append(EXPIRATION, expiration)) .append("$inc", new BasicDBObject(VERSION, 1)); q = q.append(VERSION, ver); WriteResult wr = coll.update(q, update, false, false, WriteConcern.SAFE); if (wr.getN() != 1) throw new InvalidLockException(resourceId); LOGGER.debug("{}/{} pinged", callerId, resourceId); } else throw new InvalidLockException(resourceId); }
From source file:com.redhat.lightblue.crud.mongo.Translator.java
License:Open Source License
private DBObject translateRegexMatchExpression(RegexMatchExpression expr) { StringBuilder options = new StringBuilder(); BasicDBObject regex = new BasicDBObject("$regex", expr.getRegex()); if (expr.isCaseInsensitive()) { options.append('i'); }// w w w . j av a 2 s.c om if (expr.isMultiline()) { options.append('m'); } if (expr.isExtended()) { options.append('x'); } if (expr.isDotAll()) { options.append('s'); } String opStr = options.toString(); if (opStr.length() > 0) { regex.append("$options", opStr); } return new BasicDBObject(translatePath(expr.getField()), regex); }
From source file:com.redhat.lightblue.crud.mongo.Translator.java
License:Open Source License
private void toBson(BasicDBObject dest, SimpleField fieldMd, Path path, JsonNode node) { Object value = toValue(fieldMd.getType(), node); // Should we add fields with null values to the bson doc? if (value != null) { LOGGER.debug("{} = {}", path, value); if (path.equals(ID_PATH)) { value = new ObjectId(value.toString()); }/* w w w. j a va 2 s.c o m*/ // Store big values as string. Mongo does not support big values if (value instanceof BigDecimal || value instanceof BigInteger) { value = value.toString(); } dest.append(path.tail(0), value); } }
From source file:com.redhat.lightblue.crud.mongo.Translator.java
License:Open Source License
private void convertObjectFieldToBson(JsonNode node, JsonNodeCursor cursor, BasicDBObject ret, Path path, EntityMetadata md) {// w w w. ja va2 s. co m if (node != null) { if (node instanceof ObjectNode) { if (cursor.firstChild()) { ret.append(path.tail(0), objectToBson(cursor, md)); cursor.parent(); } } else { throw Error.get(ERR_INVALID_FIELD, path.toString()); } } }
From source file:com.redhat.lightblue.crud.mongo.Translator.java
License:Open Source License
private void convertArrayFieldToBson(JsonNode node, JsonNodeCursor cursor, BasicDBObject ret, FieldTreeNode fieldMdNode, Path path, EntityMetadata md) { if (node != null) { if (node instanceof ArrayNode) { if (cursor.firstChild()) { ret.append(path.tail(0), arrayToBson(cursor, ((ArrayField) fieldMdNode).getElement(), md)); cursor.parent();/*from www. j a v a 2s . c o m*/ } } else { throw Error.get(ERR_INVALID_FIELD, path.toString()); } } }
From source file:com.redhat.lightblue.metadata.mongo.MongoMetadata.java
License:Open Source License
private void createUpdateEntityInfoIndexes(EntityInfo ei) { LOGGER.debug("createUpdateEntityInfoIndexes: begin"); Indexes indexes = ei.getIndexes();/*from w ww . j a v a 2 s . com*/ MongoDataStore ds = (MongoDataStore) ei.getDataStore(); DB entityDB = dbResolver.get(ds); DBCollection entityCollection = entityDB.getCollection(ds.getCollectionName()); Error.push("createUpdateIndex"); try { List<DBObject> existingIndexes = entityCollection.getIndexInfo(); LOGGER.debug("Existing indexes: {}", existingIndexes); for (Index index : indexes.getIndexes()) { boolean createIx = true; LOGGER.debug("Processing index {}", index); for (DBObject existingIndex : existingIndexes) { if (indexFieldsMatch(index, existingIndex) && indexOptionsMatch(index, existingIndex)) { LOGGER.debug("Same index exists, not creating"); createIx = false; break; } } if (createIx) { for (DBObject existingIndex : existingIndexes) { if (indexFieldsMatch(index, existingIndex) && !indexOptionsMatch(index, existingIndex)) { LOGGER.debug("Same index exists with different options, dropping index:{}", existingIndex); // Changing index options, drop the index using its name, recreate with new options entityCollection.dropIndex(existingIndex.get(LITERAL_NAME).toString()); } } } if (createIx) { DBObject newIndex = new BasicDBObject(); for (SortKey p : index.getFields()) { newIndex.put(p.getField().toString(), p.isDesc() ? -1 : 1); } BasicDBObject options = new BasicDBObject("unique", index.isUnique()); if (index.getName() != null && index.getName().trim().length() > 0) { options.append(LITERAL_NAME, index.getName().trim()); } LOGGER.debug("Creating index {} with options {}", newIndex, options); entityCollection.createIndex(newIndex, options); } } } catch (MongoException me) { LOGGER.error("createUpdateEntityInfoIndexes: {}", ei); throw Error.get(MongoMetadataConstants.ERR_ENTITY_INDEX_NOT_CREATED, me.getMessage()); } finally { Error.pop(); } LOGGER.debug("createUpdateEntityInfoIndexes: end"); }
From source file:com.redhat.lightblue.mongo.crud.BatchUpdate.java
License:Open Source License
/** * Returns the set of document ids that were not updated with docver * * @param docver The current document version * @param documentIds The document ids to scan * * @return The set of document ids that were not updated with docver *//*ww w . j a v a 2s .c o m*/ public static Set<Object> getFailedUpdates(DBCollection collection, ObjectId docver, List<Object> documentIds) { Set<Object> failedIds = new HashSet<>(); if (!documentIds.isEmpty()) { // documents with the given _ids and whose docver contains our docVer are the ones we managed to update // others are failures BasicDBObject query = new BasicDBObject(DOCVER_FLD, new BasicDBObject("$ne", docver)); query.append("_id", new BasicDBObject("$in", documentIds)); try (DBCursor cursor = collection.find(query, new BasicDBObject("_id", 1)) .setReadPreference(ReadPreference.primary())) { while (cursor.hasNext()) { failedIds.add(cursor.next().get("_id")); } } } return failedIds; }