Example usage for com.mongodb MongoClientOptions builder

List of usage examples for com.mongodb MongoClientOptions builder

Introduction

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

Prototype

public static Builder builder() 

Source Link

Document

Creates a builder instance.

Usage

From source file:org.springframework.boot.autoconfigure.mongo.MongoClientFactory.java

License:Apache License

private MongoClient createNetworkMongoClient(MongoClientOptions options) {
    MongoProperties properties = this.properties;
    if (properties.getUri() != null) {
        return createMongoClient(properties.getUri(), options);
    }//  w ww.  j ava  2s. c om
    if (hasCustomAddress() || hasCustomCredentials()) {
        if (options == null) {
            options = MongoClientOptions.builder().build();
        }
        MongoCredential credentials = getCredentials(properties);
        String host = getValue(properties.getHost(), "localhost");
        int port = getValue(properties.getPort(), MongoProperties.DEFAULT_PORT);
        List<ServerAddress> seeds = Collections.singletonList(new ServerAddress(host, port));
        return (credentials != null) ? new MongoClient(seeds, credentials, options)
                : new MongoClient(seeds, options);
    }
    return createMongoClient(MongoProperties.DEFAULT_URI, options);
}

From source file:org.springframework.boot.autoconfigure.mongo.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./*from   ww  w  .j  a v a  2 s .c om*/
 *
 * @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.createCredential(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
        return new MongoClient(new MongoClientURI(this.uri, builder(options)));
    } finally {
        clearPassword();
    }
}

From source file:org.springframework.data.mongodb.core.MongoClientFactoryBean.java

License:Apache License

@Override
protected Mongo createInstance() throws Exception {

    if (mongoClientOptions == null) {
        mongoClientOptions = MongoClientOptions.builder().build();
    }//from   w  w  w  . j  a  v a 2  s .  co  m

    if (credentials == null) {
        credentials = Collections.emptyList();
    }

    return createMongoClient();
}

From source file:org.springframework.data.mongodb.core.MongoClientOptionsFactoryBean.java

License:Apache License

@Override
protected MongoClientOptions createInstance() throws Exception {

    SocketFactory socketFactoryToUse = ssl
            ? (sslSocketFactory != null ? sslSocketFactory : SSLSocketFactory.getDefault())
            : this.socketFactory;

    return MongoClientOptions.builder() //
            .alwaysUseMBeans(this.alwaysUseMBeans) //
            .connectionsPerHost(this.connectionsPerHost) //
            .connectTimeout(connectTimeout) //
            .cursorFinalizerEnabled(cursorFinalizerEnabled) //
            .dbDecoderFactory(dbDecoderFactory) //
            .dbEncoderFactory(dbEncoderFactory) //
            .description(description) //
            .heartbeatConnectTimeout(heartbeatConnectTimeout) //
            .heartbeatFrequency(heartbeatFrequency) //
            .heartbeatSocketTimeout(heartbeatSocketTimeout) //
            .maxConnectionIdleTime(maxConnectionIdleTime) //
            .maxConnectionLifeTime(maxConnectionLifeTime) //
            .maxWaitTime(maxWaitTime) //
            .minConnectionsPerHost(minConnectionsPerHost) //
            .minHeartbeatFrequency(minHeartbeatFrequency) //
            .readPreference(readPreference) //
            .requiredReplicaSetName(requiredReplicaSetName) //
            .socketFactory(socketFactoryToUse) //
            .socketKeepAlive(socketKeepAlive) //
            .socketTimeout(socketTimeout) //
            .threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier) //
            .writeConcern(writeConcern).build();
}

From source file:org.springframework.integration.mongodb.rules.MongoDbAvailableRule.java

License:Apache License

@Override
public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
    return new Statement() {
        @Override//from w w  w .j a  v a  2  s.c om
        public void evaluate() throws Throwable {
            MongoDbAvailable mongoAvailable = method.getAnnotation(MongoDbAvailable.class);
            if (mongoAvailable != null) {
                try {
                    MongoClientOptions options = new MongoClientOptions.Builder().connectTimeout(100).build();
                    Mongo mongo = new MongoClient(ServerAddress.defaultHost(), options);
                    mongo.getDatabaseNames();
                } catch (Exception e) {
                    logger.warn("MongoDb is not available. Skipping the test: "
                            + target.getClass().getSimpleName() + "." + method.getName() + "()");
                    return;
                }
            }
            base.evaluate();
        }
    };
}

From source file:org.springframework.statemachine.buildtests.tck.mongodb.MongoDbRule.java

License:Apache License

@Override
public Statement apply(Statement base, Description description) {
    MongoClient client = null;//from w w  w . j  a  va  2 s .  c o m
    try {
        client = new MongoClient(new ServerAddress(), MongoClientOptions.builder().connectTimeout(50).build());
        client.getAddress();
    } catch (Exception e) {
        return super.apply(new Statement() {
            @Override
            public void evaluate() throws Throwable {
            }
        }, Description.EMPTY);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return super.apply(base, description);
}

From source file:org.teiid.resource.adapter.mongodb.MongoDBManagedConnectionFactory.java

License:Open Source License

@Override
@SuppressWarnings("serial")
public BasicConnectionFactory<MongoDBConnectionImpl> createConnectionFactory() throws ResourceException {
    if (this.remoteServerList == null) {
        throw new InvalidPropertyException(UTIL.getString("no_server")); //$NON-NLS-1$
    }//from w ww .j a  va2s  . c om
    if (this.database == null) {
        throw new InvalidPropertyException(UTIL.getString("no_database")); //$NON-NLS-1$
    }

    final List<ServerAddress> servers = getServers();
    if (servers != null) {
        //if options needed then use URL format
        final MongoClientOptions options = MongoClientOptions.builder().build();

        return new BasicConnectionFactory<MongoDBConnectionImpl>() {
            @Override
            public MongoDBConnectionImpl getConnection() throws ResourceException {
                MongoCredential credential = null;
                if (MongoDBManagedConnectionFactory.this.username != null
                        && MongoDBManagedConnectionFactory.this.password != null) {
                    credential = MongoCredential.createMongoCRCredential(
                            MongoDBManagedConnectionFactory.this.username,
                            MongoDBManagedConnectionFactory.this.database,
                            MongoDBManagedConnectionFactory.this.password.toCharArray());
                }
                return new MongoDBConnectionImpl(MongoDBManagedConnectionFactory.this.database, servers,
                        credential, options);
            }
        };
    }

    // Make connection using the URI format
    return new BasicConnectionFactory<MongoDBConnectionImpl>() {
        @Override
        public MongoDBConnectionImpl getConnection() throws ResourceException {
            try {
                return new MongoDBConnectionImpl(MongoDBManagedConnectionFactory.this.database,
                        getConnectionURI());
            } catch (UnknownHostException e) {
                throw new ResourceException(e);
            }
        }
    };

}

From source file:org.test.falcon.config.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.//from   w w  w.j  av  a  2  s .co  m
 *
 * @param options
 *            the options
 * @return the Mongo client
 * @throws UnknownHostException
 *             if the configured host is unknown
 */
public MongoClient createMongoClient(MongoClientOptions options) throws UnknownHostException {
    try {
        if (options == null) {
            options = MongoClientOptions.builder().build();
        }
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        String database = this.authenticationDatabase == null ? getMongoClientDatabase()
                : this.authenticationDatabase;
        credentials.add(MongoCredential.createCredential(this.username, database, this.password));
        String host = this.host == null ? "localhost" : this.host;
        int port = determinePort();
        return new MongoClient(Arrays.asList(new ServerAddress(host, port)), credentials, options);
    } finally {
        clearPassword();
    }
}

From source file:org.venice.piazza.servicecontroller.data.mongodb.accessors.MongoAccessor.java

License:Apache License

@PostConstruct
private void initialize() {
    try {//from   ww w  .j  a  va2 s .c  o  m
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        // Enable SSL if the `mongossl` Profile is enabled
        if (Arrays.stream(environment.getActiveProfiles()).anyMatch(env -> env.equalsIgnoreCase("mongossl"))) {
            builder.sslEnabled(true);
            builder.sslInvalidHostNameAllowed(true);
        }
        // If a username and password are provided, then associate these credentials with the connection
        if ((!StringUtils.isEmpty(DATABASE_USERNAME)) && (!StringUtils.isEmpty(DATABASE_CREDENTIAL))) {
            mongoClient = new MongoClient(new ServerAddress(DATABASE_HOST, DATABASE_PORT),
                    Arrays.asList(MongoCredential.createCredential(DATABASE_USERNAME, DATABASE_NAME,
                            DATABASE_CREDENTIAL.toCharArray())),
                    builder.threadsAllowedToBlockForConnectionMultiplier(mongoThreadMultiplier).build());
        } else {
            mongoClient = new MongoClient(new ServerAddress(DATABASE_HOST, DATABASE_PORT),
                    builder.threadsAllowedToBlockForConnectionMultiplier(mongoThreadMultiplier).build());
        }

    } catch (Exception exception) {
        LOGGER.error(String.format("Error connecting to MongoDB Instance. %s", exception.getMessage()),
                exception);

    }
}

From source file:org.wisdom.mongodb.MongoDBClient.java

License:Apache License

/**
 * Open a connection with a mongo database. 4 different configurations are currently available.
 *///  w w w.  j a va  2 s .c  om
private void openMongoConnection() {
    if (mongoClient != null) {
        mongoClient.close();
        mongoClient = null;
    }
    ServerAddress address = createAddress();
    MongoCredential credential = createMongoCredential();

    //TODO all the aspects should be configurable.
    final MongoClientOptions options = MongoClientOptions.builder().autoConnectRetry(autoConRetry)
            .connectTimeout(connectTimeout).maxAutoConnectRetryTime(maxAutoConnectRetryTime)
            .writeConcern(new WriteConcern(confMongoW, confMongoWTimeout, confMongoFsync, confMongoJ))
            .connectionsPerHost(connectionsPerHost).description(description).maxWaitTime(maxWaitTime).build();

    if (credential != null) {
        mongoClient = new MongoClient(address, Collections.singletonList(credential), options);
    } else {
        mongoClient = new MongoClient(address, options);
    }

}