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.opencb.opencga.storage.mongodb.utils.MongoCredentials.java

License:Apache License

public MongoCredentials(String mongoHost, int mongoPort, String mongoDbName, String mongoUser,
        String mongoPassword) throws IllegalOpenCGACredentialsException {
    dataStoreServerAddresses = new LinkedList<>();
    dataStoreServerAddresses.add(new DataStoreServerAddress(mongoHost, mongoPort));
    this.mongoDbName = mongoDbName;
    if (mongoUser != null && mongoPassword != null) {
        mongoCredentials = MongoCredential.createMongoCRCredential(mongoUser, mongoDbName,
                mongoPassword.toCharArray());
    }/* w  w w . j a  va 2s. c om*/

    check();
}

From source file:org.opencb.opencga.storage.mongodb.utils.MongoCredentials.java

License:Apache License

public MongoCredentials(List<DataStoreServerAddress> dataStoreServerAddresses, String dbName, String mongoUser,
        String mongoPassword) throws IllegalOpenCGACredentialsException {
    this.dataStoreServerAddresses = dataStoreServerAddresses;
    this.mongoDbName = dbName;
    if (mongoUser != null && mongoPassword != null) {
        mongoCredentials = MongoCredential.createMongoCRCredential(mongoUser, mongoDbName,
                mongoPassword.toCharArray());
    }/*from w ww  .  j  a  va 2  s .  c  om*/

    check();
}

From source file:org.opencb.opencga.storage.mongodb.utils.MongoCredentials.java

License:Apache License

@Deprecated
public MongoCredentials(Properties properties) {
    dataStoreServerAddresses = new LinkedList<>();
    String mongoHost = properties.getProperty("mongo_host");
    int mongoPort = Integer.parseInt(properties.getProperty("mongo_port", "-1"));
    dataStoreServerAddresses.add(new DataStoreServerAddress(mongoHost, mongoPort));
    this.mongoDbName = properties.getProperty("mongo_db_name");
    String mongoUser = properties.getProperty("mongo_user", null);
    String mongoPassword = properties.getProperty("mongo_password", null);
    if (mongoUser != null && mongoPassword != null) {
        mongoCredentials = MongoCredential.createMongoCRCredential(mongoUser, mongoDbName,
                mongoPassword.toCharArray());
    }//from  w w  w. ja  v  a2  s .c o m
}

From source file:org.openmhealth.reference.data.mongodb.MongoDao.java

License:Apache License

/**
 * Default constructor, which will create the connection to the MongoDB.
 * /*www  . ja  va 2  s. c  o m*/
 * @param properties
 *        The user-defined properties to use to setup the connection.
 * 
 * @throws OmhException
 *         There was a problem setting up the connection to the database.
 */
public MongoDao(final Properties properties) throws OmhException {
    super(properties);

    // Create the singular Mongo instance.
    try {
        // Create the empty list of credentials.
        List<MongoCredential> credentials = new LinkedList<MongoCredential>();

        // If a username and password were given, use them.
        if ((MongoDao.getInstance().getDatabaseUsername() != null)
                && (MongoDao.getInstance().getDatabasePassword() != null)) {

            credentials.add(MongoCredential.createMongoCRCredential(
                    MongoDao.getInstance().getDatabaseUsername(), MongoDao.getInstance().getDatabaseName(),
                    MongoDao.getInstance().getDatabaseUsername().toCharArray()));
        }

        // Create the MongoClient.
        mongo = new MongoClient(new ServerAddress(getDatabaseAddress(), getDatabasePort()), credentials);
    } catch (UnknownHostException e) {
        throw new OmhException("The database could not setup.", e);
    }

    // Instantiate the specific components.
    new MongoAuthenticationTokenBin();
    new MongoAuthorizationCodeBin();
    new MongoAuthorizationCodeResponseBin();
    new MongoAuthorizationTokenBin();
    new MongoDataSet();
    new MongoRegistry();
    new MongoThirdPartyBin();
    new MongoUserBin();
}

From source file:org.pentaho.mongo.MongoUtils.java

License:Open Source License

/**
 * Create a credentials object//from w ww  .ja v  a2  s  .c o  m
 * 
 * @param username the username to use
 * @param password the password to use (normal authentication only)
 * @param dbName the database to authenticate against (normal authentication
 *          only)
 * @param kerberos true if Kerberos authentication is to be used
 * @return a configured MongoCredential object
 */
public static MongoCredential createCredentials(String username, String password, String dbName,
        boolean kerberos) {
    MongoCredential cred = null;

    if (kerberos) {
        if (!Const.isEmpty(username)) {
            cred = MongoCredential.createGSSAPICredential(username);
        }
    } else {
        // standard authentication
        if (!Const.isEmpty(username) || !Const.isEmpty(password)) {
            cred = MongoCredential.createMongoCRCredential(username, dbName, password.toCharArray());
        }
    }

    return cred;
}

From source file:org.pentaho.mongo.MongoUtils.java

License:Open Source License

/**
 * Return a list of custom "lastErrorModes" (if any) defined in the replica
 * set configuration object on the server. These can be used as the "w"
 * setting for the write concern in addition to the standard "w" values of
 * <number> or "majority".// w w w .  j  a  va 2s  . com
 * 
 * @param hostsPorts the hosts to use
 * @param singlePort the default port to use if no ports are given in the
 *          hostsPorts spec
 * @param username the username for authentication
 * @param password the password for authentication
 * @param vars the environment variables to use
 * @param log for logging
 * @return a list of the names of any custom "lastErrorModes"
 * @throws KettleException if a problem occurs
 */
public static List<String> getLastErrorModes(String hostsPorts, String singlePort, MongoCredential cred,
        VariableSpace vars, LogChannelInterface log) throws KettleException {

    List<String> customLastErrorModes = new ArrayList<String>();

    MongoClient mongo = null;
    try {
        if (cred != null && cred.getMechanism().equals(MongoCredential.MONGODB_CR_MECHANISM)) {
            // need to make a new credential that specifies the local database
            cred = MongoCredential.createMongoCRCredential(cred.getUserName(), LOCAL_DB, cred.getPassword());
        }
        mongo = initConnection(hostsPorts, singlePort, cred, false, null, null, null, null, null, false, null,
                vars, log);

        DB local = mongo.getDB(LOCAL_DB);
        if (local != null) {

            DBCollection replset = local.getCollection(REPL_SET_COLLECTION);
            if (replset != null) {
                DBObject config = replset.findOne();

                extractLastErrorModes(config, customLastErrorModes);
            }
        }
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }

    return customLastErrorModes;
}

From source file:org.pentaho.mongo.MongoUtils.java

License:Open Source License

protected static BasicDBList getRepSetMemberRecords(String hostsPorts, String singlePort, MongoCredential cred,
        VariableSpace vars, LogChannelInterface log) throws KettleException {

    MongoClient mongo = null;/*from  ww  w  . j a  v  a2 s .com*/
    BasicDBList setMembers = null;
    try {
        if (cred != null && cred.getMechanism().equals(MongoCredential.MONGODB_CR_MECHANISM)) {
            // need to make a new credential that specifies the local database
            cred = MongoCredential.createMongoCRCredential(cred.getUserName(), LOCAL_DB, cred.getPassword());
        }
        mongo = initConnection(hostsPorts, singlePort, cred, false, null, null, null, null, null, false, null,
                vars, log);

        DB local = mongo.getDB(LOCAL_DB);
        if (local != null) {

            DBCollection replset = local.getCollection(REPL_SET_COLLECTION);
            if (replset != null) {
                DBObject config = replset.findOne();

                if (config != null) {
                    Object members = config.get(REPL_SET_MEMBERS);

                    if (members instanceof BasicDBList) {
                        if (((BasicDBList) members).size() == 0) {
                            // log that there are no replica set members defined
                            if (log != null) {
                                log.logBasic(BaseMessages.getString(PKG,
                                        "MongoUtils.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$
                            }
                        } else {
                            setMembers = (BasicDBList) members;
                        }

                    } else {
                        // log that there are no replica set members defined
                        if (log != null) {
                            log.logBasic(BaseMessages.getString(PKG,
                                    "MongoUtils.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$
                        }
                    }
                } else {
                    // log that there are no replica set members defined
                    if (log != null) {
                        log.logBasic(BaseMessages.getString(PKG,
                                "MongoUtils.Message.Warning.NoReplicaSetMembersDefined")); //$NON-NLS-1$
                    }
                }
            } else {
                // log that the replica set collection is not available
                if (log != null) {
                    log.logBasic(BaseMessages.getString(PKG,
                            "MongoUtils.Message.Warning.ReplicaSetCollectionUnavailable")); //$NON-NLS-1$
                }
            }
        } else {
            // log that the local database is not available!!
            if (log != null) {
                log.logBasic(BaseMessages.getString(PKG, "MongoUtils.Message.Warning.LocalDBNotAvailable")); //$NON-NLS-1$
            }
        }
    } catch (Exception ex) {
        throw new KettleException(ex);
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }

    return setMembers;
}

From source file:org.swissbib.docproc.flink.plugins.DSV11ContentEnrichment.java

License:Open Source License

private void initializeMongoConnection(HashMap<String, String> configuration) throws Exception {

    try {// ww w.  j av a  2  s . com

        String[] mongoClient = configuration.get("MONGO.CLIENT").split("###");
        String[] mongoAuthentication = null;

        if (configuration.containsKey("MONGO.AUTHENTICATION")) {
            mongoAuthentication = configuration.get("MONGO.AUTHENTICATION").split("###");
        }

        ServerAddress server = new ServerAddress(mongoClient[0], Integer.valueOf(mongoClient[1]));
        String[] mongoDB = configuration.get("MONGO.DB.DSV11").split("###");

        DB db = null;
        if (mongoAuthentication != null) {
            MongoCredential credential = MongoCredential.createMongoCRCredential(mongoAuthentication[1],
                    mongoAuthentication[0], mongoAuthentication[2].toCharArray());
            mClient = new MongoClient(server, Arrays.asList(credential));
            db = mClient.getDB(mongoDB[0]);
        } else {
            mClient = new MongoClient(server);
            db = mClient.getDB(mongoDB[0]);
        }

        //simple test if authentication was successfull
        CommandResult cR = db.getStats();

        if (cR != null && !cR.ok()) {
            throw new Exception(
                    "authentication against database wasn't possible - no DSV11 Processing will take place when type DSV11ContentEnrichment is called from XSLT templates");
        }

        nativeSource = mClient.getDB(mongoDB[0]);
        searchCollection = nativeSource.getCollection(mongoDB[1]);

    } catch (UnknownHostException uHE) {
        dsv11ProcessingError.error("MongoError", "Mongo Connection couldn't be established");
        dsv11ProcessingError.error("MongoError", uHE);
        uHE.printStackTrace();
        throw uHE;

    } catch (Exception ex) {
        dsv11ProcessingError.error("MongoError", "General Exception while trying to connect to Mongo");
        dsv11ProcessingError.error("MongoError", ex);
        ex.printStackTrace();
        throw ex;

    }
}

From source file:org.swissbib.docproc.flink.plugins.GNDContentEnrichment.java

License:Open Source License

private void initializeMongoConnection(HashMap<String, String> configuration) throws Exception {

    try {/*ww w.ja  v  a 2  s.c om*/

        String[] mongoClient = configuration.get("MONGO.CLIENT").split("###");
        String[] mongoAuthentication = null;

        if (configuration.containsKey("MONGO.AUTHENTICATION")) {
            mongoAuthentication = configuration.get("MONGO.AUTHENTICATION").split("###");
        }

        ServerAddress server = new ServerAddress(mongoClient[0], Integer.valueOf(mongoClient[1]));
        String[] mongoDB = configuration.get("MONGO.DB").split("###");

        DB db = null;
        if (mongoAuthentication != null) {
            MongoCredential credential = MongoCredential.createMongoCRCredential(mongoAuthentication[1],
                    mongoAuthentication[0], mongoAuthentication[2].toCharArray());
            mClient = new MongoClient(server, Arrays.asList(credential));
            db = mClient.getDB(mongoAuthentication[0]);
        } else {
            mClient = new MongoClient(server);
            db = mClient.getDB(mongoDB[0]);
        }

        //simple test if authentication was successfull
        CommandResult cR = db.getStats();

        if (cR != null && !cR.ok()) {
            throw new Exception(
                    "authentication against database wasn't possible - no GND Processing will take place when type is called from XSLT templates");
        }

        nativeSource = mClient.getDB(mongoDB[0]);
        searchCollection = nativeSource.getCollection(mongoDB[1]);
        searchField = mongoDB[2];
        responseField = mongoDB[3];
        if (mongoDB.length > 4) {
            responseFieldMACS = mongoDB[4];
        }

    } catch (UnknownHostException uHE) {
        gndProcessingError.error("MongoError", "Mongo Connection couldn't be established");
        gndProcessingError.error("MongoError", uHE);
        uHE.printStackTrace();
        throw uHE;

    } catch (Exception ex) {
        gndProcessingError.error("MongoError", "General Exception while trying to connect to Mongo");
        gndProcessingError.error("MongoError", ex);
        ex.printStackTrace();
        throw ex;

    }
}

From source file:org.swissbib.srw.SRWUpdateServiceLifecyle.java

License:Open Source License

@Override
public void startUp(ConfigurationContext configurationContext, AxisService axisService) {

    System.out.println("in startup");

    final String UPD_DIR = "updateDir";
    final String DEL_DIR = "deleteDir";
    final String DEL_PATTERN = "deletePattern";
    final String TRANSFORM_TEMPLATE = "transformTemplate";
    final String FILE_PREFIX = "filePrefix";
    final String FILE_SUFFIX = "fileSuffix";
    final String RECORD_NS = "recordWithNamespaces";
    final String NORMALIZE_CHARS = "normalizeChars";
    final String RECORD_IN_RESPONSE = "includeRecordInResponse";

    final String LOG_MESSAGES = "logMessages";
    final String MONGO_CLIENT = "MONGO.CLIENT";
    final String MONGO_AUTHENTICATION = "MONGO.AUTHENTICATION";
    final String MONGO_DB = "MONGO.DB";
    final String ACTIVE_MONGO_CLIENT = "activeMongoClient";
    final String ACTIVE_MONGO_COLLECTION = "activeMongoCollection";
    final String CHECK_LEADER_FOR_DELETE = "checkLeaderForDelete";

    try {/*from w  w w.j  av  a2  s  . c o  m*/
        Parameter updDir = axisService.getParameter(UPD_DIR);
        axisService.addParameter(updDir);

        Parameter delDir = axisService.getParameter(DEL_DIR);
        axisService.addParameter(delDir);

        Parameter filePrefix = axisService.getParameter(FILE_PREFIX);
        axisService.addParameter(filePrefix);

        Parameter fileSuffix = axisService.getParameter(FILE_SUFFIX);
        axisService.addParameter(fileSuffix);

        Parameter recordNS = axisService.getParameter(RECORD_NS);
        axisService.addParameter(recordNS);

        Parameter checkLeaderForDelete = axisService.getParameter(CHECK_LEADER_FOR_DELETE);
        boolean checkLeader = Boolean.valueOf(checkLeaderForDelete.getValue().toString());
        axisService.addParameter(CHECK_LEADER_FOR_DELETE, checkLeader);

        Parameter normalizeChars = axisService.getParameter(NORMALIZE_CHARS);
        axisService.addParameter(normalizeChars);

        Parameter recordInResponse = axisService.getParameter(RECORD_IN_RESPONSE);
        axisService.addParameter(recordInResponse);

        String transformTemplate = axisService.getParameter(TRANSFORM_TEMPLATE).getValue().toString();

        InputStream stream = getClass().getClassLoader().getResourceAsStream(transformTemplate);

        StreamSource source = new StreamSource(stream);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        //Transformer transform = transformerFactory.newTransformer(source);
        Templates recordTransformer = transformerFactory.newTemplates(source);

        axisService.addParameter(new Parameter(TRANSFORM_TEMPLATE, recordTransformer));

        //logging of messages?
        Parameter logging = axisService.getParameter(LOG_MESSAGES);

        boolean logActive = Boolean.valueOf(logging.getValue().toString());
        if (logActive) {

            try {

                //it is expected:
                // <parameter name="MONGO.CLIENT">[host]###[port]</parameter>
                String[] mongoClient = ((String) axisService.getParameter(MONGO_CLIENT).getValue())
                        .split("###");

                //Todo: right now I expect the Mongo storage is running in secure mode
                //if not the procedure to connect is a little bit different
                //take a look at GND and DSV11 Plugin in content2SearchDoc repository. Configuration for messageCatcher should be adapted

                //it is expected that mongoAuthentication contains the values for:
                //<parameter name="MONGO.AUTHENTICATION">[auth-db]###[user]###[password]</parameter>
                String[] mongoAuthentication = ((String) axisService.getParameter(MONGO_AUTHENTICATION)
                        .getValue()).split("###");
                //it is expected:
                //<parameter name="MONGO.DB">[logging DB]###[collection]</parameter>
                String[] mongoDB = ((String) axisService.getParameter(MONGO_DB).getValue()).split("###");

                System.out.println("mongoHost: " + mongoClient[0]);
                System.out.println("mongoPort: " + mongoClient[1]);

                ServerAddress server = new ServerAddress(mongoClient[0], Integer.valueOf(mongoClient[1]));

                MongoCredential credential = MongoCredential.createMongoCRCredential(mongoAuthentication[1],
                        mongoAuthentication[0], mongoAuthentication[2].toCharArray());
                MongoClient mClient = new MongoClient(server, Arrays.asList(credential));
                DB db = mClient.getDB(mongoAuthentication[0]);

                //simple test if authentication was successfull
                CommandResult cR = db.getStats();

                if (cR != null && cR.ok()) {

                    System.out.println("authenticated");
                    //mongoDB contains the application DB and collection within this DB
                    DB messageDB = mClient.getDB(mongoDB[0]);
                    DBCollection messageCollection = messageDB.getCollection(mongoDB[1]);
                    axisService.addParameter(new Parameter(ACTIVE_MONGO_COLLECTION, messageCollection));
                    axisService.addParameter(new Parameter(LOG_MESSAGES, "true"));

                } else {

                    System.out.println("not authenticated");
                    throw new Exception(
                            "authentication against Mongo database wasn't possible - message logging isn't possible");
                }

            } catch (UnknownHostException uhExc) {
                axisService.addParameter(new Parameter(LOG_MESSAGES, "false"));
                uhExc.printStackTrace();

            } catch (Exception exc) {

                axisService.addParameter(new Parameter(LOG_MESSAGES, "false"));
                exc.printStackTrace();
            }

        } else {
            axisService.addParameter(new Parameter(LOG_MESSAGES, "false"));
        }

    } catch (AxisFault aF) {
        System.out.println("Fehler bei Speichern von UPD_DIR und DEL_DIR");
        aF.printStackTrace();

    } catch (TransformerConfigurationException configExcept) {
        configExcept.printStackTrace();
    }

}