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:mvm.rya.mongodb.MongoDBRyaDAO.java

License:Apache License

public void initConnection() throws RyaDAOException {
    try {//from w  w  w . j ava 2  s.  c  o  m
        boolean useMongoTest = conf.getUseTestMongo();
        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 {
            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);
            }
        }
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:mx.iteso.msc.bda.banksimulator.dbaccess.DbClient.java

License:Apache License

public static MongoClient openConnection() {
    //        Random r = new Random();
    //        if (r.nextInt(101) < DB_SUCCESS_RATE) {
    MongoCredential credential = MongoCredential.createCredential(USERNAME, DATABASE, PASSWORD.toCharArray());
    MongoClient client = new MongoClient(new ServerAddress(SERVER, PORT), Arrays.asList(credential));

    //            try {
    //               Thread.sleep(DB_DELAY);
    //            } catch (InterruptedException ex) {
    //                Logger.getLogger(DbClient.class.getName()).log(Level.SEVERE, null, ex);
    //            }

    return client;
    //        }/*www.  java2 s  . c  o m*/
    //        else {
    //            System.out.println("Simulated database error");
    //            return null;
    //        }
}

From source file:net.es.netshell.mongodb.MongoDBProvider.java

License:Open Source License

public MongoDBProvider(String host, int port, String dbName, String mongoUser, String password) {
    this.serverAddress = new ServerAddress(host, port);
    ArrayList<MongoCredential> creds = new ArrayList<MongoCredential>();
    MongoCredential enosCred = MongoCredential.createCredential(mongoUser, dbName, password.toCharArray());
    creds.add(enosCred);/*  w w  w . ja v a 2s  . c  om*/
    this.client = new MongoClient(this.serverAddress, creds);
    this.db = client.getDatabase(dbName);
}

From source file:net.netzgut.integral.mongo.configuration.MongoConfigurationBuilder.java

License:Apache License

/**
 * Adds a {@link com.mongodb.MongoCredential} to the list of credentials
 * based on the provided username/database/password.
 *//* w w w.j a  va  2s  .c om*/
public MongoConfigurationBuilder addCredential(String username, String database, String password) {
    if (username == null || username.isEmpty()) {
        throw new IllegalArgumentException("Can't add null credentials (username).");
    }

    if (database == null || database.isEmpty()) {
        throw new IllegalArgumentException("Can't add null credentials (database).");
    }

    MongoCredential credential = MongoCredential.createCredential(username, database, password.toCharArray());

    return addCredential(credential);
}

From source file:net.ymate.platform.persistence.mongodb.impl.MongoDataSourceAdapter.java

License:Apache License

public void initialize(IMongoClientOptionsHandler optionsHandler, MongoDataSourceCfgMeta cfgMeta)
        throws Exception {
    __cfgMeta = cfgMeta;/* ww w  . j  ava 2  s  .c o m*/
    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());
        }
    }
}

From source file:nosqltools.DBConnection.java

/**
 * Passed parameters are used to connect to the MongoDB 3.0 server
 * @param username/*from   ww w.  j a v a 2s  .  co  m*/
 * @param password
 * @param database
 * @param serveraddr The IP Address of the MongoDB Server
 * @param port The port on which the MongoDB Server is running
 * @return True if the connection to the MongoDB server is a success, else false
 */
public boolean connect(String username, String password, String database, String serveraddr, int port) {
    try {
        //If any of the parameters (username, password or DB name are empty, connection will not be attempted)
        if ("".equals(username.trim()) || "".equals(password.trim()) || "".equals(database.trim()))
            return false;

        //A mongocredential object is constructed using the username, password and DB name
        MongoCredential credential = MongoCredential.createCredential(username, database,
                password.toCharArray());

        //if no server address has been specified, use localhost
        if ("".equals(serveraddr) || serveraddr == null)
            mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential));
        else
            mongoClient = new MongoClient(new ServerAddress(serveraddr, port), Arrays.asList(credential));

        //The DB instance is stored
        db = mongoClient.getDB(database);

        //Authentication to the  DB is done below using the username and password supplied by the user
        boolean auth;
        try {
            auth = db.authenticate(username, password.toCharArray());
        } catch (Exception e) {
            auth = false;
        }
        return auth;

    } catch (UnknownHostException | MongoCommandException e) {
        return false;
    }
}

From source file:org.adoptopenjdk.jcountdown.control.MongoClientProducer.java

License:Apache License

@Produces
@ApplicationScoped//from ww w  . j  a  v a 2 s.  c  o m
public MongoClient produceClient() {
    // default host is localhost, default port is 27017       

    ServerAddress serverAddress = new ServerAddress(mongoConfiguration.getHost(), mongoConfiguration.getPort());

    MongoCredential mongoCredential = MongoCredential.createCredential(mongoConfiguration.getUsername(),
            mongoConfiguration.getDatabaseName(), mongoConfiguration.getPassword());

    List<MongoCredential> credentials = new ArrayList<>();
    credentials.add(mongoCredential);
    return new MongoClient(serverAddress, credentials);
}

From source file:org.apache.gora.mongodb.store.MongoStore.java

License:Apache License

/**
 * Retrieve a client connected to the MongoDB server to be used.
 *
 * @param servers//w ww .  j  a v  a 2s  .  c  o m
 *          This value should specify the host:port (at least one) for
 *          connecting to remote MongoDB. Multiple values must be separated by
 *          coma.
 * @return a {@link Mongo} instance connected to the server
 * @throws UnknownHostException
 */
private MongoClient getClient(MongoStoreParameters params) throws UnknownHostException {
    // Configure options
    MongoClientOptions.Builder optBuilder = new MongoClientOptions.Builder()
            .dbEncoderFactory(GoraDBEncoder.FACTORY); // Utf8 serialization!
    if (params.getReadPreference() != null) {
        optBuilder.readPreference(ReadPreference.valueOf(params.getReadPreference()));
    }
    if (params.getWriteConcern() != null) {
        optBuilder.writeConcern(WriteConcern.valueOf(params.getWriteConcern()));
    }
    // If configuration contains a login + secret, try to authenticated with DB
    List<MongoCredential> credentials = null;
    if (params.getLogin() != null && params.getSecret() != null) {
        credentials = new ArrayList<MongoCredential>();
        credentials.add(MongoCredential.createCredential(params.getLogin(), params.getDbname(),
                params.getSecret().toCharArray()));
    }
    // Build server address
    List<ServerAddress> addrs = new ArrayList<ServerAddress>();
    Iterable<String> serversArray = Splitter.on(",").split(params.getServers());
    if (serversArray != null) {
        for (String server : serversArray) {
            Iterator<String> paramsIterator = Splitter.on(":").trimResults().split(server).iterator();
            if (!paramsIterator.hasNext()) {
                // No server, use default
                addrs.add(new ServerAddress());
            } else {
                String host = paramsIterator.next();
                if (paramsIterator.hasNext()) {
                    String port = paramsIterator.next();
                    addrs.add(new ServerAddress(host, Integer.parseInt(port)));
                } else {
                    addrs.add(new ServerAddress(host));
                }
            }
        }
    }
    // Connect to the Mongo server
    return new MongoClient(addrs, credentials, optBuilder.build());
}

From source file:org.apache.logging.log4j.nosql.appender.mongodb.MongoDbProvider.java

License:Apache License

/**
 * Factory method for creating a MongoDB provider within the plugin manager.
 *
 * @param collectionName The name of the MongoDB collection to which log events should be written.
 * @param writeConcernConstant The {@link WriteConcern} constant to control writing details, defaults to
 *                             {@link WriteConcern#ACKNOWLEDGED}.
 * @param writeConcernConstantClassName The name of a class containing the aforementioned static WriteConcern
 *                                      constant. Defaults to {@link WriteConcern}.
 * @param databaseName The name of the MongoDB database containing the collection to which log events should be
 *                     written. Mutually exclusive with {@code factoryClassName&factoryMethodName!=null}.
 * @param server The host name of the MongoDB server, defaults to localhost and mutually exclusive with
 *               {@code factoryClassName&factoryMethodName!=null}.
 * @param port The port the MongoDB server is listening on, defaults to the default MongoDB port and mutually
 *             exclusive with {@code factoryClassName&factoryMethodName!=null}.
 * @param userName The username to authenticate against the MongoDB server with.
 * @param password The password to authenticate against the MongoDB server with.
 * @param factoryClassName A fully qualified class name containing a static factory method capable of returning a
 *                         {@link DB} or a {@link MongoClient}.
 * @param factoryMethodName The name of the public static factory method belonging to the aforementioned factory
 *                          class./*from  w w  w  .j  a  va2s  .  c  om*/
 * @return a new MongoDB provider.
 */
@PluginFactory
public static MongoDbProvider createNoSqlProvider(
        @PluginAttribute("collectionName") final String collectionName,
        @PluginAttribute("writeConcernConstant") final String writeConcernConstant,
        @PluginAttribute("writeConcernConstantClass") final String writeConcernConstantClassName,
        @PluginAttribute("databaseName") final String databaseName,
        @PluginAttribute("server") final String server, @PluginAttribute("port") final String port,
        @PluginAttribute("userName") final String userName,
        @PluginAttribute(value = "password", sensitive = true) final String password,
        @PluginAttribute("factoryClassName") final String factoryClassName,
        @PluginAttribute("factoryMethodName") final String factoryMethodName) {
    DB database;
    String description;
    if (Strings.isNotEmpty(factoryClassName) && Strings.isNotEmpty(factoryMethodName)) {
        try {
            final Class<?> factoryClass = Loader.loadClass(factoryClassName);
            final Method method = factoryClass.getMethod(factoryMethodName);
            final Object object = method.invoke(null);

            if (object instanceof DB) {
                database = (DB) object;
            } else if (object instanceof MongoClient) {
                if (Strings.isNotEmpty(databaseName)) {
                    database = ((MongoClient) object).getDB(databaseName);
                } else {
                    LOGGER.error("The factory method [{}.{}()] returned a MongoClient so the database name is "
                            + "required.", factoryClassName, factoryMethodName);
                    return null;
                }
            } else if (object == null) {
                LOGGER.error("The factory method [{}.{}()] returned null.", factoryClassName,
                        factoryMethodName);
                return null;
            } else {
                LOGGER.error("The factory method [{}.{}()] returned an unsupported type [{}].",
                        factoryClassName, factoryMethodName, object.getClass().getName());
                return null;
            }

            description = "database=" + database.getName();
            final List<ServerAddress> addresses = database.getMongo().getAllAddress();
            if (addresses.size() == 1) {
                description += ", server=" + addresses.get(0).getHost() + ", port="
                        + addresses.get(0).getPort();
            } else {
                description += ", servers=[";
                for (final ServerAddress address : addresses) {
                    description += " { " + address.getHost() + ", " + address.getPort() + " } ";
                }
                description += "]";
            }
        } catch (final ClassNotFoundException e) {
            LOGGER.error("The factory class [{}] could not be loaded.", factoryClassName, e);
            return null;
        } catch (final NoSuchMethodException e) {
            LOGGER.error("The factory class [{}] does not have a no-arg method named [{}].", factoryClassName,
                    factoryMethodName, e);
            return null;
        } catch (final Exception e) {
            LOGGER.error("The factory method [{}.{}()] could not be invoked.", factoryClassName,
                    factoryMethodName, e);
            return null;
        }
    } else if (Strings.isNotEmpty(databaseName)) {
        List<MongoCredential> credentials = new ArrayList<>();
        description = "database=" + databaseName;
        if (Strings.isNotEmpty(userName) && Strings.isNotEmpty(password)) {
            description += ", username=" + userName + ", passwordHash="
                    + NameUtil.md5(password + MongoDbProvider.class.getName());
            credentials.add(MongoCredential.createCredential(userName, databaseName, password.toCharArray()));
        }
        try {
            if (Strings.isNotEmpty(server)) {
                final int portInt = AbstractAppender.parseInt(port, 0);
                description += ", server=" + server;
                if (portInt > 0) {
                    description += ", port=" + portInt;
                    database = new MongoClient(new ServerAddress(server, portInt), credentials)
                            .getDB(databaseName);
                } else {
                    database = new MongoClient(new ServerAddress(server), credentials).getDB(databaseName);
                }
            } else {
                database = new MongoClient(new ServerAddress(), credentials).getDB(databaseName);
            }
        } catch (final Exception e) {
            LOGGER.error("Failed to obtain a database instance from the MongoClient at server [{}] and "
                    + "port [{}].", server, port);
            return null;
        }
    } else {
        LOGGER.error("No factory method was provided so the database name is required.");
        return null;
    }

    try {
        database.getCollectionNames(); // Check if the database actually requires authentication
    } catch (final Exception e) {
        LOGGER.error(
                "The database is not up, or you are not authenticated, try supplying a username and password to the MongoDB provider.",
                e);
        return null;
    }

    WriteConcern writeConcern = toWriteConcern(writeConcernConstant, writeConcernConstantClassName);

    return new MongoDbProvider(database, writeConcern, collectionName, description);
}

From source file:org.apache.metamodel.DataContextFactory.java

License:Apache License

/**
 * Creates a new MongoDB datacontext.//  w w  w .jav  a  2 s . com
 * 
 * @param hostname
 *            The hostname of the MongoDB instance
 * @param port
 *            the port of the MongoDB instance, or null if the default port
 *            should be used.
 * @param databaseName
 *            the name of the database
 * @param username
 *            the username, or null if unauthenticated access should be used
 * @param password
 *            the password, or null if unathenticated access should be used
 * @param tableDefs
 *            an array of table definitions, or null if table definitions
 *            should be autodetected.
 * @return a DataContext object that matches the request
 */
public static UpdateableDataContext createMongoDbDataContext(String hostname, Integer port, String databaseName,
        String username, char[] password, SimpleTableDef[] tableDefs) {
    try {
        final ServerAddress serverAddress;
        if (port == null) {
            serverAddress = new ServerAddress(hostname);
        } else {
            serverAddress = new ServerAddress(hostname, port);
        }
        final MongoClient mongoClient;
        final MongoDatabase mongoDb;
        if (Strings.isNullOrEmpty(username)) {
            mongoClient = new MongoClient(serverAddress);
        } else {
            final MongoCredential credential = MongoCredential.createCredential(username, databaseName,
                    password);
            mongoClient = new MongoClient(serverAddress, Arrays.asList(credential));
        }
        mongoDb = mongoClient.getDatabase(databaseName);

        if (tableDefs == null || tableDefs.length == 0) {
            return new MongoDbDataContext(mongoDb);
        }
        return new MongoDbDataContext(mongoDb, tableDefs);
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new IllegalStateException(e);
    }
}