List of usage examples for com.mongodb MongoCredential createPlainCredential
public static MongoCredential createPlainCredential(final String userName, final String source, final char[] password)
From source file:PlainCredentialsExample.java
License:Apache License
public static void main(String[] args) throws UnknownHostException { String server = args[0];//from www .j a v a 2 s. c om String user = args[1]; String password = args[2]; String source = args[3]; System.out.println("server: " + server); System.out.println("user: " + user); System.out.println("source: " + source); System.out.println(); MongoClient mongoClient = new MongoClient(new ServerAddress(server), Arrays.asList(MongoCredential.createPlainCredential(user, source, password.toCharArray())), new MongoClientOptions.Builder().build()); DB testDB = mongoClient.getDB("test"); System.out.println("Count: " + testDB.getCollection("test").count()); System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject())); }
From source file:co.mcme.statistician.database.MongoDBUtil.java
License:Open Source License
public MongoDBUtil(String hostname, int port, String username, char[] password, String database, boolean tryAuth, String collection) throws UnknownHostException { if (tryAuth) { this.client = new MongoClient(Arrays.asList(new ServerAddress(hostname, port)), Arrays.asList(MongoCredential.createPlainCredential(username, database, password))); } else {//w w w . j a v a2 s. c o m this.client = new MongoClient(Arrays.asList(new ServerAddress(hostname, port))); } this.database = client.getDB(database); if (client != null) { if (!this.database.collectionExists(collection)) { statsCollection = this.database.createCollection(collection, new BasicDBObject()); } else { statsCollection = this.database.getCollection(collection); } } else { StatisticianLogger.severe( "Could not authenticate to '" + hostname + ":" + port + "/" + database + "' disabling plugin."); Statistician.getServerInstance().getPluginManager().disablePlugin(Statistician.getPluginInstance()); } }
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 av a 2 s .co m*/ 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.redhat.lightblue.mongo.config.MongoConfiguration.java
License:Open Source License
public static MongoCredential credentialFromJson(ObjectNode node) { String userName = null;//w ww . jav a 2s. c o m String password = null; String source = null; JsonNode xnode = node.get("mechanism"); if (xnode == null) { throw new IllegalArgumentException("mechanism is required in credentials"); } String mech = xnode.asText(); xnode = node.get("userName"); if (xnode != null) { userName = xnode.asText(); } xnode = node.get("password"); if (xnode != null) { password = xnode.asText(); } xnode = node.get("source"); if (xnode != null) { source = xnode.asText(); } MongoCredential cr; if ("GSSAPI_MECHANISM".equals(mech)) { cr = MongoCredential.createGSSAPICredential(userName); } else if ("MONGODB_CR_MECHANISM".equals(mech)) { cr = MongoCredential.createMongoCRCredential(userName, source, password == null ? null : password.toCharArray()); } else if ("MONGODB_X509_MECHANISM".equals(mech)) { cr = MongoCredential.createMongoX509Credential(userName); } else if ("PLAIN_MECHANISM".equals(mech)) { cr = MongoCredential.createPlainCredential(userName, source, password == null ? null : password.toCharArray()); } else { throw new IllegalArgumentException("invalid mechanism:" + mech + ", must be one of " + "GSSAPI_MECHANISM, MONGODB_CR_MECHANISM, " + "MONGODB_X5090_MECHANISM, or PLAIN_MECHANISM"); } return cr; }
From source file:com.stratio.decision.configuration.MongoConfiguration.java
License:Apache License
@Bean public MongoClient mongoClient() { List<ServerAddress> serverAddresses = new ArrayList(); MongoClient mongoClient = null;/*from w w w.ja v a 2 s . c o m*/ try { for (String mongoHost : configurationContext.getMongoHosts()) { String[] elements = mongoHost.split(":"); if (elements.length < 2) { //no port serverAddresses.add(new ServerAddress(elements[0])); } else { serverAddresses.add(new ServerAddress(elements[0], Integer.parseInt(elements[1]))); } } if (configurationContext.getMongoUsername() != null && configurationContext.getMongoPassword() != null) { mongoClient = new MongoClient(serverAddresses, Arrays.asList(MongoCredential.createPlainCredential(configurationContext.getMongoUsername(), "$external", configurationContext.getMongoPassword().toCharArray()))); } else { log.warn( "MongoDB user or password are not defined. User: [{}], Password: [{}]. trying anonymous connection.", configurationContext.getMongoUsername(), configurationContext.getMongoPassword()); mongoClient = new MongoClient(serverAddresses); } } catch (UnknownHostException e) { e.printStackTrace(); } log.debug("Creating Spring Bean for mongoclient"); return mongoClient; }
From source file:com.stratio.streaming.functions.SaveToMongoActionExecutionFunction.java
License:Apache License
private MongoClient getMongoClient() throws UnknownHostException { if (mongoClient == null) { List<ServerAddress> serverAddresses = new ArrayList(); for (String mongoHost : mongoHosts) { String[] elements = mongoHost.split(":"); if (elements.length < 2) { //no port serverAddresses.add(new ServerAddress(elements[0])); } else { serverAddresses.add(new ServerAddress(elements[0], Integer.parseInt(elements[1]))); }/*from w w w .j a v a2 s . c om*/ } if (username != null && password != null) { mongoClient = new MongoClient(serverAddresses, Arrays.asList( MongoCredential.createPlainCredential(username, "$external", password.toCharArray()))); } else { log.warn( "MongoDB user or password are not defined. User: [{}], Password: [{}]. trying anonymous connection.", username, password); mongoClient = new MongoClient(serverAddresses); } } return mongoClient; }
From source file:me.konglong.momei.mongodb.config.MongoCredentialPropertyEditor.java
License:Apache License
@Override public void setAsText(String text) throws IllegalArgumentException { if (!StringUtils.hasText(text)) { return;//from w w w . j a v a 2 s . co m } List<MongoCredential> credentials = new ArrayList<MongoCredential>(); for (String credentialString : extractCredentialsString(text)) { String[] userNameAndPassword = extractUserNameAndPassword(credentialString); String database = extractDB(credentialString); Properties options = extractOptions(credentialString); if (!options.isEmpty()) { if (options.containsKey(AUTH_MECHANISM_KEY)) { String authMechanism = options.getProperty(AUTH_MECHANISM_KEY); if (MongoCredential.GSSAPI_MECHANISM.equals(authMechanism)) { verifyUserNamePresent(userNameAndPassword); credentials.add(MongoCredential.createGSSAPICredential(userNameAndPassword[0])); } else if (MongoCredential.MONGODB_CR_MECHANISM.equals(authMechanism)) { verifyUsernameAndPasswordPresent(userNameAndPassword); verifyDatabasePresent(database); credentials.add(MongoCredential.createMongoCRCredential(userNameAndPassword[0], database, userNameAndPassword[1].toCharArray())); } else if (MongoCredential.MONGODB_X509_MECHANISM.equals(authMechanism)) { verifyUserNamePresent(userNameAndPassword); credentials.add(MongoCredential.createMongoX509Credential(userNameAndPassword[0])); } else if (MongoCredential.PLAIN_MECHANISM.equals(authMechanism)) { verifyUsernameAndPasswordPresent(userNameAndPassword); verifyDatabasePresent(database); credentials.add(MongoCredential.createPlainCredential(userNameAndPassword[0], database, userNameAndPassword[1].toCharArray())); } else if (MongoCredential.SCRAM_SHA_1_MECHANISM.equals(authMechanism)) { verifyUsernameAndPasswordPresent(userNameAndPassword); verifyDatabasePresent(database); credentials.add(MongoCredential.createScramSha1Credential(userNameAndPassword[0], database, userNameAndPassword[1].toCharArray())); } else { throw new IllegalArgumentException(String.format( "Cannot create MongoCredentials for unknown auth mechanism '%s'!", authMechanism)); } } } else { verifyUsernameAndPasswordPresent(userNameAndPassword); verifyDatabasePresent(database); credentials.add(MongoCredential.createCredential(userNameAndPassword[0], database, userNameAndPassword[1].toCharArray())); } } setValue(credentials); }
From source file:org.apache.calcite.adapter.mongodb.MongoSchemaFactory.java
License:Apache License
private MongoCredential createCredentials(Map<String, Object> map) { final String authMechanismName = (String) map.get("authMechanism"); final AuthenticationMechanism authenticationMechanism = AuthenticationMechanism .fromMechanismName(authMechanismName); final String username = (String) map.get("username"); final String authDatabase = (String) map.get("authDatabase"); final String password = (String) map.get("password"); switch (authenticationMechanism) { case PLAIN:/*from ww w. java 2 s .c o m*/ return MongoCredential.createPlainCredential(username, authDatabase, password.toCharArray()); case SCRAM_SHA_1: return MongoCredential.createScramSha1Credential(username, authDatabase, password.toCharArray()); case GSSAPI: return MongoCredential.createGSSAPICredential(username); case MONGODB_CR: return MongoCredential.createMongoCRCredential(username, authDatabase, password.toCharArray()); case MONGODB_X509: return MongoCredential.createMongoX509Credential(username); } throw new IllegalArgumentException("Unsupported authentication mechanism " + authMechanismName); }
From source file:org.mephi.griffin.actorcloud.storage.StorageActor.java
License:Apache License
@Override public void preStart() { logger.entering("StorageActor", "preStart"); String errors = ""; Config config = getContext().system().settings().config(); try {//from w ww. j av a2 s . com String host; int port; String login = null; String pass = null; try { host = config.getString("actorcloud.storage.host"); } catch (Missing ex) { host = "localhost"; } try { port = config.getInt("actorcloud.storage.port"); } catch (Missing ex) { port = 27017; } try { login = config.getString("actorcloud.storage.login"); pass = config.getString("actorcloud.storage.pass"); } catch (Missing ex) { if (login != null) throw ex; login = ""; pass = ""; } try { dbName = config.getString("actorcloud.storage.db"); } catch (Missing ex) { dbName = "actorcloud"; } if (!login.equals("")) client = new MongoClient(new ServerAddress(host, port), Arrays .asList(MongoCredential.createPlainCredential(login, "actorcloud", pass.toCharArray()))); else client = new MongoClient(new ServerAddress(host, port)); logger.logp(Level.FINER, "StorageActor", "preStart", "Connected to " + host + ":" + port); if (client != null) { db = client.getDB(dbName); DBCursor cursor = db.getCollection("clients").find(); boolean adminFound = false; if (cursor.count() != 0) { while (cursor.hasNext()) { DBObject doc = cursor.next(); if (doc.get("name") != null && doc.get("name").equals("admin")) { adminFound = true; break; } } } if (!adminFound) { MessageDigest md = MessageDigest.getInstance("SHA-512"); BasicDBObject doc = new BasicDBObject(); byte[] hash = md.digest(("admin").getBytes()); doc.append("name", "admin"); doc.append("hash", hash); doc.append("maxSessions", 1); doc.append("maxChilds", 0); doc.append("messageHandlers", new ArrayList<>()); doc.append("childHandlers", new ArrayList<>()); db.getCollection("clients").insert(doc); } InitSuccess msg = new InitSuccess(InitSuccess.STORAGE, null, null, 0); logger.logp(Level.FINER, "StorageActor", "preStart", "InitSuccess -> Manager: " + msg); nodeManager.tell(msg, getSelf()); logger.logp(Level.INFO, "StorageActor", "preStart", "Storage started"); } else { InitFail msg = new InitFail(InitFail.STORAGE, null, null, 0, errors); logger.logp(Level.FINER, "StorageActor", "preStart", "InitFail -> Manager: " + msg); nodeManager.tell(msg, getSelf()); logger.logp(Level.WARNING, "StorageActor", "preStart", "Failed to connect to DB:\n" + errors); getContext().stop(getSelf()); } } catch (MongoException | UnknownHostException | NoSuchAlgorithmException e) { logger.throwing("StorageActor", "preStart", e); errors += e.getMessage() + "\n"; InitFail msg = new InitFail(InitFail.STORAGE, null, null, 0, errors); logger.logp(Level.FINER, "StorageActor", "preStart", "InitFail -> Manager: " + msg); nodeManager.tell(msg, getSelf()); logger.logp(Level.WARNING, "StorageActor", "preStart", "Failed to connect to DB:\n" + errors); getContext().stop(getSelf()); } logger.exiting("StorageActor", "preStart"); }
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 va 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; } }