List of usage examples for org.springframework.data.mongodb.core DbCallback DbCallback
DbCallback
From source file:com.ewcms.mongo.demo.repositories.PersonRepositoryImpl.java
@Override public List<Person> findWorkByAgeRang(final int start, final int end) { return getMongoOperations().execute(new DbCallback<List<Person>>() { @Override/*from www.j av a2s .co m*/ public List<Person> doInDB(DB db) throws MongoException, DataAccessException { DBCollection coll = db.getCollection("person"); BasicDBObject query = new BasicDBObject(); query.put("age", new BasicDBObject("$gte", 20).append("$lte", 60)); DBCursor cur = coll.find(query); List<Person> list = new ArrayList<Person>(); for (; cur.hasNext();) { DBObject source = cur.next(); Person person = convertEntity(source); list.add(person); } return list; } }); }
From source file:se.inera.axel.shs.broker.messagestore.internal.MongoMessageStoreServiceIT.java
@Test(groups = "largeTests", enabled = true) public void testSave() { final ShsMessageEntry entry = make(a(ShsMessageEntryMaker.ShsMessageEntry)); final se.inera.axel.shs.mime.ShsMessage shsMessage = make(a(ShsMessage)); messageStore.save(entry, shsMessage); mongoOperations.execute(new DbCallback<Object>() { @Override//from ww w. j a va2 s . c om public Object doInDB(DB db) throws MongoException, DataAccessException { GridFS gridFs = new GridFS(db); assertNotNull(gridFs.findOne(entry.getId()), "Saved file was not found in grid"); return null; } }); }
From source file:se.inera.axel.shs.broker.messagestore.internal.MongoMessageStoreServiceIT.java
@Test(groups = "largeTests", enabled = true) public void existingFileShouldBeDeleted() { messageStore.delete(entry1);/*from www .j a v a 2s . c o m*/ mongoOperations.execute(new DbCallback<Object>() { @Override public Object doInDB(DB db) throws MongoException, DataAccessException { GridFS gridFs = new GridFS(db); assertNull(gridFs.findOne(entry1.getId()), "Entry was not deleted"); return null; } }); }
From source file:se.inera.axel.shs.broker.messagestore.internal.MongoMessageStoreServiceIT.java
@Test(groups = "largeTests", enabled = true) public void deletingNonExistingFileShouldBeANoOp() { messageStore.delete(make(a(ShsMessageEntryMaker.ShsMessageEntry))); mongoOperations.execute(new DbCallback<Object>() { @Override/*from ww w . j a va 2 s . c o m*/ public Object doInDB(DB db) throws MongoException, DataAccessException { GridFS gridFs = new GridFS(db); DBCursor dbCursor = gridFs.getFileList(); assertThat(dbCursor.count(), is(0)); return null; } }); }
From source file:org.grails.datastore.mapping.mongo.MongoSession.java
@Override @SuppressWarnings({ "rawtypes", "unchecked" }) protected void flushPendingInserts(final Map<PersistentEntity, Collection<PendingInsert>> inserts) { // Optimizes saving multipe entities at once for (final PersistentEntity entity : inserts.keySet()) { final MongoTemplate template = getMongoTemplate(entity.isRoot() ? entity : entity.getRootEntity()); final String collectionNameToUse = getCollectionName(entity.isRoot() ? entity : entity.getRootEntity()); template.execute(new DbCallback<Object>() { public Object doInDB(DB db) throws MongoException, DataAccessException { WriteConcern writeConcernToUse = writeConcern; writeConcernToUse = getDeclaredWriteConcern(writeConcernToUse, entity); final DBCollection collection = db.getCollection(collectionNameToUse); final Collection<PendingInsert> pendingInserts = inserts.get(entity); List<DBObject> dbObjects = new LinkedList<DBObject>(); List<PendingOperation> postOperations = new LinkedList<PendingOperation>(); for (PendingInsert pendingInsert : pendingInserts) { final List<PendingOperation> preOperations = pendingInsert.getPreOperations(); for (PendingOperation preOperation : preOperations) { preOperation.run(); }//from w ww .j av a2 s . c om dbObjects.add((DBObject) pendingInsert.getNativeEntry()); postOperations.addAll(pendingInsert.getCascadeOperations()); pendingInsert.run(); } WriteResult writeResult = collection.insert(dbObjects.toArray(new DBObject[dbObjects.size()]), writeConcernToUse); if (writeResult.getError() != null) { errorOccured = true; throw new DataIntegrityViolationException(writeResult.getError()); } for (PendingOperation pendingOperation : postOperations) { pendingOperation.run(); } return null; } }); } }
From source file:se.inera.axel.shs.broker.messagestore.internal.MongoMessageStoreServiceIT.java
@BeforeMethod public void beforeMethod() { mongoOperations.execute(new DbCallback<Object>() { @Override/*from ww w .j a va 2 s . co m*/ public Object doInDB(DB db) throws MongoException, DataAccessException { ShsMessage message = make(a(ShsMessage)); entry1 = make(a(ShsMessageEntryMaker.ShsMessageEntry)); saveMessage(entry1, message, db); return null; } }); }
From source file:org.grails.datastore.mapping.mongo.MongoDatastore.java
protected void createMongoTemplate(PersistentEntity entity, Mongo mongoInstance) { DocumentMappingContext dc = (DocumentMappingContext) getMappingContext(); String collectionName = entity.getDecapitalizedName(); String databaseName = dc.getDefaultDatabaseName(); @SuppressWarnings("unchecked") ClassMapping<MongoCollection> mapping = entity.getMapping(); final MongoCollection mongoCollection = mapping.getMappedForm() != null ? mapping.getMappedForm() : null; if (mongoCollection != null) { if (mongoCollection.getCollection() != null) { collectionName = mongoCollection.getCollection(); }//from w ww. j av a 2 s . co m if (mongoCollection.getDatabase() != null) { databaseName = mongoCollection.getDatabase(); } } final SimpleMongoDbFactory dbf; String username = read(String.class, USERNAME, connectionDetails, null); String password = read(String.class, PASSWORD, connectionDetails, null); if (username != null && password != null) { UserCredentials uc = new UserCredentials(username, password); dbf = new SimpleMongoDbFactory(mongoInstance, databaseName, uc); } else { dbf = new SimpleMongoDbFactory(mongoInstance, databaseName); } final MongoTemplate mt = new MongoTemplate(dbf); if (mongoCollection != null) { final WriteConcern writeConcern = mongoCollection.getWriteConcern(); if (writeConcern != null) { final String collectionNameToUse = collectionName; mt.executeInSession(new DbCallback<Object>() { public Object doInDB(DB db) throws MongoException, DataAccessException { if (writeConcern != null) { DBCollection collection = db.getCollection(collectionNameToUse); collection.setWriteConcern(writeConcern); } return null; } }); } } mongoTemplates.put(entity, mt); mongoCollections.put(entity, collectionName); initializeIndices(entity, mt); }
From source file:org.grails.datastore.mapping.mongo.MongoDatastore.java
/** * Indexes any properties that are mapped with index:true * @param entity The entity/* www .java 2s . c o m*/ * @param template The template */ protected void initializeIndices(final PersistentEntity entity, final MongoTemplate template) { template.execute(new DbCallback<Object>() { @SuppressWarnings({ "unchecked", "rawtypes" }) public Object doInDB(DB db) throws MongoException, DataAccessException { final DBCollection collection = db.getCollection(getCollectionName(entity)); final ClassMapping<MongoCollection> classMapping = entity.getMapping(); if (classMapping != null) { final MongoCollection mappedForm = classMapping.getMappedForm(); if (mappedForm != null) { for (Map compoundIndex : mappedForm.getCompoundIndices()) { DBObject indexDef = new BasicDBObject(compoundIndex); collection.ensureIndex(indexDef); } } } for (PersistentProperty<MongoAttribute> property : entity.getPersistentProperties()) { final boolean indexed = isIndexed(property); if (indexed) { final MongoAttribute mongoAttributeMapping = property.getMapping().getMappedForm(); DBObject dbObject = new BasicDBObject(); final String fieldName = getMongoFieldNameForProperty(property); dbObject.put(fieldName, 1); DBObject options = new BasicDBObject(); if (mongoAttributeMapping != null) { Map attributes = mongoAttributeMapping.getIndexAttributes(); if (attributes != null) { attributes = new HashMap(attributes); if (attributes.containsKey(MongoAttribute.INDEX_TYPE)) { dbObject.put(fieldName, attributes.remove(MongoAttribute.INDEX_TYPE)); } options.putAll(attributes); } } if (options.toMap().isEmpty()) { collection.ensureIndex(dbObject); } else { collection.ensureIndex(dbObject, options); } } } return null; } String getMongoFieldNameForProperty(PersistentProperty<MongoAttribute> property) { PropertyMapping<MongoAttribute> pm = property.getMapping(); String propKey = null; if (pm.getMappedForm() != null) { propKey = pm.getMappedForm().getField(); } if (propKey == null) { propKey = property.getName(); } return propKey; } }); }
From source file:org.grails.datastore.mapping.mongo.engine.MongoEntityPersister.java
@Override protected void deleteEntry(String family, final Object key, final Object entry) { mongoTemplate.execute(new DbCallback<Object>() { public Object doInDB(DB con) throws MongoException, DataAccessException { DBCollection dbCollection = getCollection(con); DBObject dbo = createDBObjectWithKey(key); MongoSession mongoSession = (MongoSession) session; dbCollection.remove(dbo, mongoSession.getWriteConcern()); return null; }//from w ww. jav a 2 s .c o m protected DBCollection getCollection(DB con) { return con.getCollection(getCollectionName(getPersistentEntity())); } }); }
From source file:org.grails.datastore.mapping.mongo.engine.MongoEntityPersister.java
@Override protected Object generateIdentifier(final PersistentEntity persistentEntity, final DBObject nativeEntry) { return mongoTemplate.execute(new DbCallback<Object>() { public Object doInDB(DB con) throws MongoException, DataAccessException { @SuppressWarnings("hiding") String collectionName = getCollectionName(persistentEntity, nativeEntry); DBCollection dbCollection = con.getCollection(collectionName + NEXT_ID_SUFFIX); // If there is a numeric identifier then we need to rely on optimistic concurrency controls to obtain a unique identifer // sequence. If the identifier is not numeric then we assume BSON ObjectIds. if (hasNumericalIdentifier) { while (true) { DBCursor result = dbCollection.find().sort(new BasicDBObject(MONGO_ID_FIELD, -1)).limit(1); long nextId; if (result.hasNext()) { final Long current = getMappingContext().getConversionService() .convert(result.next().get(MONGO_ID_FIELD), Long.class); nextId = current + 1; } else { nextId = 1;/* w ww . j av a 2 s .c o m*/ } nativeEntry.put(MONGO_ID_FIELD, nextId); final WriteResult writeResult = dbCollection.insert(nativeEntry); final CommandResult lastError = writeResult.getLastError(); if (lastError.ok()) { break; } final Object code = lastError.get("code"); // duplicate key error try again if (code != null && code.equals(11000)) { continue; } break; } return nativeEntry.get(MONGO_ID_FIELD); } ObjectId objectId = ObjectId.get(); if (ObjectId.class.isAssignableFrom(persistentEntity.getIdentity().getType())) { nativeEntry.put(MONGO_ID_FIELD, objectId); return objectId; } String stringId = objectId.toString(); nativeEntry.put(MONGO_ID_FIELD, stringId); return stringId; } }); }