Search in sources :

Example 6 with WriteResult

use of com.mongodb.WriteResult in project jetty.project by eclipse.

the class MongoSessionDataStore method delete.

/** 
     * @see org.eclipse.jetty.server.session.SessionDataStore#delete(String)
     */
@Override
public boolean delete(String id) throws Exception {
    if (LOG.isDebugEnabled())
        LOG.debug("Remove:session {} for context ", id, _context);
    /*
         * Check if the session exists and if it does remove the context
         * associated with this session
         */
    BasicDBObject mongoKey = new BasicDBObject(__ID, id);
    //DBObject sessionDocument = _dbSessions.findOne(mongoKey,_version_1);
    DBObject sessionDocument = _dbSessions.findOne(new BasicDBObject(__ID, id));
    if (sessionDocument != null) {
        DBObject c = (DBObject) getNestedValue(sessionDocument, __CONTEXT);
        if (c == null) {
            //delete whole doc
            _dbSessions.remove(mongoKey, WriteConcern.SAFE);
            return false;
        }
        Set<String> contexts = c.keySet();
        if (contexts.isEmpty()) {
            //delete whole doc
            _dbSessions.remove(mongoKey, WriteConcern.SAFE);
            return false;
        }
        if (contexts.size() == 1 && contexts.iterator().next().equals(getCanonicalContextId())) {
            //delete whole doc
            _dbSessions.remove(new BasicDBObject(__ID, id), WriteConcern.SAFE);
            return true;
        }
        //just remove entry for my context
        BasicDBObject remove = new BasicDBObject();
        BasicDBObject unsets = new BasicDBObject();
        unsets.put(getContextField(), 1);
        remove.put("$unset", unsets);
        WriteResult result = _dbSessions.update(mongoKey, remove, false, false, WriteConcern.SAFE);
        return true;
    } else {
        return false;
    }
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) WriteResult(com.mongodb.WriteResult) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject)

Example 7 with WriteResult

use of com.mongodb.WriteResult in project morphia by mongodb.

the class DatastoreImpl method save.

protected <T> Key<T> save(final DBCollection dbColl, final T entity, final InsertOptions options) {
    if (entity == null) {
        throw new UpdateException("Can not persist a null entity");
    }
    final MappedClass mc = mapper.getMappedClass(entity);
    if (mc.getAnnotation(NotSaved.class) != null) {
        throw new MappingException(format("Entity type: %s is marked as NotSaved which means you should not try to save it!", mc.getClazz().getName()));
    }
    // involvedObjects is used not only as a cache but also as a list of what needs to be called for life-cycle methods at the end.
    final LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
    final DBObject document = entityToDBObj(entity, involvedObjects);
    // try to do an update if there is a @Version field
    final Object idValue = document.get(Mapper.ID_KEY);
    WriteResult wr = tryVersionedUpdate(dbColl, entity, document, idValue, enforceWriteConcern(options, entity.getClass()), mc);
    if (wr == null) {
        saveDocument(dbColl, document, options);
    }
    return postSaveOperations(singletonList(entity), involvedObjects, dbColl).get(0);
}
Also used : WriteResult(com.mongodb.WriteResult) NotSaved(org.mongodb.morphia.annotations.NotSaved) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) UpdateException(org.mongodb.morphia.query.UpdateException) MappedClass(org.mongodb.morphia.mapping.MappedClass) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) MappingException(org.mongodb.morphia.mapping.MappingException) LinkedHashMap(java.util.LinkedHashMap)

Example 8 with WriteResult

use of com.mongodb.WriteResult in project morphia by mongodb.

the class DatastoreImpl method merge.

@Override
@SuppressWarnings("unchecked")
public <T> Key<T> merge(final T entity, final WriteConcern wc) {
    T unwrapped = entity;
    final LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
    final DBObject dbObj = mapper.toDBObject(unwrapped, involvedObjects);
    final Key<T> key = mapper.getKey(unwrapped);
    unwrapped = ProxyHelper.unwrap(unwrapped);
    final Object id = mapper.getId(unwrapped);
    if (id == null) {
        throw new MappingException("Could not get id for " + unwrapped.getClass().getName());
    }
    // remove (immutable) _id field for update.
    final Object idValue = dbObj.get(Mapper.ID_KEY);
    dbObj.removeField(Mapper.ID_KEY);
    WriteResult wr;
    final MappedClass mc = mapper.getMappedClass(unwrapped);
    final DBCollection dbColl = getCollection(unwrapped);
    // try to do an update if there is a @Version field
    wr = tryVersionedUpdate(dbColl, unwrapped, dbObj, idValue, new InsertOptions().writeConcern(wc), mc);
    if (wr == null) {
        final Query<T> query = (Query<T>) createQuery(unwrapped.getClass()).filter(Mapper.ID_KEY, id);
        wr = update(query, new BasicDBObject("$set", dbObj), false, false, wc).getWriteResult();
    }
    final UpdateResults res = new UpdateResults(wr);
    if (res.getUpdatedCount() == 0) {
        throw new UpdateException("Nothing updated");
    }
    dbObj.put(Mapper.ID_KEY, idValue);
    postSaveOperations(Collections.<Object>singletonList(entity), involvedObjects, dbColl, false);
    return key;
}
Also used : Query(org.mongodb.morphia.query.Query) MappedClass(org.mongodb.morphia.mapping.MappedClass) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) UpdateResults(org.mongodb.morphia.query.UpdateResults) LinkedHashMap(java.util.LinkedHashMap) MappingException(org.mongodb.morphia.mapping.MappingException) DBCollection(com.mongodb.DBCollection) BasicDBObject(com.mongodb.BasicDBObject) WriteResult(com.mongodb.WriteResult) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) UpdateException(org.mongodb.morphia.query.UpdateException)

Example 9 with WriteResult

use of com.mongodb.WriteResult in project morphia by mongodb.

the class DatastoreImpl method tryVersionedUpdate.

private <T> WriteResult tryVersionedUpdate(final DBCollection dbColl, final T entity, final DBObject dbObj, final Object idValue, final InsertOptions options, final MappedClass mc) {
    WriteResult wr;
    if (mc.getFieldsAnnotatedWith(Version.class).isEmpty()) {
        return null;
    }
    final MappedField mfVersion = mc.getMappedVersionField();
    final String versionKeyName = mfVersion.getNameToStore();
    Long oldVersion = (Long) mfVersion.getFieldValue(entity);
    long newVersion = nextValue(oldVersion);
    dbObj.put(versionKeyName, newVersion);
    if (idValue != null && newVersion != 1) {
        final Query<?> query = find(dbColl.getName(), entity.getClass()).disableValidation().filter(Mapper.ID_KEY, idValue).enableValidation().filter(versionKeyName, oldVersion);
        final UpdateResults res = update(query, dbObj, new UpdateOptions().bypassDocumentValidation(options.getBypassDocumentValidation()).writeConcern(options.getWriteConcern()));
        wr = res.getWriteResult();
        if (res.getUpdatedCount() != 1) {
            throw new ConcurrentModificationException(format("Entity of class %s (id='%s',version='%d') was concurrently updated.", entity.getClass().getName(), idValue, oldVersion));
        }
    } else {
        wr = saveDocument(dbColl, dbObj, options);
    }
    return wr;
}
Also used : MappedField(org.mongodb.morphia.mapping.MappedField) ConcurrentModificationException(java.util.ConcurrentModificationException) WriteResult(com.mongodb.WriteResult) Version(org.mongodb.morphia.annotations.Version) UpdateResults(org.mongodb.morphia.query.UpdateResults) DBCollectionUpdateOptions(com.mongodb.client.model.DBCollectionUpdateOptions)

Example 10 with WriteResult

use of com.mongodb.WriteResult in project graylog2-server by Graylog2.

the class V20161125161400_AlertReceiversMigrationTest method doMigrateMultipleQualifyingStreams.

@Test
public void doMigrateMultipleQualifyingStreams() throws Exception {
    final String matchingStreamId1 = new ObjectId().toHexString();
    final String matchingStreamId2 = new ObjectId().toHexString();
    final Stream stream1 = mock(Stream.class);
    when(stream1.getAlertReceivers()).thenReturn(Collections.emptyMap());
    final Stream stream2 = mock(Stream.class);
    when(stream2.getAlertReceivers()).thenReturn(ImmutableMap.of("users", ImmutableList.of("foouser"), "emails", ImmutableList.of("foo@bar.com")));
    when(stream2.getId()).thenReturn(matchingStreamId1);
    final Stream stream3 = mock(Stream.class);
    when(stream3.getAlertReceivers()).thenReturn(ImmutableMap.of("users", ImmutableList.of("foouser2")));
    when(stream3.getId()).thenReturn(matchingStreamId2);
    when(this.streamService.loadAll()).thenReturn(ImmutableList.of(stream1, stream2, stream3));
    final AlertCondition alertCondition1 = mock(AlertCondition.class);
    final AlertCondition alertCondition2 = mock(AlertCondition.class);
    when(this.streamService.getAlertConditions(eq(stream2))).thenReturn(ImmutableList.of(alertCondition1));
    when(this.streamService.getAlertConditions(eq(stream3))).thenReturn(ImmutableList.of(alertCondition2));
    final String alarmCallbackId1 = new ObjectId().toHexString();
    final AlarmCallbackConfiguration alarmCallback1 = AlarmCallbackConfigurationImpl.create(alarmCallbackId1, matchingStreamId1, EmailAlarmCallback.class.getCanonicalName(), "Email Alert Notification", new HashMap<>(), new Date(), "admin");
    final String alarmCallbackId2 = new ObjectId().toHexString();
    final AlarmCallbackConfiguration alarmCallback2 = AlarmCallbackConfigurationImpl.create(alarmCallbackId2, matchingStreamId2, EmailAlarmCallback.class.getCanonicalName(), "Email Alert Notification", new HashMap<>(), new Date(), "admin");
    final String alarmCallbackId3 = new ObjectId().toHexString();
    final AlarmCallbackConfiguration alarmCallback3 = AlarmCallbackConfigurationImpl.create(alarmCallbackId3, matchingStreamId2, EmailAlarmCallback.class.getCanonicalName(), "Email Alert Notification", new HashMap<>(), new Date(), "admin");
    final String alarmCallbackId4 = new ObjectId().toHexString();
    final AlarmCallbackConfiguration alarmCallback4 = AlarmCallbackConfigurationImpl.create(alarmCallbackId4, matchingStreamId2, HTTPAlarmCallback.class.getCanonicalName(), "Email Alert Notification", new HashMap<>(), new Date(), "admin");
    when(alarmCallbackConfigurationService.getForStream(eq(stream2))).thenReturn(ImmutableList.of(alarmCallback1));
    when(alarmCallbackConfigurationService.getForStream(eq(stream3))).thenReturn(ImmutableList.of(alarmCallback2, alarmCallback3, alarmCallback4));
    when(alarmCallbackConfigurationService.save(eq(alarmCallback1))).thenReturn(alarmCallbackId1);
    when(alarmCallbackConfigurationService.save(eq(alarmCallback2))).thenReturn(alarmCallbackId2);
    when(alarmCallbackConfigurationService.save(eq(alarmCallback3))).thenReturn(alarmCallbackId3);
    when(this.dbCollection.update(any(BasicDBObject.class), any(BasicDBObject.class))).thenReturn(new WriteResult(1, true, matchingStreamId1));
    when(this.dbCollection.update(any(BasicDBObject.class), any(BasicDBObject.class))).thenReturn(new WriteResult(1, true, matchingStreamId2));
    this.alertReceiversMigration.upgrade();
    final ArgumentCaptor<AlarmCallbackConfiguration> configurationArgumentCaptor = ArgumentCaptor.forClass(AlarmCallbackConfiguration.class);
    verify(this.alarmCallbackConfigurationService, times(3)).save(configurationArgumentCaptor.capture());
    final List<AlarmCallbackConfiguration> configurationValues = configurationArgumentCaptor.getAllValues();
    assertThat(configurationValues).isNotNull().isNotEmpty().hasSize(3).contains(alarmCallback1).contains(alarmCallback2).contains(alarmCallback3);
    for (AlarmCallbackConfiguration configurationValue : configurationValues) {
        if (configurationValue.getStreamId().equals(matchingStreamId1)) {
            assertThat(((List) configurationValue.getConfiguration().get(EmailAlarmCallback.CK_EMAIL_RECEIVERS)).size()).isEqualTo(1);
            assertThat(((List) configurationValue.getConfiguration().get(EmailAlarmCallback.CK_EMAIL_RECEIVERS)).get(0)).isEqualTo("foo@bar.com");
            assertThat(((List) configurationValue.getConfiguration().get(EmailAlarmCallback.CK_USER_RECEIVERS)).size()).isEqualTo(1);
            assertThat(((List) configurationValue.getConfiguration().get(EmailAlarmCallback.CK_USER_RECEIVERS)).get(0)).isEqualTo("foouser");
        }
        if (configurationValue.getStreamId().equals(matchingStreamId2)) {
            assertThat(configurationValue.getConfiguration().get(EmailAlarmCallback.CK_EMAIL_RECEIVERS)).isNull();
            assertThat(((List) configurationValue.getConfiguration().get(EmailAlarmCallback.CK_USER_RECEIVERS)).size()).isEqualTo(1);
            assertThat(((List) configurationValue.getConfiguration().get(EmailAlarmCallback.CK_USER_RECEIVERS)).get(0)).isEqualTo("foouser2");
        }
    }
    final ArgumentCaptor<BasicDBObject> queryCaptor = ArgumentCaptor.forClass(BasicDBObject.class);
    final ArgumentCaptor<BasicDBObject> updateCaptor = ArgumentCaptor.forClass(BasicDBObject.class);
    verify(this.dbCollection, times(2)).update(queryCaptor.capture(), updateCaptor.capture());
    final List<BasicDBObject> queries = queryCaptor.getAllValues();
    for (BasicDBObject query : queries) {
        final String streamId = (queries.indexOf(query) == 0 ? matchingStreamId1 : matchingStreamId2);
        assertThat(query.toJson()).isEqualTo("{ \"_id\" : { \"$oid\" : \"" + streamId + "\" } }");
    }
    updateCaptor.getAllValues().forEach(update -> assertThat(update.toJson()).isEqualTo("{ \"$unset\" : { \"" + StreamImpl.FIELD_ALERT_RECEIVERS + "\" : \"\" } }"));
    verifyMigrationCompletedWasPosted(ImmutableMap.of(matchingStreamId1, Optional.of(alarmCallbackId1), matchingStreamId2, Optional.of(alarmCallbackId2 + ", " + alarmCallbackId3)));
}
Also used : ObjectId(org.bson.types.ObjectId) Date(java.util.Date) BasicDBObject(com.mongodb.BasicDBObject) HTTPAlarmCallback(org.graylog2.alarmcallbacks.HTTPAlarmCallback) WriteResult(com.mongodb.WriteResult) AlertCondition(org.graylog2.plugin.alarms.AlertCondition) Stream(org.graylog2.plugin.streams.Stream) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) EmailAlarmCallback(org.graylog2.alarmcallbacks.EmailAlarmCallback) AlarmCallbackConfiguration(org.graylog2.alarmcallbacks.AlarmCallbackConfiguration) Test(org.junit.Test)

Aggregations

WriteResult (com.mongodb.WriteResult)29 BasicDBObject (com.mongodb.BasicDBObject)17 DBObject (com.mongodb.DBObject)14 DBCollection (com.mongodb.DBCollection)9 Test (org.junit.Test)5 BulkWriteResult (com.mongodb.BulkWriteResult)3 DB (com.mongodb.DB)3 Date (java.util.Date)3 List (java.util.List)3 Query (org.springframework.data.mongodb.core.query.Query)3 ImmutableList (com.google.common.collect.ImmutableList)2 MongoException (com.mongodb.MongoException)2 QueryBuilder (com.mongodb.QueryBuilder)2 IOException (java.io.IOException)2 LinkedHashMap (java.util.LinkedHashMap)2 NodeDocument (org.apache.jackrabbit.oak.plugins.document.NodeDocument)2 ObjectId (org.bson.types.ObjectId)2 AlarmCallbackConfiguration (org.graylog2.alarmcallbacks.AlarmCallbackConfiguration)2 EmailAlarmCallback (org.graylog2.alarmcallbacks.EmailAlarmCallback)2 AlertCondition (org.graylog2.plugin.alarms.AlertCondition)2