Example usage for com.mongodb MongoClientURI MongoClientURI

List of usage examples for com.mongodb MongoClientURI MongoClientURI

Introduction

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

Prototype

public MongoClientURI(final String uri) 

Source Link

Document

Creates a MongoURI from the given string.

Usage

From source file:com.yahoo.ycsb.db3.MongoDbClient.java

License:Open Source License

/**
 * Initialize any state for this DB. Called once per DB instance; there is one
 * DB instance per client thread./*ww  w.j a va 2 s  . c  o  m*/
 */
@Override
public void init() throws DBException {
    INIT_COUNT.incrementAndGet();
    synchronized (INCLUDE) {
        if (mongoClient != null) {
            return;
        }

        Properties props = getProperties();

        // Set insert batchsize, default 1 - to be YCSB-original equivalent
        batchSize = Integer.parseInt(props.getProperty("batchsize", "1"));

        // Set is inserts are done as upserts. Defaults to false.
        useUpsert = Boolean.parseBoolean(props.getProperty("mongodb.upsert", "false"));

        // Just use the standard connection format URL
        // http://docs.mongodb.org/manual/reference/connection-string/
        // to configure the client.
        String url = props.getProperty("mongodb.url", null);
        boolean defaultedUrl = false;
        if (url == null) {
            defaultedUrl = true;
            url = "mongodb://localhost:27017/ycsb?w=1";
        }

        url = OptionsSupport.updateUrl(url, props);

        if (!url.startsWith("mongodb://")) {
            System.err.println("ERROR: Invalid URL: '" + url + "'. Must be of the form "
                    + "'mongodb://<host1>:<port1>,<host2>:<port2>/database?options'. "
                    + "http://docs.mongodb.org/manual/reference/connection-string/");
            System.exit(1);
        }

        try {
            MongoClientURI uri = new MongoClientURI(url);

            String uriDb = uri.getDatabase();
            if (!defaultedUrl && (uriDb != null) && !uriDb.isEmpty() && !"admin".equals(uriDb)) {
                databaseName = uriDb;
            } else {
                // If no database is specified in URI, use "ycsb"
                databaseName = "ycsb";

            }

            readPreference = uri.getOptions().getReadPreference();
            writeConcern = uri.getOptions().getWriteConcern();

            mongoClient = new MongoClient(uri);
            database = mongoClient.getDatabase(databaseName).withReadPreference(readPreference)
                    .withWriteConcern(writeConcern);

            System.out.println("mongo client connection created with " + url);
        } catch (Exception e1) {
            System.err.println("Could not initialize MongoDB connection pool for Loader: " + e1.toString());
            e1.printStackTrace();
            return;
        }
    }
}

From source file:com.zjy.mongo.input.MongoInputSplit.java

License:Apache License

/**
 * @deprecated use {@link #setAuthURI(MongoClientURI)} instead
 * @param authURI a MongoDB URI providing credentials
 *//* www . j  ava2  s.  c o  m*/
@Deprecated
public void setAuthURI(final MongoURI authURI) {
    setAuthURI(authURI != null ? new MongoClientURI(authURI.toString()) : null);
}

From source file:com.zjy.mongo.input.MongoInputSplit.java

License:Apache License

public void readFields(final DataInput in) throws IOException {
    BSONCallback cb = new BasicBSONCallback();
    BSONObject spec;//from   w  w  w.  j  av  a 2  s .  com
    byte[] l = new byte[4];
    in.readFully(l);
    int dataLen = org.bson.io.Bits.readInt(l);
    byte[] data = new byte[dataLen + 4];
    System.arraycopy(l, 0, data, 0, 4);
    in.readFully(data, 4, dataLen - 4);
    _bsonDecoder.decode(data, cb);
    spec = (BSONObject) cb.get();
    setInputURI(new MongoClientURI((String) spec.get("inputURI")));

    if (spec.get("authURI") != null) {
        setAuthURI(new MongoClientURI((String) spec.get("authURI")));
    } else {
        setAuthURI((MongoClientURI) null);
    }

    setKeyField((String) spec.get("keyField"));
    BSONObject temp = (BSONObject) spec.get("fields");
    setFields(temp != null ? new BasicDBObject(temp.toMap()) : null);

    temp = (BSONObject) spec.get("query");
    setQuery(temp != null ? new BasicDBObject(temp.toMap()) : null);

    temp = (BSONObject) spec.get("sort");
    setSort(temp != null ? new BasicDBObject(temp.toMap()) : null);

    temp = (BSONObject) spec.get("min");
    setMin(temp != null ? new BasicDBObject(temp.toMap()) : null);

    temp = (BSONObject) spec.get("max");
    setMax(temp != null ? new BasicDBObject(temp.toMap()) : null);

    setNoTimeout((Boolean) spec.get("notimeout"));
}

From source file:com.zjy.mongo.MongoConfig.java

License:Apache License

public void setMongoURI(final String key, final MongoURI value) {
    setMongoURI(key, new MongoClientURI(value.toString()));
}

From source file:com.zjy.mongo.splitter.MongoCollectionSplitter.java

License:Apache License

/**
 * Takes an existing {@link MongoClientURI} and returns a new modified URI which replaces the original's server host + port with a
 * supplied new server host + port, but maintaining all the same original options. This is useful for generating distinct URIs for each
 * mongos instance so that large batch reads can all target them separately, distributing the load more evenly. It can also be used to
 * force a block of data to be read directly from the shard's servers directly, bypassing mongos entirely.
 *
 * @param originalUri  the URI to rewrite
 * @param newServerUri the new host(s) to target, e.g. server1:port1[,server2:port2,...]
 * @return the rewritten URI/*from ww w.  j ava2 s . c o m*/
 */
protected static MongoClientURI rewriteURI(final MongoClientURI originalUri, final String newServerUri) {
    String originalUriString = originalUri.toString();
    originalUriString = originalUriString.substring(MongoURI.MONGODB_PREFIX.length());

    // uris look like: mongodb://fred:foobar@server1[,server2]/path?options
    //

    //Locate the last character of the original hostname
    int serverEnd;
    int idx = originalUriString.lastIndexOf("/");
    serverEnd = idx < 0 ? originalUriString.length() : idx;

    //Locate the first character of the original hostname
    idx = originalUriString.indexOf("@");
    int serverStart = idx > 0 ? idx + 1 : 0;

    StringBuilder sb = new StringBuilder(originalUriString);
    sb.replace(serverStart, serverEnd, newServerUri);
    return new MongoClientURI(MongoURI.MONGODB_PREFIX + sb);
}

From source file:com.zjy.mongo.splitter.MultiCollectionSplitBuilder.java

License:Apache License

/**
 * @deprecated Use {@link #add(MongoClientURI, MongoClientURI, boolean, DBObject, DBObject, DBObject, boolean, Class)}
 * @param inputURI the input URI for the collection
 * @param authURI the URI to use for authenticating to the collection
 * @param noTimeout disables timing out when reading
 * @param fields a projection specification
 * @param sort a sort specification// w  ww .  j a v  a 2s  .  c  o m
 * @param query a query specification
 * @param useRangeQuery enables using a range query
 * @param splitClass the InputSplit class to use
 * @return the builder
 */
@Deprecated
public MultiCollectionSplitBuilder add(final MongoURI inputURI, final MongoURI authURI, final boolean noTimeout,
        final DBObject fields, final DBObject sort, final DBObject query, final boolean useRangeQuery,
        final Class<? extends MongoSplitter> splitClass) {
    return add(new MongoClientURI(inputURI.toString()), new MongoClientURI(authURI.toString()), noTimeout,
            fields, sort, query, useRangeQuery, splitClass);
}

From source file:com.zjy.mongo.util.MongoConfigUtil.java

License:Apache License

public static List<MongoClientURI> getMongoURIs(final Configuration conf, final String key) {
    String raw = conf.get(key);/*  w w w .  j ava  2 s  . c  om*/
    List<MongoClientURI> result = new LinkedList<MongoClientURI>();
    if (raw != null && !raw.trim().isEmpty()) {
        for (String connectionString : raw.split("mongodb://")) {
            // Try to be forgiving with formatting.
            connectionString = StringUtils.strip(connectionString, ", ");
            if (!connectionString.isEmpty()) {
                result.add(new MongoClientURI("mongodb://" + connectionString));
            }
        }
    }
    return result;
}

From source file:com.zjy.mongo.util.MongoConfigUtil.java

License:Apache License

/**
 * Retrieve a setting as a {@code MongoClientURI}.
 * @param conf the Configuration/* w  ww  .j av a  2  s  .com*/
 * @param key the key for the setting
 * @return the MongoClientURI stored for the given key
 */
public static MongoClientURI getMongoClientURI(final Configuration conf, final String key) {
    final String raw = conf.get(key);
    return raw != null && !raw.trim().isEmpty() ? new MongoClientURI(raw) : null;
}

From source file:com.zjy.mongo.util.MongoConfigUtil.java

License:Apache License

/**
 * @deprecated use {@link #getCollection(MongoClientURI)}
 * @param uri the MongoDB URI/*from  w  ww  .  j av a2  s. co m*/
 * @return the DBCollection in the URI
 */
@Deprecated
public static DBCollection getCollection(final MongoURI uri) {
    return getCollection(new MongoClientURI(uri.toString()));
}

From source file:com.zjy.mongo.util.MongoConfigUtil.java

License:Apache License

/**
 * @deprecated use {@link #getCollectionWithAuth(MongoClientURI, MongoClientURI)} instead
 * @param authURI the URI with which to authenticate
 * @param uri the MongoDB URI//from  ww w .jav  a 2s. c o  m
 * @return the authenticated DBCollection
 */
@Deprecated
public static DBCollection getCollectionWithAuth(final MongoURI uri, final MongoURI authURI) {
    return getCollectionWithAuth(new MongoClientURI(uri.toString()), new MongoClientURI(authURI.toString()));
}