/** * 生成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; }
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"); }
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; } }
/** * 生成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; }
/** * 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); } }
@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(); } } }
/** * 生成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; }
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); }
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); }
/** 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; }
@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); }
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); } } }
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); } } }
@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()); }
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; }
@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)); }
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 ) ); }
@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(); }
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()); } }
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()); } }
@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))); }
@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"))); }
@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"))); }
@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))); }
@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"))); }
@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"))); }
@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"))); }
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()); } }
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); } }
@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); }
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(); }
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); }
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; }
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"); }
@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())) )); }
@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()); }
/** * 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)); }
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()); }