Example usage for com.mongodb MongoClient MongoClient

List of usage examples for com.mongodb MongoClient MongoClient

Introduction

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

Prototype

public MongoClient(final List<ServerAddress> seeds, final MongoCredential credential,
        final MongoClientOptions options) 

Source Link

Document

Creates an instance based on a list of replica set members or mongos servers.

Usage

From source file:MongoCredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    String server = args[0];/* w w  w . jav a2s .c  om*/
    String user = args[1];
    String password = args[2];
    String databaseName = args[3];

    System.out.println("server: " + server);
    System.out.println("user: " + user);
    System.out.println("database: " + databaseName);

    System.out.println();

    MongoClient mongoClient = new MongoClient(new ServerAddress(server),
            Arrays.asList(MongoCredential.createMongoCRCredential(user, "test", password.toCharArray())),
            new MongoClientOptions.Builder().socketKeepAlive(true).socketTimeout(30000).build());
    DB testDB = mongoClient.getDB(databaseName);

    System.out.println("Count: " + testDB.getCollection("test").count());

    System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject()));

}

From source file:NegotiatedAuthenticationProtocolExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException, InterruptedException {
    String server = args[0];//from  w  w w .  j a  v a  2  s . co m
    String user = args[1];
    String pwd = args[2];
    String db = args[3];

    MongoCredential credentials = new MongoCredential(user, pwd.toCharArray(),
            MongoAuthenticationProtocol.NEGOTIATE, db);

    MongoClient mongoClient = new MongoClient(new ServerAddress(server), Arrays.asList(credentials),
            new MongoClientOptions.Builder().build());

    DB testDB = mongoClient.getDB(db);
    testDB.getCollection("test").insert(new BasicDBObject());
    System.out.println("Count: " + testDB.getCollection("test").count());
}

From source file:GSSAPICredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException, InterruptedException {
    // Set this property to avoid the default behavior where the program prompts on the command line for username/password
    //        Security.setProperty("auth.login.defaultCallbackHandler", "DefaultSecurityCallbackHandler");

    String server = args[0];/*from  w  w w .j  av  a  2s  .c om*/
    String user = args[1];
    String databaseName = args[2];

    System.out.println("javax.security.auth.useSubjectCredsOnly: "
            + System.getProperty("javax.security.auth.useSubjectCredsOnly"));
    System.out.println("java.security.krb5.realm: " + System.getProperty("java.security.krb5.realm"));
    System.out.println("java.security.krb5.kdc: " + System.getProperty("java.security.krb5.kdc"));
    System.out.println(
            "auth.login.defaultCallbackHandler: " + Security.getProperty("auth.login.defaultCallbackHandler"));
    System.out.println("login.configuration.provider: " + Security.getProperty("login.configuration.provider"));
    System.out.println(
            "java.security.auth.login.config: " + Security.getProperty("java.security.auth.login.config"));
    System.out.println("login.config.url.1: " + Security.getProperty("login.config.url.1"));
    System.out.println("login.config.url.2: " + Security.getProperty("login.config.url.2"));
    System.out.println("login.config.url.3: " + Security.getProperty("login.config.url.3"));

    System.out.println("server: " + server);
    System.out.println("user: " + user);
    System.out.println("database: " + databaseName);

    System.out.println();

    MongoClient mongoClient = new MongoClient(new ServerAddress(server),
            Arrays.asList(MongoCredential.createGSSAPICredential(user)),
            new MongoClientOptions.Builder().socketKeepAlive(true).socketTimeout(30000).build());
    DB testDB = mongoClient.getDB(databaseName);

    System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject()));
    System.out.println("Count: " + testDB.getCollection("test").count());
}

From source file:PlainCredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    String server = args[0];/*from w ww . ja  v a2s  .c o  m*/
    String user = args[1];
    String password = args[2];
    String source = args[3];

    System.out.println("server: " + server);
    System.out.println("user: " + user);
    System.out.println("source: " + source);

    System.out.println();

    MongoClient mongoClient = new MongoClient(new ServerAddress(server),
            Arrays.asList(MongoCredential.createPlainCredential(user, source, password.toCharArray())),
            new MongoClientOptions.Builder().build());
    DB testDB = mongoClient.getDB("test");

    System.out.println("Count: " + testDB.getCollection("test").count());

    System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject()));
}

From source file:com.bacic5i5j.framework.database.MongoContext.java

License:Open Source License

public void init(String db, String username, String password, List servers) {
    this.dbname = db;

    MongoCredential mc = MongoCredential.createMongoCRCredential(username, dbname, password.toCharArray());
    List mcs = new ArrayList();
    mcs.add(mc);/*w w  w.j a  va  2s  .  com*/

    MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(100).connectTimeout(10 * 1000)
            .readPreference(ReadPreference.secondaryPreferred()).build();

    this.mongoClient = new MongoClient(servers, mcs, options);
    this.threadLocal = new ThreadLocal<DB>();
}

From source file:com.bluedragon.mongo.MongoDSN.java

License:Open Source License

public static MongoClient newClient(String server, String user, String pass, String db)
        throws UnknownHostException {

    MongoClientOptions options = MongoClientOptions.builder()
            .readPreference(ReadPreference.secondaryPreferred()).build();

    List<InetSocketAddress> serverList = AddrUtil.getAddresses(server);
    List<ServerAddress> addrs = new ArrayList<ServerAddress>();

    Iterator<InetSocketAddress> it = serverList.iterator();
    while (it.hasNext()) {
        InetSocketAddress isa = it.next();
        addrs.add(new ServerAddress(isa.getAddress(), isa.getPort()));
    }//from  w  w w .  ja  v a  2s  . co m

    if (user != null) {
        MongoCredential cred = MongoCredential.createCredential(user, db, pass.toCharArray());
        List<MongoCredential> creds = new ArrayList<MongoCredential>();
        creds.add(cred);

        return new MongoClient(addrs, creds, options);
    } else {
        return new MongoClient(addrs, options);
    }

}

From source file:com.bnrc.sdn.properties.MongoProperties.java

License:Apache License

/** 
 * Creates a {@link MongoClient} using the given {@code options} and 
 * {@code environment}. If the configured port is zero, the value of the 
 * {@code local.mongo.port} property retrieved from the {@code environment} is used 
 * to configure the client. /*w  w w  .  j  a  v a 2s. co  m*/
 * 
 * @param options the options 
 * @param environment the environment 
 * @return the Mongo client 
 * @throws UnknownHostException if the configured host is unknown 
 */
public MongoClient createMongoClient(MongoClientOptions options, Environment environment)
        throws UnknownHostException {
    try {
        if (hasCustomAddress() || hasCustomCredentials()) {
            if (options == null) {
                options = MongoClientOptions.builder().build();
            }
            List<MongoCredential> credentials = null;
            if (hasCustomCredentials()) {
                String database = this.authenticationDatabase == null ? getMongoClientDatabase()
                        : this.authenticationDatabase;
                credentials = Arrays.asList(
                        MongoCredential.createMongoCRCredential(this.username, database, this.password));
            }
            String host = this.host == null ? "localhost" : this.host;
            int port = determinePort(environment);
            return new MongoClient(Arrays.asList(new ServerAddress(host, port)), credentials, options);
        }
        // The options and credentials are in the URI  
        System.out.println("uri=" + uri);
        return new MongoClient(new MongoClientURI(this.uri, builder(options)));
    } finally {
        clearPassword();
    }
}

From source file:com.ca.apm.mongo.Collector.java

License:Open Source License

private MongoClient setupDbClient(final String dbHost, final int dbPort) {
    final boolean useSSL = getBooleanProp(USE_SSL_PROP);
    final String clientTrustStore = getOptionalStringProp(SSL_CLIENT_TRUST_STORE_FILE_PROP);
    final String clientPasswd = getOptionalStringProp(SSL_CLIENT_TRUST_STORE_PASSWD_PROP);

    try {//w  ww  .j a  va2 s .  c  o m
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();

        if (useSSL) {
            System.setProperty(SSL_CLIENT_TRUST_STORE_FILE_PROP, clientTrustStore);
            System.setProperty(SSL_CLIENT_TRUST_STORE_PASSWD_PROP, clientPasswd);
            builder = builder.socketFactory(SSLSocketFactory.getDefault());
        }

        final MongoClientOptions options = builder.build();
        return new MongoClient(new ServerAddress(dbHost, dbPort), mongoCreds, options);
    } catch (Exception ex) {
        throw new RuntimeException("Can't initialize mongo client", ex);
    }
}

From source file:com.ca.apm.mongo.Topology.java

License:Open Source License

protected MongoClient setupDbClient(final String dbHost, final int dbPort) {
    final boolean useSSL = Collector.getBooleanProp(Collector.USE_SSL_PROP, props);
    final String clientTrustStore = Collector.getOptionalStringProp(Collector.SSL_CLIENT_TRUST_STORE_FILE_PROP,
            props);/*from   w w w  . jav  a2s .co m*/
    final String clientPasswd = Collector.getOptionalStringProp(Collector.SSL_CLIENT_TRUST_STORE_PASSWD_PROP,
            props);

    try {
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();

        if (useSSL) {
            System.setProperty(Collector.SSL_CLIENT_TRUST_STORE_FILE_PROP, clientTrustStore);
            System.setProperty(Collector.SSL_CLIENT_TRUST_STORE_PASSWD_PROP, clientPasswd);
            builder = builder.socketFactory(SSLSocketFactory.getDefault());
        }

        final MongoClientOptions options = builder.build();
        MongoClient dbClient = new MongoClient(new ServerAddress(dbHost, dbPort), mongoCreds, options);
        logger.log(Level.FINE, "Connected to mongo at {0}", dbClient.getConnectPoint());
        logger.log(Level.FINE, "Client options: " + dbClient.getMongoClientOptions());
        return dbClient;
    } catch (Exception ex) {
        throw new RuntimeException("Can't initialize mongo client", ex);
    }
}

From source file:com.effektif.mongo.MongoClientSupplier.java

License:Apache License

@Override
public Object supply(Brewery brewery) {
    MongoConfiguration mongoConfiguration = brewery.get(MongoConfiguration.class);
    List<ServerAddress> serverAddresses = mongoConfiguration.getServerAddresses();
    List<MongoCredential> credentials = mongoConfiguration.getCredentials();
    MongoClientOptions options = mongoConfiguration.getOptionBuilder().build();
    if (credentials != null) {
        return new MongoClient(serverAddresses, credentials, options);
    }//www.  j  av a2s. com
    return new MongoClient(serverAddresses, options);
}