com.mongodb.ReadConcern Java Examples

The following examples show how to use com.mongodb.ReadConcern. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ParsingReadConcernLevelTest.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Parameters(method = "validReadConcernValues")
@Test
public void should_parse_read_concern_from_connection_string(String readConcernString, ReadConcern expectedReadConcern) throws Exception {
  // given
  final JsonObject configWithConnectionString = new JsonObject().put(
    "connection_string",
    String.format("mongodb://localhost:27017/mydb?replicaSet=myRs&readconcernlevel=%s", readConcernString)
  );

  // when
  final ReadConcern parsedReadConcern = new MongoClientOptionsParser(vertx, configWithConnectionString)
    .settings()
    .getReadConcern();

  // then
  assertEquals(expectedReadConcern, parsedReadConcern);
}
 
Example #2
Source File: ParsingReadConcernLevelTest.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Parameters(method = "validReadConcernValues")
@Test
public void should_fallback_to_config_property_if_read_concern_not_present_in_connection_string(String readConcernString, ReadConcern expectedReadConcern) throws Exception {
  // given
  final JsonObject configWithReadConcernAsSeparateProperty = new JsonObject()
    .put("connection_string", "mongodb://localhost:27017/mydb?replicaSet=myRs")
    .put("readConcernLevel", readConcernString);

  // when
  final ReadConcern parsedReadConcern = new MongoClientOptionsParser(vertx, configWithReadConcernAsSeparateProperty)
    .settings()
    .getReadConcern();

  // then
  assertEquals(expectedReadConcern, parsedReadConcern);
}
 
Example #3
Source File: ParsingReadConcernLevelTest.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Test
public void should_return_default_read_concern_in_case_of_missing_read_concern_in_connection_string_or_config_object() throws Exception {
  // given
  final JsonObject configWithConnectionString = new JsonObject().put(
    "connection_string",
    "mongodb://localhost:27017/mydb?replicaSet=myRs"
  );

  // when
  final ReadConcern parsedReadConcern = new MongoClientOptionsParser(vertx, configWithConnectionString)
    .settings()
    .getReadConcern();

  // then
  assertEquals(ReadConcern.DEFAULT, parsedReadConcern);
}
 
Example #4
Source File: DefaultDataSourceCreater.java    From tangyuan2 with GNU General Public License v3.0 5 votes vote down vote up
private ReadConcern getReadConcern(String readConcern) {
	if ("LOCAL".equalsIgnoreCase(readConcern)) {
		return ReadConcern.LOCAL;
	}
	if ("MAJORITY".equalsIgnoreCase(readConcern)) {
		return ReadConcern.MAJORITY;
	}
	return ReadConcern.DEFAULT;
}
 
Example #5
Source File: ParsingReadConcernLevelTest.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Test
public void should_prefer_read_concern_passed_via_connection_string_over_property_value() throws Exception {
  // given
  final JsonObject configWithReadConcernPassedTwice = new JsonObject()
    .put("connection_string", "mongodb://localhost:27017/mydb?replicaSet=myRs&readconcernlevel=majority")
    .put("readConcernLevel", "linearizable");

  // when
  final ReadConcern parsedReadConcern = new MongoClientOptionsParser(vertx, configWithReadConcernPassedTwice)
    .settings()
    .getReadConcern();

  // then
  assertEquals(ReadConcern.MAJORITY, parsedReadConcern);
}
 
Example #6
Source File: ParsingReadConcernLevelTest.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
private Object[] validReadConcernValues() {
  return new Object[]{
    new Object[]{"local", ReadConcern.LOCAL},
    new Object[]{"majority", ReadConcern.MAJORITY},
    new Object[]{"linearizable", ReadConcern.LINEARIZABLE}
  };
}
 
Example #7
Source File: AggregationTest.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Test
public void testPlanCacheStats() {
    checkMinServerVersion(4.2);
    List<Document> list = List.of(
        parse("{ '_id' : 1, 'item' : 'abc', 'price' : NumberDecimal('12'), 'quantity' : 2, 'type': 'apparel' }"),
        parse("{ '_id' : 2, 'item' : 'jkl', 'price' : NumberDecimal('20'), 'quantity' : 1, 'type': 'electronics' }"),
        parse("{ '_id' : 3, 'item' : 'abc', 'price' : NumberDecimal('10'), 'quantity' : 5, 'type': 'apparel' }"),
        parse("{ '_id' : 4, 'item' : 'abc', 'price' : NumberDecimal('8'), 'quantity' : 10, 'type': 'apparel' }"),
        parse("{ '_id' : 5, 'item' : 'jkl', 'price' : NumberDecimal('15'), 'quantity' : 15, 'type': 'electronics' }"));

    MongoCollection<Document> orders = getDatabase().getCollection("orders");
    orders.insertMany(list);

    Assert.assertNotNull(orders.createIndex(new Document("item", 1)));
    Assert.assertNotNull(orders.createIndex(new Document("item", 1)
                                                .append("quantity", 1)));
    Assert.assertNotNull(orders.createIndex(new Document("item", 1)
                                                .append("price", 1),
        new IndexOptions()
            .partialFilterExpression(new Document("price", new Document("$gte", 10)))));
    Assert.assertNotNull(orders.createIndex(new Document("quantity", 1)));
    Assert.assertNotNull(orders.createIndex(new Document("quantity", 1)
                                                .append("type", 1)));

    orders.find(parse(" { item: 'abc', price: { $gte: NumberDecimal('10') } }"));
    orders.find(parse(" { item: 'abc', price: { $gte: NumberDecimal('5') } }"));
    orders.find(parse(" { quantity: { $gte: 20 } } "));
    orders.find(parse(" { quantity: { $gte: 5 }, type: 'apparel' } "));

    List<Document> stats = getDs().aggregate(Order.class)
                                  .planCacheStats()
                                  .execute(Document.class, new AggregationOptions()
                                                               .readConcern(ReadConcern.LOCAL))
                                  .toList();

    Assert.assertNotNull(stats);
}
 
Example #8
Source File: MongoDB.java    From aion with MIT License 5 votes vote down vote up
@Override
public boolean open() {
    if (isOpen()) {
        return true;
    }

    LOG.info("Initializing MongoDB at {}", mongoClientUri);

    // Get the client and create a session for this instance
    MongoClient mongoClient =
            MongoConnectionManager.inst().getMongoClientInstance(this.mongoClientUri);
    ClientSessionOptions sessionOptions =
            ClientSessionOptions.builder()
                    .causallyConsistent(true)
                    .defaultTransactionOptions(
                            TransactionOptions.builder()
                                    .readConcern(ReadConcern.DEFAULT)
                                    .writeConcern(WriteConcern.MAJORITY)
                                    .readPreference(ReadPreference.nearest())
                                    .build())
                    .build();
    this.clientSession = mongoClient.startSession(sessionOptions);

    // Get the database and our collection. Mongo takes care of creating these if they don't
    // exist
    MongoDatabase mongoDb = mongoClient.getDatabase(MongoConstants.AION_DB_NAME);

    // Gets the collection where we will be saving our values. Mongo creates it if it doesn't
    // yet exist
    this.collection = mongoDb.getCollection(this.name, BsonDocument.class);

    LOG.info("Finished opening the Mongo connection");
    return isOpen();
}
 
Example #9
Source File: AggregationOptions.java    From morphia with Apache License 2.0 4 votes vote down vote up
/**
 * @return the configuration value
 */
public ReadConcern getReadConcern() {
    return readConcern;
}
 
Example #10
Source File: FindOptions.java    From morphia with Apache License 2.0 4 votes vote down vote up
@Override
public ReadConcern getReadConcern() {
    return readConcern;
}
 
Example #11
Source File: AggregationOptions.java    From morphia with Apache License 2.0 4 votes vote down vote up
/**
 * @return the configuration value
 */
public ReadConcern readConcern() {
    return readConcern;
}
 
Example #12
Source File: OptionsTest.java    From morphia with Apache License 2.0 4 votes vote down vote up
@Test
public void aggregationOptions() {
    scan(com.mongodb.AggregationOptions.class, AggregationOptions.class, false, List.of(ReadConcern.class, ReadPreference.class,
        WriteConcern.class));
}
 
Example #13
Source File: OptionsTest.java    From morphia with Apache License 2.0 4 votes vote down vote up
@Test
public void countOptions() {
    scan(com.mongodb.client.model.CountOptions.class, CountOptions.class, true, List.of(ReadConcern.class, ReadPreference.class));
}
 
Example #14
Source File: ReadConcernLevelParser.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
private Optional<ReadConcern> tryToParseFromConfig() {
  return Optional.ofNullable(config)
    .flatMap(cfg -> Optional.ofNullable(cfg.getString("readConcernLevel")))
    .map(ReadConcernLevel::fromString)
    .map(ReadConcern::new);
}
 
Example #15
Source File: ReadConcernLevelParser.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
private Optional<ReadConcern> tryToParseFromConnectionString() {
  return Optional.ofNullable(connectionString)
    .flatMap(cs -> Optional.ofNullable(cs.getReadConcern()));
}
 
Example #16
Source File: ReadConcernLevelParser.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
private Optional<ReadConcern> lift(ReadConcern readConcern) {
  return Optional.ofNullable(readConcern);
}
 
Example #17
Source File: ReadConcernLevelParser.java    From vertx-mongo-client with Apache License 2.0 4 votes vote down vote up
Optional<ReadConcern> readConcern() {
  return tryToParseFromConnectionString().map(this::lift).orElseGet(this::tryToParseFromConfig);
}
 
Example #18
Source File: GridFSBucketImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 4 votes vote down vote up
@Override
public GridFSBucket withReadConcern(final ReadConcern readConcern) {
    return new GridFSBucketImpl(wrapped.withReadConcern(readConcern));
}
 
Example #19
Source File: GridFSBucketImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 4 votes vote down vote up
@Override
public ReadConcern getReadConcern() {
    return wrapped.getReadConcern();
}
 
Example #20
Source File: MongoDatabaseImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 4 votes vote down vote up
@Override
public MongoDatabase withReadConcern(final ReadConcern readConcern) {
    return new MongoDatabaseImpl(wrapped.withReadConcern(readConcern));
}
 
Example #21
Source File: MongoDatabaseImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 4 votes vote down vote up
@Override
public ReadConcern getReadConcern() {
    return wrapped.getReadConcern();
}
 
Example #22
Source File: MongoCollectionImpl.java    From mongo-java-driver-reactivestreams with Apache License 2.0 4 votes vote down vote up
@Override
public ReadConcern getReadConcern() {
    return wrapped.getReadConcern();
}
 
Example #23
Source File: MongoCollectionImpl.java    From mongo-java-driver-rx with Apache License 2.0 4 votes vote down vote up
@Override
public ReadConcern getReadConcern() {
    return wrapped.getReadConcern();
}
 
Example #24
Source File: MongoCollectionImpl.java    From mongo-java-driver-rx with Apache License 2.0 4 votes vote down vote up
@Override
public MongoCollection<TDocument> withReadConcern(final ReadConcern readConcern) {
    return new MongoCollectionImpl<TDocument>(wrapped.withReadConcern(readConcern), observableAdapter);
}
 
Example #25
Source File: MongoDatabaseImpl.java    From mongo-java-driver-rx with Apache License 2.0 4 votes vote down vote up
@Override
public ReadConcern getReadConcern() {
    return wrapped.getReadConcern();
}
 
Example #26
Source File: MongoDatabaseImpl.java    From mongo-java-driver-rx with Apache License 2.0 4 votes vote down vote up
@Override
public MongoDatabase withReadConcern(final ReadConcern readConcern) {
    return new MongoDatabaseImpl(wrapped.withReadConcern(readConcern), observableAdapter);
}
 
Example #27
Source File: GridFSBucketImpl.java    From mongo-java-driver-rx with Apache License 2.0 4 votes vote down vote up
@Override
public ReadConcern getReadConcern() {
    return wrapped.getReadConcern();
}
 
Example #28
Source File: GridFSBucketImpl.java    From mongo-java-driver-rx with Apache License 2.0 4 votes vote down vote up
@Override
public GridFSBucket withReadConcern(final ReadConcern readConcern) {
    return new GridFSBucketImpl(wrapped.withReadConcern(readConcern), observableAdapter);
}
 
Example #29
Source File: MongoDBContainerTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
/**
 * Taken from <a href="https://docs.mongodb.com/manual/core/transactions/">https://docs.mongodb.com</a>
 */
@Test
public void shouldExecuteTransactions() {
    try (
        // creatingMongoDBContainer {
        final MongoDBContainer mongoDBContainer = new MongoDBContainer()
        // }
    ) {

        // startingMongoDBContainer {
        mongoDBContainer.start();
        // }

        final String mongoRsUrl = mongoDBContainer.getReplicaSetUrl();
        assertNotNull(mongoRsUrl);
        final MongoClient mongoSyncClient = MongoClients.create(mongoRsUrl);
        mongoSyncClient.getDatabase("mydb1").getCollection("foo")
            .withWriteConcern(WriteConcern.MAJORITY).insertOne(new Document("abc", 0));
        mongoSyncClient.getDatabase("mydb2").getCollection("bar")
            .withWriteConcern(WriteConcern.MAJORITY).insertOne(new Document("xyz", 0));

        final ClientSession clientSession = mongoSyncClient.startSession();
        final TransactionOptions txnOptions = TransactionOptions.builder()
            .readPreference(ReadPreference.primary())
            .readConcern(ReadConcern.LOCAL)
            .writeConcern(WriteConcern.MAJORITY)
            .build();

        final String trxResult = "Inserted into collections in different databases";

        TransactionBody<String> txnBody = () -> {
            final MongoCollection<Document> coll1 =
                mongoSyncClient.getDatabase("mydb1").getCollection("foo");
            final MongoCollection<Document> coll2 =
                mongoSyncClient.getDatabase("mydb2").getCollection("bar");

            coll1.insertOne(clientSession, new Document("abc", 1));
            coll2.insertOne(clientSession, new Document("xyz", 999));
            return trxResult;
        };

        try {
            final String trxResultActual = clientSession.withTransaction(txnBody, txnOptions);
            assertEquals(trxResult, trxResultActual);
        } catch (RuntimeException re) {
            throw new IllegalStateException(re.getMessage(), re);
        } finally {
            clientSession.close();
            mongoSyncClient.close();
        }
    }
}
 
Example #30
Source File: MongoDBOperationExecutorInterceptorTest.java    From skywalking with Apache License 2.0 4 votes vote down vote up
private Method getMethod() throws Exception {
    return OperationExecutor.class.getMethod("execute", WriteOperation.class, ReadConcern.class);
}