Example usage for com.mongodb Mongo setWriteConcern

List of usage examples for com.mongodb Mongo setWriteConcern

Introduction

In this page you can find the example usage for com.mongodb Mongo setWriteConcern.

Prototype

@Deprecated
public void setWriteConcern(final WriteConcern writeConcern) 

Source Link

Document

Sets the default write concern to use for write operations executed on any DBCollection created indirectly from this instance, via a DB instance created from #getDB(String) .

Usage

From source file:com.malsolo.mongodb.humongous.config.Application.java

@Bean
public Mongo mongo() throws Exception {
    Mongo mongo = new MongoClient();
    mongo.setWriteConcern(WriteConcern.SAFE);
    return mongo;
}

From source file:com.oreilly.springdata.mongodb.ApplicationConfig.java

License:Apache License

@Override
public Mongo mongo() throws Exception {

    Mongo mongo = new Mongo();
    mongo.setWriteConcern(WriteConcern.SAFE);

    return mongo;
}

From source file:com.tomtom.speedtools.tracer.mongo.MongoDBTraceHandler.java

License:Apache License

@Nonnull
static DBCollection getDBCollection(@Nonnull final String servers, @Nonnull final String database,
        @Nonnull final String userName, @Nonnull final String password, final int sizeMB,
        final int connectTimeoutMsecs) throws UnknownHostException {
    assert servers != null;
    assert database != null;
    assert userName != null;
    assert password != null;
    assert connectTimeoutMsecs >= 0;

    LOG.info("getDBCollection: Creating MongoDB connection for traces: {}", servers);
    final Mongo mongo = MongoConnectionCache.getMongoDB(servers, connectTimeoutMsecs, userName, database,
            password);/*from   w  ww  .j  av  a 2 s . c  om*/

    // If this is a replica set, set read preference to secondary for traces.
    final List<ServerAddress> serverAddressList = mongo.getServerAddressList();
    if (serverAddressList.size() > 1) {
        mongo.setReadPreference(ReadPreference.secondary());
    }

    // Should writes fail, then don't throw exceptions, just ignore.
    // We care more about not disturbing the primary system then our own (traces) integrity.
    mongo.setWriteConcern(WriteConcern.UNACKNOWLEDGED);

    // The connection point may actually be null... Not an error.
    final String connectPoint = mongo.getConnectPoint();
    LOG.info("getDBCollection: MongoDB connection for traces established: '{}' at {}", database, connectPoint);

    final DB db = mongo.getDB(database);
    final DBObject options = new BasicDBObject();
    options.put("capped", true);
    options.put("size", sizeMB * MEGABYTE);

    final DBCollection collection;
    if (!db.getCollectionNames().contains(Constants.COLLECTION_NAME)) {
        collection = db.createCollection(Constants.COLLECTION_NAME, options);
    } else {
        collection = db.getCollection(Constants.COLLECTION_NAME);
    }

    return collection;
}

From source file:net.bunselmeyer.mongo.maven.plugin.MigrateMojo.java

License:Apache License

private void runMigrations(List<MigrationDetails> migrations) {
    if (migrations.isEmpty()) {
        return;//from w  w  w  . java 2s  . co  m
    }

    MigrationDetails migrationDetails = migrations.get(0);

    Mongo mongo;
    try {
        mongo = new Mongo(migrationDetails.host, Integer.parseInt(port));
    } catch (UnknownHostException e) {
        getLog().error("Failed to connect to " + migrationDetails.host + ":" + port);
        return;
    } catch (NumberFormatException e) {
        getLog().error("Invalid port: " + port);
        return;
    }

    mongo.setWriteConcern(WriteConcern.SAFE);

    DB db = mongo.getDB(migrationDetails.db);

    JacksonDBCollection<MigrationVersionDetails, ObjectId> migrationVersionCollection = createMigrationVersionCollection(
            db);

    getLog().info("Running migrations. Host: " + migrationDetails.host + ". DB: " + migrationDetails.db);

    sortMigrationDetails(migrations);

    Class<? extends Migration> lastMigration = null;
    try {
        for (MigrationDetails details : migrations) {
            lastMigration = details.migration;
            Migration m = details.migration.newInstance();

            MigrationVersionDetails versionDetails = new MigrationVersionDetails();
            versionDetails.setMigrationName(details.migration.getName());
            versionDetails.setVersion(details.version);

            if (migrationVersionCollection.getCount(versionDetails) == 0) {
                m.up(db);
                db.getLastError().throwOnError();
                getLog().info(
                        "    " + details.migration.getName() + ", v" + details.version + " migration complete");
                versionDetails.setRun(DateTime.now(DateTimeZone.UTC));
                migrationVersionCollection.insert(versionDetails);
            } else {
                getLog().info(
                        "    " + details.migration.getName() + ", v" + details.version + " was already run");
            }
        }
    } catch (Exception e) {
        String name = lastMigration != null ? lastMigration.getName() : "";
        getLog().info("    FAIL! " + name + " migration error", e);
    } finally {
        mongo.close();
    }
}

From source file:org.atlasapi.AtlasModule.java

License:Apache License

public @Bean Mongo mongo() {
    Mongo mongo = new Mongo(mongoHosts());
    mongo.setReadPreference(readPreference());
    if (isProcessing() && processingWriteConcern != null
            && !Strings.isNullOrEmpty(processingWriteConcern.get())) {

        WriteConcern writeConcern = WriteConcern.valueOf(processingWriteConcern.get());
        if (writeConcern == null) {
            throw new IllegalArgumentException(
                    "Could not parse write concern: " + processingWriteConcern.get());
        }//from   w  w w  .  j  a  v a  2 s .  c o  m
        mongo.setWriteConcern(writeConcern);
    }
    return mongo;
}

From source file:org.axonframework.eventsourcing.eventstore.mongo.MongoFactory.java

License:Apache License

/**
 * Creates a mongo instance based on the provided configuration. Read javadoc of the class to learn about the
 * configuration options. A new Mongo instance is created each time this method is called.
 *
 * @return a new Mongo instance each time this method is called.
 *///from   w w w .  j  a  va2  s .  c o  m
public Mongo createMongo() {
    Mongo mongo;
    if (mongoAddresses.isEmpty()) {
        try {
            mongo = new Mongo(new ServerAddress(), mongoOptions);
        } catch (UnknownHostException e) {
            throw new IllegalStateException(
                    String.format("No addresses were provided, but could not find IP for default host: %s",
                            ServerAddress.defaultHost()),
                    e);
        }
    } else {
        mongo = new Mongo(mongoAddresses, mongoOptions);
    }
    mongo.setWriteConcern(defaultWriteConcern());

    return mongo;
}

From source file:org.elasticsearch.river.mongodb.RiverMongoDBTestAbstract.java

License:Apache License

private void initMongoInstances(ExecutableType type) throws Exception {
    logger.debug("*** initMongoInstances(" + type + ") ***");
    CommandResult cr;/*  ww w  .j  a  v a 2 s  . c o  m*/
    Settings rsSettings = settings.getByPrefix(type.configKey + '.');
    int[] ports;
    if (rsSettings.getAsBoolean("useDynamicPorts", false)) {
        ports = new int[] { Network.getFreeServerPort(), Network.getFreeServerPort(),
                Network.getFreeServerPort() };
    } else {
        int start = 37017 + 10 * type.ordinal();
        ports = new int[] { start, start + 1, start + 2 };
    }
    String replicaSetName = "es-test-" + type.configKey;
    // Create 3 mongod processes
    Starter<IMongodConfig, MongodExecutable, MongodProcess> starter = type.newStarter();
    ImmutableList.Builder<MongoReplicaSet.Member> builder = ImmutableList.builder();
    for (int i = 1; i <= 3; ++i) {
        Storage storage = new Storage("target/" + replicaSetName + '/' + i, replicaSetName, 20);
        MongoReplicaSet.Member member = new MongoReplicaSet.Member();
        member.config = new MongodConfigBuilder()
                .version(Versions.withFeatures(new GenericVersion(rsSettings.get("version"))))
                .net(new de.flapdoodle.embed.mongo.config.Net(ports[i - 1], Network.localhostIsIPv6()))
                .replication(storage).build();
        logger.trace("replSetName in config: {}", member.config.replication().getReplSetName());
        member.executable = starter.prepare(member.config);
        member.process = member.executable.start();
        member.address = new ServerAddress(Network.getLocalHost().getHostName(), member.config.net().getPort());
        logger.debug("Server #" + i + ": {}", member.address);
        builder.add(member);
    }
    ImmutableList<MongoReplicaSet.Member> members = builder.build();
    Thread.sleep(2000);
    MongoClientOptions mco = MongoClientOptions.builder().autoConnectRetry(true).connectTimeout(15000)
            .socketTimeout(60000).build();
    Mongo mongo = new MongoClient(new ServerAddress(Network.getLocalHost().getHostName(), ports[0]), mco);
    DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME);

    cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1));
    logger.debug("isMaster: " + cr);

    // Initialize replica set
    cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate",
            (DBObject) JSON.parse("{'_id': '" + replicaSetName + "', 'members': [" + "{'_id': 0, 'host': '"
                    + members.get(0).address.getHost() + ':' + members.get(0).address.getPort() + "'}, "
                    + "{'_id': 1, 'host': '" + members.get(1).address.getHost() + ':'
                    + members.get(1).address.getPort() + "'}, " + "{'_id': 2, 'host': '"
                    + members.get(2).address.getHost() + ':' + members.get(2).address.getPort()
                    + "', 'arbiterOnly' : true}]} }")));
    logger.debug("replSetInitiate result: " + cr);

    Thread.sleep(5000);
    cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
    logger.trace("replSetGetStatus result: {}", cr);

    // Check replica set status before to proceed
    while (!isReplicaSetStarted(cr)) {
        logger.debug("Waiting 3 seconds for replicaset to change status...");
        Thread.sleep(3000);
        cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
        // logger.debug("replSetGetStatus: " + cr);
    }

    mongo.close();
    mongo = null;

    // Initialize a new client using all instances.
    List<ServerAddress> mongoServers = new ArrayList<ServerAddress>();
    for (MongoReplicaSet.Member member : members) {
        mongoServers.add(member.address);
    }
    mongo = new MongoClient(mongoServers, mco);
    Assert.assertNotNull(mongo);
    mongo.setReadPreference(ReadPreference.secondaryPreferred());
    mongo.setWriteConcern(WriteConcern.REPLICAS_SAFE);
    replicaSets.put(type, new MongoReplicaSet(type, rsSettings.get("version"), mongo, mongoAdminDB, members));
}

From source file:org.jmingo.mongo.MongoDBFactory.java

License:Apache License

private Mongo create(MongoConfig config) {
    Mongo mongo;
    try {/*from ww  w  . jav  a  2s  .  c  o  m*/
        MongoClientOptions options = createOptions(config);
        mongo = new MongoClient(new ServerAddress(config.getDatabaseHost(), config.getDatabasePort()), options);
        WriteConcern writeConcern = WriteConcern.valueOf(config.getWriteConcern());
        mongo.setWriteConcern(writeConcern);
        LOGGER.debug("set '{}' write concern", writeConcern);
    } catch (UnknownHostException e) {
        throw new MongoConfigurationException(e);
    }
    return mongo;
}

From source file:org.springframework.data.mongodb.core.MongoFactoryBean.java

License:Apache License

@Override
protected Mongo createInstance() throws Exception {

    Mongo mongo;
    ServerAddress defaultOptions = new ServerAddress();

    if (mongoOptions == null) {
        mongoOptions = new MongoOptions();
    }/*from  w w w.  j  a  v  a2 s  .c  om*/

    if (!isNullOrEmpty(replicaPair)) {
        if (replicaPair.size() < 2) {
            throw new CannotGetMongoDbConnectionException("A replica pair must have two server entries");
        }
        mongo = new Mongo(replicaPair.get(0), replicaPair.get(1), mongoOptions);
    } else if (!isNullOrEmpty(replicaSetSeeds)) {
        mongo = new Mongo(replicaSetSeeds, mongoOptions);
    } else {
        String mongoHost = StringUtils.hasText(host) ? host : defaultOptions.getHost();
        mongo = port != null ? new Mongo(new ServerAddress(mongoHost, port), mongoOptions)
                : new Mongo(mongoHost, mongoOptions);
    }

    if (writeConcern != null) {
        mongo.setWriteConcern(writeConcern);
    }

    return mongo;
}

From source file:org.yla.demo.thymeleaf.core.config.db.MongoDBConfig.java

License:Apache License

@Bean
@Override/*from  w  ww.  j a v a2s.co  m*/
public Mongo mongo() throws Exception {

    Mongo mongo = new MongoClient("127.0.0.1", 27017);
    mongo.setWriteConcern(WriteConcern.SAFE);

    return mongo;
}