List of usage examples for com.mongodb MongoCredential createMongoCRCredential
@SuppressWarnings("deprecation") @Deprecated public static MongoCredential createMongoCRCredential(final String userName, final String database, final char[] password)
From source file:com.wincere.lamda.storm.bolt.CreateTable.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args takes no args/*from w w w. j a va 2 s . c o m*/ * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017 */ public void update(BasicDBObject doc, OutputCollector collector, Tuple input) throws UnknownHostException { // connect to the local database server MongoCredential credential = MongoCredential.createMongoCRCredential("superuser", "admin", "12345678".toCharArray()); try { MongoClient mongoClient = new MongoClient(new ServerAddress("172.16.1.171", 27017), Arrays.asList(credential)); // MongoClient mongoClient = new MongoClient("172.16.1.171",27017); /* // Authenticate - optional MongoCredential credential = MongoCredential.createMongoCRCredential(userName, database, password); MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential)); */ // get handle to "mydb" DB db = mongoClient.getDB("UCAPBatchTest"); // get a collection object to work with DBCollection coll = db.getCollection("Queries1"); // DBCollection status = db.getCollection("statustest1"); //DBCollection coll1 = db.getCollection("queryaudittest1"); // drop all the data in it //coll.drop(); //status.drop(); //coll1.drop(); /* status.insert(new BasicDBObject().append("queryStatus", "Open").append("QueryStatusID","1")); status.insert(new BasicDBObject().append("queryStatus", "Answered").append("QueryStatusID","2")); status.insert(new BasicDBObject().append("queryStatus", "Closed").append("QueryStatusID","3")); status.insert(new BasicDBObject().append("queryStatus", "Cancelled").append("QueryStatusID","4")); */ // make a document and insert it int count = 0; DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss"); try { //.equals("Open")?"1":(splitValue[5].equals("Answered")?"2":"3") BasicDBObject searchQuery = new BasicDBObject().append("queryRepeatKey", (String) doc.get("queryRepeatKey")); BasicDBObject newDocument = new BasicDBObject(); DBCursor cursor = coll.find(searchQuery); //DBObject result = cursor.next(); if (cursor.hasNext()) { DBObject result = cursor.next(); String queryValue = (String) result.get("queryValue"); String queryStatusID = (String) result.get("queryStatusID"); String queryResponse = (String) result.get("queryResponse"); String queryResolvedTimeStamp = (String) result.get("queryResolvedTimeStamp"); String queryAnsweredTimeStamp = (String) result.get("queryAnsweredTimeStamp"); String queryCreatedTimeStamp = (String) result.get("queryCreatedTimeStamp"); if (doc.get("queryValue").equals("\\N")) { doc.append("queryValue", queryValue); } if (doc.get("queryStatusID").equals("\\N")) { doc.append("queryStatusID", queryStatusID); } if (doc.get("queryResponse").equals("\\N")) { doc.append("queryResponse", queryResponse); } if (doc.get("queryResolvedTimeStamp").equals("\\N")) { doc.append("queryResolvedTimeStamp", queryResolvedTimeStamp); } if (doc.get("queryAnsweredTimeStamp").equals("\\N")) { doc.append("queryAnsweredTimeStamp", queryAnsweredTimeStamp); } doc.append("queryCreatedTimeStamp", queryCreatedTimeStamp); } if (doc.get("queryStatusID").equals("Open")) doc.append("queryCreatedTimeStamp", doc.get("queryCreatedTimeStamp")); //System.out.println(count); newDocument.append("$set", doc); try { coll.update(searchQuery, newDocument, true, true); } catch (MongoException me) { collector.fail(input); } // collector.ack(input); //coll.insert(doc); } catch (Exception e) { System.err.println("CSV file cannot be read : " + e); } //System.out.println(count); // lets get all the documents in the collection and print them out /*DBCursor cursor = coll1.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 = coll.find(query); try { while (cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); }*/ // release resources //db.dropDatabase(); mongoClient.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:de.steilerdev.myVerein.server.controller.init.InitController.java
License:Open Source License
/** * This function is validating the provided information of the MongoDB server, by establishing a test connection. * @param databaseHost The hostname of the MongoDB server. * @param databasePort The port of the MongoDB server. * @param databaseUser The user used to authenticate against the MongoDB server (may be empty if not needed). * @param databasePassword The password used to authenticate against the MongoDB server (may be empty if not needed). * @param databaseCollection The name of the database collection. * @return True if the connection was successfully established, false otherwise. *///www . j a v a 2s .c om private boolean mongoIsAvailable(String databaseHost, int databasePort, String databaseUser, String databasePassword, String databaseCollection) { logger.trace("Testing MongoDB connection"); if (!databaseUser.isEmpty() && !databasePassword.isEmpty()) { logger.debug("Credentials have been provided"); mongoCredential = Arrays.asList(MongoCredential.createMongoCRCredential(databaseUser, databaseCollection, databasePassword.toCharArray())); } try { logger.debug("Creating server address"); mongoAddress = new ServerAddress(databaseHost, databasePort); } catch (UnknownHostException e) { logger.warn("Unable to resolve server host: " + e.getMessage()); return false; } logger.debug("Creating mongo client"); MongoClient mongoClient = new MongoClient(mongoAddress, mongoCredential); try { //Checking if connection REALLY works logger.debug("Establishing connection now."); List<String> databases = mongoClient.getDatabaseNames(); if (databases == null) { logger.warn("The returned list of databases is null"); return false; } else if (databases.isEmpty()) { logger.info("The databases are empty"); return true; } else { logger.debug("The database connection seems okay"); return true; } } catch (MongoException e) { logger.warn("Unable to receive list of present databases: " + e.getMessage()); return false; } finally { logger.debug("Closing mongo client"); mongoClient.close(); } }
From source file:example.MongoCredentialsExample.java
License:Apache License
public static void main(String[] args) throws UnknownHostException { String server = args[0];//from w ww .ja v a 2 s . com 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), 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:exifIndexer.MongoHandler.java
public DB connect() { MongoCredential credential = MongoCredential.createMongoCRCredential(user, bdname, password); MongoClient Client;/*from www . ja va2 s . co m*/ try { Client = new MongoClient(new ServerAddress(host, port), Arrays.asList(credential)); } catch (UnknownHostException ex) { System.err.println("Error creating Mongo DB Client"); } try { Client = new MongoClient(host, port); DB db = Client.getDB(bdname); //Elimino la bd por si hubiera datos mongoClient = Client; //db = deletedb(bdname); // mongoClient.getDB(bdname).dropDatabase(); return db; } catch (UnknownHostException ex) { Logger.getLogger(MongoHandler.class.getName()).log(Level.SEVERE, null, ex); return null; } }
From source file:ezbakehelpers.mongoutils.MongoHelper.java
License:Apache License
public MongoCredential getMongoCredential() { checkArgument(!Strings.isNullOrEmpty(mongoConfigurationHelper.getMongoDBUserName()), "Mongo Username must not be null"); checkArgument(!Strings.isNullOrEmpty(mongoConfigurationHelper.getMongoDBPassword()), "Mongo Password must not be null"); checkArgument(!Strings.isNullOrEmpty(mongoConfigurationHelper.getMongoDBDatabaseName()), "Mongo Database must not be null"); return MongoCredential.createMongoCRCredential(mongoConfigurationHelper.getMongoDBUserName(), mongoConfigurationHelper.getMongoDBDatabaseName(), mongoConfigurationHelper.getMongoDBPassword().toCharArray()); }
From source file:io.gravitee.repository.mongodb.common.MongoFactory.java
License:Apache License
@Override public Mongo getObject() throws Exception { MongoClientOptions.Builder builder = builder(); // Trying to get the MongoClientURI if uri property is defined String uri = readPropertyValue(propertyPrefix + "uri"); if (uri != null && !uri.isEmpty()) { // The builder can be configured with default options, which may be overridden by options specified in // the URI string. return new MongoClient(new MongoClientURI(uri, builder)); } else {//from w ww .j a v a2 s .c om String databaseName = readPropertyValue(propertyPrefix + "dbname", String.class, "gravitee"); String username = readPropertyValue(propertyPrefix + "username"); String password = readPropertyValue(propertyPrefix + "password"); List<MongoCredential> credentials = null; if (username != null || password != null) { credentials = Collections.singletonList( MongoCredential.createMongoCRCredential(username, databaseName, password.toCharArray())); } List<ServerAddress> seeds; int serversCount = getServersCount(); if (serversCount == 0) { String host = readPropertyValue(propertyPrefix + "host", String.class, "localhost"); int port = readPropertyValue(propertyPrefix + "port", int.class, 27017); seeds = Collections.singletonList(new ServerAddress(host, port)); } else { seeds = new ArrayList<>(serversCount); for (int i = 0; i < serversCount; i++) { seeds.add(buildServerAddress(i)); } } MongoClientOptions options = builder.build(); if (credentials == null) { return new MongoClient(seeds, options); } return new MongoClient(seeds, credentials, options); } }
From source file:MDBInt.DBMongo.java
License:Apache License
private void connectReplication() { MongoCredential credential;//from w w w . j a v a2s . c o m ArrayList<ServerAddress> lista = new ArrayList(); List<Element> servers = serverList.getChildren(); // System.out.println("dentro connect"); String ip; int porta; try { for (int s = 0; s < servers.size(); s++) { ip = servers.get(s).getChildText("serverUrl"); porta = Integer.decode(servers.get(s).getChildText("port")); // lista.add(new ServerAddress(servers.get(s).getChildText("serverUrl"),Integer.decode(servers.get(s).getChildText("port")))); lista.add(new ServerAddress(ip, porta)); } credential = MongoCredential.createMongoCRCredential(user, dbName, password.toCharArray()); mongoClient = new MongoClient(lista, Arrays.asList(credential)); connection = true; } catch (Exception ex) { ex.printStackTrace(); } }
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;// w ww .j a v a 2s .c om } 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:me.photomap.web.config.MongoConfig.java
@Bean @Override/*from ww w . j a v a 2 s .c o m*/ public Mongo mongo() throws Exception { int port = env.getProperty("mongodb.dbport", Integer.class); String host = env.getProperty("mongodb.dbhostname"); String user = env.getProperty("mongodb.dbusername"); String pass = env.getProperty("mongodb.dbpassword"); MongoCredential credential = MongoCredential.createMongoCRCredential(user, "admin", pass.toCharArray()); MongoClient m = new MongoClient(new ServerAddress(host), Arrays.asList(credential)); return m; }
From source file:net.gtaun.wl.race.RacePlugin.java
License:Open Source License
@Override protected void onEnable() throws Throwable { config = new RaceConfig(new File(getDataDir(), "config.yml")); if (config.getDbUser().isEmpty() || config.getDbPass().isEmpty()) { mongoClient = new MongoClient(config.getDbHost()); } else {/* w w w.ja v a 2 s.co m*/ mongoClient = new MongoClient(Arrays.asList(new ServerAddress(config.getDbHost())), Arrays.asList(MongoCredential.createMongoCRCredential(config.getDbName(), config.getDbName(), config.getDbPass().toCharArray()))); } morphia = new Morphia(); morphia.getMapper().getOptions().objectFactory = new DefaultCreator() { @Override protected ClassLoader getClassLoaderForClass(String clazz, DBObject object) { return getClass().getClassLoader(); } }; datastore = morphia.createDatastore(mongoClient, config.getDbName()); vehicleManagerSerivce = new RaceServiceImpl(getEventManager(), this, datastore); registerService(RaceService.class, vehicleManagerSerivce); LOGGER.info(getDescription().getName() + " " + getDescription().getVersion() + " Enabled."); }