Example usage for com.mongodb WriteConcern REPLICAS_SAFE

List of usage examples for com.mongodb WriteConcern REPLICAS_SAFE

Introduction

In this page you can find the example usage for com.mongodb WriteConcern REPLICAS_SAFE.

Prototype

WriteConcern REPLICAS_SAFE

To view the source code for com.mongodb WriteConcern REPLICAS_SAFE.

Click Source Link

Document

Exceptions are raised for network issues, and server errors; waits for at least 2 servers for the write operation.

This field has been superseded by WriteConcern.REPLICA_ACKNOWLEDGED , and may be deprecated in a future release.

Usage

From source file:ch.agent.crnickl.mongodb.MongoDB.java

License:Apache License

private WriteConcern getWriteConcernFromKeyword(String keyword) throws T2DBException {
    WriteConcern wc = null;/*from   w w w .j av  a  2 s. c  om*/
    if (keyword == null)
        keyword = "SAFE";
    WriteConcernKeyword k = null;
    try {
        k = WriteConcernKeyword.valueOf(keyword);
    } catch (IllegalArgumentException e) {
        throw T2DBMMsg.exception(e, J.J81020, keyword);
    }
    switch (k) {
    case NONE:
        wc = WriteConcern.NONE;
        break;
    case NORMAL:
        wc = WriteConcern.NORMAL;
        break;
    case SAFE:
        wc = WriteConcern.SAFE;
        break;
    case MAJORITY:
        wc = WriteConcern.MAJORITY;
        break;
    case FSYNC_SAFE:
        wc = WriteConcern.FSYNC_SAFE;
        break;
    case JOURNAL_SAFE:
        wc = WriteConcern.JOURNAL_SAFE;
        break;
    case REPLICAS_SAFE:
        wc = WriteConcern.REPLICAS_SAFE;
        break;
    default:
        throw new RuntimeException("bug: " + k.name());
    }
    if (wc != WriteConcern.SAFE)
        throw T2DBMMsg.exception(J.J81021, keyword);
    return wc;
}

From source file:com.softwear.plugins.mongodb.MongoDBScriptObject.java

License:BSD License

public WriteConcern js_getMongoWriteConcern(String _type) {
    WriteConcern wc = WriteConcern.UNACKNOWLEDGED;
    if (_type.equals("none") || _type.equals("unacknowledge")) {
        wc = WriteConcern.UNACKNOWLEDGED;
    } else if (_type.equals("normal")) {
        wc = WriteConcern.NORMAL;//from   ww w.j  a va  2  s. c  o  m
    } else if (_type.equals("safe")) {
        wc = WriteConcern.SAFE;
    } else if (_type.equals("replicas_safe")) {
        wc = WriteConcern.REPLICAS_SAFE;
    } else if (_type.equals("fsync_safe")) {
        wc = WriteConcern.FSYNC_SAFE;
    }
    return wc;
}

From source file:eu.europeana.corelib.edm.utils.construct.FullBeanHandler.java

public void clearData(String collection) {
    DBCollection records = mongoServer.getDatastore().getDB().getCollection("record");
    DBCollection proxies = mongoServer.getDatastore().getDB().getCollection("Proxy");
    DBCollection physicalThing = mongoServer.getDatastore().getDB().getCollection("PhysicalThing");
    DBCollection providedCHOs = mongoServer.getDatastore().getDB().getCollection("ProvidedCHO");
    DBCollection aggregations = mongoServer.getDatastore().getDB().getCollection("Aggregation");
    DBCollection europeanaAggregations = mongoServer.getDatastore().getDB()
            .getCollection("EuropeanaAggregation");

    DBObject query = new BasicDBObject("about", Pattern.compile("^/" + collection + "/"));
    DBObject proxyQuery = new BasicDBObject("about", Pattern.compile("^/proxy/provider/" + collection + "/"));
    DBObject europeanaProxyQuery = new BasicDBObject("about",
            Pattern.compile("^/proxy/europeana/" + collection + "/"));

    DBObject providedCHOQuery = new BasicDBObject("about", Pattern.compile("^/item/" + collection + "/"));
    DBObject aggregationQuery = new BasicDBObject("about",
            Pattern.compile("^/aggregation/provider/" + collection + "/"));
    DBObject europeanaAggregationQuery = new BasicDBObject("about",
            Pattern.compile("^/aggregation/europeana/" + collection + "/"));
    europeanaAggregations.remove(europeanaAggregationQuery, WriteConcern.REPLICAS_SAFE);
    records.remove(query, WriteConcern.REPLICAS_SAFE);
    proxies.remove(europeanaProxyQuery, WriteConcern.REPLICAS_SAFE);
    proxies.remove(proxyQuery, WriteConcern.REPLICAS_SAFE);
    physicalThing.remove(proxyQuery, WriteConcern.REPLICAS_SAFE);
    physicalThing.remove(europeanaProxyQuery, WriteConcern.REPLICAS_SAFE);
    providedCHOs.remove(providedCHOQuery, WriteConcern.REPLICAS_SAFE);
    aggregations.remove(aggregationQuery, WriteConcern.REPLICAS_SAFE);
}

From source file:org.apache.tapestry5.mongodb.modules.MongodbModule.java

License:Apache License

/**
 * Contribute coercions for {@link WriteConcern} and {@link ReadPreference} to have them from
 * {@link org.apache.tapestry5.ioc.annotations.Symbol}
 *
 * @param configuration lets help the {@link org.apache.tapestry5.ioc.services.TypeCoercer} service
 *///from   w  w  w. j a va  2s.co m
public static void contributeTypeCoercer(Configuration<CoercionTuple> configuration) {
    configuration.add(new CoercionTuple(String.class, WriteConcern.class, new Coercion<String, WriteConcern>() {
        public WriteConcern coerce(String input) {
            if (input.equalsIgnoreCase("FSYNC_SAFE")) {
                return WriteConcern.FSYNC_SAFE;
            } else if (input.equalsIgnoreCase("JOURNAL_SAFE")) {
                return WriteConcern.JOURNAL_SAFE;
            } else if (input.equalsIgnoreCase("MAJORITY")) {
                return WriteConcern.MAJORITY;
            } else if (input.equalsIgnoreCase("NONE")) {
                return WriteConcern.NONE;
            } else if (input.equalsIgnoreCase("REPLICAS_SAFE")) {
                return WriteConcern.REPLICAS_SAFE;
            } else if (input.equalsIgnoreCase("SAFE")) {
                return WriteConcern.SAFE;
            } else if (input.equalsIgnoreCase("NORMAL")) {
                return WriteConcern.NORMAL;
            } else // WriteConcern.ACKNOWLEDGED IS OUR DEFAULT
            {
                return WriteConcern.ACKNOWLEDGED;
            }
        }
    }));

    configuration
            .add(new CoercionTuple(String.class, ReadPreference.class, new Coercion<String, ReadPreference>() {
                public ReadPreference coerce(String input) {
                    if (input.equalsIgnoreCase("SECONDARY")) {
                        return ReadPreference.secondary();
                    } else // PRIMARY IS OUR DEFAULT
                    {
                        return ReadPreference.primary();
                    }
                }
            }));
}

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

License:Apache License

private WriteConcern defaultWriteConcern() {
    if (writeConcern != null) {
        return this.writeConcern;
    } else if (mongoAddresses.size() > 1) {
        return WriteConcern.REPLICAS_SAFE;
    } else {/*from w  w w.  j a  v a2s . c o  m*/
        return WriteConcern.FSYNC_SAFE;
    }
}

From source file:org.eclipse.persistence.nosql.adapters.mongo.MongoConnectionSpec.java

License:Open Source License

/**
 * Connect with the specified properties and return the Connection.
 *//*from ww w.  j a  v a2  s.c  o m*/
public Connection connectToDataSource(EISAccessor accessor, Properties properties)
        throws DatabaseException, ValidationException {
    if ((this.connectionFactory == null) && (this.name == null)) {
        this.connectionFactory = new MongoConnectionFactory();
    }
    if (!properties.isEmpty()) {
        if (this.connectionSpec == null) {
            this.connectionSpec = new MongoJCAConnectionSpec();
        }
        MongoJCAConnectionSpec spec = (MongoJCAConnectionSpec) this.connectionSpec;
        String host = (String) properties.get(HOST);
        String port = (String) properties.get(PORT);
        String db = (String) properties.get(DB);
        if (host != null) {
            if (host.indexOf(',') == -1) {
                spec.getHosts().add(host);
                if (port != null) {
                    spec.getPorts().add(new Integer(port));
                }
            } else {
                int startIndex = 0;
                while (startIndex < (host.length() - 1)) {
                    int endIndex = host.indexOf(',', startIndex);
                    if (endIndex == -1) {
                        endIndex = host.length();
                    }
                    String nextHost = host.substring(startIndex, endIndex);
                    spec.getHosts().add(nextHost);
                    startIndex = endIndex + 1;
                }
                while (startIndex < (port.length() - 1)) {
                    int endIndex = port.indexOf(',', startIndex);
                    if (endIndex == -1) {
                        endIndex = port.length();
                    }
                    String nextPort = port.substring(startIndex, endIndex);
                    spec.getPorts().add(new Integer(nextPort));
                    startIndex = endIndex + 1;
                }
            }
        }
        if (db != null) {
            spec.setDB(db);
        }

        String user = (String) properties.get("user");
        Object password = properties.get("password");
        if (password instanceof String) {
            password = ((String) password).toCharArray();
        }
        if ((user != null) && (user.length() != 0)) {
            spec.setUser(user);
            spec.setPassword((char[]) password);
        }

        // Allows setting of read preference as a property.
        Object preference = properties.get(READ_PREFERENCE);
        if (preference instanceof ReadPreference) {
            spec.setReadPreference((ReadPreference) preference);
        } else if (preference instanceof String) {
            String constant = (String) preference;
            if (constant.equals("PRIMARY")) {
                spec.setReadPreference(ReadPreference.PRIMARY);
            } else if (constant.equals("SECONDARY")) {
                spec.setReadPreference(ReadPreference.SECONDARY);
            } else {
                throw new EISException("Invalid read preference property value: " + constant);
            }
        }

        // Allows setting of write concern as a property.
        Object concern = properties.get(WRITE_CONCERN);
        if (concern instanceof WriteConcern) {
            spec.setWriteConcern((WriteConcern) concern);
        } else if (concern instanceof String) {
            String constant = (String) concern;
            if (constant.equals("FSYNC_SAFE")) {
                spec.setWriteConcern(WriteConcern.FSYNC_SAFE);
            } else if (constant.equals("ACKNOWLEDGED")) {
                spec.setWriteConcern(WriteConcern.ACKNOWLEDGED);
            } else if (constant.equals("JOURNAL_SAFE")) {
                spec.setWriteConcern(WriteConcern.JOURNAL_SAFE);
            } else if (constant.equals("MAJORITY")) {
                spec.setWriteConcern(WriteConcern.MAJORITY);
            } else if (constant.equals("NONE")) {
                spec.setWriteConcern(WriteConcern.NONE);
            } else if (constant.equals("NORMAL")) {
                spec.setWriteConcern(WriteConcern.NORMAL);
            } else if (constant.equals("REPLICAS_SAFE")) {
                spec.setWriteConcern(WriteConcern.REPLICAS_SAFE);
            } else if (constant.equals("SAFE")) {
                spec.setWriteConcern(WriteConcern.SAFE);
            } else {
                throw new EISException("Invalid read preference property value: " + constant);
            }
        }

        // Allows setting of options as a property.
        Object options = properties.get(OPTIONS);
        if (options instanceof Number) {
            spec.setOptions(((Number) options).intValue());
        } else if (options instanceof String) {
            spec.setOptions(Integer.valueOf(((String) options)));
        }
    }

    return super.connectToDataSource(accessor, properties);
}

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;/*from ww w  .j a va2  s  . c  om*/
    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.elasticsearch.river.mongodb.simple.RiverMongoCollectionWithDot.java

License:Apache License

private void createDatabase(String database, String collection) {
    logger.debug("createDatabase {}", database);
    try {//from  w  w  w  .j av  a 2 s .co  m
        mongoDB = getMongo().getDB(database);
        mongoDB.setWriteConcern(WriteConcern.REPLICAS_SAFE);
        logger.info("Start createCollection");
        mongoCollection = mongoDB.createCollection(collection, null);
        Assert.assertNotNull(mongoCollection);
    } catch (Throwable t) {
        logger.error("createDatabase failed.", t);
    }
}

From source file:org.elasticsearch.river.mongodb.simple.RiverMongoCollectionWithDot.java

License:Apache License

@Test
public void initialImport() throws Throwable {
    logger.debug("Start initialImport");
    long timestamp = System.currentTimeMillis();
    String database = "db-" + timestamp;
    try {/*www  . j  av  a 2s  . c om*/
        String collection = "collection." + timestamp;
        createDatabase(database, collection);

        DBObject dbObject = new BasicDBObject("name", "richard-" + timestamp);
        mongoCollection.insert(dbObject);
        Thread.sleep(wait);
        String id = dbObject.get("_id").toString();

        createRiver(database, collection);
        Thread.sleep(wait);
        refreshIndex(collection);

        ActionFuture<IndicesExistsResponse> response = getNode().client().admin().indices()
                .exists(new IndicesExistsRequest(collection));
        assertThat(response.actionGet().isExists(), equalTo(true));
        refreshIndex(collection);
        logger.info("Request: [{}] - count: [{}]", getRequest(collection).id(id),
                getNode().client().count(countRequest(collection)).get().getCount());
        GetResponse getResponse = getNode().client().get(getRequest(collection).id(id)).get();
        assertThat(getResponse.isExists(), equalTo(true));

        mongoCollection.remove(dbObject, WriteConcern.REPLICAS_SAFE);

        Thread.sleep(wait);
        refreshIndex(collection);
        getResponse = getNode().client().get(getRequest(collection).id(id)).get();
        assertThat(getResponse.isExists(), equalTo(false));

    } catch (Throwable t) {
        logger.error("initialImport failed.", t);
        t.printStackTrace();
        throw t;
    } finally {
        cleanUp();
    }
}

From source file:org.elasticsearch.river.mongodb.simple.RiverMongoCollectionWithDot.java

License:Apache License

@Test
public void collectionWithDot_Issue206() throws Throwable {
    logger.debug("Start collectionWithDot_Issue206");
    long timestamp = System.currentTimeMillis();
    String database = "db-" + timestamp;
    try {//  ww w . j  av  a  2  s . co m
        String collection = "collection." + timestamp;
        createDatabase(database, collection);
        createRiver(database, collection);
        DBObject dbObject = new BasicDBObject("name", "richard-" + timestamp);
        WriteResult result = mongoCollection.insert(dbObject);
        Thread.sleep(wait);
        String id = dbObject.get("_id").toString();
        logger.info("WriteResult: {}", result.toString());
        logger.info("dbObject: {}", dbObject.toString());
        ActionFuture<IndicesExistsResponse> response = getNode().client().admin().indices()
                .exists(new IndicesExistsRequest(collection));
        assertThat(response.actionGet().isExists(), equalTo(true));
        refreshIndex(collection);
        logger.info("Request: [{}] - count: [{}]", getRequest(collection).id(id),
                getNode().client().count(countRequest(collection)).get().getCount());
        GetResponse getResponse = getNode().client().get(getRequest(collection).id(id)).get();
        assertThat(getResponse.isExists(), equalTo(true));

        mongoCollection.remove(dbObject, WriteConcern.REPLICAS_SAFE);

        Thread.sleep(wait);
        refreshIndex(collection);
        getResponse = getNode().client().get(getRequest(collection).id(id)).get();
        assertThat(getResponse.isExists(), equalTo(false));

    } catch (Throwable t) {
        logger.error("collectionWithDot_Issue206 failed.", t);
        t.printStackTrace();
        throw t;
    } finally {
        cleanUp();
    }
}