List of usage examples for com.mongodb BasicDBObjectBuilder get
public DBObject get()
From source file:org.forgerock.openidm.repo.mongodb.impl.MongoDBRepoService.java
License:Open Source License
/** * Updates the specified object in the object set. * <p>// www . ja v a2 s .c o m * This implementation requires MVCC and hence enforces that clients state what revision they expect * to be updating * * If successful, this method updates metadata properties within the passed object, * including: a new {@code _rev} value for the revised object's version * * @param fullId the identifier of the object to be put, or {@code null} to request a generated identifier. * @param rev the version of the object to update; or {@code null} if not provided. * @param obj the contents of the object to put in the object set. * @throws ConflictException if version is required but is {@code null}. * @throws ForbiddenException if access to the object is forbidden. * @throws NotFoundException if the specified object could not be found. * @throws PreconditionFailedException if version did not match the existing object in the set. * @throws BadRequestException if the passed identifier is invalid */ @Override public void update(String fullId, String rev, Map<String, Object> obj) throws ObjectSetException { String localId = getLocalId(fullId); String type = getObjectType(fullId, false); if (rev == null) { throw new ConflictException("Object passed into update does not have revision it expects set."); } else { DocumentUtil.parseVersion(rev); obj.put(DocumentUtil.TAG_REV, rev); } DBCollection collection = getCollection(type); DBObject existingDoc = predefinedQueries.getByID(localId, collection); if (existingDoc == null) { throw new NotFoundException("Update on object " + fullId + " could not find existing object."); } obj.remove(DocumentUtil.TAG_ID); obj.put(DocumentUtil.MONGODB_PRIMARY_KEY, localId); BasicDBObjectBuilder builder = BasicDBObjectBuilder.start(obj); DBObject jo = builder.get(); jo = DocumentUtil.normalizeForWrite(jo); WriteResult res = collection.update(new BasicDBObject(DocumentUtil.TAG_ID, localId), jo); logger.trace("Updated doc for id {} to save {}", fullId, jo); }
From source file:org.mongoj.samples.service.persistence.CarPersistenceImpl.java
License:Open Source License
protected Car updateImpl(org.mongoj.samples.model.Car car) throws UpdateException, SystemException { DBCollection collection = getDB().getCollection(CarImpl.COLLECTION_NAME); if (car.isNew()) { car.setNew(false);//from ww w .j a va 2 s . com CarImpl carImpl = (CarImpl) car; carImpl.addMap.clear(); carImpl.appendMap.clear(); carImpl.removeMap.clear(); carImpl.setMap.clear(); WriteResult writeResult = collection.insert(getDBObject(car)); String err = writeResult.getError(); if (err != null) { throw new UpdateException(err); } } else { DBObject criteria = new QueryBuilder().put("_id").is(new ObjectId(car.getId())).get(); CarImpl carImpl = (CarImpl) car; BasicDBObjectBuilder updateBuilder = BasicDBObjectBuilder.start(); BasicDBObjectBuilder setUpdates = BasicDBObjectBuilder.start(); BasicDBObjectBuilder pushUpdates = BasicDBObjectBuilder.start(); BasicDBObjectBuilder pushAllUpdates = BasicDBObjectBuilder.start(); BasicDBObjectBuilder addUpdates = BasicDBObjectBuilder.start(); BasicDBObjectBuilder removeUpdates = BasicDBObjectBuilder.start(); BasicDBObjectBuilder removeAllUpdates = BasicDBObjectBuilder.start(); for (String field : carImpl.setMap.keySet()) { setUpdates = setUpdates.add(field, carImpl.setMap.get(field)); } if (!setUpdates.isEmpty()) { updateBuilder.add(SET_OPERATOR, setUpdates.get()); } for (String field : carImpl.appendMap.keySet()) { List<Object> list = (List<Object>) carImpl.appendMap.get(field); if (!list.isEmpty()) { if (list.size() == 1) { pushUpdates = pushUpdates.add(field, ((List) carImpl.appendMap.get(field)).get(0)); } else { pushAllUpdates = pushAllUpdates.add(field, carImpl.appendMap.get(field)); } } } if (!pushUpdates.isEmpty()) { updateBuilder.add(PUSH_OPERATOR, pushUpdates.get()); } if (!pushAllUpdates.isEmpty()) { updateBuilder.add(PUSH_ALL_OPERATOR, pushAllUpdates.get()); } for (String field : carImpl.addMap.keySet()) { List<Object> list = (List<Object>) carImpl.addMap.get(field); if (!list.isEmpty()) { if (list.size() == 1) { addUpdates = addUpdates.add(field, ((List) carImpl.addMap.get(field)).get(0)); } else { DBObject each = BasicDBObjectBuilder.start() .add(EACH_OPERATOR, ((List) carImpl.addMap.get(field)).toArray()).get(); addUpdates = addUpdates.add(field, each); } } } if (!addUpdates.isEmpty()) { updateBuilder.add(ADD_TO_SET_OPERATOR, addUpdates.get()); } for (String field : carImpl.removeMap.keySet()) { List<Object> list = (List<Object>) carImpl.removeMap.get(field); if (!list.isEmpty()) { if (list.size() == 1) { removeUpdates = removeUpdates.add(field, ((List) carImpl.removeMap.get(field)).get(0)); } else { removeAllUpdates = removeAllUpdates.add(field, carImpl.removeMap.get(field)); } } } if (!removeUpdates.isEmpty()) { updateBuilder.add(PULL_OPERATOR, removeUpdates.get()); } if (!removeAllUpdates.isEmpty()) { updateBuilder.add(PULL_ALL_OPERATOR, removeAllUpdates.get()); } if (!updateBuilder.isEmpty()) { DBObject update = updateBuilder.get(); _log.debug("Update query = {}", update); WriteResult writeResult = collection.update(criteria, update); String err = writeResult.getError(); if (err != null) { throw new UpdateException(err); } } } return car; }
From source file:org.mongoj.samples.service.persistence.UserPersistenceImpl.java
License:Open Source License
protected User updateImpl(org.mongoj.samples.model.User user) throws UpdateException, SystemException { DBCollection collection = getDB().getCollection(UserImpl.COLLECTION_NAME); if (user.isNew()) { user.setNew(false);/* w w w. j a va2 s .c om*/ UserImpl userImpl = (UserImpl) user; userImpl.addMap.clear(); userImpl.appendMap.clear(); userImpl.removeMap.clear(); userImpl.setMap.clear(); WriteResult writeResult = collection.insert(getDBObject(user)); String err = writeResult.getError(); if (err != null) { throw new UpdateException(err); } } else { DBObject criteria = new QueryBuilder().put("_id").is(new ObjectId(user.getId())).get(); UserImpl userImpl = (UserImpl) user; BasicDBObjectBuilder updateBuilder = BasicDBObjectBuilder.start(); BasicDBObjectBuilder setUpdates = BasicDBObjectBuilder.start(); BasicDBObjectBuilder pushUpdates = BasicDBObjectBuilder.start(); BasicDBObjectBuilder pushAllUpdates = BasicDBObjectBuilder.start(); BasicDBObjectBuilder addUpdates = BasicDBObjectBuilder.start(); BasicDBObjectBuilder removeUpdates = BasicDBObjectBuilder.start(); BasicDBObjectBuilder removeAllUpdates = BasicDBObjectBuilder.start(); for (String field : userImpl.setMap.keySet()) { setUpdates = setUpdates.add(field, userImpl.setMap.get(field)); } if (!setUpdates.isEmpty()) { updateBuilder.add(SET_OPERATOR, setUpdates.get()); } for (String field : userImpl.appendMap.keySet()) { List<Object> list = (List<Object>) userImpl.appendMap.get(field); if (!list.isEmpty()) { if (list.size() == 1) { pushUpdates = pushUpdates.add(field, ((List) userImpl.appendMap.get(field)).get(0)); } else { pushAllUpdates = pushAllUpdates.add(field, userImpl.appendMap.get(field)); } } } if (!pushUpdates.isEmpty()) { updateBuilder.add(PUSH_OPERATOR, pushUpdates.get()); } if (!pushAllUpdates.isEmpty()) { updateBuilder.add(PUSH_ALL_OPERATOR, pushAllUpdates.get()); } for (String field : userImpl.addMap.keySet()) { List<Object> list = (List<Object>) userImpl.addMap.get(field); if (!list.isEmpty()) { if (list.size() == 1) { addUpdates = addUpdates.add(field, ((List) userImpl.addMap.get(field)).get(0)); } else { DBObject each = BasicDBObjectBuilder.start() .add(EACH_OPERATOR, ((List) userImpl.addMap.get(field)).toArray()).get(); addUpdates = addUpdates.add(field, each); } } } if (!addUpdates.isEmpty()) { updateBuilder.add(ADD_TO_SET_OPERATOR, addUpdates.get()); } for (String field : userImpl.removeMap.keySet()) { List<Object> list = (List<Object>) userImpl.removeMap.get(field); if (!list.isEmpty()) { if (list.size() == 1) { removeUpdates = removeUpdates.add(field, ((List) userImpl.removeMap.get(field)).get(0)); } else { removeAllUpdates = removeAllUpdates.add(field, userImpl.removeMap.get(field)); } } } if (!removeUpdates.isEmpty()) { updateBuilder.add(PULL_OPERATOR, removeUpdates.get()); } if (!removeAllUpdates.isEmpty()) { updateBuilder.add(PULL_ALL_OPERATOR, removeAllUpdates.get()); } if (!updateBuilder.isEmpty()) { DBObject update = updateBuilder.get(); _log.debug("Update query = {}", update); WriteResult writeResult = collection.update(criteria, update); String err = writeResult.getError(); if (err != null) { throw new UpdateException(err); } } } return user; }
From source file:org.mule.modules.morphia.MorphiaConnector.java
License:Open Source License
/** * Calculates aggregates values without the need for complex map-reduce operations * * <p/>//from www. java2 s . c o m * {@sample.xml ../../../doc/mule-module-morphia.xml.sample morphia:aggregate} * * @param collection collection name * @param pipeline list of pipeline operators * @param exception The exception that needs to be thrown if there is an error executing the aggregation query * @param username the username to use in case authentication is required * @param password the password to use in case authentication is required, null * if no authentication is desired * @param host The host of the Mongo server. If the host is part of a replica set then you can specify all the hosts * separated by comma. * @param port The port of the Mongo server * @param database The database name of the Mongo server * @return the aggregation result * @throws Exception if there is an exception while aggregating */ @Processor public BasicDBList aggregate(String collection, List<Pipeline> pipeline, @Optional String exception, @Optional String username, @Optional @Password String password, @Optional String host, @Optional Integer port, @Optional String database) throws Exception { if (!pipeline.isEmpty()) { Datastore datastore = getDatastore(username, password, database, host, port); List<DBObject> dbObjects = new ArrayList<DBObject>(); for (Pipeline pipelineOperator : pipeline) { Object dbObject = JSON.parse(pipelineOperator.toJson()); if (dbObject == null || !(dbObject instanceof DBObject)) { throw new IllegalArgumentException("Illegal pipeline operator '" + pipelineOperator + "'"); } dbObjects.add((DBObject) dbObject); } BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add("aggregate", collection); builder.append("pipeline", dbObjects.toArray()); CommandResult result = datastore.getDB().command(builder.get()); if (result.ok()) { return (BasicDBList) result.get("result"); } if (exception != null) { throw getExceptionFromClassName(exception); } } // Return an empty list return new BasicDBList(); }
From source file:org.obiba.magma.datasource.mongodb.converter.VariableConverter.java
License:Open Source License
public static DBObject marshall(Variable variable) { BasicDBObjectBuilder builder = BasicDBObjectBuilder.start() // .add("name", variable.getName()) // .add("valueType", variable.getValueType().getName()) // .add("entityType", variable.getEntityType()) // .add("mimeType", variable.getMimeType()) // .add("repeatable", variable.isRepeatable()) // .add("occurrenceGroup", variable.getOccurrenceGroup()) // .add("referencedEntityType", variable.getReferencedEntityType()) // .add("unit", variable.getUnit()).add("index", variable.getIndex()); if (variable.hasCategories()) { Collection<Object> list = new BasicDBList(); for (Category category : variable.getCategories()) { list.add(marshall(category)); }//from ww w .j av a 2 s . c o m builder.add("categories", list); } if (variable.hasAttributes()) { Collection<Object> list = new BasicDBList(); for (Attribute attribute : variable.getAttributes()) { list.add(marshall(attribute)); } builder.add("attributes", list); } return builder.get(); }
From source file:org.obiba.magma.datasource.mongodb.converter.VariableConverter.java
License:Open Source License
private static DBObject marshall(Category category) { BasicDBObjectBuilder builder = BasicDBObjectBuilder.start() // .add("name", category.getName()).add("missing", category.isMissing()); if (category.hasAttributes()) { Collection<Object> list = new BasicDBList(); for (Attribute attribute : category.getAttributes()) { list.add(marshall(attribute)); }//from ww w . j a v a 2s . c o m builder.add("attributes", list); } return builder.get(); }
From source file:org.obiba.magma.datasource.mongodb.MongoDBValueTable.java
License:Open Source License
/** * Drop the files from the {@link com.mongodb.gridfs.GridFS} for this table. *///from ww w. ja v a 2s . com private void dropFiles() { GridFS gridFS = getMongoDBDatasource().getMongoDBFactory().getGridFS(); BasicDBObjectBuilder metaDataQuery = BasicDBObjectBuilder.start() // .add("metadata.datasource", getDatasource().getName()) // .add("metadata.table", getName()); gridFS.remove(metaDataQuery.get()); }
From source file:org.sglover.checksum.dao.mongo.MongoChecksumDAO.java
License:Open Source License
private DBObject toDBObject(NodeChecksums documentChecksums) { BasicDBObjectBuilder checksumsObjectBuilder = BasicDBObjectBuilder.start(); for (Map.Entry<Integer, List<Checksum>> checksums : documentChecksums.getChecksums().entrySet()) { List<DBObject> checksumDBObjects = new LinkedList<>(); for (Checksum checksum : checksums.getValue()) { DBObject checksumDBObject = toDBObject(checksum); checksumDBObjects.add(checksumDBObject); }// www . j a v a 2 s. c om checksumsObjectBuilder.add(String.valueOf(checksums.getKey()), checksumDBObjects); } DBObject dbObject = BasicDBObjectBuilder.start("n", documentChecksums.getNodeId()) .add("ni", documentChecksums.getNodeInternalId()).add("v", documentChecksums.getNodeVersion()) .add("l", documentChecksums.getVersionLabel()).add("b", documentChecksums.getBlockSize()) .add("nb", documentChecksums.getNumBlocks()).add("c", checksumsObjectBuilder.get()).get(); return dbObject; }
From source file:org.sglover.entities.dao.mongo.MongoEntitiesDAO.java
License:Open Source License
@Override // TODO use skip and maxItems public Stream<Entity<String>> getNames(Node node, int skip, int maxItems) { String nodeId = node.getNodeId(); String nodeVersion = node.getVersionLabel(); Collection<Entity<String>> ret = new LinkedList<>(); QueryBuilder queryBuilder = QueryBuilder.start("n").is(nodeId).and("v").is(nodeVersion); DBObject query = queryBuilder.get(); BasicDBObjectBuilder orderByBuilder = BasicDBObjectBuilder.start("nm", 1); DBObject orderBy = orderByBuilder.get(); DBCursor cursor = entitiesData.find(query).sort(orderBy); try {/* w w w . ja va 2s . co m*/ for (DBObject dbObject : cursor) { String name = (String) dbObject.get("nm"); int count = (Integer) dbObject.get("c"); String type = map.get("nm"); Entity<String> entity = new Entity<>(EntityType.valueOf(type), name, count); ret.add(entity); } } finally { if (cursor != null) { cursor.close(); } } return ret.stream(); }
From source file:org.sglover.entities.dao.mongo.MongoEntitiesDAO.java
License:Open Source License
@Override // TODO use skip and maxItems public Stream<Entity<String>> getOrgs(Node node, int skip, int maxItems) { String nodeId = node.getNodeId(); String nodeVersion = node.getVersionLabel(); Collection<Entity<String>> ret = new LinkedList<>(); QueryBuilder queryBuilder = QueryBuilder.start("n").is(nodeId).and("v").is(nodeVersion); DBObject query = queryBuilder.get(); BasicDBObjectBuilder orderByBuilder = BasicDBObjectBuilder.start("o", 1); DBObject orderBy = orderByBuilder.get(); DBCursor cursor = entitiesData.find(query).sort(orderBy); try {/* ww w . j av a2s .co m*/ for (DBObject dbObject : cursor) { String org = (String) dbObject.get("o"); int count = (Integer) dbObject.get("c"); String type = map.get("nm"); Entity<String> entity = new Entity<>(EntityType.valueOf(type), org, count); ret.add(entity); } } finally { if (cursor != null) { cursor.close(); } } return ret.stream(); }