use of com.mongodb.WriteConcern in project mongo-java-driver by mongodb.
the class AbstractUnifiedTest method setUp.
@Before
public void setUp() {
assumeFalse(skipTest);
assumeTrue("Skipping test: " + definition.getString("skipReason", new BsonString("")).getValue(), !definition.containsKey("skipReason"));
assumeFalse("Skipping test of count", filename.equals("count.json"));
collectionHelper = new CollectionHelper<Document>(new DocumentCodec(), new MongoNamespace(databaseName, collectionName));
collectionHelper.killAllSessions();
if (!isDataLakeTest()) {
collectionHelper.create(collectionName, new CreateCollectionOptions(), WriteConcern.MAJORITY);
}
if (!data.isEmpty()) {
List<BsonDocument> documents = new ArrayList<BsonDocument>();
for (BsonValue document : data) {
documents.add(document.asDocument());
}
collectionHelper.insertDocuments(documents, WriteConcern.MAJORITY);
}
if (definition.containsKey("failPoint")) {
collectionHelper.runAdminCommand(definition.getDocument("failPoint"));
}
final BsonDocument clientOptions = definition.getDocument("clientOptions", new BsonDocument());
connectionString = getConnectionString();
useMultipleMongoses = definition.getBoolean("useMultipleMongoses", BsonBoolean.FALSE).getValue();
if (useMultipleMongoses) {
assumeTrue(isSharded());
connectionString = getMultiMongosConnectionString();
assumeTrue("The system property org.mongodb.test.transaction.uri is not set.", connectionString != null);
}
MongoClientSettings.Builder builder = getMongoClientSettingsBuilder().applyConnectionString(connectionString).addCommandListener(commandListener).applyToClusterSettings(clusterSettingsBuilder -> {
if (clientOptions.containsKey("serverSelectionTimeoutMS")) {
clusterSettingsBuilder.serverSelectionTimeout(clientOptions.getNumber("serverSelectionTimeoutMS").longValue(), MILLISECONDS);
}
if (clientOptions.containsKey("directConnection")) {
setDirectConnection(clusterSettingsBuilder);
}
}).applyToSocketSettings(new Block<SocketSettings.Builder>() {
@Override
public void apply(final SocketSettings.Builder builder) {
builder.readTimeout(clientOptions.getInt32("socketTimeoutMS", new BsonInt32(toIntExact(SECONDS.toMillis(5)))).getValue(), MILLISECONDS);
if (clientOptions.containsKey("connectTimeoutMS")) {
builder.connectTimeout(clientOptions.getNumber("connectTimeoutMS").intValue(), MILLISECONDS);
}
}
}).writeConcern(getWriteConcern(clientOptions)).readConcern(getReadConcern(clientOptions)).readPreference(getReadPreference(clientOptions)).retryWrites(clientOptions.getBoolean("retryWrites", BsonBoolean.FALSE).getValue()).retryReads(false).applyToConnectionPoolSettings(poolSettingsBuilder -> {
poolSettingsBuilder.addConnectionPoolListener(connectionPoolListener);
if (clientOptions.containsKey("minPoolSize")) {
poolSettingsBuilder.minSize(clientOptions.getInt32("minPoolSize").getValue());
}
}).applyToServerSettings(new Block<ServerSettings.Builder>() {
@Override
public void apply(final ServerSettings.Builder builder) {
builder.heartbeatFrequency(50, MILLISECONDS);
builder.minHeartbeatFrequency(MIN_HEARTBEAT_FREQUENCY_MS, MILLISECONDS);
builder.addServerListener(serverListener);
}
});
if (clientOptions.containsKey("heartbeatFrequencyMS")) {
builder.applyToServerSettings(new Block<ServerSettings.Builder>() {
@Override
public void apply(final ServerSettings.Builder builder) {
builder.heartbeatFrequency(clientOptions.getInt32("heartbeatFrequencyMS").intValue(), MILLISECONDS);
}
});
}
if (clientOptions.containsKey("appname")) {
builder.applicationName(clientOptions.getString("appname").getValue());
}
if (clientOptions.containsKey("w")) {
if (clientOptions.isString("w")) {
builder.writeConcern(new WriteConcern(clientOptions.getString("w").getValue()));
} else if (clientOptions.isNumber("w")) {
builder.writeConcern(new WriteConcern(clientOptions.getNumber("w").intValue()));
}
}
StreamFactoryFactory streamFactoryFactory = getStreamFactoryFactory();
if (streamFactoryFactory != null) {
builder.streamFactoryFactory(streamFactoryFactory);
}
mongoClient = createMongoClient(builder.build());
database = mongoClient.getDatabase(databaseName);
if (useMultipleMongoses) {
// non-transactional distinct operation to avoid StaleDbVersion error
runDistinctOnEachNode();
}
helper = new JsonPoweredCrudTestHelper(description, database, database.getCollection(collectionName, BsonDocument.class), null, mongoClient);
sessionsMap = new HashMap<>();
lsidMap = new HashMap<>();
if (createSessions && serverVersionAtLeast(3, 6)) {
ClientSession sessionZero = createSession("session0");
ClientSession sessionOne = createSession("session1");
sessionsMap.put("session0", sessionZero);
sessionsMap.put("session1", sessionOne);
lsidMap.put("session0", sessionZero.getServerSession().getIdentifier());
lsidMap.put("session1", sessionOne.getServerSession().getIdentifier());
}
}
use of com.mongodb.WriteConcern 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;
}
use of com.mongodb.WriteConcern 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());
}
use of com.mongodb.WriteConcern 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();
}
use of com.mongodb.WriteConcern in project spring-data-mongodb by spring-projects.
the class MongoTemplate method saveDocument.
protected Object saveDocument(String collectionName, Document dbDoc, Class<?> entityClass) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("Saving Document containing fields: %s", dbDoc.keySet()));
}
return execute(collectionName, collection -> {
MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.SAVE, collectionName, entityClass, dbDoc, null);
WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
MappedDocument mapped = MappedDocument.of(dbDoc);
MongoCollection<Document> collectionToUse = //
writeConcernToUse == null ? //
collection : collection.withWriteConcern(writeConcernToUse);
if (!mapped.hasId()) {
collectionToUse.insertOne(dbDoc);
} else {
MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass);
UpdateContext updateContext = queryOperations.replaceSingleContext(mapped, true);
Document replacement = updateContext.getMappedUpdate(entity);
Document filter = updateContext.getMappedQuery(entity);
if (updateContext.requiresShardKey(filter, entity)) {
if (entity.getShardKey().isImmutable()) {
filter = updateContext.applyShardKey(entity, filter, null);
} else {
filter = updateContext.applyShardKey(entity, filter, collection.find(filter, Document.class).projection(updateContext.getMappedShardKey(entity)).first());
}
}
collectionToUse.replaceOne(filter, replacement, new ReplaceOptions().upsert(true));
}
return mapped.getId();
});
}
Aggregations