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:io.gravitee.am.identityprovider.mongo.authentication.spring.MongoAuthenticationProviderConfiguration.java

License:Apache License

@Bean
public MongoClient mongoClient() {
    MongoClient mongoClient;//from   w  ww  .  j  a  va  2s .  c o m
    if ((this.configuration.getUri() != null) && (!this.configuration.getUri().isEmpty())) {
        mongoClient = MongoClients.create(this.configuration.getUri());
    } else {
        ServerAddress serverAddress = new ServerAddress(this.configuration.getHost(),
                this.configuration.getPort());
        ClusterSettings clusterSettings = ClusterSettings.builder().hosts(asList(serverAddress)).build();
        MongoClientSettings.Builder settings = MongoClientSettings.builder().clusterSettings(clusterSettings);
        if (this.configuration.isEnableCredentials()) {
            MongoCredential credential = MongoCredential.createCredential(
                    this.configuration.getUsernameCredentials(), this.configuration.getDatabaseCredentials(),
                    this.configuration.getPasswordCredentials().toCharArray());
            settings.credential(credential);
        }
        mongoClient = MongoClients.create(settings.build());
    }
    return mongoClient;
}

From source file:io.gravitee.am.repository.mongodb.common.MongoFactory.java

License:Apache License

@Override
public MongoClient getObject() throws Exception {
    // Client settings
    MongoClientSettings.Builder builder = MongoClientSettings.builder();
    builder.writeConcern(WriteConcern.ACKNOWLEDGED);

    // codec configuration for pojo mapping
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClients.getDefaultCodecRegistry(),
            fromProviders(PojoCodecProvider.builder().automatic(true).build()));
    builder.codecRegistry(pojoCodecRegistry);

    // Trying to get the MongoClientURI if uri property is defined
    String uri = readPropertyValue(propertyPrefix + "uri");
    if (uri != null && !uri.isEmpty()) {
        // The builder can be configured with default options, which may be overridden by options specified in
        // the URI string.
        MongoClientSettings settings = builder.codecRegistry(pojoCodecRegistry)
                .applyConnectionString(new ConnectionString(uri)).build();

        return MongoClients.create(settings);
    } else {//from www.java  2 s .c  o  m
        // Advanced configuration
        SocketSettings.Builder socketBuilder = SocketSettings.builder();
        ClusterSettings.Builder clusterBuilder = ClusterSettings.builder();
        ConnectionPoolSettings.Builder connectionPoolBuilder = ConnectionPoolSettings.builder();
        ServerSettings.Builder serverBuilder = ServerSettings.builder();
        SslSettings.Builder sslBuilder = SslSettings.builder();

        Integer connectTimeout = readPropertyValue(propertyPrefix + "connectTimeout", Integer.class, 1000);
        Integer maxWaitTime = readPropertyValue(propertyPrefix + "maxWaitTime", Integer.class);
        Integer socketTimeout = readPropertyValue(propertyPrefix + "socketTimeout", Integer.class, 1000);
        Boolean socketKeepAlive = readPropertyValue(propertyPrefix + "socketKeepAlive", Boolean.class, true);
        Integer maxConnectionLifeTime = readPropertyValue(propertyPrefix + "maxConnectionLifeTime",
                Integer.class);
        Integer maxConnectionIdleTime = readPropertyValue(propertyPrefix + "maxConnectionIdleTime",
                Integer.class);

        // We do not want to wait for a server
        Integer serverSelectionTimeout = readPropertyValue(propertyPrefix + "serverSelectionTimeout",
                Integer.class, 1000);
        Integer minHeartbeatFrequency = readPropertyValue(propertyPrefix + "minHeartbeatFrequency",
                Integer.class);
        String description = readPropertyValue(propertyPrefix + "description", String.class, "gravitee.io");
        Integer heartbeatFrequency = readPropertyValue(propertyPrefix + "heartbeatFrequency", Integer.class);
        Boolean sslEnabled = readPropertyValue(propertyPrefix + "sslEnabled", Boolean.class);

        if (maxWaitTime != null)
            connectionPoolBuilder.maxWaitTime(maxWaitTime, TimeUnit.MILLISECONDS);
        if (connectTimeout != null)
            socketBuilder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
        if (socketTimeout != null)
            socketBuilder.readTimeout(socketTimeout, TimeUnit.MILLISECONDS);
        if (socketKeepAlive != null)
            socketBuilder.keepAlive(socketKeepAlive);
        if (maxConnectionLifeTime != null)
            connectionPoolBuilder.maxConnectionLifeTime(maxConnectionLifeTime, TimeUnit.MILLISECONDS);
        if (maxConnectionIdleTime != null)
            connectionPoolBuilder.maxConnectionIdleTime(maxConnectionIdleTime, TimeUnit.MILLISECONDS);
        if (minHeartbeatFrequency != null)
            serverBuilder.minHeartbeatFrequency(minHeartbeatFrequency, TimeUnit.MILLISECONDS);
        if (description != null)
            clusterBuilder.description(description);
        if (heartbeatFrequency != null)
            serverBuilder.heartbeatFrequency(heartbeatFrequency, TimeUnit.MILLISECONDS);
        if (sslEnabled != null)
            sslBuilder.enabled(sslEnabled);
        if (serverSelectionTimeout != null)
            clusterBuilder.serverSelectionTimeout(serverSelectionTimeout, TimeUnit.MILLISECONDS);

        // credentials option
        String username = readPropertyValue(propertyPrefix + "username");
        String password = readPropertyValue(propertyPrefix + "password");
        MongoCredential credentials = null;
        if (username != null || password != null) {
            String authSource = readPropertyValue(propertyPrefix + "authSource", String.class, "gravitee-am");
            credentials = MongoCredential.createCredential(username, authSource, password.toCharArray());
            builder.credential(credentials);
        }

        // clustering option
        List<ServerAddress> seeds;
        int serversCount = getServersCount();
        if (serversCount == 0) {
            String host = readPropertyValue(propertyPrefix + "host", String.class, "localhost");
            int port = readPropertyValue(propertyPrefix + "port", int.class, 27017);
            seeds = Collections.singletonList(new ServerAddress(host, port));
        } else {
            seeds = new ArrayList<>(serversCount);
            for (int i = 0; i < serversCount; i++) {
                seeds.add(buildServerAddress(i));
            }
        }
        clusterBuilder.hosts(seeds);

        SocketSettings socketSettings = socketBuilder.build();
        ClusterSettings clusterSettings = clusterBuilder.build();
        ConnectionPoolSettings connectionPoolSettings = connectionPoolBuilder.build();
        ServerSettings serverSettings = serverBuilder.build();
        SslSettings sslSettings = sslBuilder.build();
        MongoClientSettings settings = builder
                .applyToClusterSettings(builder1 -> builder1.applySettings(clusterSettings))
                .applyToSocketSettings(builder1 -> builder1.applySettings(socketSettings))
                .applyToConnectionPoolSettings(builder1 -> builder1.applySettings(connectionPoolSettings))
                .applyToServerSettings(builder1 -> builder1.applySettings(serverSettings))
                .applyToSslSettings(builder1 -> builder1.applySettings(sslSettings)).build();

        return MongoClients.create(settings);
    }
}

From source file:io.seventyone.mongoutils.MongoServiceImplementation.java

License:Apache License

public MongoServiceImplementation(String host, int port, String dbName, String user, String password) {

    ServerAddress serverAddress = new ServerAddress(host, port);
    if (StringUtils.isBlank(user)) {
        this.mongoClient = new MongoClient(serverAddress);
    } else {// www .j  av a2 s . c o m
        MongoCredential credential = MongoCredential.createCredential(user, dbName, password.toCharArray());
        this.mongoClient = new MongoClient(serverAddress, Collections.singletonList(credential));
    }

    this.db = this.mongoClient.getDatabase(dbName);
}

From source file:joliex.mongodb.MongoDbConnector.java

@RequestResponse
public void connect(Value request) throws FaultException {
    try {//from ww  w  . java 2s  .  c om
        host = request.getFirstChild("host").strValue();
        port = request.getFirstChild("port").intValue();
        dbname = request.getFirstChild("dbname").strValue();
        timeZone = request.getFirstChild("timeZone").strValue();
        password = request.getFirstChild("password").strValue();
        username = request.getFirstChild("username").strValue();
        log = Logger.getLogger("org.mongodb.driver");
        log.setLevel(Level.OFF);
        if (request.hasChildren("jsonStringDebug")) {
            jsonDebuger = request.getFirstChild("jsonStringDebug").boolValue();
        }
        if (request.hasChildren("logStreamDebug")) {
            logStream = request.getFirstChild("logStreamDebug").boolValue();
            logString = "Processing Steps at " + System.currentTimeMillis();
        }
        if (System.getProperty("os.arch").contains("64")) {
            is64 = true;
        } else {
            is64 = false;
        }

        zone = DateTimeZone.forID(timeZone);

        ServerAddress serverAddress = new ServerAddress(host, port);
        MongoCredential credential = MongoCredential.createCredential(username, dbname, password.toCharArray());
        mongoClientOptions = MongoClientOptions.builder().build();

        if (null != mongoClient) {
            System.out.println("recovering client");
            db = mongoClient.getDatabase(dbname);
        } else {

            mongoClient = new MongoClient(serverAddress, credential, mongoClientOptions);
            db = mongoClient.getDatabase(dbname);
        }

    } catch (MongoException ex) {
        throw new FaultException("LoginConnection", ex);
    }
}

From source file:lets.helloworld.MangoConnection.java

public MangoConnection(String database, String user, String pass) {

    List<MongoCredential> creds = new ArrayList<>();
    MongoCredential cred = MongoCredential.createCredential(user, database, pass.toCharArray());
    creds.add(cred);/*  w  w  w  . j ava 2s. co m*/
    mClient = new MongoClient(address, creds);
    mDB = mClient.getDatabase(database);
}

From source file:me.konglong.momei.mongodb.config.MongoCredentialPropertyEditor.java

License:Apache License

@Override
public void setAsText(String text) throws IllegalArgumentException {

    if (!StringUtils.hasText(text)) {
        return;/*from   w  w  w  .j av  a2 s  .com*/
    }

    List<MongoCredential> credentials = new ArrayList<MongoCredential>();

    for (String credentialString : extractCredentialsString(text)) {

        String[] userNameAndPassword = extractUserNameAndPassword(credentialString);
        String database = extractDB(credentialString);
        Properties options = extractOptions(credentialString);

        if (!options.isEmpty()) {

            if (options.containsKey(AUTH_MECHANISM_KEY)) {

                String authMechanism = options.getProperty(AUTH_MECHANISM_KEY);

                if (MongoCredential.GSSAPI_MECHANISM.equals(authMechanism)) {

                    verifyUserNamePresent(userNameAndPassword);
                    credentials.add(MongoCredential.createGSSAPICredential(userNameAndPassword[0]));
                } else if (MongoCredential.MONGODB_CR_MECHANISM.equals(authMechanism)) {

                    verifyUsernameAndPasswordPresent(userNameAndPassword);
                    verifyDatabasePresent(database);
                    credentials.add(MongoCredential.createMongoCRCredential(userNameAndPassword[0], database,
                            userNameAndPassword[1].toCharArray()));
                } else if (MongoCredential.MONGODB_X509_MECHANISM.equals(authMechanism)) {

                    verifyUserNamePresent(userNameAndPassword);
                    credentials.add(MongoCredential.createMongoX509Credential(userNameAndPassword[0]));
                } else if (MongoCredential.PLAIN_MECHANISM.equals(authMechanism)) {

                    verifyUsernameAndPasswordPresent(userNameAndPassword);
                    verifyDatabasePresent(database);
                    credentials.add(MongoCredential.createPlainCredential(userNameAndPassword[0], database,
                            userNameAndPassword[1].toCharArray()));
                } else if (MongoCredential.SCRAM_SHA_1_MECHANISM.equals(authMechanism)) {

                    verifyUsernameAndPasswordPresent(userNameAndPassword);
                    verifyDatabasePresent(database);
                    credentials.add(MongoCredential.createScramSha1Credential(userNameAndPassword[0], database,
                            userNameAndPassword[1].toCharArray()));
                } else {
                    throw new IllegalArgumentException(String.format(
                            "Cannot create MongoCredentials for unknown auth mechanism '%s'!", authMechanism));
                }
            }
        } else {

            verifyUsernameAndPasswordPresent(userNameAndPassword);
            verifyDatabasePresent(database);
            credentials.add(MongoCredential.createCredential(userNameAndPassword[0], database,
                    userNameAndPassword[1].toCharArray()));
        }
    }

    setValue(credentials);
}

From source file:me.lucko.luckperms.common.storage.backing.MongoDBBacking.java

License:Open Source License

@Override
public void init() {
    MongoCredential credential = null;//from   w w  w. j  a  v  a2s  . c o  m

    if (configuration.getUsername() != null && !configuration.getUsername().equals("")
            && configuration.getDatabase() != null && !configuration.getDatabase().equals("")) {
        if (configuration.getPassword() == null || configuration.getPassword().equals("")) {
            credential = MongoCredential.createCredential(configuration.getUsername(),
                    configuration.getDatabase(), null);
        } else {
            credential = MongoCredential.createCredential(configuration.getUsername(),
                    configuration.getDatabase(), configuration.getPassword().toCharArray());
        }
    }

    String[] addressSplit = 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) {
        mongoClient = new MongoClient(address, Collections.emptyList());
    } else {
        mongoClient = new MongoClient(address, Collections.singletonList(credential));
    }

    database = mongoClient.getDatabase(configuration.getDatabase());
    setAcceptingLogins(true);
}

From source file:me.lucko.luckperms.common.storage.dao.mongodb.MongoDao.java

License:MIT License

@Override
public void init() {
    MongoCredential credential = null;//  www  . j a va  2  s  . c  o m
    if (!Strings.isNullOrEmpty(configuration.getUsername())) {
        credential = MongoCredential.createCredential(configuration.getUsername(), configuration.getDatabase(),
                Strings.isNullOrEmpty(configuration.getPassword()) ? null
                        : configuration.getPassword().toCharArray());
    }

    String[] addressSplit = 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) {
        mongoClient = new MongoClient(address, Collections.emptyList());
    } else {
        mongoClient = new MongoClient(address, Collections.singletonList(credential));
    }

    database = mongoClient.getDatabase(configuration.getDatabase());
}

From source file:me.lucko.luckperms.storage.methods.MongoDBDatastore.java

License:Open Source License

@Override
public void init() {
    MongoCredential credential = MongoCredential.createCredential(configuration.getUsername(),
            configuration.getDatabase(), configuration.getPassword().toCharArray());

    ServerAddress address = new ServerAddress(configuration.getAddress().split(":")[0],
            Integer.parseInt(configuration.getAddress().split(":")[1]));

    mongoClient = new MongoClient(address, Collections.singletonList(credential));
    database = mongoClient.getDatabase(configuration.getDatabase());
    setAcceptingLogins(true);/*from  www.j  av  a 2  s.c  om*/
}

From source file:mvm.rya.indexing.mongodb.MongoGeoIndexer.java

License:Apache License

private void init() throws NumberFormatException, IOException {
    boolean useMongoTest = conf.getBoolean(MongoDBRdfConfiguration.USE_TEST_MONGO, false);
    if (useMongoTest) {
        testsFactory = MongodForTestsFactory.with(Version.Main.PRODUCTION);
        mongoClient = testsFactory.newMongo();
        int port = mongoClient.getServerAddressList().get(0).getPort();
        conf.set(MongoDBRdfConfiguration.MONGO_INSTANCE_PORT, Integer.toString(port));
    } else {//w  w  w .java  2 s . c  o  m
        ServerAddress server = new ServerAddress(conf.get(MongoDBRdfConfiguration.MONGO_INSTANCE),
                Integer.valueOf(conf.get(MongoDBRdfConfiguration.MONGO_INSTANCE_PORT)));
        if (conf.get(MongoDBRdfConfiguration.MONGO_USER) != null) {
            MongoCredential cred = MongoCredential.createCredential(
                    conf.get(MongoDBRdfConfiguration.MONGO_USER),
                    conf.get(MongoDBRdfConfiguration.MONGO_DB_NAME),
                    conf.get(MongoDBRdfConfiguration.MONGO_USER_PASSWORD).toCharArray());
            mongoClient = new MongoClient(server, Arrays.asList(cred));
        } else {
            mongoClient = new MongoClient(server);
        }
    }
    predicates = ConfigUtils.getGeoPredicates(conf);
    tableName = conf.get(MongoDBRdfConfiguration.MONGO_DB_NAME);
    db = mongoClient.getDB(tableName);
    coll = db.getCollection(conf.get(MongoDBRdfConfiguration.MONGO_COLLECTION_PREFIX, "rya"));
    storageStrategy = new GeoMongoDBStorageStrategy(
            Double.valueOf(conf.get(MongoDBRdfConfiguration.MONGO_GEO_MAXDISTANCE, "1e-10")));
}