Example usage for com.mongodb ReadPreference secondaryPreferred

List of usage examples for com.mongodb ReadPreference secondaryPreferred

Introduction

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

Prototype

public static ReadPreference secondaryPreferred() 

Source Link

Document

Gets a read preference that forces reads to a secondary if one is available, otherwise to the primary.

Usage

From source file:com.navercorp.pinpoint.plugin.mongodb.MongoDBIT_3_2_x_IT.java

License:Apache License

@Override
public void setClient() {
    mongoClient = new com.mongodb.MongoClient("localhost", 27018);
    database = mongoClient.getDatabase("myMongoDbFake").withReadPreference(ReadPreference.secondaryPreferred())
            .withWriteConcern(WriteConcern.MAJORITY);
}

From source file:com.navercorp.pinpoint.plugin.mongodb.MongoDBIT_3_7_x_IT.java

License:Apache License

@Override
public void setClient() {
    mongoClient = MongoClients.create("mongodb://localhost:27018");
    database = mongoClient.getDatabase("myMongoDbFake").withReadPreference(ReadPreference.secondaryPreferred())
            .withWriteConcern(WriteConcern.MAJORITY);
}

From source file:com.ott.bookings.auth.form.impl.MongoTockenStore.java

License:Apache License

/**
 * Create the {@link MongoClient}./*from   w  ww .ja v  a2  s .  co  m*/
 * 
 */
private void getConnection() {
    try {

        /* create the client using the Mongo options */
        ReadPreference readPreference = ReadPreference.primaryPreferred();
        if (this.useSlaves) {
            readPreference = ReadPreference.secondaryPreferred();
        }
        MongoClientOptions options = MongoClientOptions.builder().connectTimeout(connectionTimeoutMs)
                .maxWaitTime(connectionWaitTimeoutMs).connectionsPerHost(maxPoolSize).writeConcern(writeConcern)
                .readPreference(readPreference).build();

        log.info("[Mongo Token Store]: Connecting to MongoDB [" + this.hostsString + "]");

        /* connect */
        this.mongoClient = new MongoClient(getServerAddresses(), options);

        /* get a connection to our db */
        log.info("[Mongo Token Store]: Using Database [" + this.dbName + "]");
        this.db = this.mongoClient.getDB(this.dbName);
        /* get a reference to the collection */
        this.collection = this.db.getCollection(this.collectionName);

        log.info("[Mongo Token Store]: Store ready.");
    } catch (UnknownHostException uhe) {
        log.error("Unable to Connect to MongoDB", uhe);
    } catch (MongoException me) {
        log.error("Unable to Connect to MongoDB", me);
    }
}

From source file:com.redhat.lightblue.mongo.config.MongoReadPreference.java

License:Open Source License

public static ReadPreference parse(String value) {
    value = value.trim();//from w w w  . j  a v a2 s. com
    int paren = value.indexOf('(');
    String pref;
    List<TagSet> tags;
    if (paren != -1) {
        pref = value.substring(0, paren).trim();
        String argsStr = value.substring(paren + 1).trim();
        if (!argsStr.endsWith(")")) {
            throw new InvalidReadPreference(value);
        }
        tags = parseArgs(argsStr.substring(0, argsStr.length() - 1));
    } else {
        pref = value;
        tags = null;
    }
    switch (pref) {
    case READ_PREFERENCE_NEAREST:
        if (tags == null) {
            return ReadPreference.nearest();
        } else {
            return ReadPreference.nearest(tags);
        }
    case READ_PREFERENCE_PRIMARY:
        return ReadPreference.primary();
    case READ_PREFERENCE_PRIMARY_PREFERRED:
        if (tags == null) {
            return ReadPreference.primaryPreferred();
        } else {
            return ReadPreference.primaryPreferred(tags);
        }
    case READ_PREFERENCE_SECONDARY:
        if (tags == null) {
            return ReadPreference.secondary();
        } else {
            return ReadPreference.secondary(tags);
        }
    case READ_PREFERENCE_SECONDARY_PREFERRED:
        if (tags == null) {
            return ReadPreference.secondaryPreferred();
        } else {
            return ReadPreference.secondaryPreferred(tags);
        }
    default:
        throw new InvalidReadPreference(value);
    }
}

From source file:com.ricardolorenzo.identity.user.impl.UserIdentityManagerMongoDB.java

License:Open Source License

public UserIdentityManagerMongoDB(final Properties conf) throws UnknownHostException {
    this.properties = conf;

    this.databaseUsers = new Boolean(this.properties.getProperty("mongodb.databaseUsers", "true"));

    WriteConcern writeConcern = WriteConcern.MAJORITY;
    String writeConcernType = conf.getProperty("mongodb.writeConcern", "majority").toLowerCase();
    if ("majority".equals(writeConcernType)) {
        writeConcern = WriteConcern.UNACKNOWLEDGED;
    } else if ("unacknowledged".equals(writeConcernType)) {
        writeConcern = WriteConcern.UNACKNOWLEDGED;
    } else if ("acknowledged".equals(writeConcernType)) {
        writeConcern = WriteConcern.ACKNOWLEDGED;
    } else if ("journaled".equals(writeConcernType)) {
        writeConcern = WriteConcern.JOURNALED;
    } else if ("replica_acknowledged".equals(writeConcernType)) {
        writeConcern = WriteConcern.REPLICA_ACKNOWLEDGED;
    }//from  w ww .j  ava 2  s  .  c o m

    ReadPreference readPreference = null;
    String readPreferenceType = conf.getProperty("mongodb.readPreference", "primary").toLowerCase();
    if ("primary".equals(readPreferenceType)) {
        readPreference = ReadPreference.primary();
    } else if ("primary_preferred".equals(readPreferenceType)) {
        readPreference = ReadPreference.primaryPreferred();
    } else if ("secondary".equals(readPreferenceType)) {
        readPreference = ReadPreference.secondary();
    } else if ("secondary_preferred".equals(readPreferenceType)) {
        readPreference = ReadPreference.secondaryPreferred();
    } else if ("nearest".equals(readPreferenceType)) {
        readPreference = ReadPreference.nearest();
    }

    MongoClientOptions.Builder options = MongoClientOptions.builder();
    options.writeConcern(writeConcern);
    options.readPreference(readPreference);
    try {
        options.connectionsPerHost(Integer.parseInt(conf.getProperty("mongodb.threads", "100")));
    } catch (NumberFormatException e) {
        options.connectionsPerHost(100);
    }

    MongoClientURI mongoClientURI = new MongoClientURI(
            conf.getProperty("mongodb.url", "mongodb://localhost:27017"), options);
    if (!this.properties.containsKey("mongodb.database")) {
        if (mongoClientURI.getDatabase() != null && !mongoClientURI.getDatabase().isEmpty()) {
            this.properties.setProperty("mongodb.database", mongoClientURI.getDatabase());
        } else {
            this.properties.setProperty("mongodb.database", DEFAULT_DATABASE);
        }
    }
    mongoClient = new MongoClient(mongoClientURI);
}

From source file:com.stratio.connector.mongodb.core.configuration.MongoClientConfiguration.java

License:Apache License

/**
 * Convert the Mongo connector string option to the appropriate Read Preference.
 *
 * @param readSetting// ww  w.ja v  a  2  s .c  o  m
 *            the read preference string setting
 * @return the read preference.
 * @throws MongoValidationException
 *             if the value cannot be parsed to a ReadPreference
 */
private ReadPreference settingToReadPreference(String readSetting) throws MongoValidationException {
    ReadPreference readPreference = null;
    switch (readSetting.trim().toLowerCase()) {
    case "primary":
        readPreference = ReadPreference.primary();
        break;
    case "primarypreferred":
        readPreference = ReadPreference.primaryPreferred();
        break;
    case "secondary":
        readPreference = ReadPreference.secondary();
        break;
    case "secondarypreferred":
        readPreference = ReadPreference.secondaryPreferred();
        break;
    case "nearest":
        readPreference = ReadPreference.nearest();
        break;
    default:
        throw new MongoValidationException("Read preference " + readSetting + " is not a legal value");
    }
    return readPreference;

}

From source file:com.ttpod.rest.web.spring.MongoFactoryBean.java

License:Apache License

@Override
public void afterPropertiesSet() throws Exception {
    String[] host_ports = urls.split(",");
    List<ServerAddress> addList = new ArrayList<ServerAddress>(host_ports.length);
    for (String host_port : host_ports) {
        String[] kv = host_port.split(":");
        addList.add(new ServerAddress(kv[0], Integer.parseInt(kv[1])));
    }/*from   w  ww. j  ava  2  s.c  o m*/

    if (autoSlaveOk && addList.size() > 1) {
        options.readPreference = ReadPreference.secondaryPreferred();
    }

    this.mongo = new Mongo(addList, options);
}

From source file:dk.au.cs.karibu.backend.mongo.MongoDBStorage.java

License:Apache License

private void createConnection(MongoConfiguration conf) {

    String databaseName = conf.getDatabaseName();
    List<ServerAddress> addr = conf.getServerAddressList();

    // connect to the database server 
    mongoDB = null;/*w  ww .j  a v  a2s. co m*/
    try {
        mongoDB = new MongoClient(addr);
    } catch (MongoException e) {
        String theTrace = ExceptionUtils.getStackTrace(e);
        log.error("MongoException. " + theTrace);
        System.exit(-1);
    }
    // get handle to the required database 
    database = mongoDB.getDB(databaseName);
    // authenticate in case there is a username in the config
    if (conf.getUsername() != null) {
        boolean auth = database.authenticate(conf.getUsername(), conf.getPassword().toCharArray());
        if (!auth) {
            log.error("Mongo authentication failed for username: " + conf.getUsername() + " on DB: "
                    + conf.getDatabaseName());
            System.out.println("MongoDB authentication failed. Review log.");
            // Fail fast!
            System.exit(-1);
        }
    }

    // From javadoc:  
    // By default, all read and write operations will be made on the primary,  
    // but it's possible to read from secondaries by changing the read preference 
    mongoDB.setReadPreference(ReadPreference.secondaryPreferred());

    // From javadoc: Exceptions are raised for network issues, and server errors;  
    // waits on a server for the write operation 
    mongoDB.setWriteConcern(WriteConcern.SAFE);

    log.info("MongoDB connected...");

    // Register a shutdown hook to close the mongo  
    // connection 
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            log.info("MongoDB disconnected...");
            mongoDB.close();
        }
    });

}

From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoBlobStore.java

License:Apache License

private MongoBlob getBlob(String id, long lastMod) {
    DBObject query = getBlobQuery(id, lastMod);

    // try the secondary first
    // TODO add a configuration option for whether to try reading from secondary
    ReadPreference pref = ReadPreference.secondaryPreferred();
    DBObject fields = new BasicDBObject();
    fields.put(MongoBlob.KEY_DATA, 1);//from www.  j  av a2s  . c  o m
    MongoBlob blob = (MongoBlob) getBlobCollection().findOne(query, fields, pref);
    if (blob == null) {
        // not found in the secondary: try the primary
        pref = ReadPreference.primary();
        blob = (MongoBlob) getBlobCollection().findOne(query, fields, pref);
    }
    return blob;
}

From source file:org.apache.jackrabbit.oak.plugins.document.mongo.MongoVersionGCSupport.java

License:Apache License

@Override
public CloseableIterable<NodeDocument> getPossiblyDeletedDocs(final long lastModifiedTime) {
    //_deletedOnce == true && _modified < lastModifiedTime
    DBObject query = start(NodeDocument.DELETED_ONCE).is(Boolean.TRUE).put(NodeDocument.MODIFIED_IN_SECS)
            .lessThan(NodeDocument.getModifiedInSecs(lastModifiedTime)).get();
    DBCursor cursor = getNodeCollection().find(query).setReadPreference(ReadPreference.secondaryPreferred());
    if (!disableIndexHint) {
        cursor.hint(new BasicDBObject(NodeDocument.DELETED_ONCE, 1));
    }/* w  ww  .ja  v a2 s.c  om*/

    return CloseableIterable.wrap(transform(cursor, new Function<DBObject, NodeDocument>() {
        @Override
        public NodeDocument apply(DBObject input) {
            return store.convertFromDBObject(NODES, input);
        }
    }), cursor);
}