Example usage for com.mongodb ReadPreference primaryPreferred

List of usage examples for com.mongodb ReadPreference primaryPreferred

Introduction

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

Prototype

public static ReadPreference primaryPreferred() 

Source Link

Document

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

Usage

From source file:org.hbr.session.store.MongoStore.java

License:Apache License

/**
 * Create the {@link MongoClient}.//from   w w w .  j  a  v a  2s .  c o  m
 * @throws LifecycleException
 */
private void getConnection() throws LifecycleException {
    try {
        /* create our MongoClient */
        if (this.connectionUri != null) {
            manager.getContainer().getLogger().info(getStoreName() + "[" + this.getName()
                    + "]: Connecting to MongoDB [" + this.connectionUri + "]");
            this.mongoClient = new MongoClient(this.connectionUri);
        } else {
            /* 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();

            /* build up the host list */
            List<ServerAddress> hosts = new ArrayList<ServerAddress>();
            String[] dbHosts = this.hosts.split(",");
            for (String dbHost : dbHosts) {
                String[] hostInfo = dbHost.split(":");
                ServerAddress address = new ServerAddress(hostInfo[0], Integer.parseInt(hostInfo[1]));
                hosts.add(address);
            }

            this.manager.getContainer().getLogger().info(
                    getStoreName() + "[" + this.getName() + "]: Connecting to MongoDB [" + this.hosts + "]");

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

        /* get a connection to our db */
        this.manager.getContainer().getLogger()
                .info(getStoreName() + "[" + this.getName() + "]: Using Database [" + this.dbName + "]");
        this.db = this.mongoClient.getDB(this.dbName);

        /* see if we need to authenticate */
        if (this.username != null || this.password != null) {
            this.manager.getContainer().getLogger().info(
                    getStoreName() + "[" + this.getName() + "]: Authenticating using [" + this.username + "]");
            if (!this.db.authenticate(this.username, this.password.toCharArray())) {
                throw new RuntimeException("MongoDB Authentication Failed");
            }
        }

        /* get a reference to the collection */
        this.collection = this.db.getCollection(this.collectionName);
        this.manager.getContainer().getLogger()
                .info(getStoreName() + "[" + this.getName() + "]: Preparing indexes");

        /* drop any existing indexes */
        try {
            this.collection.dropIndex(new BasicDBObject(lastModifiedProperty, 1));
            this.collection.dropIndex(new BasicDBObject(appContextProperty, 1));
        } catch (Exception e) {
            /* these indexes may not exist, so ignore */
        }

        /* make sure the last modified and app name indexes exists */
        this.collection.ensureIndex(new BasicDBObject(appContextProperty, 1));

        /* determine if we need to expire our db sessions */
        if (this.timeToLive != -1) {
            /* use the time to live set */
            this.collection.ensureIndex(new BasicDBObject(lastModifiedProperty, 1),
                    new BasicDBObject("lastModifiedProperty", this.timeToLive));
        } else {
            /* no custom time to live specified, use the manager's settings */
            if (this.manager.getMaxInactiveInterval() != -1) {
                /* create a ttl index on the app property */
                this.collection.ensureIndex(new BasicDBObject(lastModifiedProperty, 1),
                        new BasicDBObject("lastModifiedProperty", this.manager.getMaxInactiveInterval()));
            } else {
                /* create a regular index */
                this.collection.ensureIndex(new BasicDBObject(lastModifiedProperty, 1));
            }
        }

        this.manager.getContainer().getLogger().info(getStoreName() + "[" + this.getName() + "]: Store ready.");
    } catch (UnknownHostException uhe) {
        this.manager.getContainer().getLogger().error("Unable to Connect to MongoDB", uhe);
        throw new LifecycleException(uhe);
    } catch (MongoException me) {
        this.manager.getContainer().getLogger().error("Unable to Connect to MongoDB", me);
        throw new LifecycleException(me);
    }
}

From source file:org.springframework.data.mongodb.config.ReadPreferencePropertyEditor.java

License:Apache License

@Override
public void setAsText(String readPreferenceString) throws IllegalArgumentException {

    if (readPreferenceString == null) {
        return;/* ww w .  j av  a  2 s .c  o  m*/
    }

    ReadPreference preference = null;

    try {
        preference = ReadPreference.valueOf(readPreferenceString);
    } catch (IllegalArgumentException ex) {
        // ignore this one and try to map it differently
    }

    if (preference != null) {
        setValue(preference);
    } else if ("PRIMARY".equalsIgnoreCase(readPreferenceString)) {
        setValue(ReadPreference.primary());
    } else if ("PRIMARY_PREFERRED".equalsIgnoreCase(readPreferenceString)) {
        setValue(ReadPreference.primaryPreferred());
    } else if ("SECONDARY".equalsIgnoreCase(readPreferenceString)) {
        setValue(ReadPreference.secondary());
    } else if ("SECONDARY_PREFERRED".equalsIgnoreCase(readPreferenceString)) {
        setValue(ReadPreference.secondaryPreferred());
    } else if ("NEAREST".equalsIgnoreCase(readPreferenceString)) {
        setValue(ReadPreference.nearest());
    } else {
        throw new IllegalArgumentException(
                String.format("Cannot find matching ReadPreference for %s", readPreferenceString));
    }
}

From source file:org.unitedid.shibboleth.attribute.resolver.provider.dataConnector.MongoDbDataConnector.java

License:Apache License

/**
 * Gets preferred read method for MongoDB.
 * Defaults to primaryPreferred.//from  w w w  .j a v  a2s.  co m
 *
 * @return a ReadPreference
 */
public ReadPreference getPreferredRead() {
    if (preferredRead != null && !preferredRead.isEmpty()) {
        return MONGO_READ_PREF.get(preferredRead);
    }
    return ReadPreference.primaryPreferred();
}