com.mongodb.MongoCredential Java Examples

The following examples show how to use com.mongodb.MongoCredential. 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: EclipseLinkConfigurationTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #2
Source File: MongoSchemaFactory.java    From Quicksql with MIT License 6 votes vote down vote up
private MongoCredential createCredentials(Map<String, Object> map) {
  final String authMechanismName = (String) map.get("authMechanism");
  final AuthenticationMechanism authenticationMechanism =
      AuthenticationMechanism.fromMechanismName(authMechanismName);
  final String username = (String) map.get("userName");
  final String authDatabase = (String) map.get("dbName");
  final String password = (String) map.get("password");

  switch (authenticationMechanism) {
  case PLAIN:
    return MongoCredential.createPlainCredential(username, authDatabase,
        password.toCharArray());
  case SCRAM_SHA_1:
    return MongoCredential.createScramSha1Credential(username, authDatabase,
        password.toCharArray());
  case GSSAPI:
    return MongoCredential.createGSSAPICredential(username);
  case MONGODB_CR:
    return MongoCredential.createMongoCRCredential(username, authDatabase,
        password.toCharArray());
  case MONGODB_X509:
    return MongoCredential.createMongoX509Credential(username);
  }
  throw new IllegalArgumentException("Unsupported authentication mechanism "
      + authMechanismName);
}
 
Example #3
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 #4
Source File: DefaultHygieiaServiceImpl.java    From ExecDashboard with Apache License 2.0 6 votes vote down vote up
@Override
public MongoClient getMongoClient(BunitCredentials bunitCredential) {
	try {
		if (bunitCredential != null) {
			ServerAddress serverAddr = new ServerAddress(bunitCredential.getHost(), bunitCredential.getPort());

			MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(
					bunitCredential.getDbUserName(), bunitCredential.getDbName(),
					bunitCredential.getDbUserCredentials().toCharArray());
			MongoClient client = new MongoClient(serverAddr, Collections.singletonList(mongoCredential));
			return client;
		}
	} catch (Exception e) {
		LOG.error(e.getMessage());
	}
	return null;
}
 
Example #5
Source File: MongoConfig.java    From iot-dc3 with Apache License 2.0 6 votes vote down vote up
public MongoDbFactory mongoDbFactory(MongoClientOptionProperties properties) {
    //创建客户端参数
    MongoClientOptions options = mongoClientOptions(properties);

    //创建客户端和Factory
    List<ServerAddress> serverAddresses = new ArrayList<>();
    for (String address : properties.getAddress()) {
        String[] hostAndPort = address.split(":");
        String host = hostAndPort[0];
        int port = Integer.parseInt(hostAndPort[1]);
        ServerAddress serverAddress = new ServerAddress(host, port);
        serverAddresses.add(serverAddress);
    }

    //创建认证客户端
    MongoCredential mongoCredential = MongoCredential
            .createScramSha1Credential(
                    properties.getUsername(),
                    properties.getAuthenticationDatabase() != null ? properties.getAuthenticationDatabase() : properties.getDatabase(),
                    properties.getPassword().toCharArray()
            );
    MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredential, options);

    return new SimpleMongoDbFactory(mongoClient, properties.getDatabase());
}
 
Example #6
Source File: CredentialListParserTest.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuth_PLAIN() {
  JsonObject config = new JsonObject();
  String username = TestUtils.randomAlphaString(8);
  String password = TestUtils.randomAlphaString(20);
  String authSource = TestUtils.randomAlphaString(10);
  config.put("username", username);
  config.put("password", password);
  config.put("authSource", authSource);
  config.put("authMechanism", "PLAIN");

  List<MongoCredential> credentials = new CredentialListParser(config).credentials();
  assertEquals(1, credentials.size());
  MongoCredential credential = credentials.get(0);
  assertEquals(username, credential.getUserName());
  assertArrayEquals(password.toCharArray(), credential.getPassword());
  assertEquals(authSource, credential.getSource());

  assertEquals(AuthenticationMechanism.PLAIN, credential.getAuthenticationMechanism());
}
 
Example #7
Source File: MongoTransactionRecoverRepository.java    From Raincat with GNU Lesser General Public License v3.0 6 votes vote down vote up
private MongoClientFactoryBean buildMongoClientFactoryBean(final 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;
}
 
Example #8
Source File: HelperMongo.java    From helper with MIT License 6 votes vote down vote up
public HelperMongo(@Nonnull MongoDatabaseCredentials credentials) {
    MongoCredential mongoCredential = MongoCredential.createCredential(
            credentials.getUsername(),
            credentials.getDatabase(),
            credentials.getPassword().toCharArray()
    );

    this.client = new MongoClient(
            new ServerAddress(credentials.getAddress(), credentials.getPort()),
            mongoCredential,
            MongoClientOptions.builder().build()
    );
    this.database = this.client.getDatabase(credentials.getDatabase());
    this.morphia = new Morphia();
    this.morphiaDatastore = this.morphia.createDatastore(this.client, credentials.getDatabase());
    this.morphia.getMapper().getOptions().setObjectFactory(new DefaultCreator() {
        @Override
        protected ClassLoader getClassLoaderForClass() {
            return LoaderUtils.getPlugin().getClassloader();
        }
    });
}
 
Example #9
Source File: CredentialListParserTest.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuth_MONGODB_X509() {
  JsonObject config = new JsonObject();
  String username = TestUtils.randomAlphaString(8);
  String authSource = TestUtils.randomAlphaString(10);
  config.put("username", username);
  config.put("authSource", authSource);
  config.put("authMechanism", "MONGODB-X509");

  List<MongoCredential> credentials = new CredentialListParser(config).credentials();
  assertEquals(1, credentials.size());
  MongoCredential credential = credentials.get(0);
  assertEquals(username, credential.getUserName());
  assertNotEquals(authSource, credential.getSource()); // It should ignore the source we pass in

  assertEquals(AuthenticationMechanism.MONGODB_X509, credential.getAuthenticationMechanism());
}
 
Example #10
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 #11
Source File: MongoTransactionOperateRepository.java    From Lottor with MIT License 6 votes vote down vote up
/**
 * 生成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;
}
 
Example #12
Source File: MongoCoordinatorRepository.java    From hmily with Apache License 2.0 6 votes vote down vote up
private MongoClientFactoryBean buildMongoClientFactoryBean(final HmilyMongoConfig hmilyMongoConfig) {
    MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
    MongoCredential credential = MongoCredential.createScramSha1Credential(hmilyMongoConfig.getMongoUserName(),
            hmilyMongoConfig.getMongoDbName(),
            hmilyMongoConfig.getMongoUserPwd().toCharArray());
    clientFactoryBean.setCredentials(new MongoCredential[]{credential});

    List<String> urls = Lists.newArrayList(Splitter.on(",").trimResults().split(hmilyMongoConfig.getMongoDbUrl()));
    ServerAddress[] sds = new ServerAddress[urls.size()];
    for (int i = 0; i < sds.length; i++) {
        List<String> adds = Lists.newArrayList(Splitter.on(":").trimResults().split(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;
}
 
Example #13
Source File: MongoStoreProvider.java    From alchemy with MIT License 6 votes vote down vote up
@Override
public ExperimentsStoreProvider createProvider() throws UnknownHostException {
    final io.rtr.alchemy.db.mongo.MongoStoreProvider.Builder builder = io.rtr.alchemy.db.mongo.MongoStoreProvider.newBuilder();
    for (final HostAndPort host : hosts) {
        if (!host.hasPort()) {
            builder.addHost(new ServerAddress(host.getHost()));
        } else {
            builder.addHost(new ServerAddress(host.getHost(), host.getPort()));
        }
    }

    if (username != null) {
        builder.addCredential(MongoCredential.createPlainCredential(username, db, password.toCharArray()));
    }

    builder.setDatabase(db);

    return builder.build();
}
 
Example #14
Source File: MongoClientWrapperTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
private static void assertWithExpected(final DittoMongoClient mongoClient, final boolean sslEnabled,
        final boolean withCredentials) {

    final MongoClientSettings mongoClientSettings = mongoClient.getSettings();
    assertThat(mongoClientSettings.getClusterSettings().getHosts())
            .isEqualTo(Collections.singletonList(new ServerAddress(KNOWN_SERVER_ADDRESS)));

    final List<MongoCredential> expectedCredentials = withCredentials ? Collections.singletonList(
            MongoCredential.createCredential(KNOWN_USER, KNOWN_DB_NAME, KNOWN_PASSWORD.toCharArray())) :
            Collections.emptyList();
    assertThat(mongoClientSettings.getCredentialList()).isEqualTo(
            expectedCredentials);
    assertThat(mongoClientSettings.getSslSettings().isEnabled()).isEqualTo(sslEnabled);

    final MongoDatabase mongoDatabase = mongoClient.getDefaultDatabase();
    assertThat(mongoDatabase).isNotNull();
    assertThat(mongoDatabase.getName()).isEqualTo(KNOWN_DB_NAME);
}
 
Example #15
Source File: CredentialListParserTest.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleAuthWithSource() {
  JsonObject config = new JsonObject();
  String username = TestUtils.randomAlphaString(8);
  String password = TestUtils.randomAlphaString(20);
  String authSource = TestUtils.randomAlphaString(10);
  config.put("username", username);
  config.put("password", password);
  config.put("authSource", authSource);

  List<MongoCredential> credentials = new CredentialListParser(config).credentials();
  assertEquals(1, credentials.size());
  MongoCredential credential = credentials.get(0);
  assertEquals(username, credential.getUserName());
  assertArrayEquals(password.toCharArray(), credential.getPassword());
  assertEquals(authSource, credential.getSource());
}
 
Example #16
Source File: Main.java    From sql-to-mongo-db-query-converter with Apache License 2.0 6 votes vote down vote up
private static MongoClient getMongoClient(String[] hosts, String authdb, String username, String password) {
    final Pattern hostAndPort = Pattern.compile("^(.[^:]*){1}([:]){0,1}(\\d+){0,1}$");
    List<ServerAddress> serverAddresses = Lists.transform(Arrays.asList(hosts), new Function<String, ServerAddress>() {
        @Override
        public ServerAddress apply(@Nonnull String string) {
            Matcher matcher = hostAndPort.matcher(string.trim());
            if (matcher.matches()) {
                String hostname = matcher.group(1);
                String port = matcher.group(3);
                return new ServerAddress(hostname,port!=null ? Integer.parseInt(port) : Integer.parseInt(DEFAULT_MONGO_PORT));

            } else {
                throw new IllegalArgumentException(string + " doesn't appear to be a hostname.");
            }
        }
    });
    if (username!=null && password!=null) {
        return new MongoClient(serverAddresses,Arrays.asList(MongoCredential.createCredential(username,authdb,password.toCharArray())));
    } else {
        return new MongoClient(serverAddresses);
    }
}
 
Example #17
Source File: MongoDBConfig.java    From datacollector with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #18
Source File: MongoServiceConnectorCreatorTest.java    From spring-cloud-connectors with Apache License 2.0 6 votes vote down vote up
@Test
public void cloudMongoCreationNoConfig() throws Exception {
	MongoServiceInfo serviceInfo = new MongoServiceInfo("id", TEST_HOST, TEST_PORT, TEST_USERNAME, TEST_PASSWORD, TEST_DB);

	MongoDbFactory mongoDbFactory = testCreator.create(serviceInfo, null);
	assertNotNull(mongoDbFactory);

	MongoClient mongoClient = getMongoClientField(mongoDbFactory);

	MongoCredential credentials = mongoClient.getCredentialsList().get(0);

	List<ServerAddress> addresses = extractServerAddresses(mongoClient);
	assertEquals(1, addresses.size());

	ServerAddress address = addresses.get(0);

	assertEquals(serviceInfo.getHost(), address.getHost());
	assertEquals(serviceInfo.getPort(), address.getPort());
	assertEquals(serviceInfo.getUserName(), credentials.getUserName());
	assertNotNull(credentials.getPassword());

	// Don't do connector.getDatabase().getName() as that will try to initiate the connection
	assertEquals(serviceInfo.getDatabase(), ReflectionTestUtils.getField(mongoDbFactory, "databaseName"));
}
 
Example #19
Source File: ReplicaSetBaseTest.java    From bugu-mongo with Apache License 2.0 6 votes vote down vote up
protected void connectDB(){
    List<ServerAddress> serverList = new ArrayList<ServerAddress>();
    serverList.add(new ServerAddress("192.168.0.200", 27017));
    serverList.add(new ServerAddress("192.168.0.200", 27018));
    serverList.add(new ServerAddress("192.168.0.200", 27019));
    
    List<MongoCredential> credentialList = new ArrayList<MongoCredential>();
    MongoCredential credentialA = MongoCredential.createCredential("test", "test", "test".toCharArray());
    MongoCredential credentialB = MongoCredential.createCredential("test", "test", "test".toCharArray());
    MongoCredential credentialC = MongoCredential.createCredential("test", "test", "test".toCharArray());
    credentialList.add(credentialA);
    credentialList.add(credentialB);
    credentialList.add(credentialC);
    BuguConnection conn = BuguFramework.getInstance().createConnection();
    conn.setServerList(serverList).setCredentialList(credentialList).setDatabase("test").connect();
}
 
Example #20
Source File: SharedMongoResourceTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #21
Source File: KunderaConfigurationTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #22
Source File: SharedMongoResource.java    From baleen with Apache License 2.0 6 votes vote down vote up
private void connectToMongo(
    String host, int port, String database, String username, String password)
    throws BaleenException {
  try {
    // Connect to Mongo
    ServerAddress sa = new ServerAddress(host, port);
    Optional<MongoCredential> cred = createCredentials(username, password, database);

    m = createMongoClient(sa, cred);

    getMonitor().debug("Getting Mongo Database '{}'", db);
    db = m.getDatabase(database);
  } catch (Exception e) {
    throw new BaleenException("Unable to connect to Mongo", e);
  }
}
 
Example #23
Source File: CredentialListParserTest.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuth_SCRAM_SHA_256() {
  JsonObject config = new JsonObject();
  String username = TestUtils.randomAlphaString(8);
  String password = TestUtils.randomAlphaString(20);
  String authSource = TestUtils.randomAlphaString(10);
  config.put("username", username);
  config.put("password", password);
  config.put("authSource", authSource);
  config.put("authMechanism", "SCRAM-SHA-256");

  List<MongoCredential> credentials = new CredentialListParser(config).credentials();
  assertEquals(1, credentials.size());
  MongoCredential credential = credentials.get(0);
  assertEquals(username, credential.getUserName());
  assertArrayEquals(password.toCharArray(), credential.getPassword());
  assertEquals(authSource, credential.getSource());

  assertEquals(AuthenticationMechanism.SCRAM_SHA_256, credential.getAuthenticationMechanism());
}
 
Example #24
Source File: MongoConfiguration.java    From mongolastic with MIT License 6 votes vote down vote up
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;
}
 
Example #25
Source File: HibernateOgmConfigurationTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #26
Source File: CredentialListParserTest.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuth_GSSAPI() {
  JsonObject config = new JsonObject();
  String username = TestUtils.randomAlphaString(8);
  String authSource = TestUtils.randomAlphaString(10);
  config.put("username", username);
  config.put("authSource", authSource);
  config.put("authMechanism", "GSSAPI");

  List<MongoCredential> credentials = new CredentialListParser(config).credentials();
  assertEquals(1, credentials.size());
  MongoCredential credential = credentials.get(0);
  assertEquals(username, credential.getUserName());
  assertNotEquals(authSource, credential.getSource()); // It should ignore the source we pass in

  assertEquals(AuthenticationMechanism.GSSAPI, credential.getAuthenticationMechanism());
}
 
Example #27
Source File: MongoSchemaFactory.java    From calcite with Apache License 2.0 6 votes vote down vote up
private MongoCredential createCredential(Map<String, Object> map) {
  final String authMechanismName = (String) map.get("authMechanism");
  final AuthenticationMechanism authenticationMechanism =
      AuthenticationMechanism.fromMechanismName(authMechanismName);
  final String username = (String) map.get("username");
  final String authDatabase = (String) map.get("authDatabase");
  final String password = (String) map.get("password");

  switch (authenticationMechanism) {
  case PLAIN:
    return MongoCredential.createPlainCredential(username, authDatabase,
        password.toCharArray());
  case SCRAM_SHA_1:
    return MongoCredential.createScramSha1Credential(username, authDatabase,
        password.toCharArray());
  case SCRAM_SHA_256:
    return MongoCredential.createScramSha256Credential(username, authDatabase,
        password.toCharArray());
  case GSSAPI:
    return MongoCredential.createGSSAPICredential(username);
  case MONGODB_X509:
    return MongoCredential.createMongoX509Credential(username);
  }
  throw new IllegalArgumentException("Unsupported authentication mechanism "
      + authMechanismName);
}
 
Example #28
Source File: MongoFactoryBean.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
public MongoFactoryBean(String[] serverAddresses, String mechanism, String username, String database, String pwd) {
    replSeeds(serverAddresses);
    if (StringUtils.isNotEmpty(username)) {
        if (MongoCredential.GSSAPI_MECHANISM.equals(mechanism)) {
            mongoCredentials.add(MongoCredential.createGSSAPICredential(username));
        } else {
            mongoCredentials.add(MongoCredential.createMongoCRCredential(username, database, pwd.toCharArray()));
        }
    }
}
 
Example #29
Source File: SharedMongoResource.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a MongoCredential if a username, password and database are supplied, or returns
 * absent() otherwise
 *
 * @param username The username to connect to Mongo with
 * @param password The password to connect to Mongo with
 * @param database The database to connect to
 */
public static Optional<MongoCredential> createCredentials(
    String username, String password, String database) {
  if (!Strings.isNullOrEmpty(username)
      && !Strings.isNullOrEmpty(password)
      && !Strings.isNullOrEmpty(database)) {
    return Optional.of(
        MongoCredential.createMongoCRCredential(username, database, password.toCharArray()));
  } else {
    return Optional.absent();
  }
}
 
Example #30
Source File: MongoSchema.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a MongoDB schema.
 *
 * @param host Mongo host, e.g. "localhost"
 * @param credential Optional credentials (null for none)
 * @param options Mongo connection options
 * @param database Mongo database name, e.g. "foodmart"
 */
MongoSchema(String host, String database,
    MongoCredential credential, MongoClientOptions options) {
  super();
  try {
    final MongoClient mongo = credential == null
        ? new MongoClient(new ServerAddress(host), options)
        : new MongoClient(new ServerAddress(host), credential, options);
    this.mongoDb = mongo.getDatabase(database);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}