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:MongoCredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    String server = args[0];/*from w  ww .  j  av a2  s.  c  o  m*/
    String user = args[1];
    String password = args[2];
    String databaseName = args[3];

    System.out.println("server: " + server);
    System.out.println("user: " + user);
    System.out.println("database: " + databaseName);

    System.out.println();

    MongoClient mongoClient = new MongoClient(new ServerAddress(server),
            Arrays.asList(MongoCredential.createMongoCRCredential(user, "test", password.toCharArray())),
            new MongoClientOptions.Builder().socketKeepAlive(true).socketTimeout(30000).build());
    DB testDB = mongoClient.getDB(databaseName);

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

    System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject()));

}

From source file:RestrictedService.java

License:Open Source License

public void init() throws ServletException {
    if (!gateInited) {
        try {//  ww  w  .  j  a v a2s. c o m
            // GATE home is setted, so it can be used by SAGA.
            ServletContext ctx = getServletContext();
            File gateHome = new File(ctx.getRealPath("/WEB-INF"));
            Gate.setGateHome(gateHome);
            // GATE user configuration file is setted. 
            Gate.setUserConfigFile(new File(gateHome, "user-gate.xml"));
            //GATE is initialized as non visible.
            Gate.init();
            // We load the plugins that are going to be used by the SAGA modules.
            // Load ANNIE.
            Gate.getCreoleRegister().registerDirectories(ctx.getResource("/WEB-INF/plugins/ANNIE"));
            // Load processingResources (from SAGA)
            Gate.getCreoleRegister()
                    .registerDirectories(ctx.getResource("/WEB-INF/plugins/processingResources"));
            // Load webProcessingResources (from SAGA)
            Gate.getCreoleRegister()
                    .registerDirectories(ctx.getResource("/WEB-INF/plugins/webProcessingResources"));
            // Now we create the sentiment analysis modules that are going to be provided by the service.
            // English financial module.
            ArrayList<URL> dictionaries = new ArrayList<URL>();
            dictionaries.add((new RestrictedService()).getClass().getResource("/LoughranMcDonald/lists.def"));
            modules.put("enFinancial",
                    new DictionaryBasedSentimentAnalyzer("SAGA - Sentiment Analyzer", dictionaries));
            // English financial + emoticon module.
            ArrayList<URL> dictionaries2 = new ArrayList<URL>();
            dictionaries2.add((new RestrictedService()).getClass().getResource("/LoughranMcDonald/lists.def"));
            dictionaries2.add((new RestrictedService()).getClass()
                    .getResource("/resources/gazetteer/emoticon/lists.def"));
            modules.put("enFinancialEmoticon",
                    new DictionaryBasedSentimentAnalyzer("SAGA - Sentiment Analyzer", dictionaries2));
            // Mongo login
            String user = "";
            String password = "";
            MongoCredential credential = MongoCredential.createMongoCRCredential(user, "RestrictedDictionaries",
                    password.toCharArray());
            MongoClient mongoClient = new MongoClient(new ServerAddress("localhost"),
                    Arrays.asList(credential));
            db = mongoClient.getDB("RestrictedDictionaries");

            gateInited = true;

        } catch (Exception ex) {
            throw new ServletException("Exception initialising GATE", ex);
        }
    }
}

From source file:ch.bfh.uniboard.persistence.mongodb.ConnectionManagerImpl.java

License:GNU General Public License

@PostConstruct
private void init() {

    Properties props = cm.getConfiguration(CONFIG_NAME);

    if (props == null) {
        logger.log(Level.SEVERE, "Configuration could not be loaded.");
        return;//from   w ww . j a  v a  2 s  .c o m
    }
    //DB Connection Information
    String host;
    String dbName;
    String collectionName;
    int port;
    String username;
    String password;
    boolean authentication;
    //Check if values are set or use defaults
    if (props.containsKey(HOST_KEY)) {
        host = props.getProperty(HOST_KEY);
    } else {
        host = "localhost";
    }
    if (props.containsKey(DBNAME_KEY)) {
        dbName = props.getProperty(DBNAME_KEY);
    } else {
        dbName = "uniboard";
    }
    if (props.containsKey(COLLECTION_KEY)) {
        collectionName = props.getProperty(COLLECTION_KEY);
    } else {
        collectionName = "default";
    }
    if (props.containsKey(PORT_KEY)) {
        port = Integer.parseInt(props.getProperty(PORT_KEY));
    } else {
        port = 27017;
    }
    if (props.containsKey(USERNAME_KEY)) {
        username = props.getProperty(USERNAME_KEY);
    } else {
        username = "admin";
    }
    if (props.containsKey(PASSWORD_KEY)) {
        password = props.getProperty(PASSWORD_KEY);
    } else {
        password = "password";
    }
    if (props.containsKey(AUTH_KEY)) {
        authentication = Boolean.parseBoolean(props.getProperty(AUTH_KEY));
    } else {
        authentication = false;
    }

    try {
        if (authentication) {
            MongoCredential credential = MongoCredential.createMongoCRCredential(username, dbName,
                    password.toCharArray());
            //MongoClient already works as a pool if only one instance is used (http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/)
            mongoClient = new MongoClient(new ServerAddress(host, port), Arrays.asList(credential));
        } else {
            mongoClient = new MongoClient(host, port);
        }
        this.connected = true;
    } catch (UnknownHostException ex) {
        logger.log(Level.SEVERE, "DB creation error", ex);
        return;
    }

    //Create or load the database
    DB db = mongoClient.getDB(dbName);

    //create the collection if it does not exist
    if (!db.collectionExists(collectionName)) {
        collection = db.createCollection(collectionName, null);
    }
    //load the collection
    collection = db.getCollection(collectionName);
}

From source file:com.almende.eve.state.mongo.MongoStateConfig.java

License:Apache License

/**
 * Helper method to fetch the list of Mongocredentials based on the
 * config./*  w  ww . j  a v a2 s.com*/
 *
 * @return the mongo credentials
 */
@JsonIgnore
public List<MongoCredential> getMongoCredentials() {

    ArrayNode credentials = getCredentials();
    List<MongoCredential> mongoCredentials = null;
    if (credentials != null) {
        mongoCredentials = new ArrayList<MongoCredential>(1);
        for (JsonNode credential : credentials) {
            if (credential.has("user") && credential.has("database") && credential.has("password")) {
                mongoCredentials.add(MongoCredential.createMongoCRCredential(credential.get("user").asText(),
                        credential.get("database").asText(),
                        credential.get("password").asText().toCharArray()));
            }
        }
    }
    return mongoCredentials;
}

From source file:com.bacic5i5j.framework.database.MongoContext.java

License:Open Source License

public void init(String db, String username, String password, List servers) {
    this.dbname = db;

    MongoCredential mc = MongoCredential.createMongoCRCredential(username, dbname, password.toCharArray());
    List mcs = new ArrayList();
    mcs.add(mc);//from   www  .ja  va  2 s . c o m

    MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(100).connectTimeout(10 * 1000)
            .readPreference(ReadPreference.secondaryPreferred()).build();

    this.mongoClient = new MongoClient(servers, mcs, options);
    this.threadLocal = new ThreadLocal<DB>();
}

From source file:com.bnrc.sdn.properties.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. //w  w w . jav a2 s .  c om
 * 
 * @param options the options 
 * @param environment the environment 
 * @return the Mongo client 
 * @throws UnknownHostException if the configured host is unknown 
 */
public MongoClient createMongoClient(MongoClientOptions options, Environment environment)
        throws UnknownHostException {
    try {
        if (hasCustomAddress() || hasCustomCredentials()) {
            if (options == null) {
                options = MongoClientOptions.builder().build();
            }
            List<MongoCredential> credentials = null;
            if (hasCustomCredentials()) {
                String database = this.authenticationDatabase == null ? getMongoClientDatabase()
                        : this.authenticationDatabase;
                credentials = Arrays.asList(
                        MongoCredential.createMongoCRCredential(this.username, database, this.password));
            }
            String host = this.host == null ? "localhost" : this.host;
            int port = determinePort(environment);
            return new MongoClient(Arrays.asList(new ServerAddress(host, port)), credentials, options);
        }
        // The options and credentials are in the URI  
        System.out.println("uri=" + uri);
        return new MongoClient(new MongoClientURI(this.uri, builder(options)));
    } finally {
        clearPassword();
    }
}

From source file:com.bosscs.spark.mongodb.reader.MongoReader.java

License:Apache License

/**
 * Init void./* www .  ja  v a  2s.  c  o  m*/
 *
 * @param partition the partition
 */
public void init(Partition partition) {
    try {

        List<ServerAddress> addressList = new ArrayList<>();

        for (String s : (List<String>) ((HadoopPartition) partition).splitWrapper().getReplicas()) {
            addressList.add(new ServerAddress(s));
        }

        //Credentials
        List<MongoCredential> mongoCredentials = new ArrayList<>();

        if (mongoDeepJobConfig.getUsername() != null && mongoDeepJobConfig.getPassword() != null) {
            MongoCredential credential = MongoCredential.createMongoCRCredential(
                    mongoDeepJobConfig.getUsername(), mongoDeepJobConfig.getDatabase(),
                    mongoDeepJobConfig.getPassword().toCharArray());
            mongoCredentials.add(credential);

        }

        mongoClient = new MongoClient(addressList, mongoCredentials);
        //mongoClient.setReadPreference(ReadPreference.valueOf(mongoDeepJobConfig.getReadPreference()));
        db = mongoClient.getDB(mongoDeepJobConfig.getDatabase());
        collection = db.getCollection(mongoDeepJobConfig.getCollection());

        dbCursor = collection.find(generateFilterQuery((MongoPartition) partition),
                mongoDeepJobConfig.getDBFields());

    } catch (UnknownHostException e) {
        throw new ExtractorInitializationException(e);
    }
}

From source file:com.buzz.buzzdata.MongoBuzz.java

public MongoBuzz(String host, int port, String db, String userName, String passwd) throws UnknownHostException {
    MongoCredential credential = MongoCredential.createMongoCRCredential(userName, db, passwd.toCharArray());
    mongoClient = new MongoClient(new ServerAddress(host, port), Arrays.asList(credential));
    mongoDB = mongoClient.getDB(db);/*from  w w w.  j  a  va2 s. c  o  m*/
}

From source file:com.ca.apm.mongo.Collector.java

License:Open Source License

public static void setupCreds(final List<MongoCredential> mc, final Properties iprops) {
    final String type = getStringProp(DB_AUTH_PROP, iprops);
    String user;/*w w  w .  j  a v  a 2  s  .  c om*/
    String pw;
    if (AUTH_NONE.equalsIgnoreCase(type)) {
        // nothing to do
    } else if (AUTH_CR.equalsIgnoreCase(type)) {
        user = getStringProp(DB_USER_PROP, iprops);
        pw = getStringProp(DB_PASSWD_PROP, iprops);
        mc.add(MongoCredential.createMongoCRCredential(user, "admin", pw.toCharArray()));
    } else if (AUTH_X509.equalsIgnoreCase(type)) {
        user = getStringProp(DB_USER_PROP, iprops);
        System.out.printf("X509 cred user(%s)%n", user);
        mc.add(MongoCredential.createMongoX509Credential(user));
    } else if (AUTH_KERBEROS.equalsIgnoreCase(type)) {
        user = getStringProp(DB_USER_PROP, iprops);
        mc.add(MongoCredential.createGSSAPICredential(user));
    } else if (AUTH_SASL.equalsIgnoreCase(type)) {
        user = getStringProp(DB_USER_PROP, iprops);
        pw = getStringProp(DB_PASSWD_PROP, iprops);
        mc.add(MongoCredential.createPlainCredential(user, "$external", pw.toCharArray()));
    } else {
        throw new IllegalArgumentException(String.format("Invalid %s property", DB_AUTH_PROP));
    }
}

From source file:com.camel.realtimelog.PersistenceMongoAccessor.java

License:Open Source License

private void setMongoClient() {
    if (mongo == null) {
        try {/*from ww w .  j a v a 2  s .  c o m*/
            ServerAddress sa = new ServerAddress(serverAddress);
            MongoCredential mc = MongoCredential.createMongoCRCredential(username, dbName,
                    password.toCharArray());
            List<MongoCredential> mcs = new ArrayList<MongoCredential>();
            mcs.add(mc);
            mongo = new MongoClient(sa, mcs);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        db = mongo.getDB(dbName);
        logs = db.getCollection(collectionName);
    }
}