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:com.streamsets.pipeline.stage.common.mongodb.MongoDBConfig.java

License:Apache License

private List<MongoCredential> createCredentials() throws StageException {
    MongoCredential credential = null;//  w  w  w .  j a  v a 2 s. c  om
    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;
}

From source file:com.streamsets.pipeline.stage.origin.mongodb.MongoDBSource.java

License:Apache License

private List<MongoCredential> createCredentials() {
    List<MongoCredential> credentials = new ArrayList<>(1);
    MongoCredential credential = null;/*from  w ww  .ja va  2s  .  c o  m*/
    switch (authenticationType) {
    case USER_PASS:
        credential = MongoCredential.createCredential(username, mongoDatabaseName, password.toCharArray());
        break;
    case NONE:
    default:
        break;
    }

    if (null != credential) {
        credentials.add(credential);
    }
    return credentials;
}

From source file:com.supermy.im.mongo.MongoRepository.java

License:Apache License

@Bean(name = "mongoClient")
public MongoClient mongoClient() {
    System.out.println("*******************" + mongoAddress);

    ClusterSettings clusterSettings = ClusterSettings.builder()
            .hosts(Arrays.asList(new ServerAddress(mongoAddress))).build();
    MongoCredential credential = MongoCredential.createCredential(mongoUser, mydb, mongoPasswd.toCharArray());

    MongoClientSettings settings = MongoClientSettings.builder()
            .streamFactoryFactory(new NettyStreamFactoryFactory()).clusterSettings(clusterSettings)
            .credentialList(Arrays.asList(credential)).build();

    //        MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential));

    MongoClient mongoClient = MongoClients.create(settings);
    return mongoClient;
}

From source file:com.telefonica.iot.cygnus.backends.mongo.MongoBackend.java

License:Open Source License

/**
 * Gets a Mongo database./*from w w  w  .ja  v  a  2s.  com*/
 * @param dbName
 * @return
 */
private MongoDatabase getDatabase(String dbName) {
    // create a ServerAddress object for each configured URI
    List<ServerAddress> servers = new ArrayList<ServerAddress>();
    String[] uris = mongoHosts.split(",");

    for (String uri : uris) {
        String[] uriParts = uri.split(":");
        servers.add(new ServerAddress(uriParts[0], new Integer(uriParts[1])));
    } // for

    // create a Mongo client

    if (client == null) {
        if (mongoUsername.length() != 0) {
            MongoCredential credential = MongoCredential.createCredential(mongoUsername, dbName,
                    mongoPassword.toCharArray());
            client = new MongoClient(servers, Arrays.asList(credential));
        } else {
            client = new MongoClient(servers);
        } // if else
    } // if

    // get the database
    return client.getDatabase(dbName);
}

From source file:com.themodernway.server.mongodb.support.spring.MongoDBDescriptor.java

License:Open Source License

private final boolean init() {
    if (null == m_baseprop) {
        m_baseprop = MongoDBContextInstance.getMongoDBContextInstance().getMongoDBProvider()
                .getMongoDBDefaultPropertiesBase();
    }//from   w  w  w . j  a  v a  2 s  .c  o  m
    final IPropertiesResolver prop = ServerContextInstance.getServerContextInstance().getPropertiesResolver();

    setName(prop.getPropertyByName(m_baseprop + ".name"));

    setDefaultDB(prop.getPropertyByName(m_baseprop + ".db"));

    setReplicas(Boolean.valueOf(prop.getPropertyByName(m_baseprop + ".replicas", "false")));

    setCreateID(Boolean.valueOf(prop.getPropertyByName(m_baseprop + ".createid", "false")));

    final ArrayList<ServerAddress> addrlist = new ArrayList<>();

    for (String name : StringOps.requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".host.list"))
            .split(",")) {
        name = StringOps.toTrimOrNull(name);

        if (null != name) {
            final String addr = StringOps
                    .requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".host." + name + ".addr"));

            final String port = StringOps
                    .requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".host." + name + ".port"));

            addrlist.add(new ServerAddress(addr, Integer.parseInt(port)));
        }
    }
    if (addrlist.isEmpty()) {
        throw new IllegalArgumentException("no MongoDB server address");
    }
    m_addrlist = addrlist;

    m_authlist = new ArrayList<>();

    final String temp = StringOps.toTrimOrNull(prop.getPropertyByName(m_baseprop + ".auth.list"));

    if (null != temp) {
        for (String name : temp.split(",")) {
            name = StringOps.toTrimOrNull(name);

            if (null != name) {
                final String user = StringOps
                        .requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".auth." + name + ".user"));

                final String pass = StringOps
                        .requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".auth." + name + ".pass"));

                final String data = StringOps
                        .requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".auth." + name + ".db"));

                m_authlist.add(MongoCredential.createCredential(user, data, pass.toCharArray()));
            }
        }
    }
    if (null == getClientOptions()) {
        setClientOptions(MongoClientOptions.builder().connectionsPerHost(getConnectionPoolSize())
                .threadsAllowedToBlockForConnectionMultiplier(getConnectionMultiplier())
                .connectTimeout(getConnectionTimeout()).build());
    }
    m_doptions = new LinkedHashMap<>();

    final String conf = StringOps.toTrimOrNull(prop.getPropertyByName(m_baseprop + ".dbconfig.list"));

    if (null != conf) {
        for (String name : conf.split(",")) {
            name = StringOps.toTrimOrNull(name);

            if ((null != name) && (null == m_doptions.get(name))) {
                boolean doid = isCreateID();

                final ArrayList<IMongoDBCollectionOptions> list = new ArrayList<>();

                final String dbid = StringOps
                        .toTrimOrNull(prop.getPropertyByName(m_baseprop + ".dbconfig." + name + ".createid"));

                if (null != dbid) {
                    doid = Boolean.valueOf(dbid);
                }
                final String base = m_baseprop + ".dbconfig." + name + ".collections";

                final String cols = StringOps.toTrimOrNull(prop.getPropertyByName(base));

                if (null != cols) {
                    for (String coln : cols.split(",")) {
                        coln = StringOps.toTrimOrNull(coln);

                        if (null != coln) {
                            final String icid = StringOps
                                    .toTrimOrNull(prop.getPropertyByName(base + "." + coln + ".createid"));

                            if (null != icid) {
                                list.add(new MongoDBCollectionOptions(coln, Boolean.valueOf(icid)));
                            } else {
                                list.add(new MongoDBCollectionOptions(coln, doid));
                            }
                        }
                    }
                }
                m_doptions.put(name, new MongoDBOptions(name, doid, list));
            }
        }
    }
    return true;
}

From source file:com.tomtom.speedtools.mongodb.MongoConnectionCache.java

License:Apache License

/**
 * Get a MongoDB instance, given its server address(es). The server specification should be formatted as follows:
 * <pre>/*from  www .j  av  a  2 s.co  m*/
 *      hostname:port[,hostname:port]*
 * </pre>
 *
 * @param servers             Server addresses, format see above.
 * @param connectTimeoutMsecs Timeout in seconds.
 * @param userName            User name.
 * @param database            Database.
 * @param password            Password.
 * @return MongoDB instance.
 * @throws UnknownHostException If the MongoDB server cannot be found.
 */
@Nonnull
public static Mongo getMongoDB(@Nonnull final String servers, final int connectTimeoutMsecs,
        @Nonnull final String userName, @Nonnull final String database, @Nonnull final String password)
        throws UnknownHostException {
    assert servers != null;
    assert connectTimeoutMsecs >= 0;
    assert userName != null;
    assert database != null;
    assert password != null;
    try {
        return mongoDBInstances.get(servers, () -> {
            LOG.info("getMongoDB: MongoDB servers: " + servers);

            final List<ServerAddress> replicaSetSeeds = getMongoDBServerAddresses(servers);
            final List<MongoCredential> credentials = new ArrayList<>();
            if (!userName.isEmpty()) {
                LOG.debug("getMongoDB: credentials provided (username/password)");
                final MongoCredential credential = MongoCredential.createCredential(userName, database,
                        password.toCharArray());
                credentials.add(credential);
            }
            return new MongoClient(replicaSetSeeds, credentials,
                    MongoClientOptions.builder().connectTimeout(connectTimeoutMsecs).build());
        });
    } catch (final ExecutionException e) {
        throw new UnknownHostException(
                "Couldn't connect to MongoDB at: " + servers + ", cause: " + e.getCause());
    }
}

From source file:com.vcredit.lrh.db.mongodb.LRHMongoConfiguration.java

@Override
public Mongo mongo() throws Exception {
    if (mongoProperties.getUsername() != null && mongoProperties.getPassword() != null) {
        return new MongoClient(
                singletonList(new ServerAddress(mongoProperties.getHost(), mongoProperties.getPort())),
                singletonList(MongoCredential.createCredential(mongoProperties.getUsername(),
                        mongoProperties.getDatabase(), mongoProperties.getPassword().toCharArray())));
    } else {/*from  w ww  . j a  v a  2s .c  o  m*/
        return new MongoClient(
                singletonList(new ServerAddress(mongoProperties.getHost(), mongoProperties.getPort())));
    }

}

From source file:com.wlobs.wilqor.server.config.MongoConfig.java

License:Apache License

@Override
public Mongo mongo() throws Exception {
    return new MongoClient(Collections.singletonList(new ServerAddress(host, port)), Collections
            .singletonList(MongoCredential.createCredential(userName, database, password.toCharArray())));
}

From source file:com.wordpress.kuylim.configuration.MongoConfig.java

@Override
@Bean/*w  w  w  .  j  a v  a 2s .c o m*/
public Mongo mongo() throws Exception {
    return new MongoClient(singletonList(new ServerAddress(host, port)),
            singletonList(MongoCredential.createCredential(username, database, password.toCharArray())));
}

From source file:course.PrivateCloudController.java

License:Apache License

public PrivateCloudController(String mongoURIString) throws IOException {
    MongoCredential cred = MongoCredential.createCredential("admin", "cmpe283project1", "admin".toCharArray());
    final MongoClient mongoClient = new MongoClient(new ServerAddress("ds061721.mongolab.com:61721"),
            Arrays.asList(cred));
    final MongoDatabase blogDatabase = mongoClient.getDatabase("cmpe283project1");

    userDAO = new UserDAO(blogDatabase);
    sessionDAO = new SessionDAO(blogDatabase);

    statsDAO = new StatsDAO(mongoClient.getDatabase("cmpe283project1"));

    VMsDBCollection = mongoClient.getDatabase("cmpe283project1").getCollection("virtual_machines");
    if (VMsDBCollection != null) {
        System.out.println("VMs DB Collection found");
    } else/*from ww  w  .ja  v  a 2s.c om*/
        System.out.println("Sorry VMs DB Collection NOT found");

    cfg = createFreemarkerConfiguration();
    this.servInst = null;
    this.Path = null;
    //this.VMsDBCollection = null;

    servInst = new ServiceInstance(new URL(SJSULAB.getVCenterURL()), SJSULAB.getVCenterLogin(),
            SJSULAB.getVCenterPassword(), true);
    if (servInst == null) {
        System.out.println("Connection with " + SJSULAB.getVCenterURL() + " FAILED");
    } else {
        Path = servInst.getRootFolder();
        if (Path == null) {
            System.out.println("Getting Root Folder FAILED");
        }
    }
    setPort(8082);
    initializeRoutes();

    // Start the Statistics Collection Thread
    Thread statsThread = new Thread(new statsCollector());
    statsThread.start();

    //Start the Availability Manager Thread
    AvailabiltyManager av = new AvailabiltyManager();
    av.begin();

}