Java 类com.mongodb.ServerAddress 实例源码

项目:myth    文件:MongoCoordinatorRepository.java   
/**
 * 生成mongoClientFacotryBean
 *
 * @param mythMongoConfig 配置信息
 * @return bean
 */
private MongoClientFactoryBean buildMongoClientFactoryBean(MythMongoConfig mythMongoConfig) {
    MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
    MongoCredential credential = MongoCredential.createScramSha1Credential(mythMongoConfig.getMongoUserName(),
            mythMongoConfig.getMongoDbName(),
            mythMongoConfig.getMongoUserPwd().toCharArray());
    clientFactoryBean.setCredentials(new MongoCredential[]{
            credential
    });
    List<String> urls = Splitter.on(",").trimResults().splitToList(mythMongoConfig.getMongoDbUrl());

    final ServerAddress[] sds = urls.stream().map(url -> {
        List<String> adds = Splitter.on(":").trimResults().splitToList(url);
        InetSocketAddress address = new InetSocketAddress(adds.get(0), Integer.parseInt(adds.get(1)));
        return new ServerAddress(address);
    }).collect(Collectors.toList()).toArray(new ServerAddress[]{});

    clientFactoryBean.setReplicaSetSeeds(sds);
    return clientFactoryBean;
}
项目:QDrill    文件:MongoTestSuit.java   
private static void setup() throws UnknownHostException, IOException {
  IMongoCmdOptions cmdOptions = new MongoCmdOptionsBuilder().verbose(false)
      .enableAuth(authEnabled).build();

  IMongodConfig mongodConfig = new MongodConfigBuilder()
      .version(Version.Main.PRODUCTION)
      .net(new Net(LOCALHOST, MONGOS_PORT, Network.localhostIsIPv6()))
      .cmdOptions(cmdOptions).build();

  IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaults(
      Command.MongoD).build();
  mongodExecutable = MongodStarter.getInstance(runtimeConfig).prepare(
      mongodConfig);
  mongod = mongodExecutable.start();
  mongoClient = new MongoClient(new ServerAddress(LOCALHOST, MONGOS_PORT));
  createDbAndCollections(EMPLOYEE_DB, EMPINFO_COLLECTION, "employee_id");
  createDbAndCollections(EMPLOYEE_DB, SCHEMA_CHANGE_COLLECTION, "field_2");
}
项目:athena    文件:FeatureDatabaseMgmtManager.java   
public boolean connectToDatabaseCluster(final List<String> seeds) {
    try {
        List<ServerAddress> seedList = new ArrayList<>();
        for (String ip : seeds) {
            seedList.add(new ServerAddress(ip, MONGO_PORT));
        }
        mongoClient = new MongoClient(seedList);
        mongoDatabase = mongoClient.getDatabase("featureStore");
        dbCollectionList = getCollectionList(mongoDatabase);
        log.info("Connect to database cluster successfully!!");

        return true;
    } catch (Exception e) {
        log.warn(e.getMessage());
        return false;
    }
}
项目:happylifeplat-transaction    文件:MongoTransactionRecoverRepository.java   
/**
 * 生成mongoClientFacotryBean
 *
 * @param config 配置信息
 * @return bean
 */
private MongoClientFactoryBean buildMongoClientFactoryBean(TxMongoConfig config) {
    MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
    MongoCredential credential = MongoCredential.createScramSha1Credential(config.getMongoUserName(),
            config.getMongoDbName(),
            config.getMongoUserPwd().toCharArray());
    clientFactoryBean.setCredentials(new MongoCredential[]{
            credential
    });
    List<String> urls = Splitter.on(",").trimResults().splitToList(config.getMongoDbUrl());
    final ServerAddress[] serverAddresses = urls.stream().filter(Objects::nonNull)
            .map(url -> {
                List<String> adds = Splitter.on(":").trimResults().splitToList(url);
                return new ServerAddress(adds.get(0), Integer.valueOf(adds.get(1)));
            }).collect(Collectors.toList()).toArray(new ServerAddress[urls.size()]);

    clientFactoryBean.setReplicaSetSeeds(serverAddresses);
    return clientFactoryBean;
}
项目:dragoman    文件:IsMongoConnected.java   
/**
 * Check that we can talk to the configured MongoDB instance.
 *
 * @return a {@link Result} with details of whether this check was successful or not
 * @throws Exception not thrown, any failure to perform the check results in a failed {@link
 *     Result}
 */
@Override
protected Result check() throws Exception {
  MongoClient mongoClient = mongoProvider.provide();

  List<ServerAddress> serverAddresses = mongoClient.getSettings().getClusterSettings().getHosts();
  String address =
      serverAddresses.stream().map(ServerAddress::toString).collect(Collectors.joining(","));

  try {
    // any read will suffice to prove connectivity
    mongoClient.getDatabase("xyz");
    return Result.healthy("Connected to MongoDB at " + address);
  } catch (Exception ex) {
    return Result.unhealthy("Cannot connect to MongoDB at " + address);
  }
}
项目:nitrite-database    文件:BaseMongoBenchMark.java   
@Override
public void beforeTest() {
    final MongoCredential credential =
            MongoCredential.createCredential("bench", "benchmark", "bench".toCharArray());
    ServerAddress serverAddress = new ServerAddress("127.0.0.1", 27017);
    mongoClient = new MongoClient(serverAddress, new ArrayList<MongoCredential>() {{ add(credential); }});
    db = mongoClient.getDatabase("benchmark");

    Person[] personList = testHelper.loadData();
    documents = new ArrayList<>();
    ObjectMapper objectMapper = new ObjectMapper();

    for (Person person : personList) {
        StringWriter writer = new StringWriter();
        try {
            objectMapper.writeValue(writer, person);
            Document document = Document.parse(writer.toString());
            documents.add(document);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
项目:happylifeplat-tcc    文件:MongoCoordinatorRepository.java   
/**
 * 生成mongoClientFacotryBean
 *
 * @param tccMongoConfig 配置信息
 * @return bean
 */
private MongoClientFactoryBean buildMongoClientFactoryBean(TccMongoConfig tccMongoConfig) {
    MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
    MongoCredential credential = MongoCredential.createScramSha1Credential(tccMongoConfig.getMongoUserName(),
            tccMongoConfig.getMongoDbName(),
            tccMongoConfig.getMongoUserPwd().toCharArray());
    clientFactoryBean.setCredentials(new MongoCredential[]{
            credential
    });
    List<String> urls = Splitter.on(",").trimResults().splitToList(tccMongoConfig.getMongoDbUrl());
    ServerAddress[] sds = new ServerAddress[urls.size()];
    for (int i = 0; i < sds.length; i++) {
        List<String> adds = Splitter.on(":").trimResults().splitToList(urls.get(i));
        InetSocketAddress address = new InetSocketAddress(adds.get(0), Integer.parseInt(adds.get(1)));
        sds[i] = new ServerAddress(address);
    }
    clientFactoryBean.setReplicaSetSeeds(sds);
    return clientFactoryBean;
}
项目:KernelHive    文件:DataManager.java   
public DataAddress uploadData(String data, DataAddress dataAddress) throws UnknownHostException {
      ServerAddress server = new ServerAddress(dataAddress.hostname, dataAddress.port);
      GridFS database = connectToDatabase(server);

      logger.info("Database connected");

      GridFSInputFile file = database.createFile(data.getBytes());
      int newID = getNextId(database);
      logger.info("Got new id for uploaded file: " + newID);
file.setFilename(String.valueOf(newID));
      file.put("_id", newID);
      file.save();

      logger.info("after save");

      return new DataAddress(dataAddress.hostname, dataAddress.port, newID);
  }
项目:polymorphia    文件:Tutorial.java   
public static void main(String[] args) {
    MongoClientOptions mongoClientOptions = new MongoClientOptions.Builder().codecRegistry(getCodecRegistry()).build();
    MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), mongoClientOptions);

    MongoDatabase database = mongoClient.getDatabase("tutorial");
    MongoCollection<PolymorphicPojo> collection = database.getCollection("entities").withDocumentClass(PolymorphicPojo.class);

    // create some pojo
    Pojo pojo = new Pojo();
    pojo.setName("A nice name");
    pojo.setPojos(Arrays.asList(new SubPojo(42), new SubPojo(48)));

    // insert into db
    collection.insertOne(pojo);

    // read from db
    PolymorphicPojo foundPojo = collection.find(Filters.eq("_id", pojo.getId())).first();

    // output
    LOGGER.debug("Found pojo {}", foundPojo);
}
项目:botmill-core    文件:MongoDBAdapter.java   
/** The mongodb ops. */

    /* (non-Javadoc)
     * @see co.aurasphere.botmill.core.datastore.adapter.DataAdapter#setup()
     */
    public void setup() {

        MongoCredential credential = MongoCredential.createCredential(
                ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.username"), 
                ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.database"), 
                ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.password").toCharArray());
        ServerAddress serverAddress = new ServerAddress(
                ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.server"), 
                Integer.valueOf(ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.port")));
        MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(credential));
        SimpleMongoDbFactory simpleMongoDbFactory = new SimpleMongoDbFactory(mongoClient, ConfigurationUtils.getEncryptedConfiguration().getProperty("mongodb.database"));

        MongoTemplate mongoTemplate = new MongoTemplate(simpleMongoDbFactory);
        this.source = (MongoOperations) mongoTemplate;
    }
项目:leopard    文件:MongoImpl.java   
@SuppressWarnings("deprecation")
public void init() {
    String[] list = server.split(":");
    String host = list[0];
    int port = Integer.parseInt(list[1]);
    int connectTimeout = 1000 * 60;
    MongoClientOptions options = new MongoClientOptions.Builder().connectTimeout(connectTimeout).build();
    client = new MongoClient(new ServerAddress(host, port), options);
    this.db = client.getDB(this.database);
    if (username != null && username.length() > 0) {
        if (password != null && password.length() > 0) {
            db.addUser(username, password.toCharArray());
        }
    }
    this.collection = db.getCollection(collectionName);
}
项目:konker-platform    文件:MongoAuditConfig.java   
public MongoAuditConfig() {
    Map<String, Object> defaultMap = new HashMap<>();
    defaultMap.put("mongoAudit.hostname", "localhost");
    defaultMap.put("mongoAudit.port", 27017);
    defaultMap.put("mongoAudit.username", "");
    defaultMap.put("mongoAudit.password", "");
    Config defaultConf = ConfigFactory.parseMap(defaultMap);

    Config config = ConfigFactory.load().withFallback(defaultConf);
    setPort(config.getInt("mongoAudit.port"));
    setUsername(config.getString("mongoAudit.username"));
    setPassword(config.getString("mongoAudit.password"));

    List<String> seedList = Optional.ofNullable(config.getString("mongoAudit.hostname")).isPresent() ?
            Arrays.asList(config.getString("mongoAudit.hostname").split(",")) : null;

    for (String seed : seedList) {
        try {
            hostname.add(new ServerAddress(seed, port));
        } catch (Exception e) {
            LOG.error("Error constructing mongo factory", e);
        }
    }

}
项目:konker-platform    文件:MongoBillingConfig.java   
public MongoBillingConfig() {
    Map<String, Object> defaultMap = new HashMap<>();
    defaultMap.put("mongoBilling.hostname", "localhost");
    defaultMap.put("mongoBilling.port", 27017);
    defaultMap.put("mongoBilling.username", "");
    defaultMap.put("mongoBilling.password", "");
    Config defaultConf = ConfigFactory.parseMap(defaultMap);

    Config config = ConfigFactory.load().withFallback(defaultConf);
    setPort(config.getInt("mongoBilling.port"));
    setUsername(config.getString("mongoBilling.username"));
    setPassword(config.getString("mongoBilling.password"));

    List<String> seedList = Optional.ofNullable(config.getString("mongoBilling.hostname")).isPresent() ?
            Arrays.asList(config.getString("mongoBilling.hostname").split(",")) : null;

    for (String seed : seedList) {
        try {
            hostname.add(new ServerAddress(seed, port));
        } catch (Exception e) {
            LOG.error("Error constructing mongo factory", e);
        }
    }

}
项目:LuckPerms    文件:MongoDao.java   
@Override
public void init() {
    MongoCredential credential = null;
    if (!Strings.isNullOrEmpty(this.configuration.getUsername())) {
        credential = MongoCredential.createCredential(
                this.configuration.getUsername(),
                this.configuration.getDatabase(),
                Strings.isNullOrEmpty(this.configuration.getPassword()) ? null : this.configuration.getPassword().toCharArray()
        );
    }

    String[] addressSplit = this.configuration.getAddress().split(":");
    String host = addressSplit[0];
    int port = addressSplit.length > 1 ? Integer.parseInt(addressSplit[1]) : 27017;
    ServerAddress address = new ServerAddress(host, port);

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

    this.database = this.mongoClient.getDatabase(this.configuration.getDatabase());
}
项目:djigger    文件:MongoConnection.java   
public MongoDatabase connect(String host, int port, String user, String password) {
    Builder o = MongoClientOptions.builder().serverSelectionTimeout(3000);

    String databaseName = "djigger";

    List<MongoCredential> credentials = new ArrayList<>();
    if (user != null && password != null && !user.trim().isEmpty() && !password.trim().isEmpty()) {
        credentials.add(MongoCredential.createCredential(user, databaseName, password.toCharArray()));
    }

    mongoClient = new MongoClient(new ServerAddress(host,port), credentials, o.build());

    // call this method to check if the connection succeeded as the mongo client lazy loads the connection 
    mongoClient.getAddress();

    db = mongoClient.getDatabase(databaseName);
    return db;
}
项目:spring-morphia    文件:MongoClientConfiguration.java   
@Bean
@Profile("!test")
public MongoClient mongoClient(final MongoSettings mongoSettings) throws Exception {
    final List<ServerAddress> serverAddresses = mongoSettings.getServers()
            .stream()
            .map((MongoServer input) -> new ServerAddress(input.getName(), input.getPort()))
            .collect(toList());

    final MongoCredential credential = MongoCredential.createCredential(
            mongoSettings.getUsername(),
            mongoSettings.getDatabase(),
            mongoSettings.getPassword().toCharArray());

    return new MongoClient(
            serverAddresses, newArrayList(credential));
}
项目:analytics4github    文件:MondoDbOpenshiftConfig.java   
private MongoTemplate getMongoTemplate(String host, int port,
                                       String authenticationDB,//TODO: is it redundant ?
                                       String database,
                                       String user, char[] password)
        throws UnknownHostException {
    return new MongoTemplate(
            new SimpleMongoDbFactory(
                    new MongoClient(
                            new ServerAddress(host, port),
                            Collections.singletonList(
                                    MongoCredential.createCredential(
                                            user,
                                            authenticationDB,
                                            password
                                    )
                            )
                    ),
                    database
            )
    );
}
项目:spring-content    文件:HypermediaConfigurationTest.java   
@Override
public MongoDbFactory mongoDbFactory() throws Exception {

    if (System.getenv("spring_eg_content_mongo_host") != null) {
        String host = System.getenv("spring_eg_content_mongo_host");
        String port = System.getenv("spring_eg_content_mongo_port");
        String username = System.getenv("spring_eg_content_mongo_username");
        String password = System.getenv("spring_eg_content_mongo_password");

         // Set credentials      
        MongoCredential credential = MongoCredential.createCredential(username, getDatabaseName(), password.toCharArray());
        ServerAddress serverAddress = new ServerAddress(host, Integer.parseInt(port));

        // Mongo Client
        MongoClient mongoClient = new MongoClient(serverAddress,Arrays.asList(credential)); 

        // Mongo DB Factory
        return new SimpleMongoDbFactory(mongoClient, getDatabaseName());
    }
    return super.mongoDbFactory();
}
项目:spring-content    文件:RestConfigurationTest.java   
@Override
public MongoDbFactory mongoDbFactory() throws Exception {

    if (System.getenv("spring_eg_content_mongo_host") != null) {
        String host = System.getenv("spring_eg_content_mongo_host");
        String port = System.getenv("spring_eg_content_mongo_port");
        String username = System.getenv("spring_eg_content_mongo_username");
        String password = System.getenv("spring_eg_content_mongo_password");

         // Set credentials      
        MongoCredential credential = MongoCredential.createCredential(username, getDatabaseName(), password.toCharArray());
        ServerAddress serverAddress = new ServerAddress(host, Integer.parseInt(port));

        // Mongo Client
        MongoClient mongoClient = new MongoClient(serverAddress,Arrays.asList(credential)); 

        // Mongo DB Factory
        return new SimpleMongoDbFactory(mongoClient, getDatabaseName());
    }
    return super.mongoDbFactory();
}
项目:jpa-unit    文件:EclipseLinkConfiguration.java   
private void configureServerAddresses(final Map<String, Object> properties) {
    final String ports = (String) properties.get(ECLIPSELINK_NOSQL_PROPERTY_MONGO_PORT);
    final String hosts = (String) properties.get(ECLIPSELINK_NOSQL_PROPERTY_MONGO_HOST);
    final String[] hostList = hosts != null ? hosts.split(",") : new String[] {};
    final String[] portList = ports != null ? ports.split(",") : new String[] {};

    serverAddresses = new ArrayList<>();
    for (int i = 0; i < hostList.length; i++) {
        int port;
        if (i >= portList.length) {
            port = ServerAddress.defaultPort();
        } else {
            port = Integer.valueOf(portList[i].trim());
        }
        serverAddresses.add(new ServerAddress(hostList[i].trim(), port));
    }
    if (serverAddresses.isEmpty()) {
        serverAddresses.add(new ServerAddress());
    }
}
项目:jpa-unit    文件:KunderaConfiguration.java   
private void configureServerAddresses(final Map<String, Object> properties) {
    final String port = (String) properties.get(KUNDERA_PORT);
    final String hosts = (String) properties.get(KUNDERA_NODES);

    final String[] hostList = hosts != null ? hosts.split(",") : new String[] {};
    final Integer defaultPort = port != null ? Integer.valueOf(port) : 27017;

    serverAddresses = new ArrayList<>();
    for (int i = 0; i < hostList.length; i++) {
        final HostAndPort hostAndPort = HostAndPort.fromString(hostList[i].trim());
        serverAddresses.add(new ServerAddress(hostAndPort.getHost(), hostAndPort.getPortOrDefault(defaultPort)));
    }
    if (serverAddresses.isEmpty()) {
        serverAddresses.add(new ServerAddress());
    }
}
项目:jpa-unit    文件:KunderaConfigurationTest.java   
@Test
public void testHost() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    properties.put("kundera.keyspace", "foo");
    properties.put("kundera.nodes", "www.example.com, 192.0.2.2:123, [2001:db8::ff00:42:8329]:27027, www2.example.com");
    properties.put("kundera.port", "27016");

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final List<ServerAddress> serverAddresses = configuration.getServerAddresses();
    assertThat(serverAddresses, notNullValue());
    assertThat(serverAddresses.size(), equalTo(4));
    assertThat(serverAddresses, hasItems(new ServerAddress("www.example.com", 27016), new ServerAddress("192.0.2.2", 123),
            new ServerAddress("2001:db8::ff00:42:8329", 27027), new ServerAddress("www2.example.com", 27016)));
}
项目:jpa-unit    文件:KunderaConfigurationTest.java   
@Test
public void testDefaultHost() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    properties.put("kundera.keyspace", "foo");

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final List<ServerAddress> serverAddresses = configuration.getServerAddresses();
    assertThat(serverAddresses, notNullValue());
    assertThat(serverAddresses.size(), equalTo(1));
    assertThat(serverAddresses, hasItems(new ServerAddress("127.0.0.1")));
}
项目:jpa-unit    文件:DataNucleusConfigurationTest.java   
@Test
public void testDefaultHost() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    properties.put("datanucleus.ConnectionURL", "mongodb:/foo");

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final List<ServerAddress> serverAddresses = configuration.getServerAddresses();
    assertThat(serverAddresses, notNullValue());
    assertThat(serverAddresses.size(), equalTo(1));
    assertThat(serverAddresses, hasItems(new ServerAddress("127.0.0.1")));
}
项目:jpa-unit    文件:HibernateOgmConfigurationTest.java   
@Test
public void testHost() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    properties.put("hibernate.ogm.datastore.database", "foo");
    properties.put("hibernate.ogm.datastore.host",
            "www.example.com, www2.example.com:123, 192.0.2.1, 192.0.2.2:123, 2001:db8::ff00:42:8329, [2001:db8::ff00:42:8329]:123 ");

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final List<ServerAddress> serverAddresses = configuration.getServerAddresses();
    assertThat(serverAddresses, notNullValue());
    assertThat(serverAddresses.size(), equalTo(6));
    assertThat(serverAddresses,
            hasItems(new ServerAddress("www.example.com"), new ServerAddress("www2.example.com", 123), new ServerAddress("192.0.2.1"),
                    new ServerAddress("192.0.2.2", 123), new ServerAddress("2001:db8::ff00:42:8329"),
                    new ServerAddress("[2001:db8::ff00:42:8329]", 123)));
}
项目:jpa-unit    文件:HibernateOgmConfigurationTest.java   
@Test
public void testDefaultHost() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    properties.put("hibernate.ogm.datastore.database", "foo");

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final List<ServerAddress> serverAddresses = configuration.getServerAddresses();
    assertThat(serverAddresses, notNullValue());
    assertThat(serverAddresses.size(), equalTo(1));
    assertThat(serverAddresses, hasItems(new ServerAddress("127.0.0.1")));
}
项目:jpa-unit    文件:EclipseLinkConfigurationTest.java   
@Test
public void testHost() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    properties.put("eclipselink.nosql.property.mongo.db", "foo");
    properties.put("eclipselink.nosql.property.mongo.host", "www.example.com, 192.0.2.2, 2001:db8::ff00:42:8329, www2.example.com");
    properties.put("eclipselink.nosql.property.mongo.port", "27016, 27001, 123");

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final List<ServerAddress> serverAddresses = configuration.getServerAddresses();
    assertThat(serverAddresses, notNullValue());
    assertThat(serverAddresses.size(), equalTo(4));
    assertThat(serverAddresses, hasItems(new ServerAddress("www.example.com", 27016), new ServerAddress("192.0.2.2", 27001),
            new ServerAddress("2001:db8::ff00:42:8329", 123), new ServerAddress("www2.example.com")));
}
项目:jpa-unit    文件:EclipseLinkConfigurationTest.java   
@Test
public void testDefaultHost() {
    // GIVEN
    final Map<String, Object> properties = new HashMap<>();
    when(descriptor.getProperties()).thenReturn(properties);

    properties.put("eclipselink.nosql.property.mongo.db", "foo");

    final ConfigurationFactory factory = new ConfigurationFactoryImpl();

    // WHEN
    final Configuration configuration = factory.createConfiguration(descriptor);

    // THEN
    assertThat(configuration, notNullValue());

    final List<ServerAddress> serverAddresses = configuration.getServerAddresses();
    assertThat(serverAddresses, notNullValue());
    assertThat(serverAddresses.size(), equalTo(1));
    assertThat(serverAddresses, hasItems(new ServerAddress("127.0.0.1")));
}
项目:mdw    文件:DatabaseAccess.java   
private static synchronized void openMongoDbClient() {
    if (mongoClient == null) {
        String mongoHost = PropertyManager.getProperty(PropertyNames.MDW_MONGODB_HOST);
        int mongoPort = PropertyManager.getIntegerProperty(PropertyNames.MDW_MONGODB_PORT, 27017);
        int maxConnections = PropertyManager.getIntegerProperty(PropertyNames.MDW_MONGODB_POOLSIZE, PropertyManager.getIntegerProperty(PropertyNames.MDW_DB_POOLSIZE, 100));

        MongoClientOptions.Builder options = MongoClientOptions.builder();
        options.socketKeepAlive(true);
        if (maxConnections > 100)  // MongoClient default is 100 max connections per host
            options.connectionsPerHost(maxConnections);

        mongoClient = new MongoClient(new ServerAddress(mongoHost, mongoPort), options.build());

        for (String name : mongoClient.getDatabase("mdw").listCollectionNames()) {
            createMongoDocIdIndex(name);
        }
        LoggerUtil.getStandardLogger().info(mongoClient.getMongoClientOptions().toString());
    }
}
项目:light-task-scheduler    文件:MongoFactoryBean.java   
private void replSeeds(String... serverAddresses) {
    try {
        replicaSetSeeds.clear();
        for (String addr : serverAddresses) {
            String[] a = addr.split(":");
            String host = a[0];
            if (a.length > 2) {
                throw new IllegalArgumentException("Invalid Server Address : " + addr);
            } else if (a.length == 2) {
                replicaSetSeeds.add(new ServerAddress(host, Integer.parseInt(a[1])));
            } else {
                replicaSetSeeds.add(new ServerAddress(host));
            }
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
}
项目:timpani    文件:MongoDBSecurityDefinitionStore.java   
@Override
public CompletableFuture<SecurityDefinitionStore> open() {
  List<ServerAddress> hostList =
      Arrays.stream(hosts).map(h -> new ServerAddress(h)).collect(Collectors.toList());
  ClusterSettings clusterSettings = ClusterSettings.builder().hosts(hostList).build();
  MongoClientSettings settings =
      MongoClientSettings.builder().clusterSettings(clusterSettings).build();
  mongoClient = MongoClients.create(settings);

  database = mongoClient.getDatabase(DATABASE_NAME);
  collection = database.getCollection(SECDEF_COLLECTION_NAME);

  // In the case of MongoDB, open is synchronous because it doesn't
  // actually communicate with the server until a query is invoked.
  return CompletableFuture.completedFuture(this);
}
项目:navi    文件:NaviMongoListDriver.java   
public NaviMongoListDriver(ServerUrlUtil.ServerUrl server, String auth, NaviPoolConfig poolConfig) throws NumberFormatException, MongoException, UnknownHostException {
    super(server, auth, poolConfig);

    String masterUrl = null;
    if (server.getHost() != null && server.getPort() != 0)
        masterUrl = server.getHost() + ":" + server.getPort();
    List<ServerAddress> addresslist = new ArrayList<>();
    // 找到master
    List<String> listHostPorts = new ArrayList<>();
    String[] hostPorts = server.getUrl().split(",");
    Collections.addAll(listHostPorts, hostPorts);
    for (int i = 0; i < listHostPorts.size(); i++) {
        if (listHostPorts.get(0).equals(masterUrl))
            break;
        listHostPorts.add(listHostPorts.remove(0));
    }
    for (String hostPort : listHostPorts) {
        addresslist.add(new ServerAddress(hostPort));
    }

    mongo = new Mongo(addresslist, getMongoOptions(poolConfig));
    // mongo.setReadPreference(ReadPreference.SECONDARY);

    startIdleConnCheck();
}
项目:step    文件:MongoClientSession.java   
protected void initMongoClient() {
    String host = configuration.getProperty("db.host");
    Integer port = configuration.getPropertyAsInteger("db.port",27017);
    String user = configuration.getProperty("db.username");
    String pwd = configuration.getProperty("db.password");

    db = configuration.getProperty("db.database","step");

    ServerAddress address = new ServerAddress(host, port);
    List<MongoCredential> credentials = new ArrayList<>();
    if(user!=null) {
        MongoCredential credential = MongoCredential.createMongoCRCredential(user, db, pwd.toCharArray());
        credentials.add(credential);
    }

    mongoClient = new MongoClient(address, credentials);
}
项目:drill    文件:MongoStoragePlugin.java   
public synchronized MongoClient getClient(List<ServerAddress> addresses) {
  // Take the first replica from the replicated servers
  final ServerAddress serverAddress = addresses.get(0);
  final MongoCredential credential = clientURI.getCredentials();
  String userName = credential == null ? null : credential.getUserName();
  MongoCnxnKey key = new MongoCnxnKey(serverAddress, userName);
  MongoClient client = addressClientMap.getIfPresent(key);
  if (client == null) {
    if (credential != null) {
      List<MongoCredential> credentialList = Arrays.asList(credential);
      client = new MongoClient(addresses, credentialList, clientURI.getOptions());
    } else {
      client = new MongoClient(addresses, clientURI.getOptions());
    }
    addressClientMap.put(key, client);
    logger.debug("Created connection to {}.", key.toString());
    logger.debug("Number of open connections {}.", addressClientMap.size());
  }
  return client;
}
项目:drill    文件:MongoTestSuit.java   
private static void setup() throws UnknownHostException, IOException {
  IMongoCmdOptions cmdOptions = new MongoCmdOptionsBuilder().verbose(false)
      .enableAuth(authEnabled).build();

  IMongodConfig mongodConfig = new MongodConfigBuilder()
      .version(Version.Main.PRODUCTION)
      .net(new Net(LOCALHOST, MONGOS_PORT, Network.localhostIsIPv6()))
      .cmdOptions(cmdOptions).build();

  IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaults(
      Command.MongoD).build();
  mongodExecutable = MongodStarter.getInstance(runtimeConfig).prepare(
      mongodConfig);
  mongod = mongodExecutable.start();
  mongoClient = new MongoClient(new ServerAddress(LOCALHOST, MONGOS_PORT));
  createDbAndCollections(EMPLOYEE_DB, EMPINFO_COLLECTION, "employee_id");
  createDbAndCollections(EMPLOYEE_DB, SCHEMA_CHANGE_COLLECTION, "field_2");
  createDbAndCollections(EMPLOYEE_DB, EMPTY_COLLECTION, "field_2");
  createDbAndCollections(DATATYPE_DB, DATATYPE_COLLECTION, "_id");
}
项目:uppercore    文件:MongoDb.java   
@Override
public Connection connect(String database, String host, int port, String user, String password) {
    return new ImplConnection(database, new MongoClient(
            new ServerAddress(host, port),
            singletonList(createCredential(user, database, password.toCharArray()))
    ));
}
项目:cas-5.1.0    文件:MongoDbCloudConfigBootstrapConfiguration.java   
@Override
public Mongo mongo() throws Exception {
    final MongoCredential credential = MongoCredential.createCredential(
            mongoClientUri().getUsername(),
            getDatabaseName(),
            mongoClientUri().getPassword());

    final String hostUri = mongoClientUri().getHosts().get(0);
    final String[] host = hostUri.split(":");
    return new MongoClient(new ServerAddress(
            host[0], host.length > 1 ? Integer.parseInt(host[1]) : DEFAULT_PORT),
            Collections.singletonList(credential),
            mongoClientOptions());
}
项目:cas-5.1.0    文件:Beans.java   
/**
 * New mongo db client.
 *
 * @param mongo the mongo
 * @return the mongo
 */
public static Mongo newMongoDbClient(final AbstractMongoInstanceProperties mongo) {
    return new MongoClient(new ServerAddress(
            mongo.getHost(),
            mongo.getPort()),
            Collections.singletonList(
                    MongoCredential.createCredential(
                            mongo.getUserId(),
                            mongo.getDatabaseName(),
                            mongo.getPassword().toCharArray())),
            newMongoDbClientOptions(mongo));
}
项目:helper    文件:MongoWrapper.java   
public MongoWrapper(@Nonnull MongoDatabaseCredentials credentials) {
    MongoCredential mongoCredential = MongoCredential.createCredential(
            credentials.getUsername(),
            credentials.getDatabase(),
            credentials.getPassword().toCharArray()
    );

    client = new MongoClient(
            new ServerAddress(credentials.getAddress(), credentials.getPort()),
            Collections.singletonList(mongoCredential)
    );
    database = client.getDatabase(credentials.getDatabase());
    morphia = new Morphia();
    morphiaDatastore = morphia.createDatastore(client, credentials.getDatabase());
}