/** * 生成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; }
/** * 生成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; }
@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; }
/** 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; }
@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(); }
@Test public void testMongoCredentialsAreEmptyIfUsernameIsNotConfigured() { // GIVEN final Map<String, Object> properties = new HashMap<>(); when(descriptor.getProperties()).thenReturn(properties); properties.put("kundera.keyspace", "foo"); properties.put("kundera.password", "pass"); final ConfigurationFactory factory = new ConfigurationFactoryImpl(); // WHEN final Configuration configuration = factory.createConfiguration(descriptor); // THEN assertThat(configuration, notNullValue()); final List<MongoCredential> credentials = configuration.getCredentials(); assertThat(credentials, notNullValue()); assertTrue(credentials.isEmpty()); }
@Test public void testMongoCredentialsAreEmptyIfUsernameIsNotConfigured() { // GIVEN final Map<String, Object> properties = new HashMap<>(); when(descriptor.getProperties()).thenReturn(properties); properties.put("datanucleus.ConnectionURL", "mongodb:/foo"); properties.put("datanucleus.ConnectionPassword", "foo"); final ConfigurationFactory factory = new ConfigurationFactoryImpl(); // WHEN final Configuration configuration = factory.createConfiguration(descriptor); // THEN assertThat(configuration, notNullValue()); final List<MongoCredential> credentials = configuration.getCredentials(); assertThat(credentials, notNullValue()); assertTrue(credentials.isEmpty()); }
@Test public void testMongoCredentialsAreEmptyIfUsernameIsNotConfigured() { // 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.password", "foo"); final ConfigurationFactory factory = new ConfigurationFactoryImpl(); // WHEN final Configuration configuration = factory.createConfiguration(descriptor); // THEN assertThat(configuration, notNullValue()); final List<MongoCredential> credentials = configuration.getCredentials(); assertThat(credentials, notNullValue()); assertTrue(credentials.isEmpty()); }
@Test public void testMongoCredentialsAreEmptyIfUsernameIsNotConfigured() { // 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.password", "pass"); final ConfigurationFactory factory = new ConfigurationFactoryImpl(); // WHEN final Configuration configuration = factory.createConfiguration(descriptor); // THEN assertThat(configuration, notNullValue()); final List<MongoCredential> credentials = configuration.getCredentials(); assertThat(credentials, notNullValue()); assertTrue(credentials.isEmpty()); }
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; }
@Override public void activateService() throws Exception { loadConfiguration(); // Create Mongo driver and open the database MongoClientOptions options = MongoClientOptions.builder().writeConcern( writeConcern ).build(); if( username.isEmpty() ) { mongo = new MongoClient( serverAddresses, options ); } else { MongoCredential credential = MongoCredential.createMongoCRCredential( username, databaseName, password ); mongo = new MongoClient( serverAddresses, Collections.singletonList( credential ), options ); } db = mongo.getDatabase( databaseName ); // Create index if needed MongoCollection<Document> entities = db.getCollection( collectionName ); if( !entities.listIndexes().iterator().hasNext() ) { entities.createIndex( new BasicDBObject( IDENTITY_COLUMN, 1 ) ); } }
public void initialize(IMongoClientOptionsHandler optionsHandler, MongoDataSourceCfgMeta cfgMeta) throws Exception { __cfgMeta = cfgMeta; MongoClientOptions.Builder _builder = null; if (optionsHandler != null) { _builder = optionsHandler.handler(cfgMeta.getName()); } if (_builder == null) { _builder = MongoClientOptions.builder(); } if (StringUtils.isNotBlank(cfgMeta.getConnectionUrl())) { __mongoClient = new MongoClient(new MongoClientURI(cfgMeta.getConnectionUrl(), _builder)); } else { String _username = StringUtils.trimToNull(cfgMeta.getUserName()); String _password = StringUtils.trimToNull(cfgMeta.getPassword()); if (_username != null && _password != null) { if (__cfgMeta.isPasswordEncrypted() && __cfgMeta.getPasswordClass() != null) { _password = __cfgMeta.getPasswordClass().newInstance().decrypt(_password); } MongoCredential _credential = MongoCredential.createCredential(cfgMeta.getUserName(), cfgMeta.getDatabaseName(), _password == null ? null : _password.toCharArray()); __mongoClient = new MongoClient(cfgMeta.getServers(), Collections.singletonList(_credential), _builder.build()); } else { __mongoClient = new MongoClient(cfgMeta.getServers(), _builder.build()); } } }
private MongoCredential findMongoCredential(String user, String database, char[] pwd, String mechanism) { MongoCredential credential = null; switch (mechanism) { case "scram-sha-1": credential = MongoCredential.createScramSha1Credential(user, database, pwd); break; case "x509": credential = MongoCredential.createMongoX509Credential(user); break; case "cr": credential = MongoCredential.createMongoCRCredential(user, database, pwd); break; case "plain": credential = MongoCredential.createPlainCredential(user, database, pwd); break; case "gssapi": credential = MongoCredential.createGSSAPICredential(user); break; default: credential = MongoCredential.createCredential(user, database, pwd); break; } return credential; }
@Override @Bean public MongoClient mongo() throws Exception { ServerAddress serverAddr = new ServerAddress(host, port); LOGGER.info("Initializing Mongo Client server at: {}", serverAddr); MongoClient client; if (StringUtils.isEmpty(userName)) { client = new MongoClient(serverAddr); } else { MongoCredential mongoCredential = MongoCredential.createScramSha1Credential( userName, databaseName, password.toCharArray()); client = new MongoClient(serverAddr, Collections.singletonList(mongoCredential)); } LOGGER.info("Connecting to Mongo: {}", client); return client; }
@BeforeClass public static void init() throws UnknownHostException { ServerAddress mongoServer = new ServerAddress(dbConfig.host, Integer.valueOf(dbConfig.port)); MongoCredential credential = MongoCredential.createCredential( dbConfig.username, dbConfig.name, dbConfig.password.toCharArray() ); MongoClient mongoClient = new MongoClient(mongoServer, new ArrayList<MongoCredential>() {{ add(credential); }}); DB db = mongoClient.getDB(dbConfig.name); accountService = new MongoAccountService( db); }
@Test public void testCredentials(){ Optional<MongoCredential> credentials = SharedMongoResource.createCredentials(TEST_USER, TEST_PASS, TEST_DB); assertTrue(credentials.isPresent()); assertEquals(TEST_USER, credentials.get().getUserName()); assertEquals(TEST_PASS, new String(credentials.get().getPassword())); credentials = SharedMongoResource.createCredentials(null, TEST_PASS, TEST_DB); assertFalse(credentials.isPresent()); credentials = SharedMongoResource.createCredentials(TEST_USER, null, TEST_DB); assertFalse(credentials.isPresent()); credentials = SharedMongoResource.createCredentials(TEST_USER, TEST_PASS, null); assertFalse(credentials.isPresent()); }
@Override @Bean public Mongo mongo() throws Exception { String host = Optional.ofNullable(properties.getHost()).orElse("localhost"); Integer port = Optional.ofNullable(properties.getPort()).orElse(27017); String database = Optional.ofNullable(properties.getDatabase()).orElse("test"); Optional<String> username = Optional.ofNullable(properties.getUsername()); Optional<char[]> password = Optional.ofNullable(properties.getPassword()); if (username.isPresent() || password.isPresent()) { return new MongoClient(singletonList(new ServerAddress(host, port)), singletonList(MongoCredential.createCredential(username.get(), database, password.get()))); } else { return new MongoClient(singletonList(new ServerAddress(host, port))); } }
@Test public void testCreate() { final String test1_hostname = "example.com"; final String test1_username = "username"; final String test1_password = "password"; final String test1_database = "database"; final List<ServerAddress> servers = ImmutableList.of( new ServerAddress(test1_hostname) ); final List<MongoCredential> credentials = ImmutableList.of( MongoCredential.createCredential(test1_username, test1_database, test1_password.toCharArray()) ); final MongoClientOptions options = new MongoClientOptions.Builder().build(); final ComposeForMongoDBServiceInfo serviceInfo = new ComposeForMongoDBServiceInfo("id", servers, credentials, options); assertTrue(creator.create(serviceInfo, new ServiceConnectorConfig() { }) instanceof MongoClient); }
private MongoClient createClientFromParams(PluginTask task) { if (!task.getHosts().isPresent()) { throw new ConfigException("'hosts' option's value is required but empty"); } if (!task.getDatabase().isPresent()) { throw new ConfigException("'database' option's value is required but empty"); } List<ServerAddress> addresses = new ArrayList<>(); for (HostTask host : task.getHosts().get()) { addresses.add(new ServerAddress(host.getHost(), host.getPort())); } if (task.getUser().isPresent()) { MongoCredential credential = MongoCredential.createCredential( task.getUser().get(), task.getDatabase().get(), task.getPassword().get().toCharArray() ); return new MongoClient(addresses, Arrays.asList(credential)); } else { return new MongoClient(addresses); } }
@Override public void configure(Binder binder) { Logger.info("Configuring MongoDb Module"); ServerAddress serverAddress = new ServerAddress(MONGO_DB_SERVER, Integer.parseInt(MONGO_DB_PORT)); MongoCredential credential = MongoCredential.createCredential(MONGO_DB_USER, DATABASE, MONGO_DB_PASSWORD.toCharArray()); List<MongoCredential> auths = Collections.singletonList(credential); MongoClient client = new MongoClient(serverAddress, auths); Dao<String, Category> categoryDao = new MongoDbDao<>(client, DATABASE, Category.class); Dao<String, Snippet> snippetDao = new CachingDao<>(new MongoDbDao<>(client, DATABASE, Snippet.class)); binder.bind(new TypeLiteral<Dao<String, Category>>() { }).toInstance(categoryDao); binder.bind(new TypeLiteral<Dao<String, Snippet>>() { }).toInstance(snippetDao); }
private List<MongoCredential> createCredentials() throws StageException { MongoCredential credential = null; List<MongoCredential> credentials = new ArrayList<>(1); String authdb = (authSource.isEmpty() ? database : authSource); switch (authenticationType) { case USER_PASS: credential = MongoCredential.createCredential(username.get(), authdb, password.get().toCharArray()); break; case LDAP: credential = MongoCredential.createCredential(username.get(), "$external", password.get().toCharArray()); break; case NONE: default: break; } if (credential != null) { credentials.add(credential); } return credentials; }
@SuppressWarnings("deprecation") private void init() { if(mongoClient != null) return; try { MongoCredential credential = MongoCredential.createCredential( MongoDBDrive.getInstance().getUsername(), MongoDBDrive.getInstance().getDatabase(), MongoDBDrive.getInstance().getPassword().toCharArray()); MongoDBDrive.getInstance().mongoClient = new MongoClient( new ServerAddress(MongoDBDrive.getInstance().getUrl()), Arrays.asList(credential)); MongoDBDrive.getInstance().mongoClient.setWriteConcern(WriteConcern.NORMAL); } catch (Exception e) { return; } return; }
private static DB conectar() { MongoClient mongoClient = null; MongoCredential mongoCredential = MongoCredential .createMongoCRCredential("trivialuser", "trivial", "4btrivialmongouser".toCharArray()); try { mongoClient = new MongoClient(new ServerAddress( "ds062797.mongolab.com", 62797), Arrays.asList(mongoCredential)); } catch (UnknownHostException e) { e.printStackTrace(); } DB db = mongoClient.getDB("trivial"); System.out.println("Conexion creada con la base de datos"); return db; }
public static DB getDBInstance() { try { if (mongo == null) { if (LODVaderProperties.MONGODB_DB == null) new LODVaderProperties().loadProperties(); if (LODVaderProperties.MONGODB_SECURE_MODE) { MongoCredential credential = MongoCredential.createMongoCRCredential( LODVaderProperties.MONGODB_USERNAME, LODVaderProperties.MONGODB_DB, LODVaderProperties.MONGODB_PASSWORD.toCharArray()); mongo = new MongoClient(new ServerAddress(LODVaderProperties.MONGODB_HOST), Arrays.asList(credential)); } else { mongo = new MongoClient(LODVaderProperties.MONGODB_HOST, LODVaderProperties.MONGODB_PORT); } db = mongo.getDB(LODVaderProperties.MONGODB_DB); } } catch (Exception e) { e.printStackTrace(); } return db; }
public static void connect(String server, int port, String dbname, String user, String pass) throws UnknownHostException { disconnect(); ServerAddress sa = new ServerAddress(server, port); if (user != null && user.length() > 0) { List<MongoCredential> creds = new ArrayList<>(); creds.add(MongoCredential.createScramSha1Credential(user, dbname, pass.toCharArray())); Connection = new MongoClient(sa, creds); } else { Connection = new MongoClient(sa); } Database = Connection.getDatabase(dbname); Server = server; Port = port; DatabaseName = dbname; User = user; Password = pass; Connection.setWriteConcern(WriteConcern.SAFE); Database.listCollectionNames().first(); }
public Boolean isValidCredentials(String userName, String db, String password) { try { client = createClient(MongoCredential.createCredential(userName, db, password.toCharArray())); // Simple command that needs authentication client.listDatabaseNames().first(); return Boolean.TRUE; } catch (MongoTimeoutException timeout) { if (MongoException.fromThrowable(timeout).toString().contains("Authentication failed.")) { System.out.println("ERROR: Authentication Failed."); } timeout.printStackTrace(); return Boolean.FALSE; } finally { client.close(); } }
@Before public void setup() { credential = MongoCredential.createCredential(USER, "admin", PASSWORD.toCharArray()); mockStatic(MongoConnector.class); when(MongoConnector.getConnector(HOST, PORT)).thenReturn(connector); when(connector.createClient(Matchers.any())).thenReturn(client); when(client.getDatabase(DBNAME)).thenReturn(database); when(database.getCollection(MetaInformation.COLLECTION.getValue())).thenReturn(collection); createRepositoryConfiguration(); studioDatabase = new StudioMongoDatabase(configuration); when(database.getCollection(MetaInformation.COLLECTION.getValue()).find()).thenReturn(iterable); when(iterable.limit(1)).thenReturn(info); }
private com.mongodb.client.MongoDatabase initDB3(String url, Integer port, String dbName, String user, String password) throws UnknownHostException, MongoException { MongoClient mongoClient = null; List<ServerAddress> seeds = new ArrayList<ServerAddress>(); if(StringUtils.isNotEmpty(url)){ String[] urls = url.split(","); for(String ul:urls){ if(StringUtils.isNotEmpty(ul)){ seeds.add(new ServerAddress(ul, port != null ? port : 27017)); } } } MongoCredential credential = MongoCredential.createCredential(user, dbName, password.toCharArray()); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); //credentials.add(credential); mongoClient = new MongoClient(seeds, credentials); return mongoClient.getDatabase(dbName); }
@Inject public MongoClientWrapper(MongoClientConfiguration configuration) throws UnreachableMongoServerException { try { MongoClientOptions options = toMongoClientOptions(configuration); ImmutableList<MongoCredential> credentials = toMongoCredentials(configuration); testAddress(configuration.getHostAndPort(), options); this.configuration = configuration; this.driverClient = new com.mongodb.MongoClient( new ServerAddress( configuration.getHostAndPort().getHostText(), configuration.getHostAndPort().getPort()), credentials, options ); version = calculateVersion(); codecRegistry = CodecRegistries.fromCodecs(new DocumentCodec()); closed = false; } catch (com.mongodb.MongoException ex) { throw new UnreachableMongoServerException(configuration.getHostAndPort(), ex); } }
private MongoCredential toMongoCredential(MongoAuthenticationConfiguration authConfiguration) { switch (authConfiguration.getMechanism()) { case cr: return MongoCredential.createMongoCRCredential(authConfiguration.getUser(), authConfiguration.getSource(), authConfiguration.getPassword().toCharArray()); case scram_sha1: return MongoCredential.createScramSha1Credential(authConfiguration.getUser(), authConfiguration.getSource(), authConfiguration.getPassword().toCharArray()); case negotiate: return MongoCredential.createCredential(authConfiguration.getUser(), authConfiguration .getSource(), authConfiguration.getPassword().toCharArray()); case x509: return MongoCredential.createMongoX509Credential(authConfiguration.getUser()); default: throw new UnsupportedOperationException("Authentication mechanism " + authConfiguration .getMechanism() + " not supported"); } }
public static List<MongoCredential> credentialsFromJson(JsonNode node) { List<MongoCredential> list = new ArrayList<>(); try { if (node instanceof ArrayNode) { for (Iterator<JsonNode> itr = node.elements(); itr.hasNext();) { list.add(credentialFromJson((ObjectNode) itr.next())); } } else if (node != null) { list.add(credentialFromJson((ObjectNode) node)); } } catch (ClassCastException e) { LOGGER.debug("Invalid credentials node: " + node); throw new IllegalArgumentException("Invalid credentials node, see debug log for details"); } return list; }
protected MongoUtil() { props=new Properties(); try { props.load(this.getClass().getResourceAsStream("/dbconnect.properties")); String user=props.getProperty("mongo.user"); if(!CommonUtil.isEmpty(user)) client=new MongoClient(new ServerAddress(props.getProperty("mongo.ip","localhost"),Integer.parseInt(props.getProperty("mongo.port","27017"))), Arrays.asList(MongoCredential.createCredential(user, props.getProperty("mongo.db"), props.getProperty("mongo.pwd").toCharArray()))); else client=new MongoClient(new ServerAddress(String.valueOf(props.get("mongo.ip")),Integer.parseInt(String.valueOf(props.get("mongo.port"))))); } catch (Exception e) { log.error("MongoDB Connect Fail"); } }
@Override public MongoCredential convert(MongoCredentialRepresentation value) { MongoCredential credential; switch (value.getType()) { case PLAIN: credential = MongoCredential.createPlainCredential(value.getUsername(), value.getSource(), value.getPassword().toCharArray()); break; case GSSAPI: credential = MongoCredential.createGSSAPICredential(value.getUsername()); break; case X509: credential = MongoCredential.createMongoX509Credential(value.getUsername()); break; case CR: default: credential = MongoCredential.createMongoCRCredential(value.getUsername(), value.getDatabase(), value.getPassword().toCharArray()); } for (Map.Entry<String,Object> entry : value.getProperties().entrySet()) { credential = credential.withMechanismProperty(entry.getKey(), entry.getValue()); } return credential; }