Search in sources :

Example 6 with ReadConcern

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

the class AggregationOptions method prepare.

@Override
public <C> MongoCollection<C> prepare(MongoCollection<C> collection) {
    MongoCollection<C> updated = collection;
    WriteConcern writeConcern = writeConcern();
    if (writeConcern != null) {
        updated = updated.withWriteConcern(writeConcern);
    }
    ReadConcern readConcern = getReadConcern();
    if (readConcern != null) {
        updated = updated.withReadConcern(readConcern);
    }
    ReadPreference readPreference = getReadPreference();
    if (readPreference != null) {
        updated = updated.withReadPreference(readPreference);
    }
    return updated;
}
Also used : ReadPreference(com.mongodb.ReadPreference) WriteConcern(com.mongodb.WriteConcern) ReadConcern(com.mongodb.ReadConcern)

Example 7 with ReadConcern

use of com.mongodb.ReadConcern in project cas by apereo.

the class MongoDbConnectionFactory method buildMongoDbClient.

/**
 * Build mongo db client.
 *
 * @param mongo the mongo
 * @return the mongo client
 */
public MongoClient buildMongoDbClient(final BaseMongoDbProperties mongo) {
    val settingsBuilder = MongoClientSettings.builder();
    if (StringUtils.isNotBlank(mongo.getClientUri())) {
        LOGGER.debug("Using MongoDb client URI [{}] to connect to MongoDb instance", mongo.getClientUri());
        settingsBuilder.applyConnectionString(new ConnectionString(mongo.getClientUri()));
    } else {
        val serverAddresses = mongo.getHost().split(",");
        if (serverAddresses.length == 0) {
            throw new BeanCreationException("Unable to build a MongoDb client without any hosts/servers defined");
        }
        val servers = new ArrayList<ServerAddress>(0);
        if (serverAddresses.length > 1) {
            LOGGER.debug("Multiple MongoDb server addresses are defined. Ignoring port [{}], " + "assuming ports are defined as part of the address", mongo.getPort());
            Arrays.stream(serverAddresses).filter(StringUtils::isNotBlank).map(ServerAddress::new).forEach(servers::add);
        } else {
            val port = mongo.getPort() > 0 ? mongo.getPort() : DEFAULT_PORT;
            LOGGER.debug("Found single MongoDb server address [{}] using port [{}]", mongo.getHost(), port);
            val addr = new ServerAddress(mongo.getHost(), port);
            servers.add(addr);
        }
        settingsBuilder.applyToClusterSettings(builder -> builder.hosts(servers));
        val credential = buildMongoCredential(mongo);
        settingsBuilder.credential(credential).writeConcern(WriteConcern.valueOf(mongo.getWriteConcern())).codecRegistry(CodecRegistries.fromRegistries(CodecRegistries.fromProviders(new BaseConverters.ZonedDateTimeCodecProvider()), MongoClientSettings.getDefaultCodecRegistry())).readConcern(new ReadConcern(ReadConcernLevel.valueOf(mongo.getReadConcern()))).applyToConnectionPoolSettings(builder -> {
            val poolConfig = mongo.getPool();
            val pool = ConnectionPoolSettings.builder().maxConnectionLifeTime(Beans.newDuration(poolConfig.getLifeTime()).toMillis(), TimeUnit.MILLISECONDS).maxConnectionIdleTime(Beans.newDuration(poolConfig.getIdleTime()).toMillis(), TimeUnit.MILLISECONDS).maxSize(poolConfig.getMaxSize()).minSize(poolConfig.getMinSize()).maxWaitTime(Beans.newDuration(poolConfig.getMaxWaitTime()).toMillis(), TimeUnit.MILLISECONDS).build();
            builder.applySettings(pool);
        }).applyToSocketSettings(builder -> {
            val socket = SocketSettings.builder().connectTimeout((int) Beans.newDuration(mongo.getTimeout()).toMillis(), TimeUnit.MILLISECONDS).readTimeout((int) Beans.newDuration(mongo.getTimeout()).toMillis(), TimeUnit.MILLISECONDS).build();
            builder.applySettings(socket);
        }).applyToSslSettings(builder -> {
            val ssl = SslSettings.builder().enabled(mongo.isSslEnabled()).context(this.sslContext).build();
            builder.applySettings(ssl);
        }).applyToServerSettings(builder -> {
            val server = ServerSettings.builder().heartbeatFrequency((int) Beans.newDuration(mongo.getTimeout()).toMillis(), TimeUnit.MILLISECONDS).build();
            builder.applySettings(server);
        }).retryWrites(mongo.isRetryWrites());
    }
    return MongoClients.create(settingsBuilder.build());
}
Also used : lombok.val(lombok.val) SSLContext(javax.net.ssl.SSLContext) Arrays(java.util.Arrays) SneakyThrows(lombok.SneakyThrows) Beans(org.apereo.cas.configuration.support.Beans) StringUtils(org.apache.commons.lang3.StringUtils) Document(org.springframework.data.mongodb.core.mapping.Document) LoggingUtils(org.apereo.cas.util.LoggingUtils) SocketSettings(com.mongodb.connection.SocketSettings) SSLContexts(org.apache.http.ssl.SSLContexts) ReadConcern(com.mongodb.ReadConcern) AnnotationTypeFilter(org.springframework.core.type.filter.AnnotationTypeFilter) ClassUtils(org.springframework.util.ClassUtils) PropertyNameFieldNamingStrategy(org.springframework.data.mapping.model.PropertyNameFieldNamingStrategy) MongoClients(com.mongodb.client.MongoClients) Collection(java.util.Collection) Set(java.util.Set) CodecRegistries(org.bson.codecs.configuration.CodecRegistries) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Stream(java.util.stream.Stream) JodaTimeConverters(org.springframework.data.convert.JodaTimeConverters) MongoClientSettings(com.mongodb.MongoClientSettings) IndexDefinition(org.springframework.data.mongodb.core.index.IndexDefinition) ConnectionPoolSettings(com.mongodb.connection.ConnectionPoolSettings) MongoMappingContext(org.springframework.data.mongodb.core.mapping.MongoMappingContext) MongoCredential(com.mongodb.MongoCredential) MongoClient(com.mongodb.client.MongoClient) MongoCollection(com.mongodb.client.MongoCollection) MongoCustomConversions(org.springframework.data.mongodb.core.convert.MongoCustomConversions) FieldNamingStrategy(org.springframework.data.mapping.model.FieldNamingStrategy) MongoDatabaseFactory(org.springframework.data.mongodb.MongoDatabaseFactory) ServerSettings(com.mongodb.connection.ServerSettings) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) BeanCreationException(org.springframework.beans.factory.BeanCreationException) CollectionUtils(org.apereo.cas.util.CollectionUtils) Jsr310Converters(org.springframework.data.convert.Jsr310Converters) ServerAddress(com.mongodb.ServerAddress) SslSettings(com.mongodb.connection.SslSettings) Converter(org.springframework.core.convert.converter.Converter) Persistent(org.springframework.data.annotation.Persistent) ClassPathScanningCandidateComponentProvider(org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider) lombok.val(lombok.val) TimeUnit(java.util.concurrent.TimeUnit) MappingMongoConverter(org.springframework.data.mongodb.core.convert.MappingMongoConverter) ConnectionString(com.mongodb.ConnectionString) ReadConcernLevel(com.mongodb.ReadConcernLevel) BaseMongoDbProperties(org.apereo.cas.configuration.model.support.mongo.BaseMongoDbProperties) MongoOperations(org.springframework.data.mongodb.core.MongoOperations) DefaultDbRefResolver(org.springframework.data.mongodb.core.convert.DefaultDbRefResolver) WriteConcern(com.mongodb.WriteConcern) SimpleMongoClientDatabaseFactory(org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory) BeanCreationException(org.springframework.beans.factory.BeanCreationException) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) ServerAddress(com.mongodb.ServerAddress) ConnectionString(com.mongodb.ConnectionString) ReadConcern(com.mongodb.ReadConcern)

Example 8 with ReadConcern

use of com.mongodb.ReadConcern in project spring-data-mongodb by spring-projects.

the class MongoClientSettingsFactoryBean method createInstance.

@Override
protected MongoClientSettings createInstance() {
    Builder builder = // 
    MongoClientSettings.builder().readPreference(// 
    readPreference).writeConcern(// 
    writeConcern).readConcern(// 
    readConcern).codecRegistry(// 
    codecRegistry).applicationName(// 
    applicationName).autoEncryptionSettings(// 
    autoEncryptionSettings).applyToClusterSettings((settings) -> {
        settings.serverSelectionTimeout(clusterServerSelectionTimeoutMS, TimeUnit.MILLISECONDS);
        if (clusterConnectionMode != null) {
            settings.mode(clusterConnectionMode);
        }
        settings.requiredReplicaSetName(clusterRequiredReplicaSetName);
        if (!CollectionUtils.isEmpty(clusterHosts)) {
            settings.hosts(clusterHosts);
        }
        settings.localThreshold(clusterLocalThresholdMS, TimeUnit.MILLISECONDS);
        // settings.maxWaitQueueSize(clusterMaxWaitQueueSize);
        settings.requiredClusterType(custerRequiredClusterType);
        if (StringUtils.hasText(clusterSrvHost)) {
            settings.srvHost(clusterSrvHost);
        }
    }).applyToConnectionPoolSettings((settings) -> {
        settings.minSize(poolMinSize);
        settings.maxSize(poolMaxSize);
        settings.maxConnectionIdleTime(poolMaxConnectionIdleTimeMS, TimeUnit.MILLISECONDS);
        settings.maxWaitTime(poolMaxWaitTimeMS, TimeUnit.MILLISECONDS);
        settings.maxConnectionLifeTime(poolMaxConnectionLifeTimeMS, TimeUnit.MILLISECONDS);
        // settings.maxWaitQueueSize(poolMaxWaitQueueSize);
        settings.maintenanceFrequency(poolMaintenanceFrequencyMS, TimeUnit.MILLISECONDS);
        settings.maintenanceInitialDelay(poolMaintenanceInitialDelayMS, TimeUnit.MILLISECONDS);
    }).applyToServerSettings((settings) -> {
        settings.minHeartbeatFrequency(serverMinHeartbeatFrequencyMS, TimeUnit.MILLISECONDS);
        settings.heartbeatFrequency(serverHeartbeatFrequencyMS, TimeUnit.MILLISECONDS);
    }).applyToSocketSettings((settings) -> {
        settings.connectTimeout(socketConnectTimeoutMS, TimeUnit.MILLISECONDS);
        settings.readTimeout(socketReadTimeoutMS, TimeUnit.MILLISECONDS);
        settings.receiveBufferSize(socketReceiveBufferSize);
        settings.sendBufferSize(socketSendBufferSize);
    }).applyToSslSettings((settings) -> {
        settings.enabled(sslEnabled);
        if (sslEnabled) {
            settings.invalidHostNameAllowed(sslInvalidHostNameAllowed);
            try {
                settings.context(StringUtils.hasText(sslProvider) ? SSLContext.getInstance(sslProvider) : SSLContext.getDefault());
            } catch (NoSuchAlgorithmException e) {
                throw new IllegalArgumentException(e.getMessage(), e);
            }
        }
    });
    if (streamFactoryFactory != null) {
        builder = builder.streamFactoryFactory(streamFactoryFactory);
    }
    if (retryReads != null) {
        builder = builder.retryReads(retryReads);
    }
    if (retryWrites != null) {
        builder = builder.retryWrites(retryWrites);
    }
    if (uUidRepresentation != null) {
        builder = builder.uuidRepresentation(uUidRepresentation);
    }
    if (serverApi != null) {
        builder = builder.serverApi(serverApi);
    }
    return builder.build();
}
Also used : ReadPreference(com.mongodb.ReadPreference) ServerAddress(com.mongodb.ServerAddress) Arrays(java.util.Arrays) SSLContext(javax.net.ssl.SSLContext) ServerApi(com.mongodb.ServerApi) ClusterType(com.mongodb.connection.ClusterType) CodecRegistry(org.bson.codecs.configuration.CodecRegistry) AutoEncryptionSettings(com.mongodb.AutoEncryptionSettings) UuidRepresentation(org.bson.UuidRepresentation) AbstractFactoryBean(org.springframework.beans.factory.config.AbstractFactoryBean) TimeUnit(java.util.concurrent.TimeUnit) Builder(com.mongodb.MongoClientSettings.Builder) StreamFactoryFactory(com.mongodb.connection.StreamFactoryFactory) List(java.util.List) CollectionUtils(org.springframework.util.CollectionUtils) ClusterConnectionMode(com.mongodb.connection.ClusterConnectionMode) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Nullable(org.springframework.lang.Nullable) MongoClientSettings(com.mongodb.MongoClientSettings) ReadConcern(com.mongodb.ReadConcern) WriteConcern(com.mongodb.WriteConcern) Collections(java.util.Collections) StringUtils(org.springframework.util.StringUtils) Builder(com.mongodb.MongoClientSettings.Builder) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 9 with ReadConcern

use of com.mongodb.ReadConcern in project mongo-java-driver by mongodb.

the class OperationExecutorImpl method execute.

@Override
public <T> Mono<T> execute(final AsyncReadOperation<T> operation, final ReadPreference readPreference, final ReadConcern readConcern, @Nullable final ClientSession session) {
    notNull("operation", operation);
    notNull("readPreference", readPreference);
    notNull("readConcern", readConcern);
    if (session != null) {
        session.notifyOperationInitiated(operation);
    }
    return Mono.from(subscriber -> clientSessionHelper.withClientSession(session, OperationExecutorImpl.this).map(clientSession -> getReadWriteBinding(getContext(subscriber), readPreference, readConcern, clientSession, session == null && clientSession != null)).switchIfEmpty(Mono.fromCallable(() -> getReadWriteBinding(getContext(subscriber), readPreference, readConcern, session, false))).flatMap(binding -> {
        if (session != null && session.hasActiveTransaction() && !binding.getReadPreference().equals(primary())) {
            binding.release();
            return Mono.error(new MongoClientException("Read preference in a transaction must be primary"));
        } else {
            return Mono.<T>create(sink -> operation.executeAsync(binding, (result, t) -> {
                try {
                    binding.release();
                } finally {
                    sinkToCallback(sink).onResult(result, t);
                }
            })).doOnError((t) -> {
                labelException(session, t);
                unpinServerAddressOnTransientTransactionError(session, t);
            });
        }
    }).subscribe(subscriber));
}
Also used : MongoInternalException(com.mongodb.MongoInternalException) ReadPreference(com.mongodb.ReadPreference) AsyncReadWriteBinding(com.mongodb.internal.binding.AsyncReadWriteBinding) MongoClientException(com.mongodb.MongoClientException) MongoSocketException(com.mongodb.MongoSocketException) MongoQueryException(com.mongodb.MongoQueryException) CryptBinding(com.mongodb.reactivestreams.client.internal.crypt.CryptBinding) TRANSIENT_TRANSACTION_ERROR_LABEL(com.mongodb.MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL) IgnorableRequestContext(com.mongodb.internal.IgnorableRequestContext) ReadConcern(com.mongodb.ReadConcern) Subscriber(org.reactivestreams.Subscriber) MongoException(com.mongodb.MongoException) AsyncWriteOperation(com.mongodb.internal.operation.AsyncWriteOperation) Mono(reactor.core.publisher.Mono) RequestContext(com.mongodb.RequestContext) ClientSessionBinding(com.mongodb.internal.async.client.ClientSessionBinding) ClientSession(com.mongodb.reactivestreams.client.ClientSession) ReactiveContextProvider(com.mongodb.reactivestreams.client.ReactiveContextProvider) MongoTimeoutException(com.mongodb.MongoTimeoutException) Crypt(com.mongodb.reactivestreams.client.internal.crypt.Crypt) Assertions.notNull(com.mongodb.assertions.Assertions.notNull) ContextProvider(com.mongodb.ContextProvider) AsyncReadOperation(com.mongodb.internal.operation.AsyncReadOperation) AsyncClusterBinding(com.mongodb.internal.binding.AsyncClusterBinding) UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL(com.mongodb.MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) ReadPreference.primary(com.mongodb.ReadPreference.primary) MongoOperationPublisher.sinkToCallback(com.mongodb.reactivestreams.client.internal.MongoOperationPublisher.sinkToCallback) Nullable(com.mongodb.lang.Nullable) AsyncClusterAwareReadWriteBinding(com.mongodb.internal.binding.AsyncClusterAwareReadWriteBinding) MongoClientException(com.mongodb.MongoClientException)

Example 10 with ReadConcern

use of com.mongodb.ReadConcern in project mongo-java-driver by mongodb.

the class ClientSessionPublisherImpl method abortTransaction.

@Override
public Publisher<Void> abortTransaction() {
    if (transactionState == TransactionState.ABORTED) {
        throw new IllegalStateException("Cannot call abortTransaction twice");
    }
    if (transactionState == TransactionState.COMMITTED) {
        throw new IllegalStateException("Cannot call abortTransaction after calling commitTransaction");
    }
    if (transactionState == TransactionState.NONE) {
        throw new IllegalStateException("There is no transaction started");
    }
    if (!messageSentInCurrentTransaction) {
        cleanupTransaction(TransactionState.ABORTED);
        return Mono.create(MonoSink::success);
    } else {
        ReadConcern readConcern = transactionOptions.getReadConcern();
        if (readConcern == null) {
            throw new MongoInternalException("Invariant violated. Transaction options read concern can not be null");
        }
        return executor.execute(new AbortTransactionOperation(transactionOptions.getWriteConcern()).recoveryToken(getRecoveryToken()), readConcern, this).onErrorResume(Throwable.class, (e) -> Mono.empty()).doOnTerminate(() -> {
            clearTransactionContext();
            cleanupTransaction(TransactionState.ABORTED);
        });
    }
}
Also used : MonoSink(reactor.core.publisher.MonoSink) MongoInternalException(com.mongodb.MongoInternalException) MongoClientException(com.mongodb.MongoClientException) MonoSink(reactor.core.publisher.MonoSink) AsyncClientSession(com.mongodb.internal.async.client.AsyncClientSession) MongoClient(com.mongodb.reactivestreams.client.MongoClient) TransactionOptions(com.mongodb.TransactionOptions) TRANSIENT_TRANSACTION_ERROR_LABEL(com.mongodb.MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL) BaseClientSessionImpl(com.mongodb.internal.session.BaseClientSessionImpl) Assertions.isTrue(com.mongodb.assertions.Assertions.isTrue) ServerSessionPool(com.mongodb.internal.session.ServerSessionPool) ReadConcern(com.mongodb.ReadConcern) CommitTransactionOperation(com.mongodb.internal.operation.CommitTransactionOperation) MongoException(com.mongodb.MongoException) AsyncWriteOperation(com.mongodb.internal.operation.AsyncWriteOperation) Publisher(org.reactivestreams.Publisher) Mono(reactor.core.publisher.Mono) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) ClientSession(com.mongodb.reactivestreams.client.ClientSession) SingleResultCallback(com.mongodb.internal.async.SingleResultCallback) Assertions.notNull(com.mongodb.assertions.Assertions.notNull) ClientSessionOptions(com.mongodb.ClientSessionOptions) Assertions.assertTrue(com.mongodb.assertions.Assertions.assertTrue) AsyncReadOperation(com.mongodb.internal.operation.AsyncReadOperation) UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL(com.mongodb.MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) AbortTransactionOperation(com.mongodb.internal.operation.AbortTransactionOperation) WriteConcern(com.mongodb.WriteConcern) ReadConcern(com.mongodb.ReadConcern) AbortTransactionOperation(com.mongodb.internal.operation.AbortTransactionOperation) MongoInternalException(com.mongodb.MongoInternalException)

Aggregations

ReadConcern (com.mongodb.ReadConcern)12 WriteConcern (com.mongodb.WriteConcern)7 MongoException (com.mongodb.MongoException)5 MongoInternalException (com.mongodb.MongoInternalException)5 ReadPreference (com.mongodb.ReadPreference)5 MongoClientSettings (com.mongodb.MongoClientSettings)4 ClientSessionOptions (com.mongodb.ClientSessionOptions)3 MongoClientException (com.mongodb.MongoClientException)3 ReadConcernLevel (com.mongodb.ReadConcernLevel)3 ServerAddress (com.mongodb.ServerAddress)3 TransactionOptions (com.mongodb.TransactionOptions)3 List (java.util.List)3 TimeUnit (java.util.concurrent.TimeUnit)3 ClusterFixture.getMultiMongosConnectionString (com.mongodb.ClusterFixture.getMultiMongosConnectionString)2 ClusterFixture.isSharded (com.mongodb.ClusterFixture.isSharded)2 ConnectionString (com.mongodb.ConnectionString)2 TRANSIENT_TRANSACTION_ERROR_LABEL (com.mongodb.MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL)2 UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL (com.mongodb.MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL)2 ServerApi (com.mongodb.ServerApi)2 Assertions.notNull (com.mongodb.assertions.Assertions.notNull)2