Example usage for com.mongodb MongoCredential createMongoCRCredential

List of usage examples for com.mongodb MongoCredential createMongoCRCredential

Introduction

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

Prototype

@SuppressWarnings("deprecation")
@Deprecated
public static MongoCredential createMongoCRCredential(final String userName, final String database,
        final char[] password) 

Source Link

Document

Creates a MongoCredential instance for the MongoDB Challenge Response protocol.

Usage

From source file:org.teiid.resource.adapter.mongodb.MongoDBManagedConnectionFactory.java

License:Open Source License

@Override
@SuppressWarnings("serial")
public BasicConnectionFactory<MongoDBConnectionImpl> createConnectionFactory() throws ResourceException {
    if (this.remoteServerList == null) {
        throw new InvalidPropertyException(UTIL.getString("no_server")); //$NON-NLS-1$
    }//from www .  ja v  a 2s  .  co m
    if (this.database == null) {
        throw new InvalidPropertyException(UTIL.getString("no_database")); //$NON-NLS-1$
    }

    final List<ServerAddress> servers = getServers();
    if (servers != null) {
        //if options needed then use URL format
        final MongoClientOptions options = MongoClientOptions.builder().build();

        return new BasicConnectionFactory<MongoDBConnectionImpl>() {
            @Override
            public MongoDBConnectionImpl getConnection() throws ResourceException {
                MongoCredential credential = null;
                if (MongoDBManagedConnectionFactory.this.username != null
                        && MongoDBManagedConnectionFactory.this.password != null) {
                    credential = MongoCredential.createMongoCRCredential(
                            MongoDBManagedConnectionFactory.this.username,
                            MongoDBManagedConnectionFactory.this.database,
                            MongoDBManagedConnectionFactory.this.password.toCharArray());
                }
                return new MongoDBConnectionImpl(MongoDBManagedConnectionFactory.this.database, servers,
                        credential, options);
            }
        };
    }

    // Make connection using the URI format
    return new BasicConnectionFactory<MongoDBConnectionImpl>() {
        @Override
        public MongoDBConnectionImpl getConnection() throws ResourceException {
            try {
                return new MongoDBConnectionImpl(MongoDBManagedConnectionFactory.this.database,
                        getConnectionURI());
            } catch (UnknownHostException e) {
                throw new ResourceException(e);
            }
        }
    };

}

From source file:org.trustedanalytics.modelcatalog.storage.db.MongoConfig.java

License:Apache License

@Bean
@Override/*from w w  w  . ja  v  a2s  .  c o  m*/
public Mongo mongo() throws UnknownHostException {
    ServerAddress serverAddress = new ServerAddress(mongoProperties.getServerName(),
            mongoProperties.getServerPort());
    List<MongoCredential> credentialList = new ArrayList<>();

    String user = mongoProperties.getUser();
    if (user != null && !user.isEmpty()) {
        credentialList.add(MongoCredential.createMongoCRCredential(user, mongoProperties.getDbName(),
                mongoProperties.getPassword().toCharArray()));
    }

    return new MongoClient(serverAddress, credentialList);
}

From source file:org.wisdom.mongodb.MongoDBClient.java

License:Apache License

/**
 * Creates a MongoCredential instance with an unspecified mechanism.
 *
 * @return the credential, {@code null} if not set
 *//* ww  w  .  ja  v a2 s.  c  o  m*/
private MongoCredential createMongoCredential() {
    if (mongDbUser != null) {
        return MongoCredential.createMongoCRCredential(mongoDbName, mongoDbHost, mongoDbPwd.toCharArray());
    }
    return null;
}

From source file:org.wso2.carbon.dataservices.core.description.config.MongoConfig.java

License:Open Source License

private MongoCredential createCredential(Map<String, String> properties) throws DataServiceFault {
    MongoCredential credential = null;//from www.ja v  a 2s . co  m
    String authenticationType = properties.get(DBConstants.MongoDB.AUTHENTICATION_TYPE);
    String username = properties.get(DBConstants.MongoDB.USERNAME);
    String password = properties.get(DBConstants.MongoDB.PASSWORD);
    String database = properties.get(DBConstants.MongoDB.DATABASE);
    if (authenticationType != null) {
        switch (authenticationType) {
        case DBConstants.MongoDB.MongoAuthenticationTypes.PLAIN:
            credential = MongoCredential.createPlainCredential(username, database, password.toCharArray());
            break;
        case DBConstants.MongoDB.MongoAuthenticationTypes.SCRAM_SHA_1:
            credential = MongoCredential.createScramSha1Credential(username, database, password.toCharArray());
            break;
        case DBConstants.MongoDB.MongoAuthenticationTypes.MONGODB_CR:
            credential = MongoCredential.createMongoCRCredential(username, database, password.toCharArray());
            break;
        case DBConstants.MongoDB.MongoAuthenticationTypes.GSSAPI:
            credential = MongoCredential.createGSSAPICredential(username);
            break;
        case DBConstants.MongoDB.MongoAuthenticationTypes.MONGODB_X509:
            credential = MongoCredential.createMongoX509Credential(username);
            break;
        default:
            throw new DataServiceFault("Invalid Authentication type. ");
        }
        return credential;
    } else {
        return null;
    }
}

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 a  2 s  .  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:org.wso2.security.tools.util.DatabaseUtils.java

License:Open Source License

private static MongoClient getMongoClient_2() {
    MongoCredential credential = MongoCredential.createMongoCRCredential(USERNAME, Constants.DB_NAME,
            PASSWORD.toCharArray());//from  w w w  .  j  a  va2  s  . com
    MongoClient mongoClient = new MongoClient(new ServerAddress(Constants.HOST, Constants.PORT),
            Arrays.asList(credential));
    return mongoClient;
}

From source file:parlare.application.server.model.Database.java

private void doConnectionMongo() {
    try {/*from  w w w.  ja v a 2 s . c  o m*/

        System.out.println("MONGO server: " + server);
        System.out.println("MONGO user: " + user);
        System.out.println("MONGO source: " + source);

        System.out.println();

        MongoClient mongoClient = new MongoClient(new ServerAddress(server),
                Arrays.asList(MongoCredential.createMongoCRCredential(user, source, password.toCharArray())),
                new MongoClientOptions.Builder().build());

        DB testDB = mongoClient.getDB("html5apps");

        System.out.println("Count: " + testDB.getCollection("html5apps").count());

        System.out.println("Insert result: " + testDB.getCollection("html5apps").insert(new BasicDBObject()));
    } catch (UnknownHostException ex) {
        Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:parlare.application.server.model.Database.java

private String doClientMongo() {

    String print = "";

    System.out.println("User:" + user + " Source:" + source + " Password:" + password);

    try {/*from w  w w.  j  a  v  a 2  s . com*/

        // connect to the local database server
        MongoClient mongoClient = new MongoClient(new ServerAddress(server),
                Arrays.asList(MongoCredential.createMongoCRCredential(user, source, password.toCharArray())),
                new MongoClientOptions.Builder().build());

        // get handle to "mydb"
        DB db = mongoClient.getDB("html5apps");

        // Authenticate - optional
        // boolean auth = db.authenticate("foo", "bar");

        // get a list of the collections in this database and print them out
        Set<String> collectionNames = db.getCollectionNames();
        for (String s : collectionNames) {

            System.out.println(s);
        }

        // get a collection object to work with
        DBCollection testCollection = db.getCollection("testCollection");

        // drop all the data in it
        testCollection.drop();

        // make a document and insert it
        BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1)
                .append("info", new BasicDBObject("x", 203).append("y", 102));

        testCollection.insert(doc);

        // get it (since it's the only one in there since we dropped the rest earlier on)
        DBObject myDoc = testCollection.findOne();
        System.out.println(myDoc);

        // now, lets add lots of little documents to the collection so we can explore queries and cursors
        for (int i = 0; i < 100; i++) {
            testCollection.insert(new BasicDBObject().append("i", i));
        }
        System.out.println("total # of documents after inserting 100 small ones (should be 101) "
                + testCollection.getCount());

        //  lets get all the documents in the collection and print them out
        DBCursor cursor = testCollection.find();
        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        //  now use a query to get 1 document out
        BasicDBObject query = new BasicDBObject("i", 71);
        cursor = testCollection.find(query);

        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        //  now use a range query to get a larger subset
        query = new BasicDBObject("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50
        cursor = testCollection.find(query);

        try {
            while (cursor.hasNext()) {
                System.out.println("Cursor: " + cursor.next());
            }
        } finally {
            cursor.close();
        }

        // range query with multiple constraints
        query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e.   20 < i <= 30
        cursor = testCollection.find(query);

        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        // create an index on the "i" field
        testCollection.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending

        //  list the indexes on the collection
        List<DBObject> list = testCollection.getIndexInfo();
        for (DBObject o : list) {
            System.out.println(o);
        }

        // See if the last operation had an error
        System.out.println("Last error : " + db.getLastError());

        // see if any previous operation had an error
        System.out.println("Previous error : " + db.getPreviousError());

        // force an error
        db.forceError();

        // See if the last operation had an error
        System.out.println("Last error : " + db.getLastError());

        db.resetError();

        // release resources
        mongoClient.close();

    } catch (UnknownHostException ex) {
        Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
    }

    return print;

}

From source file:parser.RestrictedParser.java

License:Open Source License

/**
 * To parse ANEW dictionaries//from  www  .ja v  a  2  s.  co  m
 * 
 * @param dbName Name of the database
 * @param collectionName Name of the new collection
 * @param dicFile Dictionary file in tsv format
 */
public static void parseANEW(String dbName, String collectionName, String dicFile) {
    try {
        System.out.println("Se conecta a la base de datos");
        // Credentials to login into your database
        String user = "";
        String password = "";
        MongoCredential credential = MongoCredential.createMongoCRCredential(user, dbName,
                password.toCharArray());
        MongoClient mongoClient = new MongoClient(new ServerAddress("localhost"), Arrays.asList(credential));
        // Get the DB
        DB db = mongoClient.getDB(dbName);
        // Create the collection
        db.createCollection(collectionName, null);
        // Get the collection
        DBCollection coll = db.getCollection(collectionName);
        // Parse the dictionary
        System.out.println("Comienza el parseo del diccionario");
        FileReader input = new FileReader(dicFile);
        BufferedReader bufRead = new BufferedReader(input);
        String myLine = null;
        myLine = bufRead.readLine(); // The first line is not needed
        while ((myLine = bufRead.readLine()) != null) {
            String[] word = myLine.split("   ");
            BasicDBObject doc = new BasicDBObject("Word", word[0]).append("Wdnum", new Double(word[1]))
                    .append("ValMn", new Double(word[2])).append("ValSD", new Double(word[3]))
                    .append("AroMn", new Double(word[4])).append("AroSD", new Double(word[5]))
                    .append("DomMn", new Double(word[6])).append("DomSD", new Double(word[7]));
            coll.insert(doc);
            System.out.println("Parseando -> " + myLine);
        }

        bufRead.close();
    } catch (Exception e) {
        System.err.println(e);
    }
}

From source file:Persistence.MongoMorphia.java

License:Open Source License

public void initialize() {
    try {//from w  ww .  j  av a 2 s  .c  o m
        MongoCredential credential = MongoCredential.createMongoCRCredential("admin", "admin",
                "$$PASdefumee1984".toCharArray());
        ServerAddress server = new ServerAddress(Admin.ipMongo(), 27017);
        mongoClient = new MongoClient(server, Arrays.asList(credential));
        morphia = new Morphia();
        dsOAuth = morphia.createDatastore(mongoClient, "oAuth");
        dsAccessToken = morphia.createDatastore(mongoClient, "AccessToken");
        dsSessions = morphia.createDatastore(mongoClient, "Session");
        dsUsers = morphia.createDatastore(mongoClient, "User");

        morphia.map(Record.class);
        morphia.map(AccessTokenPlus.class);
        morphia.map(User.class);
        morphia.map(Session.class);

    } catch (UnknownHostException ex) {
        Logger.getLogger(MongoMorphia.class.getName()).log(Level.SEVERE, null, ex);
    }

}