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.springframework.boot.autoconfigure.mongo.ReactiveMongoClientFactory.java

License:Apache License

private void applyCredentials(Builder builder) {
    String database = (this.properties.getAuthenticationDatabase() != null)
            ? this.properties.getAuthenticationDatabase()
            : this.properties.getMongoClientDatabase();
    builder.credential((MongoCredential.createCredential(this.properties.getUsername(), database,
            this.properties.getPassword())));
}

From source file:org.test.falcon.config.MongoProperties.java

License:Apache License

/**
 * Creates a {@link MongoClient} using the given {@code options} and
 * {@code environment}. If the configured port is zero, the value of the
 * {@code local.mongo.port} property retrieved from the {@code environment}
 * is used to configure the client./*from  w w  w . ja  v a2s  . com*/
 *
 * @param options
 *            the options
 * @return the Mongo client
 * @throws UnknownHostException
 *             if the configured host is unknown
 */
public MongoClient createMongoClient(MongoClientOptions options) throws UnknownHostException {
    try {
        if (options == null) {
            options = MongoClientOptions.builder().build();
        }
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        String database = this.authenticationDatabase == null ? getMongoClientDatabase()
                : this.authenticationDatabase;
        credentials.add(MongoCredential.createCredential(this.username, database, this.password));
        String host = this.host == null ? "localhost" : this.host;
        int port = determinePort();
        return new MongoClient(Arrays.asList(new ServerAddress(host, port)), credentials, options);
    } finally {
        clearPassword();
    }
}

From source file:org.venice.piazza.servicecontroller.data.mongodb.accessors.MongoAccessor.java

License:Apache License

@PostConstruct
private void initialize() {
    try {/*from   w w  w.j  a v  a2 s. c  om*/
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        // Enable SSL if the `mongossl` Profile is enabled
        if (Arrays.stream(environment.getActiveProfiles()).anyMatch(env -> env.equalsIgnoreCase("mongossl"))) {
            builder.sslEnabled(true);
            builder.sslInvalidHostNameAllowed(true);
        }
        // If a username and password are provided, then associate these credentials with the connection
        if ((!StringUtils.isEmpty(DATABASE_USERNAME)) && (!StringUtils.isEmpty(DATABASE_CREDENTIAL))) {
            mongoClient = new MongoClient(new ServerAddress(DATABASE_HOST, DATABASE_PORT),
                    Arrays.asList(MongoCredential.createCredential(DATABASE_USERNAME, DATABASE_NAME,
                            DATABASE_CREDENTIAL.toCharArray())),
                    builder.threadsAllowedToBlockForConnectionMultiplier(mongoThreadMultiplier).build());
        } else {
            mongoClient = new MongoClient(new ServerAddress(DATABASE_HOST, DATABASE_PORT),
                    builder.threadsAllowedToBlockForConnectionMultiplier(mongoThreadMultiplier).build());
        }

    } catch (Exception exception) {
        LOGGER.error(String.format("Error connecting to MongoDB Instance. %s", exception.getMessage()),
                exception);

    }
}

From source file:org.wso2.carbon.datasource.reader.mongo.MongoDataSourceReaderUtil.java

License:Open Source License

private static MongoCredential createCredentials(MongoDataSourceConfiguration fileConfig) {
    MongoCredential credential;/* w  w  w  .  ja v  a2s.c o m*/
    switch (fileConfig.getAuthenticationMethodEnum()) {
    case SCRAM_SHA_1:
        credential = MongoCredential.createScramSha1Credential(fileConfig.getUsername(),
                fileConfig.getDatabase(), fileConfig.getPassword().toCharArray());
        break;
    case MONGODB_CR:
        credential = MongoCredential.createMongoCRCredential(fileConfig.getUsername(), fileConfig.getDatabase(),
                fileConfig.getPassword().toCharArray());
    case LDAP_PLAIN:
        credential = MongoCredential.createPlainCredential(fileConfig.getUsername(), fileConfig.getAuthSource(),
                fileConfig.getPassword().toCharArray());
    case X_509:
        credential = MongoCredential.createMongoX509Credential(fileConfig.getUsername());
    case GSSAPI:
        credential = MongoCredential.createGSSAPICredential(fileConfig.getUsername());
    case DEFAULT:
    default:
        credential = MongoCredential.createCredential(fileConfig.getUsername(), fileConfig.getDatabase(),
                fileConfig.getPassword().toCharArray());
    }
    return credential;
}

From source file:redmart.crm.product.dao.ProductDAO.java

public ProductDAO() {
    this.host = ApplicationConstants.MONGO_DB_HOST;
    this.port = ApplicationConstants.MONGO_DB_PORT;
    this.databaseName = ApplicationConstants.MONGO_DB_NAME;
    this.userName = ApplicationConstants.MONGO_DB_USER;
    this.password = ApplicationConstants.MONGO_DB_PWD;
    List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
    MongoCredential credentia = MongoCredential.createCredential(userName, databaseName,
            password.toCharArray());/* www. ja v  a 2  s  .  c o m*/
    credentialsList.add(credentia);
    ServerAddress addr = new ServerAddress(host, port);
    MongoClient mongoClient = new MongoClient(addr, credentialsList);
    Morphia morphia = new Morphia();
    morphia.mapPackage(ApplicationConstants.MONGO_PACKAGE);
    datastore = morphia.createDatastore(mongoClient, databaseName);
    datastore.ensureIndexes();
}

From source file:servlets.module.challenge.NoSqlInjection1.java

License:Open Source License

/**
 * Users have to use NoSQL injection to get a specific user (Marlo) gamer ID. The query they are injecting into by default only outputs usernames.
 * The input they enter is also been filtered.
 * @param theUserName User name used in database look up.
 *///from  ww w .  j  ava 2 s . c  om
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //Setting IpAddress To Log and taking header for original IP if forwarded from proxy
    ShepherdLogManager.setRequestIp(request.getRemoteAddr(), request.getHeader("X-Forwarded-For"));
    //Attempting to recover user name of session that made request
    HttpSession ses = request.getSession(true);
    if (Validate.validateSession(ses)) {
        ShepherdLogManager.setRequestIp(request.getRemoteAddr(), request.getHeader("X-Forwarded-For"),
                ses.getAttribute("userName").toString());
        log.debug(levelName + " servlet accessed by: " + ses.getAttribute("userName").toString());

        PrintWriter out = response.getWriter();
        out.print(getServletInfo());
        String htmlOutput = new String();
        Encoder encoder = ESAPI.encoder();

        //MongoDb
        // To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
        // if it's a member of a replica set:
        MongoClient mongoClient;
        @SuppressWarnings("unused")
        MongoCredential credential;
        DB mongoDb;
        //BasicDBObject whereQuery = new BasicDBObject();
        DBCollection coll;
        DBCursor cursor = null;

        String user; // the user name
        String database; // the name of the database in which the user is defined
        char[] password; // the password as a character array

        try {

            log.debug("Getting Connection to Mongo Database");
            // To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
            // if it's a member of a replica set:
            mongoClient = new MongoClient();

            user = "gamer1";
            database = "shepherdGames";
            password = new char[] { '$', 'e', 'c', 'S', 'h', '3', 'p', 'd', 'b' };

            credential = MongoCredential.createCredential(user, database, password);
            mongoDb = mongoClient.getDB("shepherdGames");
            coll = mongoDb.getCollection("gamer");

            String gamerId = request.getParameter("theGamerName");
            log.debug("User Submitted - " + gamerId);
            String ApplicationRoot = getServletContext().getRealPath("");
            log.debug("Servlet root = " + ApplicationRoot);

            //whereQuery.put("_id", gamerId);
            DBObject whereQuery = new BasicDBObject("$where", "this._id == '" + gamerId + "'");
            cursor = coll.find(whereQuery);

            Object id;
            Object name;
            Object address;

            try {

                int i = 0;
                htmlOutput = "<h2 class='title'>Gamer Info</h2>";
                htmlOutput += "<table><tr><th>GamerId</th><th>Name</th><th>Address</th>";

                log.debug("Opening Result Set from query");

                while (cursor.hasNext()) {
                    DBObject result = cursor.next();
                    id = result.get("_id");
                    name = result.get("name");
                    address = result.get("address");

                    log.debug("Mongodb Query Results " + result.toString());
                    htmlOutput += "<tr><td>" + encoder.encodeForHTML(id.toString()) + "</td><td>"
                            + encoder.encodeForHTML(name.toString()) + "</td><td>"
                            + encoder.encodeForHTML(address.toString()) + "</td></tr>";
                    i++;
                }
                htmlOutput += "</table>";
                if (i == 0) {
                    htmlOutput = "<p>There were no results found in your search</p>";
                }

            } catch (MongoException e) {
                log.debug("MongoDb Error caught - " + e.toString());
                htmlOutput += "<p>An error was detected!</p>" + "<p>" + encoder.encodeForHTML(e.toString())
                        + "</p>";
            } catch (Exception e) {
                out.write("An Error Occurred! You must be getting funky!");
                log.fatal(levelName + " - " + e.toString());
            } finally {
                cursor.close();
            }
        } catch (MongoException e) {
            log.debug("MongoDb Error caught - " + e.toString());
            htmlOutput += "<p>An error was detected!</p>" + "<p>" + encoder.encodeForHTML(e.toString())
                    + "</p>";
        }

        log.debug("Outputting HTML");
        out.write(htmlOutput);
    } else {
        log.error(levelName + " servlet accessed with no session");
    }
}

From source file:sockslib.utils.mongo.MongoDBUtil.java

License:Apache License

private MongoClient getConnectedClient() {
    if (Strings.isEmpty(username)) {
        return new MongoClient(host, port);
    } else {/*from   ww  w .ja  va2 s . com*/
        MongoCredential credential = MongoCredential.createCredential(username, databaseName,
                password.toCharArray());
        return new MongoClient(new ServerAddress(host, port), Lists.newArrayList(credential));
    }
}

From source file:Tests.AddElementToCollection.java

public void addToCollection(String jsonString) {
    MongoClient mongoClient = new MongoClient(new ServerAddress(),
            Arrays.asList(MongoCredential.createCredential("admin", "test", "password".toCharArray())));
    try {/*from  w  ww.j a  v a 2 s.  c  om*/
        for (String databaseName : mongoClient.listDatabaseNames()) {
            System.out.println("Database: " + databaseName);
        }
        MongoDatabase db = mongoClient.getDatabase("test");
        MongoCollection coll = db.getCollection("test2");

        Document doc = Document.parse(jsonString);
        coll.insertOne(doc);
    } finally {
        mongoClient.close();
    }
}

From source file:Tests.PrintFristElementOfCollection.java

public static void main(String[] args) throws UnknownHostException {

    MongoClient mongoClient = new MongoClient(new ServerAddress(),
            Arrays.asList(MongoCredential.createCredential("admin", "test", "password".toCharArray())));
    try {/*ww  w  .java 2s . com*/
        for (String databaseName : mongoClient.listDatabaseNames()) {
            System.out.println("Database: " + databaseName);
        }
        MongoDatabase db = mongoClient.getDatabase("test");
        MongoCollection coll = db.getCollection("test");
        System.out.println(coll.find().first());
    } finally {
        mongoClient.close();
    }
}

From source file:testt.mongoConnector.java

public mongoConnector() throws UnknownHostException {
    /*// w  ww.  j  a  v  a 2  s.c  om
    *  this section won't cause any exception yet, exception will be thrown
    *  when committing update to the database        
    */
    Scanner sc = new Scanner(System.in);
    String pwd;
    System.out.print("password:");
    pwd = sc.next();

    /*char [] pwd;
    pwd = System.console().readPassword();*/
    MongoCredential mc = MongoCredential.createCredential("rwmy", "myDB", pwd.toCharArray());
    ServerAddress sa = new ServerAddress("localhost");
    client = new MongoClient(sa, Arrays.asList(mc));
    db = client.getDB("myDB");
    coll = db.getCollection("websites");
    client.setWriteConcern(WriteConcern.ACKNOWLEDGED);
}