All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.mongodb.MongoClientSettings Maven / Gradle / Ivy

Go to download

The MongoDB Java Driver uber-artifact, containing mongodb-driver, mongodb-driver-core, and bson

There is a newer version: 3.12.14
Show newest version
/*
 * Copyright 2008-present MongoDB, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mongodb;

import com.mongodb.annotations.Immutable;
import com.mongodb.annotations.NotThreadSafe;
import com.mongodb.client.gridfs.codecs.GridFSFileCodecProvider;
import com.mongodb.client.model.geojson.codecs.GeoJsonCodecProvider;
import com.mongodb.connection.ClusterSettings;
import com.mongodb.connection.ConnectionPoolSettings;
import com.mongodb.connection.ServerSettings;
import com.mongodb.connection.SocketSettings;
import com.mongodb.connection.SslSettings;
import com.mongodb.connection.StreamFactoryFactory;
import com.mongodb.event.CommandListener;
import com.mongodb.lang.Nullable;
import org.bson.codecs.BsonValueCodecProvider;
import org.bson.codecs.DocumentCodecProvider;
import org.bson.codecs.IterableCodecProvider;
import org.bson.codecs.MapCodecProvider;
import org.bson.codecs.ValueCodecProvider;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.jsr310.Jsr310CodecProvider;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.mongodb.assertions.Assertions.isTrueArgument;
import static com.mongodb.assertions.Assertions.notNull;
import static java.util.Arrays.asList;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;


/**
 * Various settings to control the behavior of a {@code MongoClient}.
 *
 * @since 3.7
 */
@Immutable
public final class MongoClientSettings {
    private static final CodecRegistry DEFAULT_CODEC_REGISTRY =
            fromProviders(asList(new ValueCodecProvider(),
                    new BsonValueCodecProvider(),
                    new DBRefCodecProvider(),
                    new DBObjectCodecProvider(),
                    new DocumentCodecProvider(new DocumentToDBRefTransformer()),
                    new IterableCodecProvider(new DocumentToDBRefTransformer()),
                    new MapCodecProvider(new DocumentToDBRefTransformer()),
                    new GeoJsonCodecProvider(),
                    new GridFSFileCodecProvider(),
                    new Jsr310CodecProvider()));

    private final ReadPreference readPreference;
    private final WriteConcern writeConcern;
    private final boolean retryWrites;
    private final ReadConcern readConcern;
    private final MongoCredential credential;
    private final StreamFactoryFactory streamFactoryFactory;
    private final List commandListeners;
    private final CodecRegistry codecRegistry;

    private final ClusterSettings clusterSettings;
    private final SocketSettings socketSettings;
    private final SocketSettings heartbeatSocketSettings;
    private final ConnectionPoolSettings connectionPoolSettings;
    private final ServerSettings serverSettings;
    private final SslSettings sslSettings;
    private final String applicationName;
    private final List compressorList;

    /**
     * Gets the default codec registry.  It includes the following providers:
     *
     * 
    *
  • {@link org.bson.codecs.ValueCodecProvider}
  • *
  • {@link org.bson.codecs.BsonValueCodecProvider}
  • *
  • {@link com.mongodb.DBRefCodecProvider}
  • *
  • {@link com.mongodb.DBObjectCodecProvider}
  • *
  • {@link org.bson.codecs.DocumentCodecProvider}
  • *
  • {@link org.bson.codecs.IterableCodecProvider}
  • *
  • {@link org.bson.codecs.MapCodecProvider}
  • *
  • {@link com.mongodb.client.model.geojson.codecs.GeoJsonCodecProvider}
  • *
  • {@link com.mongodb.client.gridfs.codecs.GridFSFileCodecProvider}
  • *
  • {@link org.bson.codecs.jsr310.Jsr310CodecProvider}
  • *
* * @return the default codec registry */ public static CodecRegistry getDefaultCodecRegistry() { return DEFAULT_CODEC_REGISTRY; } /** * Convenience method to create a Builder. * * @return a builder */ public static Builder builder() { return new Builder(); } /** * Convenience method to create a from an existing {@code MongoClientSettings}. * * @param settings create a builder from existing settings * @return a builder */ public static Builder builder(final MongoClientSettings settings) { return new Builder(settings); } /** * A builder for {@code MongoClientSettings} so that {@code MongoClientSettings} can be immutable, and to support easier construction * through chaining. */ @NotThreadSafe public static final class Builder { private ReadPreference readPreference = ReadPreference.primary(); private WriteConcern writeConcern = WriteConcern.ACKNOWLEDGED; private boolean retryWrites; private ReadConcern readConcern = ReadConcern.DEFAULT; private CodecRegistry codecRegistry = MongoClientSettings.getDefaultCodecRegistry(); private StreamFactoryFactory streamFactoryFactory; private List commandListeners = new ArrayList(); private final ClusterSettings.Builder clusterSettingsBuilder = ClusterSettings.builder(); private final SocketSettings.Builder socketSettingsBuilder = SocketSettings.builder(); private final ConnectionPoolSettings.Builder connectionPoolSettingsBuilder = ConnectionPoolSettings.builder(); private final ServerSettings.Builder serverSettingsBuilder = ServerSettings.builder(); private final SslSettings.Builder sslSettingsBuilder = SslSettings.builder(); private MongoCredential credential; private String applicationName; private List compressorList = Collections.emptyList(); private Builder() { } private Builder(final MongoClientSettings settings) { notNull("settings", settings); applicationName = settings.getApplicationName(); commandListeners = new ArrayList(settings.getCommandListeners()); compressorList = new ArrayList(settings.getCompressorList()); codecRegistry = settings.getCodecRegistry(); readPreference = settings.getReadPreference(); writeConcern = settings.getWriteConcern(); retryWrites = settings.getRetryWrites(); readConcern = settings.getReadConcern(); credential = settings.getCredential(); streamFactoryFactory = settings.getStreamFactoryFactory(); clusterSettingsBuilder.applySettings(settings.getClusterSettings()); serverSettingsBuilder.applySettings(settings.getServerSettings()); socketSettingsBuilder.applySettings(settings.getSocketSettings()); connectionPoolSettingsBuilder.applySettings(settings.getConnectionPoolSettings()); sslSettingsBuilder.applySettings(settings.getSslSettings()); } /** * Takes the settings from the given {@code ConnectionString} and applies them to the builder * * @param connectionString the connection string containing details of how to connect to MongoDB * @return this */ public Builder applyConnectionString(final ConnectionString connectionString) { if (connectionString.getApplicationName() != null) { applicationName = connectionString.getApplicationName(); } clusterSettingsBuilder.applyConnectionString(connectionString); if (!connectionString.getCompressorList().isEmpty()) { compressorList = connectionString.getCompressorList(); } connectionPoolSettingsBuilder.applyConnectionString(connectionString); if (connectionString.getCredential() != null) { credential = connectionString.getCredential(); } if (connectionString.getReadConcern() != null) { readConcern = connectionString.getReadConcern(); } if (connectionString.getReadPreference() != null) { readPreference = connectionString.getReadPreference(); } if (connectionString.getRetryWritesValue() != null) { retryWrites = connectionString.getRetryWrites(); } serverSettingsBuilder.applyConnectionString(connectionString); socketSettingsBuilder.applyConnectionString(connectionString); sslSettingsBuilder.applyConnectionString(connectionString); if (connectionString.getWriteConcern() != null) { writeConcern = connectionString.getWriteConcern(); } return this; } /** * Applies the {@link ClusterSettings.Builder} block and then sets the clusterSettings. * * @param block the block to apply to the ClusterSettings. * @return this * @see MongoClientSettings#getClusterSettings() */ public Builder applyToClusterSettings(final Block block) { notNull("block", block).apply(clusterSettingsBuilder); return this; } /** * Applies the {@link SocketSettings.Builder} block and then sets the socketSettings. * * @param block the block to apply to the SocketSettings. * @return this * @see MongoClientSettings#getSocketSettings() */ public Builder applyToSocketSettings(final Block block) { notNull("block", block).apply(socketSettingsBuilder); return this; } /** * Applies the {@link ConnectionPoolSettings.Builder} block and then sets the connectionPoolSettings. * * @param block the block to apply to the ConnectionPoolSettings. * @return this * @see MongoClientSettings#getConnectionPoolSettings() */ public Builder applyToConnectionPoolSettings(final Block block) { notNull("block", block).apply(connectionPoolSettingsBuilder); return this; } /** * Applies the {@link ServerSettings.Builder} block and then sets the serverSettings. * * @param block the block to apply to the ServerSettings. * @return this * @see MongoClientSettings#getServerSettings() */ public Builder applyToServerSettings(final Block block) { notNull("block", block).apply(serverSettingsBuilder); return this; } /** * Applies the {@link SslSettings.Builder} block and then sets the sslSettings. * * @param block the block to apply to the SslSettings. * @return this * @see MongoClientSettings#getSslSettings() */ public Builder applyToSslSettings(final Block block) { notNull("block", block).apply(sslSettingsBuilder); return this; } /** * Sets the read preference. * * @param readPreference read preference * @return this * @see MongoClientSettings#getReadPreference() */ public Builder readPreference(final ReadPreference readPreference) { this.readPreference = notNull("readPreference", readPreference); return this; } /** * Sets the write concern. * * @param writeConcern the write concern * @return this * @see MongoClientSettings#getWriteConcern() */ public Builder writeConcern(final WriteConcern writeConcern) { this.writeConcern = notNull("writeConcern", writeConcern); return this; } /** * Sets whether writes should be retried if they fail due to a network error. * * @param retryWrites sets if writes should be retried if they fail due to a network error. * @return this * @see #getRetryWrites() * @mongodb.server.release 3.6 */ public Builder retryWrites(final boolean retryWrites) { this.retryWrites = retryWrites; return this; } /** * Sets the read concern. * * @param readConcern the read concern * @return this * @mongodb.server.release 3.2 * @mongodb.driver.manual reference/readConcern/ Read Concern */ public Builder readConcern(final ReadConcern readConcern) { this.readConcern = notNull("readConcern", readConcern); return this; } /** * Sets the credential. * * @param credential the credential * @return this */ public Builder credential(final MongoCredential credential) { this.credential = notNull("credential", credential); return this; } /** * Sets the codec registry * * @param codecRegistry the codec registry * @return this * @see MongoClientSettings#getCodecRegistry() */ public Builder codecRegistry(final CodecRegistry codecRegistry) { this.codecRegistry = notNull("codecRegistry", codecRegistry); return this; } /** * Sets the factory to use to create a {@code StreamFactory}. * * @param streamFactoryFactory the stream factory factory * @return this */ public Builder streamFactoryFactory(final StreamFactoryFactory streamFactoryFactory) { this.streamFactoryFactory = notNull("streamFactoryFactory", streamFactoryFactory); return this; } /** * Adds the given command listener. * * @param commandListener the command listener * @return this */ public Builder addCommandListener(final CommandListener commandListener) { notNull("commandListener", commandListener); commandListeners.add(commandListener); return this; } /** * Sets the the command listeners * * @param commandListeners the list of command listeners * @return this */ public Builder commandListenerList(final List commandListeners) { notNull("commandListeners", commandListeners); this.commandListeners = new ArrayList(commandListeners); return this; } /** * Sets the logical name of the application using this MongoClient. The application name may be used by the client to identify * the application to the server, for use in server logs, slow query logs, and profile collection. * * @param applicationName the logical name of the application using this MongoClient. It may be null. * The UTF-8 encoding may not exceed 128 bytes. * @return this * @see #getApplicationName() * @mongodb.server.release 3.4 */ public Builder applicationName(@Nullable final String applicationName) { if (applicationName != null) { isTrueArgument("applicationName UTF-8 encoding length <= 128", applicationName.getBytes(Charset.forName("UTF-8")).length <= 128); } this.applicationName = applicationName; return this; } /** * Sets the compressors to use for compressing messages to the server. The driver will use the first compressor in the list * that the server is configured to support. * * @param compressorList the list of compressors to request * @return this * @see #getCompressorList() * @mongodb.server.release 3.4 */ public Builder compressorList(final List compressorList) { notNull("compressorList", compressorList); this.compressorList = new ArrayList(compressorList); return this; } /** * Build an instance of {@code MongoClientSettings}. * * @return the settings from this builder */ public MongoClientSettings build() { return new MongoClientSettings(this); } } /** * The read preference to use for queries, map-reduce, aggregation, and count. * *

Default is {@code ReadPreference.primary()}.

* * @return the read preference * @see ReadPreference#primary() */ public ReadPreference getReadPreference() { return readPreference; } /** * Gets the credential. * * @return the credential, which may be null */ @Nullable public MongoCredential getCredential() { return credential; } /** * The write concern to use. * *

Default is {@code WriteConcern.ACKNOWLEDGED}.

* * @return the write concern * @see WriteConcern#ACKNOWLEDGED */ public WriteConcern getWriteConcern() { return writeConcern; } /** * Returns true if writes should be retried if they fail due to a network error. The default is false. * * @return the retryWrites value * @mongodb.server.release 3.6 */ public boolean getRetryWrites() { return retryWrites; } /** * The read concern to use. * * @return the read concern * @mongodb.server.release 3.2 * @mongodb.driver.manual reference/readConcern/ Read Concern */ public ReadConcern getReadConcern() { return readConcern; } /** * The codec registry to use, or null if not set. * * @return the codec registry */ public CodecRegistry getCodecRegistry() { return codecRegistry; } /** * Gets the factory to use to create a {@code StreamFactory}. * * @return the stream factory factory */ @Nullable public StreamFactoryFactory getStreamFactoryFactory() { return streamFactoryFactory; } /** * Gets the list of added {@code CommandListener}. * *

The default is an empty list.

* * @return the unmodifiable list of command listeners */ public List getCommandListeners() { return Collections.unmodifiableList(commandListeners); } /** * Gets the logical name of the application using this MongoClient. The application name may be used by the client to identify * the application to the server, for use in server logs, slow query logs, and profile collection. * *

Default is null.

* * @return the application name, which may be null * @mongodb.server.release 3.4 */ @Nullable public String getApplicationName() { return applicationName; } /** * Gets the compressors to use for compressing messages to the server. The driver will use the first compressor in the list * that the server is configured to support. * *

Default is the empty list.

* * @return the compressors * @mongodb.server.release 3.4 */ public List getCompressorList() { return Collections.unmodifiableList(compressorList); } /** * Gets the cluster settings. * * @return the cluster settings */ public ClusterSettings getClusterSettings() { return clusterSettings; } /** * Gets the SSL settings. * * @return the SSL settings */ public SslSettings getSslSettings() { return sslSettings; } /** * Gets the connection-specific settings wrapped in a settings object. This settings object uses the values for connectTimeout, * socketTimeout and socketKeepAlive. * * @return a SocketSettings object populated with the connection settings from this {@code MongoClientSettings} instance. * @see SocketSettings */ public SocketSettings getSocketSettings() { return socketSettings; } /** * Gets the connection settings for the heartbeat thread (the background task that checks the state of the cluster) wrapped in a * settings object. * * @return the SocketSettings for the heartbeat thread * @see SocketSettings */ public SocketSettings getHeartbeatSocketSettings() { return heartbeatSocketSettings; } /** * Gets the settings for the connection provider in a settings object. This settings object wraps the values for minConnectionPoolSize, * maxConnectionPoolSize, maxWaitTime, maxConnectionIdleTime and maxConnectionLifeTime, and uses maxConnectionPoolSize and * threadsAllowedToBlockForConnectionMultiplier to calculate maxWaitQueueSize. * * @return a ConnectionPoolSettings populated with the settings from this {@code MongoClientSettings} instance that relate to the * connection provider. * @see ConnectionPoolSettings */ public ConnectionPoolSettings getConnectionPoolSettings() { return connectionPoolSettings; } /** * Gets the server-specific settings wrapped in a settings object. This settings object uses the heartbeatFrequency and * minHeartbeatFrequency values from this {@code MongoClientSettings} instance. * * @return a ServerSettings * @see ServerSettings */ public ServerSettings getServerSettings() { return serverSettings; } private MongoClientSettings(final Builder builder) { readPreference = builder.readPreference; writeConcern = builder.writeConcern; retryWrites = builder.retryWrites; readConcern = builder.readConcern; credential = builder.credential; streamFactoryFactory = builder.streamFactoryFactory; codecRegistry = builder.codecRegistry; commandListeners = builder.commandListeners; applicationName = builder.applicationName; clusterSettings = builder.clusterSettingsBuilder.build(); serverSettings = builder.serverSettingsBuilder.build(); socketSettings = builder.socketSettingsBuilder.build(); connectionPoolSettings = builder.connectionPoolSettingsBuilder.build(); sslSettings = builder.sslSettingsBuilder.build(); compressorList = builder.compressorList; SocketSettings.Builder heartbeatSocketSettingsBuilder = SocketSettings.builder() .readTimeout(socketSettings.getConnectTimeout(MILLISECONDS), MILLISECONDS) .connectTimeout(socketSettings.getConnectTimeout(MILLISECONDS), MILLISECONDS); heartbeatSocketSettings = heartbeatSocketSettingsBuilder.build(); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy