Java Code Examples for com.mongodb.MongoClientOptions#Builder

The following examples show how to use com.mongodb.MongoClientOptions#Builder . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MongoLocalConfig.java    From bearchoke with Apache License 2.0 6 votes vote down vote up
@Bean
public MongoClient mongo() throws UnknownHostException {
    // location of db
    ServerAddress sa = new ServerAddress(
            environment.getProperty("mongodb.host"),
            environment.getProperty("mongodb.port", Integer.class)
    );

    // set optional default parameters here
    MongoClientOptions.Builder builder = MongoClientOptions.builder();

    // none yet

    MongoClientOptions options = builder.build();

    return new MongoClient(sa, options);
}
 
Example 2
Source File: MongoSchemaFactory.java    From calcite with Apache License 2.0 6 votes vote down vote up
public Schema create(SchemaPlus parentSchema, String name,
    Map<String, Object> operand) {
  final String host = (String) operand.get("host");
  final String database = (String) operand.get("database");
  final String authMechanismName = (String) operand.get("authMechanism");

  final MongoClientOptions.Builder options = MongoClientOptions.builder();

  final MongoCredential credential;
  if (authMechanismName != null) {
    credential = createCredential(operand);
  } else {
    credential = null;
  }

  return new MongoSchema(host, database, credential, options.build());
}
 
Example 3
Source File: MongoDB.java    From jelectrum with MIT License 6 votes vote down vote up
public MongoDB(Config config)
  throws Exception
{
  super(config);

  conf.require("mongo_db_host");
  conf.require("mongo_db_name");
  conf.require("mongo_db_connections_per_host");

  MongoClientOptions.Builder opts = MongoClientOptions.builder();
  opts.connectionsPerHost(conf.getInt("mongo_db_connections_per_host"));
  opts.threadsAllowedToBlockForConnectionMultiplier(100);
  opts.socketTimeout(3600000);


  mc = new MongoClient(new ServerAddress(conf.get("mongo_db_host")), opts.build());

  db = mc.getDB(conf.get("mongo_db_name"));


  open();
}
 
Example 4
Source File: AbstractConfiguration.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
protected void setOptions(final MongoClientOptions.Builder builder, final ConfigurationPropertyRetriever propertyRetriever) {

        final Map<String, Method> settingsMap = createSettingsMap();
        for (final Map.Entry<String, Method> entry : settingsMap.entrySet()) {
            final String value = propertyRetriever.get(entry.getKey());
            if (value == null) {
                continue;
            }

            final Method setterMethod = entry.getValue();
            try {
                setterMethod.invoke(builder, convertTo(entry.getValue().getParameterTypes()[0], value));
            } catch (InvocationTargetException | IllegalAccessException e) {
                LOG.error("Could not set options", e);
            }
        }
    }
 
Example 5
Source File: MongoSchemaFactory.java    From Quicksql with MIT License 6 votes vote down vote up
public Schema create(SchemaPlus parentSchema, String name,
    Map<String, Object> operand) {
  final String host = (String) operand.get("host");
  final Integer port = Integer.valueOf(operand.get("port").toString());
  final String database = (String) operand.get("dbName");
  final String authMechanismName = (String) operand.get("authMechanism");

  final MongoClientOptions.Builder options = MongoClientOptions.builder();

  final List<MongoCredential> credentials = new ArrayList<>();
  if (authMechanismName != null) {
    final MongoCredential credential = createCredentials(operand);
    credentials.add(credential);
  }

  return new MongoSchema(host, port,database, credentials, options.build());
}
 
Example 6
Source File: MongoConfig.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private MongoClientOptions extractMongoOptions(Map<String, String> properties) {
    MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
    String connectionsPerHost = properties.get(DBConstants.MongoDB.CONNECTIONS_PER_HOST);
    if (!DBUtils.isEmptyString(connectionsPerHost)) {
        builder.connectionsPerHost(Integer.parseInt(connectionsPerHost));
    }
    String maxWaitTime = properties.get(DBConstants.MongoDB.MAX_WAIT_TIME);
    if (!DBUtils.isEmptyString(maxWaitTime)) {
        builder.maxWaitTime(Integer.parseInt(maxWaitTime));
    }
    String connectTimeout = properties.get(DBConstants.MongoDB.CONNECT_TIMEOUT);
    if (!DBUtils.isEmptyString(connectTimeout)) {
        builder.connectTimeout(Integer.parseInt(connectTimeout));
    }
    String socketTimeout = properties.get(DBConstants.MongoDB.SOCKET_TIMEOUT);
    if (!DBUtils.isEmptyString(socketTimeout)) {
        builder.socketTimeout(Integer.parseInt(socketTimeout));
    }
    String threadsAllowedToBlockForConnectionMultiplier = properties.get(
            DBConstants.MongoDB.THREADS_ALLOWED_TO_BLOCK_CONN_MULTIPLIER);
    if (!DBUtils.isEmptyString(threadsAllowedToBlockForConnectionMultiplier)) {
        builder.threadsAllowedToBlockForConnectionMultiplier(
                Integer.parseInt(threadsAllowedToBlockForConnectionMultiplier));
    }
    return builder.build();
}
 
Example 7
Source File: MongoDBFactory.java    From database-transform-tool with Apache License 2.0 5 votes vote down vote up
/**
 * @decription 初始化配置
 * @author yi.zhang
 * @time 2017年6月2日 下午2:15:57
 */
public void init(String servers,String database,String schema,String username,String password) {
	try {
		List<ServerAddress> saddress = new ArrayList<ServerAddress>();
		if (servers != null && !"".equals(servers)) {
			for (String server : servers.split(",")) {
				String[] address = server.split(":");
				String ip = address[0];
				int port = 27017;
				if (address != null && address.length > 1) {
					port = Integer.valueOf(address[1]);
				}
				saddress.add(new ServerAddress(ip, port));
			}
		}
		MongoCredential credential = MongoCredential.createScramSha1Credential(username, database,password.toCharArray());
		List<MongoCredential> credentials = new ArrayList<MongoCredential>();
		credentials.add(credential);
		Builder builder = new MongoClientOptions.Builder();
		builder.maxWaitTime(MAX_WAIT_TIME);
		// 通过连接认证获取MongoDB连接
		MongoClient client = new MongoClient(saddress, credentials, builder.build());
		// 连接到数据库
		session = client.getDatabase(schema);
	} catch (Exception e) {
		logger.error("-----MongoDB Config init Error-----", e);
	}
}
 
Example 8
Source File: MongoDBConfiguration.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
public MongoClientOptions getOptions() {
    //if options needed then use URL format
    final MongoClientOptions.Builder builder = MongoClientOptions.builder();
    if (getSsl()) {
        builder.sslEnabled(true);
    }
    return builder.build();
}
 
Example 9
Source File: MongoConfiguration.java    From carts with Apache License 2.0 5 votes vote down vote up
@Bean
public MongoClientOptions optionsProvider() {
    MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();
    optionsBuilder.serverSelectionTimeout(10000);
    MongoClientOptions options = optionsBuilder.build();
    return options;
}
 
Example 10
Source File: MongoImpl.java    From tephra with MIT License 5 votes vote down vote up
@Override
public void create(JSONObject config) {
    String key = config.getString("key");
    if (mongos.containsKey(key))
        return;

    String schema = config.getString("schema");
    if (validator.isEmpty(schema))
        throw new NullPointerException("未设置schema值[" + config + "]!");

    JSONArray array = config.getJSONArray("ips");
    if (array == null || array.size() == 0)
        throw new NullPointerException("未设置ips值[" + config + "]!");

    String username = config.getString("username");
    String password = config.getString("password");
    boolean ssl = json.hasTrue(config, "ssl");
    MongoClientOptions.Builder builder = MongoClientOptions.builder().connectionsPerHost(maxActive).maxWaitTime(maxWait);
    List<MongoClient> list = new ArrayList<>();
    for (int i = 0; i < array.size(); i++)
        list.add(new MongoClient(new MongoClientURI("mongodb://" + username + ":" + password + "@" + array.getString(i)
                + "/" + schema + (ssl ? "?ssl=true" : ""), builder)));
    schemas.put(key, schema);
    mongos.put(key, list);

    if (logger.isDebugEnable())
        logger.debug("Mongo数据库[{}]初始化完成。", config);
}
 
Example 11
Source File: EclipseLinkConfiguration.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
private void configureClientOptions(final Map<String, Object> properties) {
    final MongoClientOptions.Builder builder = MongoClientOptions.builder();
    final String writeConcern = (String) properties.get(ECLIPSELINK_NOSQL_PROPERTY_MONGO_WRITE_CONCERN);
    final String readPreference = (String) properties.get(ECLIPSELINK_NOSQL_PROPERTY_MONGO_READ_PREFERENCE);

    if (writeConcern != null) {
        builder.writeConcern(WriteConcern.valueOf(writeConcern));
    }
    if (readPreference != null) {
        builder.readPreference(ReadPreference.valueOf(readPreference));
    }

    mongoClientOptions = builder.build();
}
 
Example 12
Source File: MongoDBDriver.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private static MongoClientURI getMongoURI( Properties connProps,
		MongoClientOptions.Builder clientOptionsBuilder ) throws Exception
{
       // check if explicitly indicated not to use URI, even if URI value exists
       Boolean ignoreURI = getBooleanPropValue( connProps, IGNORE_URI_PROP );
       if( ignoreURI != null && ignoreURI )
           return null;

       String uri = getStringPropValue( connProps, MONGO_URI_PROP );
       if( uri == null || uri.isEmpty() )
           return null;
       
       try
       {
		if ( clientOptionsBuilder != null )
		{
			return new MongoClientURI( uri, clientOptionsBuilder );
		}
		else
		{
			return new MongoClientURI( uri );
		}
       }
       catch( Exception ex )
       {
           // log and ignore
           getLogger().log( Level.INFO, Messages.bind( "Invalid Mongo Database URI: {0}", uri ), ex ); //$NON-NLS-1$
		throw ex;
       }
       //return null;
   }
 
Example 13
Source File: MongoDBDriver.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private static MongoClientOptions.Builder createDefaultClientOptionsBuilder(Properties connProperties )
  {
      Builder clientOptionsBuilder = new MongoClientOptions.Builder( );
if ( connProperties != null )
{
	if ( hasKeepSocketAlive( connProperties ) ) // need to change
												// setting,
												// as MongoDB default is
												// false
		clientOptionsBuilder.socketKeepAlive( true );

}
return clientOptionsBuilder;
  }
 
Example 14
Source File: MongoConfiguration.java    From orders with Apache License 2.0 5 votes vote down vote up
@Bean
public MongoClientOptions optionsProvider() {
    MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();
    optionsBuilder.serverSelectionTimeout(10000);
    MongoClientOptions options = optionsBuilder.build();
    return options;
}
 
Example 15
Source File: DefaultDataSourceCreater.java    From tangyuan2 with GNU General Public License v3.0 4 votes vote down vote up
private MongoClientOptions createOptions(Map<String, String> properties) {

		// builder.autoConnectRetry(false) // 是否重试机制

		MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
		// 是否保持长链接
		builder.socketKeepAlive(DSPropertyUtil.getBooleanValue(properties, "socketKeepAlive".toUpperCase(), true));
		// 长链接的最大等待时间
		builder.maxWaitTime(DSPropertyUtil.getIntValue(properties, "maxWaitTime".toUpperCase(), 1000 * 60 * 10));
		// 链接超时时间
		builder.connectTimeout(DSPropertyUtil.getIntValue(properties, "connectTimeout".toUpperCase(), 60 * 1000));
		// read数据超时时间
		builder.socketTimeout(DSPropertyUtil.getIntValue(properties, "socketTimeout".toUpperCase(), 60 * 1000));
		// 最近优先策略
		builder.readPreference(ReadPreference.primary());
		// 每个地址最大请求数
		builder.connectionsPerHost(DSPropertyUtil.getIntValue(properties, "connectionsPerHost".toUpperCase(), 30));
		// 一个socket最大的等待请求数
		builder.threadsAllowedToBlockForConnectionMultiplier(
				DSPropertyUtil.getIntValue(properties, "threadsAllowedToBlockForConnectionMultiplier".toUpperCase(), 50));

		if (properties.containsKey("minConnectionsPerHost".toUpperCase())) {
			builder.minConnectionsPerHost(Integer.parseInt(properties.get("minConnectionsPerHost".toUpperCase())));
		}

		if (properties.containsKey("maxConnectionIdleTime".toUpperCase())) {
			builder.maxConnectionIdleTime(Integer.parseInt(properties.get("maxConnectionIdleTime".toUpperCase())));
		}

		if (properties.containsKey("maxConnectionLifeTime".toUpperCase())) {
			builder.maxConnectionLifeTime(Integer.parseInt(properties.get("maxConnectionLifeTime".toUpperCase())));
		}

		if (properties.containsKey("minHeartbeatFrequency".toUpperCase())) {
			builder.minHeartbeatFrequency(Integer.parseInt(properties.get("minHeartbeatFrequency".toUpperCase())));
		}

		if (properties.containsKey("serverSelectionTimeout".toUpperCase())) {
			builder.serverSelectionTimeout(Integer.parseInt(properties.get("serverSelectionTimeout".toUpperCase())));
		}

		if (properties.containsKey("sslInvalidHostNameAllowed".toUpperCase())) {
			builder.sslInvalidHostNameAllowed(Boolean.parseBoolean(properties.get("sslInvalidHostNameAllowed".toUpperCase())));
		}

		if (properties.containsKey("sslEnabled".toUpperCase())) {
			builder.sslEnabled(Boolean.parseBoolean(properties.get("sslEnabled".toUpperCase())));
		}

		if (properties.containsKey("requiredReplicaSetName".toUpperCase())) {
			builder.requiredReplicaSetName(properties.get("requiredReplicaSetName".toUpperCase()));
		}

		// 这里统一设置,其他地方需要保持一致
		if (properties.containsKey("writeConcern".toUpperCase())) {
			String writeConcern = properties.get("writeConcern".toUpperCase());
			WriteConcern defaultWriteConcern = getWriteConcern(writeConcern);
			builder.writeConcern(getWriteConcern(writeConcern));
			this.defaultWriteConcern = defaultWriteConcern;
		}

		if (properties.containsKey("readConcern".toUpperCase())) {
			String readConcern = properties.get("readConcern".toUpperCase());
			builder.readConcern(getReadConcern(readConcern));
		}

		// alwaysUseMBeans = options.isAlwaysUseMBeans();
		// heartbeatFrequency = options.getHeartbeatFrequency();
		// minHeartbeatFrequency = options.getMinHeartbeatFrequency();
		// heartbeatConnectTimeout = options.getHeartbeatConnectTimeout();
		// heartbeatSocketTimeout = options.getHeartbeatSocketTimeout();
		// localThreshold = options.getLocalThreshold();
		// requiredReplicaSetName = options.getRequiredReplicaSetName();
		// dbDecoderFactory = options.getDbDecoderFactory();
		// dbEncoderFactory = options.getDbEncoderFactory();
		// socketFactory = options.getSocketFactory();
		// cursorFinalizerEnabled = options.isCursorFinalizerEnabled();

		return builder.build();
	}
 
Example 16
Source File: KunderaConfiguration.java    From jpa-unit with Apache License 2.0 4 votes vote down vote up
private void configureClientOptions(final Map<String, Object> properties) {
    final MongoClientOptions.Builder builder = MongoClientOptions.builder();
    setOptions(builder, (final String key) -> (String) properties.get(KUDERA_KEYS.get(key)));
    mongoClientOptions = builder.build();
}
 
Example 17
Source File: DataNucleusConfiguration.java    From jpa-unit with Apache License 2.0 4 votes vote down vote up
private void configureClientOptions(final Map<String, Object> properties) {
    final MongoClientOptions.Builder builder = MongoClientOptions.builder();
    setOptions(builder, (final String key) -> (String) properties.get(DATANUCLEUS_MONGODB_OPTIONS_PREFIX + "." + key));
    mongoClientOptions = builder.build();
}
 
Example 18
Source File: MongoDBControllerService.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected MongoClientOptions.Builder getClientOptions(final SSLContext sslContext) {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    builder.sslEnabled(true);
    builder.socketFactory(sslContext.getSocketFactory());
    return builder;
}
 
Example 19
Source File: AbstractMongoProcessor.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected Builder getClientOptions(final SSLContext sslContext) {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    builder.sslEnabled(true);
    builder.socketFactory(sslContext.getSocketFactory());
    return builder;
}
 
Example 20
Source File: IMongoClientOptionsHandler.java    From ymate-platform-v2 with Apache License 2.0 votes vote down vote up
MongoClientOptions.Builder handler(String dataSourceName);