Example usage for com.mongodb MongoCredential createCredential

List of usage examples for com.mongodb MongoCredential createCredential

Introduction

In this page you can find the example usage for com.mongodb MongoCredential createCredential.

Prototype

public static MongoCredential createCredential(final String userName, final String database,
        final char[] password) 

Source Link

Document

Creates a MongoCredential instance with an unspecified mechanism.

Usage

From source file:org.apache.rya.kafka.connect.mongo.MongoRyaSinkTask.java

License:Apache License

@Override
protected void checkRyaInstanceExists(final Map<String, String> taskConfig) throws IllegalStateException {
    requireNonNull(taskConfig);/*w w w  .j  a va 2 s  .  c  o  m*/

    // Parse the configuration object.
    final MongoRyaSinkConfig config = new MongoRyaSinkConfig(taskConfig);
    @Nullable
    final String username = Strings.isNullOrEmpty(config.getUsername()) ? null : config.getUsername();
    @Nullable
    final char[] password = Strings.isNullOrEmpty(config.getPassword()) ? null
            : config.getPassword().toCharArray();

    // Connect a Mongo Client to the configured Mongo DB instance.
    final ServerAddress serverAddr = new ServerAddress(config.getHostname(), config.getPort());
    final boolean hasCredentials = username != null && password != null;

    try (MongoClient mongoClient = hasCredentials
            ? new MongoClient(serverAddr,
                    Arrays.asList(
                            MongoCredential.createCredential(username, config.getRyaInstanceName(), password)))
            : new MongoClient(serverAddr)) {
        // Use a RyaClient to see if the configured instance exists.
        // Create the Mongo Connection Details that describe the Mongo DB Server we are interacting with.
        final MongoConnectionDetails connectionDetails = new MongoConnectionDetails(config.getHostname(),
                config.getPort(), Optional.ofNullable(username), Optional.ofNullable(password));

        final RyaClient client = MongoRyaClientFactory.build(connectionDetails, mongoClient);
        if (!client.getInstanceExists().exists(config.getRyaInstanceName())) {
            throw new ConnectException("The Rya Instance named " + LogUtils.clean(config.getRyaInstanceName())
                    + " has not been installed.");
        }
    } catch (final RyaClientException e) {
        throw new ConnectException("Unable to determine if the Rya Instance named "
                + LogUtils.clean(config.getRyaInstanceName()) + " has been installed.", e);
    }
}

From source file:org.apache.rya.mongodb.MongoConnectorFactory.java

License:Apache License

/**
 * Create a MongoDB client object and assign it to this class's static mongoClient
 * @param conf configuration containing connection parameters
 * @throws ConfigurationRuntimeException - Thrown if the configured server, port, user, or others are missing.
 * @throws MongoException  if can't connect despite conf parameters are given
 *///from w  ww  . j ava 2 s . co m
private static void createMongoClientForServer(final Configuration conf)
        throws ConfigurationRuntimeException, MongoException {
    // Connect to a running Mongo server
    final String host = requireNonNull(conf.get(MongoDBRdfConfiguration.MONGO_INSTANCE),
            MSG_INTRO + "host name is required");
    final int port = requireNonNullInt(conf.get(MongoDBRdfConfiguration.MONGO_INSTANCE_PORT),
            MSG_INTRO + "Port number is required.");
    final ServerAddress server = new ServerAddress(host, port);
    // check for authentication credentials
    if (conf.get(MongoDBRdfConfiguration.MONGO_USER) != null) {
        final String username = conf.get(MongoDBRdfConfiguration.MONGO_USER);
        final String dbName = requireNonNull(conf.get(MongoDBRdfConfiguration.MONGO_DB_NAME),
                MSG_INTRO + MongoDBRdfConfiguration.MONGO_DB_NAME + " is null but required configuration if "
                        + MongoDBRdfConfiguration.MONGO_USER + " is configured.");
        final char[] pswd = requireNonNull(conf.get(MongoDBRdfConfiguration.MONGO_USER_PASSWORD),
                MSG_INTRO + MongoDBRdfConfiguration.MONGO_USER_PASSWORD
                        + " is null but required configuration if " + MongoDBRdfConfiguration.MONGO_USER
                        + " is configured.").toCharArray();
        final MongoCredential cred = MongoCredential.createCredential(username, dbName, pswd);
        mongoClient = new MongoClient(server, Arrays.asList(cred));
    } else {
        // No user was configured:
        mongoClient = new MongoClient(server);
    }
}

From source file:org.audit4j.mongodb.MongoRepository.java

@Override
public void createDataStore(String dataStoreName) throws HandlerException {
    MongoClient client;/*w w w. j  a va 2s .co m*/
    List<ServerAddress> mongoServerAddresses = null;
    ServerAddress mongoServerAddress = null;
    List<MongoCredential> mongoCredentials = null;
    MongoCredential mongoCredential = null;

    if (serverAddresses != null && !serverAddresses.isEmpty() && serverAddresses.size() == 1) {
        mongoServerAddress = new ServerAddress(serverAddresses.get(0).getHost(),
                serverAddresses.get(0).getPort());
    }
    if (serverAddresses != null && !serverAddresses.isEmpty()) {
        mongoServerAddresses = new ArrayList<>();
        for (StoreServerAddress address : serverAddresses) {
            mongoServerAddresses.add(new ServerAddress(address.getHost(), address.getPort()));
        }
    }
    if (credentials != null && !credentials.isEmpty() && credentials.size() == 1) {
        mongoCredential = MongoCredential.createCredential(credentials.get(0).getUsername(), dbName.getName(),
                credentials.get(0).getPassword().toCharArray());
    }

    if (credentials != null && !credentials.isEmpty()) {
        mongoCredentials = new ArrayList<>();
        for (StoreCredential storeCredential : credentials) {
            mongoCredentials.add(MongoCredential.createCredential(storeCredential.getUsername(),
                    dbName.getName(), storeCredential.getPassword().toCharArray()));
        }
    }

    if (mongoServerAddress != null && mongoCredential == null && mongoCredentials == null) {
        client = new MongoClient(mongoServerAddress);
    } else if (mongoServerAddress != null && mongoCredentials != null && !mongoCredentials.isEmpty()) {
        client = new MongoClient(mongoServerAddress, mongoCredentials);
    } else if (mongoServerAddresses != null && !mongoServerAddresses.isEmpty() && mongoCredential == null
            && mongoCredentials == null) {
        client = new MongoClient(mongoServerAddresses);
    } else if (mongoServerAddresses != null && !mongoServerAddresses.isEmpty() && mongoCredentials != null
            && !mongoCredentials.isEmpty()) {
        client = new MongoClient(mongoServerAddresses, mongoCredentials);
    }
}

From source file:org.dizitart.no2.datagate.NitriteDataGate.java

License:Apache License

@Bean
public Jongo jongo() {
    MongoCredential credential = MongoCredential.createCredential(mongoUser, mongoDatabase,
            mongoPassword.toCharArray());
    ServerAddress serverAddress = new ServerAddress(mongoHost, mongoPort);
    MongoClient mongoClient = new MongoClient(serverAddress, new ArrayList<MongoCredential>() {
        {/* www.j  a va2  s.  c  o m*/
            add(credential);
        }
    });

    DB db = mongoClient.getDB(mongoDatabase);
    return new Jongo(db);
}

From source file:org.edgexfoundry.AppConfig.java

License:Apache License

private List<MongoCredential> getMongoCredentials() {
    MongoCredential credential = MongoCredential.createCredential(username, getDatabaseName(),
            password.toCharArray());/* w w w.  j av  a 2s .co m*/
    return Arrays.asList(credential);
}

From source file:org.geosdi.geoplatform.experimental.mongodb.spring.client.GPMongoClientConfig.java

License:Open Source License

@Bean(name = "gpSpringMongoClient")
public MongoClient gpMongoClient(@Qualifier(value = "gpSpringMongoProp") MongoProperties gpSpringMongoProp)
        throws Exception {
    logger.debug("###################### GeoPlatform Experimental Version ::== Building MongoClient.\n");

    return (gpSpringMongoProp.getMongoAuth().isMongoAuthEnabled()
            ? new MongoClient(
                    new ServerAddress(gpSpringMongoProp.getMongoHost(), gpSpringMongoProp.getMongoPort()),
                    Arrays.asList(MongoCredential.createCredential(
                            gpSpringMongoProp.getMongoAuth().getMongoUserName(),
                            gpSpringMongoProp.getMongoDatabaseName(),
                            gpSpringMongoProp.getMongoAuth().getMongoPassword().toCharArray())))
            : new MongoClient(
                    new ServerAddress(gpSpringMongoProp.getMongoHost(), gpSpringMongoProp.getMongoPort())));
}

From source file:org.grails.datastore.gorm.mongo.bean.factory.MongoClientFactoryBean.java

License:Apache License

public void afterPropertiesSet() throws UnknownHostException {
    // apply defaults - convenient when used to configure for tests
    // in an application context
    if (mongo != null) {
        return;//from ww w  . ja  v  a2 s.c o m
    }

    ServerAddress defaultOptions = new ServerAddress();
    List<MongoCredential> credentials = new ArrayList<MongoCredential>();
    if (mongoOptions == null) {
        MongoClientOptions.Builder builder = MongoClientOptions.builder();
        builder.codecRegistry(CodecRegistries.fromRegistries(codecRegistries));
        mongoOptions = builder.build();
    }
    // If username/pw exists and we are not authenticated, authenticate now
    if (username != null && password != null) {
        credentials.add(MongoCredential.createCredential(username, database, password.toCharArray()));
    }

    if (replicaPair != null) {
        if (replicaPair.size() < 2) {
            throw new DatastoreConfigurationException("A replica pair must have two server entries");
        }
        mongo = new MongoClient(replicaPair, credentials, mongoOptions);
    } else if (replicaSetSeeds != null) {
        mongo = new MongoClient(replicaSetSeeds, credentials, mongoOptions);
    } else if (clientURI != null) {
        mongo = new MongoClient(clientURI);
    } else if (connectionString != null) {
        mongo = new MongoClient(new MongoClientURI(connectionString));
    } else {
        String mongoHost = host != null ? host : defaultOptions.getHost();
        if (port != null) {
            mongo = new MongoClient(new ServerAddress(mongoHost, port), credentials, mongoOptions);
        } else {
            mongo = new MongoClient(new ServerAddress(host), credentials, mongoOptions);
        }
    }

}

From source file:org.hillview.storage.MongoDBLoader.java

License:Open Source License

public MongoDBLoader(JdbcConnectionInformation info) {
    super(Converters.checkNull(info.table), null);
    this.info = info;
    assert info.database != null;
    assert info.password != null;

    MongoCredential credential = MongoCredential.createCredential(info.user, info.database,
            info.password.toCharArray());
    ServerAddress address = new ServerAddress(info.host, info.port);
    MongoClientOptions options = MongoClientOptions.builder().build();
    MongoClient client = new MongoClient(address); //, credential, options);

    this.database = client.getDatabase(info.database);
    //this.oldDatabase = client.getDB(info.database);
}

From source file:org.jboss.as.quickstarts.kitchensink.util.Resources.java

License:Apache License

@Produces
private MongoClient produceMongoClient() {
    List<DbServicePrefixMappingParser.DbServicePrefixMapping> mappings = dbServicePrefixMappingParser
            .parseDbServicePrefixMappingEnvVar(System.getenv(DB_SERVICE_PREFIX_MAPPING));
    for (DbServicePrefixMappingParser.DbServicePrefixMapping mapping : mappings) {
        if ("MONGODB".equals(mapping.getDatabaseType().toUpperCase())) {
            String hostname = System.getenv(mapping.getServiceName() + "_SERVICE_HOST");
            String port = System.getenv(mapping.getServiceName() + "_SERVICE_PORT");
            String database = System.getenv(mapping.getEnvPrefix() + "_DATABASE");
            String username = System.getenv(mapping.getEnvPrefix() + "_USERNAME");
            String password = System.getenv(mapping.getEnvPrefix() + "_PASSWORD");
            MongoCredential credential = MongoCredential.createCredential(username, database,
                    password.toCharArray());
            return new MongoClient(new ServerAddress(hostname, Integer.parseInt(port)),
                    Collections.singletonList(credential));
        }//  w w w .j  ava2  s .  com
    }
    throw new IllegalStateException("No MongoDB mapping in " + DB_SERVICE_PREFIX_MAPPING);
}

From source file:org.jenkinsci.plugins.compatibilityaction.MongoDBHolderService.java

public MongoClient createClient() throws UnknownHostException {
    if (!StringUtils.isBlank(Secret.toString(password))) {
        return new MongoClient(new ServerAddress(host, port), Arrays.asList(
                MongoCredential.createCredential(user, database, Secret.toString(password).toCharArray())));
    } else {// w  w w. j  ava2 s  .  c  o  m
        ServerAddress addr = new ServerAddress(host, port);
        return new MongoClient(addr);
    }
}