Example usage for com.mongodb ReadPreference valueOf

List of usage examples for com.mongodb ReadPreference valueOf

Introduction

In this page you can find the example usage for com.mongodb ReadPreference valueOf.

Prototype

public static ReadPreference valueOf(final String name) 

Source Link

Document

Creates a read preference from the given read preference name.

Usage

From source file:com.socialsky.mods.MongoPersistor.java

License:Apache License

@Override
public void start() {
    super.start();

    address = getOptionalStringConfig("address", "vertx.mongopersistor");

    host = getOptionalStringConfig("host", "localhost");
    port = getOptionalIntConfig("port", 27017);
    dbName = getOptionalStringConfig("db_name", "default_db");
    username = getOptionalStringConfig("username", null);
    password = getOptionalStringConfig("password", null);
    readPreference = ReadPreference.valueOf(getOptionalStringConfig("read_preference", "primary"));
    int poolSize = getOptionalIntConfig("pool_size", 10);
    autoConnectRetry = getOptionalBooleanConfig("auto_connect_retry", true);
    socketTimeout = getOptionalIntConfig("socket_timeout", 60000);
    useSSL = getOptionalBooleanConfig("use_ssl", false);

    JsonArray seedsProperty = config.getArray("seeds");

    try {/* w  w  w  .  j  a  v a 2 s .c  om*/
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(poolSize);
        builder.autoConnectRetry(autoConnectRetry);
        builder.socketTimeout(socketTimeout);
        builder.readPreference(readPreference);

        if (useSSL) {
            builder.socketFactory(SSLSocketFactory.getDefault());
        }

        if (seedsProperty == null) {
            ServerAddress address = new ServerAddress(host, port);
            mongo = new MongoClient(address, builder.build());
        } else {
            List<ServerAddress> seeds = makeSeeds(seedsProperty);
            mongo = new MongoClient(seeds, builder.build());
        }

        db = mongo.getDB(dbName);
        if (username != null && password != null) {
            db.authenticate(username, password.toCharArray());
        }
    } catch (UnknownHostException e) {
        logger.error("Failed to connect to mongo server", e);
    }
    eb.registerHandler(address, this);
}

From source file:com.stratio.deep.mongodb.reader.MongoReader.java

License:Apache License

/**
 * Init void.//from  ww  w  .  j  av  a  2  s.  c o m
 *
 * @param partition the partition
 */
public void init(Partition partition) {
    try {

        List<ServerAddress> addressList = new ArrayList<>();

        for (String s : (List<String>) ((DeepPartition) partition).splitWrapper().getReplicas()) {
            addressList.add(new ServerAddress(s));
        }

        //Credentials
        List<MongoCredential> mongoCredentials = new ArrayList<>();

        if (mongoDeepJobConfig.getUsername() != null && mongoDeepJobConfig.getPassword() != null) {
            MongoCredential credential = MongoCredential.createMongoCRCredential(
                    mongoDeepJobConfig.getUsername(), mongoDeepJobConfig.getDatabase(),
                    mongoDeepJobConfig.getPassword().toCharArray());
            mongoCredentials.add(credential);

        }

        mongoClient = new MongoClient(addressList, mongoCredentials);
        mongoClient.setReadPreference(ReadPreference.valueOf(mongoDeepJobConfig.getReadPreference()));
        db = mongoClient.getDB(mongoDeepJobConfig.getDatabase());
        collection = db.getCollection(mongoDeepJobConfig.getCollection());

        dbCursor = collection.find(generateFilterQuery((MongoPartition) partition),
                mongoDeepJobConfig.getDBFields());

    } catch (UnknownHostException e) {
        throw new DeepExtractorInitializationException(e);
    }
}

From source file:fr.wseduc.gridfs.GridFSPersistor.java

License:Apache License

public void start() {
    super.start();

    address = getOptionalStringConfig("address", "vertx.gridfspersistor");

    host = getOptionalStringConfig("host", "localhost");
    port = getOptionalIntConfig("port", 27017);
    dbName = getOptionalStringConfig("db_name", "default_db");
    username = getOptionalStringConfig("username", null);
    password = getOptionalStringConfig("password", null);
    ReadPreference readPreference = ReadPreference
            .valueOf(getOptionalStringConfig("read_preference", "primary"));
    int poolSize = getOptionalIntConfig("pool_size", 10);
    boolean autoConnectRetry = getOptionalBooleanConfig("auto_connect_retry", true);
    int socketTimeout = getOptionalIntConfig("socket_timeout", 60000);
    boolean useSSL = getOptionalBooleanConfig("use_ssl", false);
    JsonArray seedsProperty = config.getArray("seeds");
    bucket = getOptionalStringConfig("bucket", "fs");

    try {/*from   w w  w .j  a v a  2  s . c om*/
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(poolSize);
        builder.autoConnectRetry(autoConnectRetry);
        builder.socketTimeout(socketTimeout);
        builder.readPreference(readPreference);

        if (useSSL) {
            builder.socketFactory(SSLSocketFactory.getDefault());
        }

        if (seedsProperty == null) {
            ServerAddress address = new ServerAddress(host, port);
            mongo = new MongoClient(address, builder.build());
        } else {
            List<ServerAddress> seeds = makeSeeds(seedsProperty);
            mongo = new MongoClient(seeds, builder.build());
        }

        db = mongo.getDB(dbName);
        if (username != null && password != null) {
            db.authenticate(username, password.toCharArray());
        }
    } catch (UnknownHostException e) {
        logger.error("Failed to connect to mongo server", e);
    }
    eb.registerHandler(address, this);
    eb.registerHandler(address + ".json", new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> message) {
            String action = message.body().getString("action", "");
            switch (action) {
            case "write":
                writeTo(message);
                break;
            default:
                sendError(message, "Invalid action");
            }
        }
    });
}

From source file:org.apache.camel.component.gridfs.GridFsEndpoint.java

License:Apache License

/** 
 * Sets a MongoDB {@link ReadPreference} on the Mongo connection. Read preferences set directly on the connection will be
 * overridden by this setting.//  w  w  w.j a  va  2s  .  c  o  m
 * <p/>
 * The {@link com.mongodb.ReadPreference#valueOf(String)} utility method is used to resolve the passed {@code readPreference}
 * value. Some examples for the possible values are {@code nearest}, {@code primary} or {@code secondary} etc.
 * 
 * @param readPreference the name of the read preference to set
 */
public void setReadPreference(String readPreference) {
    this.readPreference = ReadPreference.valueOf(readPreference);
}

From source file:org.apache.gora.mongodb.store.MongoStore.java

License:Apache License

/**
 * Retrieve a client connected to the MongoDB server to be used.
 *
 * @param servers/* ww  w .  ja  v a2 s  .  c o  m*/
 *          This value should specify the host:port (at least one) for
 *          connecting to remote MongoDB. Multiple values must be separated by
 *          coma.
 * @return a {@link Mongo} instance connected to the server
 * @throws UnknownHostException
 */
private MongoClient getClient(MongoStoreParameters params) throws UnknownHostException {
    // Configure options
    MongoClientOptions.Builder optBuilder = new MongoClientOptions.Builder()
            .dbEncoderFactory(GoraDBEncoder.FACTORY); // Utf8 serialization!
    if (params.getReadPreference() != null) {
        optBuilder.readPreference(ReadPreference.valueOf(params.getReadPreference()));
    }
    if (params.getWriteConcern() != null) {
        optBuilder.writeConcern(WriteConcern.valueOf(params.getWriteConcern()));
    }
    // If configuration contains a login + secret, try to authenticated with DB
    List<MongoCredential> credentials = null;
    if (params.getLogin() != null && params.getSecret() != null) {
        credentials = new ArrayList<MongoCredential>();
        credentials.add(MongoCredential.createCredential(params.getLogin(), params.getDbname(),
                params.getSecret().toCharArray()));
    }
    // Build server address
    List<ServerAddress> addrs = new ArrayList<ServerAddress>();
    Iterable<String> serversArray = Splitter.on(",").split(params.getServers());
    if (serversArray != null) {
        for (String server : serversArray) {
            Iterator<String> paramsIterator = Splitter.on(":").trimResults().split(server).iterator();
            if (!paramsIterator.hasNext()) {
                // No server, use default
                addrs.add(new ServerAddress());
            } else {
                String host = paramsIterator.next();
                if (paramsIterator.hasNext()) {
                    String port = paramsIterator.next();
                    addrs.add(new ServerAddress(host, Integer.parseInt(port)));
                } else {
                    addrs.add(new ServerAddress(host));
                }
            }
        }
    }
    // Connect to the Mongo server
    return new MongoClient(addrs, credentials, optBuilder.build());
}

From source file:org.apache.jackrabbit.oak.plugins.document.memory.MemoryDocumentStore.java

License:Apache License

@Override
public void setReadWriteMode(String readWriteMode) {
    if (readWriteMode == null || readWriteMode.equals(lastReadWriteMode)) {
        return;//from   w w  w  .  ja va2 s. c  o m
    }
    lastReadWriteMode = readWriteMode;
    try {
        Map<String, String> map = Splitter.on(", ").withKeyValueSeparator(":").split(readWriteMode);
        String read = map.get("read");
        if (read != null) {
            ReadPreference readPref = ReadPreference.valueOf(read);
            if (!readPref.equals(this.readPreference)) {
                this.readPreference = readPref;
            }
        }
        String write = map.get("write");
        if (write != null) {
            WriteConcern writeConcern = WriteConcern.valueOf(write);
            if (!writeConcern.equals(this.writeConcern)) {
                this.writeConcern = writeConcern;
            }
        }
    } catch (Exception e) {
        // unsupported or parse error - ignore
    }
}

From source file:org.jooby.mongodb.MongoRx.java

License:Apache License

static MongoClientSettings.Builder settings(final ConnectionString cstr, final Config conf) {
    MongoClientSettings.Builder settings = MongoClientSettings.builder();

    settings.clusterSettings(cluster(cstr, conf));
    settings.connectionPoolSettings(pool(cstr, conf));
    settings.heartbeatSocketSettings(socket("heartbeat", cstr, conf));

    withStr("readConcern", conf,
            v -> settings.readConcern(Match(v.toUpperCase())
                    .option(Case("DEFAULT", ReadConcern.DEFAULT), Case("LOCAL", ReadConcern.LOCAL),
                            Case("MAJORITY", ReadConcern.MAJORITY))
                    .getOrElseThrow(() -> new IllegalArgumentException("readConcern=" + v))));

    withStr("readPreference", conf, v -> settings.readPreference(ReadPreference.valueOf(v)));

    settings.serverSettings(server(conf));
    settings.socketSettings(socket("socket", cstr, conf));
    settings.sslSettings(ssl(cstr, conf));

    withStr("writeConcern", conf,
            v -> settings.writeConcern(Match(v.toUpperCase())
                    .option(Case("W1", WriteConcern.W1), Case("W2", WriteConcern.W2),
                            Case("W3", WriteConcern.W3), Case("ACKNOWLEDGED", WriteConcern.ACKNOWLEDGED),
                            Case("JOURNALED", WriteConcern.JOURNALED), Case("MAJORITY", WriteConcern.MAJORITY))
                    .getOrElseThrow(() -> new IllegalArgumentException("writeConcern=" + v))));

    return settings;
}

From source file:org.mongodb.tse.tests.RunQueryThreadPool.java

public static MongoCollection getCollection(CommandLine cline, MongoDatabase database,
        String collectionParameter) {
    MongoCollection collection = null;/*from  www .j  a v a  2s  . c  o  m*/
    if (cline.hasOption("readPreference")) {
        String p = cline.getOptionValue("readPreference");
        collection = database.getCollection(collectionParameter).withReadPreference(ReadPreference.valueOf(p));
    } else
        collection = database.getCollection(collectionParameter)
                .withReadPreference(ReadPreference.secondaryPreferred());
    return collection;
}

From source file:org.mongodb.tse.tests.Timings.java

public static void main(String[] args) throws ParseException {

    Option help = Option.builder("help").argName("help").desc("get help").build();
    Option test = Option.builder("test").argName("test").desc("quick test").build();
    Option ouri = Option.builder("uri").argName("uri").desc("mongodb uri, required").hasArg().type(String.class)
            .build();//from   w ww. j  av  a2s  .  com
    Option odatabase = Option.builder("database").argName("database")
            .desc("mongodb database, default productpersistdb").hasArg().type(String.class).build();
    Option ocollection = Option.builder("collection").argName("collection")
            .desc("mongodb collection, default product").hasArg().type(String.class).build();
    Option osleep = Option.builder("sleep").argName("sleep").desc("sleep between runs, default 10 seconds")
            .hasArg().type(Integer.class).build();
    Option otimes = Option.builder("times").argName("times").desc("number of times to run, default 100")
            .hasArg().type(Integer.class).build();
    Option readPreference = Option.builder("readPreference").argName("readPreference")
            .desc("read preference, default is secondaryPreferred").hasArg().type(String.class).build();
    Option oids = Option.builder("ids").argName("ids").desc("list of comma separated ids").hasArg()
            .type(String.class).build();
    Option oidFile = Option.builder("idFile").argName("idFile").desc("file containing ids per line").hasArg()
            .type(String.class).build();
    Option odoc = Option.builder("doc").argName("doc")
            .desc("get a Document instead of RawBsonDocument, no size output with this option").build();

    Options options = new Options();
    options.addOption(help);
    options.addOption(test);
    options.addOption(ouri);
    options.addOption(odatabase);
    options.addOption(ocollection);
    options.addOption(osleep);
    options.addOption(otimes);
    options.addOption(readPreference);
    options.addOption(oids);
    options.addOption(oidFile);
    options.addOption(odoc);

    CommandLineParser parser = new DefaultParser();
    CommandLine cline = null;
    try {
        // parse the command line arguments
        cline = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }

    if (args.length == 0 || cline.hasOption("help") || !cline.hasOption("uri")) {
        printHelp(options);
    }

    if (cline.hasOption("test")) {
        List<Double> testList = new ArrayList<Double>();
        for (int i = 0; i < 100; i++) {
            testList.add(new Double(i));
        }
        Collections.sort(testList);
        System.out.println(String.format("P50: %.2f, P75: %.2f, P90: %.2f, P95: %.2f, P99: %.2f",
                percentile(testList, 0.50), percentile(testList, 0.75), percentile(testList, 0.90),
                percentile(testList, 0.95), percentile(testList, 0.99)));
        System.exit(0);
    }

    String[] ids = null;
    if (cline.hasOption("idFile")) {
        ids = parseIdFile(new File(cline.getOptionValue("idFile")));
    } else
        ids = cline.getOptionValue("ids", "517886481000").split(",");

    List<Double> timeList = new ArrayList<>();

    String uriParameter = cline.getOptionValue("uri");
    String databaseParameter = cline.getOptionValue("database", "productpersistdb");
    String collectionParameter = cline.getOptionValue("collection", "product");
    System.out.println("Using database: " + databaseParameter + " and collection: " + collectionParameter);

    MongoClientURI uri = new MongoClientURI(uriParameter);
    MongoClient mongoClient = new MongoClient(uri);

    MongoDatabase database = mongoClient.getDatabase(databaseParameter);
    MongoCollection<Document> collection = null;
    MongoCollection<RawBsonDocument> rawCollection = null;

    boolean doDoc = cline.hasOption("doc");
    if (doDoc) {
        if (cline.hasOption("readPreference")) {
            String p = cline.getOptionValue("readPreference");
            collection = database.getCollection(collectionParameter)
                    .withReadPreference(ReadPreference.valueOf(p));
        } else
            collection = database.getCollection(collectionParameter)
                    .withReadPreference(ReadPreference.secondaryPreferred());
    } else {
        if (cline.hasOption("readPreference")) {
            String p = cline.getOptionValue("readPreference");
            rawCollection = database.getCollection(collectionParameter, RawBsonDocument.class)
                    .withReadPreference(ReadPreference.valueOf(p));
        } else
            rawCollection = database.getCollection(collectionParameter, RawBsonDocument.class)
                    .withReadPreference(ReadPreference.secondaryPreferred());
    }

    long sleep = 10000;
    if (cline.hasOption("sleep"))
        sleep = Integer.parseInt(cline.getOptionValue("sleep")) * 1000;
    int times = 100;
    if (cline.hasOption("times"))
        times = Integer.parseInt(cline.getOptionValue("times"));

    int count = 0;
    int max = ids.length;
    while (count < times) {
        String id = ids[(count % max)];
        Document doc = null;
        RawBsonDocument raw = null;

        Date date = new Date();
        long end = 0L;
        long start = System.nanoTime();
        if (doDoc) {
            doc = collection.find(eq("_id", id)).first();
            end = System.nanoTime();
            if (doc == null)
                System.out.println("Could not find " + id);
        } else {
            raw = rawCollection.find(eq("_id", id)).first();
            end = System.nanoTime();
            if (raw == null)
                System.out.println("Could not find " + id);
        }

        int size = 0;
        if (raw != null)
            size = raw.getByteBuffer().capacity();

        if (raw != null) {
            System.out.println(String.format("id: %s, start: %s, elasped: %s ns, docSize: %s", id, date,
                    (end - start), size));
        } else {
            System.out.println(String.format("id: %s, start: %s, elasped: %s ns", id, date, (end - start)));
        }
        timeList.add(new Double(end - start));
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
        }
        count++;
    }

    Collections.sort(timeList);

    System.out.println(String.format("P50: %.2f, P75: %.2f, P90: %.2f, P95: %.2f, P99: %.2f",
            percentile(timeList, 0.50), percentile(timeList, 0.75), percentile(timeList, 0.90),
            percentile(timeList, 0.95), percentile(timeList, 0.99)));
}

From source file:org.opencb.commons.datastore.mongodb.MongoDataStoreManager.java

License:Apache License

private MongoDataStore create(String database, MongoDBConfiguration mongoDBConfiguration) {
    MongoDataStore mongoDataStore = null;
    MongoClient mc = null;//ww  w  .ja  v  a  2  s. co  m
    logger.debug(
            "MongoDataStoreManager: creating a MongoDataStore object for database: '" + database + "' ...");
    long t0 = System.currentTimeMillis();
    if (database != null && !database.trim().equals("")) {
        // read DB configuration for that SPECIES.VERSION, by default
        // PRIMARY_DB is selected
        //            String dbPrefix = applicationProperties.getProperty(speciesVersionPrefix + ".DB", "PRIMARY_DB");
        // We create the MongoClientOptions
        MongoClientOptions mongoClientOptions;
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder()
                .connectionsPerHost(
                        mongoDBConfiguration.getInt(CONNECTIONS_PER_HOST, CONNECTIONS_PER_HOST_DEFAULT))
                .connectTimeout(mongoDBConfiguration.getInt(CONNECT_TIMEOUT, CONNECT_TIMEOUT_DEFAULT))
                .readPreference(ReadPreference.valueOf(
                        mongoDBConfiguration.getString(READ_PREFERENCE, READ_PREFERENCE_DEFAULT.getValue())));

        if (mongoDBConfiguration.getString(REPLICA_SET) != null
                && !mongoDBConfiguration.getString(REPLICA_SET).isEmpty()) {
            logger.debug("Setting replicaSet to " + mongoDBConfiguration.getString(REPLICA_SET));
            builder = builder.requiredReplicaSetName(mongoDBConfiguration.getString(REPLICA_SET));
        }

        if (mongoDBConfiguration.getBoolean(SSL_ENABLED)) {
            logger.debug("SSL connections enabled for " + database);
            builder = builder.sslEnabled(mongoDBConfiguration.getBoolean(SSL_ENABLED));
        }

        mongoClientOptions = builder.build();

        assert (dataStoreServerAddresses != null);

        // We create the MongoCredential object
        String user = mongoDBConfiguration.getString(USERNAME, "");
        String pass = mongoDBConfiguration.getString(PASSWORD, "");
        MongoCredential mongoCredential = null;
        if ((user != null && !user.equals("")) || (pass != null && !pass.equals(""))) {
            //                final DB authenticationDatabase;
            if (mongoDBConfiguration.get(AUTHENTICATION_DATABASE) != null
                    && !mongoDBConfiguration.getString(AUTHENTICATION_DATABASE).isEmpty()) {
                //                        authenticationDatabase = mc.getDB(mongoDBConfiguration.getString("authenticationDatabase"));
                mongoCredential = MongoCredential.createScramSha1Credential(user,
                        mongoDBConfiguration.getString(AUTHENTICATION_DATABASE), pass.toCharArray());
            } else {
                //                        authenticationDatabase = db;
                mongoCredential = MongoCredential.createScramSha1Credential(user, "", pass.toCharArray());
            }
            //                    authenticationDatabase.authenticate(user, pass.toCharArray());
        }

        mc = newMongoClient(mongoClientOptions, mongoCredential);

        //                mc.setReadPreference(ReadPreference.secondary(new BasicDBObject("dc", "PG")));
        //                mc.setReadPreference(ReadPreference.primary());
        //                System.out.println("Replica Status: "+mc.getReplicaSetStatus());
        logger.debug(mongoDBConfiguration.toString());
        MongoDatabase db = mc.getDatabase(database);
        //                db.setReadPreference(ReadPreference.secondary(new BasicDBObject("dc", "PG")));
        //                db.setReadPreference(ReadPreference.primary());

        long t1 = System.currentTimeMillis();
        logger.debug("MongoDataStoreManager: MongoDataStore object for database: '" + database + "' created in "
                + (t0 - t1) + "ms");
        mongoDataStore = new MongoDataStore(mc, db, mongoDBConfiguration);
    } else {
        logger.debug("MongoDB database is null or empty");
    }
    return mongoDataStore;
}