java类com.mongodb.MongoCredential的实例源码

MongoCoordinatorRepository.java 文件源码 项目:myth 阅读 40 收藏 0 点赞 0 评论 0
/**
 * 生成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;
}
MongoTransactionRecoverRepository.java 文件源码 项目:happylifeplat-transaction 阅读 39 收藏 0 点赞 0 评论 0
/**
 * 生成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;
}
BaseMongoBenchMark.java 文件源码 项目:nitrite-database 阅读 31 收藏 0 点赞 0 评论 0
@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();
        }
    }
}
MongoCoordinatorRepository.java 文件源码 项目:happylifeplat-tcc 阅读 40 收藏 0 点赞 0 评论 0
/**
 * 生成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;
}
MongoDBAdapter.java 文件源码 项目:botmill-core 阅读 26 收藏 0 点赞 0 评论 0
/** 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;
    }
MongoDao.java 文件源码 项目:LuckPerms 阅读 35 收藏 0 点赞 0 评论 0
@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());
}
MongoConnection.java 文件源码 项目:djigger 阅读 28 收藏 0 点赞 0 评论 0
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;
}
MongoClientConfiguration.java 文件源码 项目:spring-morphia 阅读 23 收藏 0 点赞 0 评论 0
@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));
}
MondoDbOpenshiftConfig.java 文件源码 项目:analytics4github 阅读 25 收藏 0 点赞 0 评论 0
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
            )
    );
}
HypermediaConfigurationTest.java 文件源码 项目:spring-content 阅读 21 收藏 0 点赞 0 评论 0
@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();
}
RestConfigurationTest.java 文件源码 项目:spring-content 阅读 23 收藏 0 点赞 0 评论 0
@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();
}
KunderaConfigurationTest.java 文件源码 项目:jpa-unit 阅读 31 收藏 0 点赞 0 评论 0
@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());
}
DataNucleusConfigurationTest.java 文件源码 项目:jpa-unit 阅读 32 收藏 0 点赞 0 评论 0
@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());
}
HibernateOgmConfigurationTest.java 文件源码 项目:jpa-unit 阅读 35 收藏 0 点赞 0 评论 0
@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());
}
EclipseLinkConfigurationTest.java 文件源码 项目:jpa-unit 阅读 23 收藏 0 点赞 0 评论 0
@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());
}
MongoClientSession.java 文件源码 项目:step 阅读 30 收藏 0 点赞 0 评论 0
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);
}
MongoStoragePlugin.java 文件源码 项目:drill 阅读 38 收藏 0 点赞 0 评论 0
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;
}
MongoDBEntityStoreMixin.java 文件源码 项目:polygene-java 阅读 30 收藏 0 点赞 0 评论 0
@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 ) );
    }
}
MongoDataSourceAdapter.java 文件源码 项目:ymate-platform-v2 阅读 25 收藏 0 点赞 0 评论 0
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());
        }
    }
}
MongoConfiguration.java 文件源码 项目:mongolastic 阅读 44 收藏 0 点赞 0 评论 0
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;
}
MongoConfig.java 文件源码 项目:hygieia-temp 阅读 37 收藏 0 点赞 0 评论 0
@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;
}
MongoAccountServiceTests.java 文件源码 项目:kurve-server 阅读 31 收藏 0 点赞 0 评论 0
@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);
}
SharedMongoResourceTest.java 文件源码 项目:baleen 阅读 29 收藏 0 点赞 0 评论 0
@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());
}
MongoConfiguration.java 文件源码 项目:gear-service 阅读 40 收藏 0 点赞 0 评论 0
@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)));
    }

}
ComposeForMongoDBInstanceCreatorTest.java 文件源码 项目:bluemix-cloud-connectors 阅读 26 收藏 0 点赞 0 评论 0
@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);
}
MongodbInputPlugin.java 文件源码 项目:embulk-input-mongodb 阅读 32 收藏 0 点赞 0 评论 0
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);
    }
}
MongoDbModule.java 文件源码 项目:mysnipserver 阅读 36 收藏 0 点赞 0 评论 0
@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);
}
MongoDBConfig.java 文件源码 项目:datacollector 阅读 27 收藏 0 点赞 0 评论 0
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;
}
MongoDBDrive.java 文件源码 项目:LYLab 阅读 34 收藏 0 点赞 0 评论 0
@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;
}
TrivialAPI.java 文件源码 项目:Trivial4b 阅读 30 收藏 0 点赞 0 评论 0
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;
}


问题


面经


文章

微信
公众号

扫码关注公众号