public EMSMongoClient() throws IOException { Properties config = new Properties(); InputStream in = this.getClass().getClassLoader().getResourceAsStream("config.properties"); config.load(in); MongoClient client; List<ServerAddress> serverAddresses = Arrays.asList( new ServerAddress( config.getProperty("mongo_host"), Integer.parseInt(config.getProperty("mongo_port")))); if (config.containsKey("mongo_user") && config.containsKey("mongo_password")) { MongoCredential credential = MongoCredential.createMongoCRCredential( config.getProperty("mongo_user"), config.getProperty("mongo_db"), config.getProperty("mongo_password").toCharArray()); client = new MongoClient(serverAddresses, Arrays.asList(credential)); } else { client = new MongoClient(serverAddresses); } DB db = client.getDB(config.getProperty("mongo_db")); this.collection = db.getCollection("sessions"); }
public static void main(String[] args) { System.setProperty("javax.net.ssl.trustStore", args[0]); System.setProperty("javax.net.ssl.trustStorePassword", args[1]); MongoClientOptions.Builder options = builder().sslEnabled(true).sslInvalidHostNameAllowed(true); String uri = "mongodb://127.0.0.1:27017/"; MongoClientURI connectionString = new MongoClientURI(uri, options); MongoClient mongoClient = new MongoClient(connectionString); // with username and password char[] pwd = "mypasswrd!".toCharArray(); MongoCredential credential = MongoCredential.createCredential( "myadmin", "admin", pwd); // user "myadmin" on admin database List<MongoCredential> credentials = Collections.singletonList(credential); List<ServerAddress> hosts = Arrays.asList( new ServerAddress("mongodb01.host.dblayer.com:10054"), new ServerAddress("mongodb02.host.1.dblayer.com:10071")); mongoClient = new MongoClient(hosts, credentials, options.build()); MongoDatabase foxtrot = mongoClient.getDatabase("foxtrot"); MongoIterable<String> collectionNames = foxtrot.listCollectionNames(); }
/** * 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. * * @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 return new MongoClient(new MongoClientURI(this.uri, builder(options))); } finally { clearPassword(); } }
@Override public void onEnable() { instance = this; Bukkit.getPluginManager().registerEvents(new PlayerJoinListener(), this); Bukkit.getPluginManager().registerEvents(new PlayerQuitListener(), this); Bukkit.getPluginManager().registerEvents(new InventoryClickListener(), this); Bukkit.getPluginManager().registerEvents(new InventoryCloseListener(), this); Bukkit.getPluginManager().registerEvents(new PlayerInteractListener(), this); mongoClient = new MongoClient( new ServerAddress("craplezz.de", 27017), Collections.singletonList( MongoCredential.createCredential( "Overload", "admin", "1999mani123".toCharArray()))); localeManager = new LocaleManager(mongoClient, "todo", "general"); serverManager = new ServerManager( new CachedServerInfo( getServer().getServerName(), getServer().getMaxPlayers(), getServer().getOnlinePlayers().size(), getServer().getMotd())); getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); // Broadcast own server info serverManager.broadcastServerInfoData(); }
/** * 配置MongoDB的Bean * * @return * @throws Exception */ public @Bean MongoDbFactory mongoDbFactory() throws Exception { List<MongoCredential> credentialsList = new ArrayList<MongoCredential>(); MongoCredential userCredentials = MongoCredential.createCredential(user, authenticationDatabase, password.toCharArray()); credentialsList.add(userCredentials); return new SimpleMongoDbFactory( new MongoClient(new ServerAddress(host, port), credentialsList), database); }
public MongoConnector() { if (Constants.Mongo.AUTH_ENABLED) { mongoCredential = MongoCredential.createCredential( Constants.Mongo.USER, Constants.Mongo.DATABASE, Constants.Mongo.USER_PASS); } mongoServerAddress = new ServerAddress(Constants.Mongo.HOST, Constants.Mongo.PORT); this.mongoClient = new MongoClient(mongoServerAddress, Arrays.asList(mongoCredential)); }
private MongoCredential createCredentials( Map<String, List<String>> optionsMap, final String userName, final char[] password, String database) { if (userName == null) { return null; } if (database == null) { database = "admin"; } String mechanism = MongoCredential.MONGODB_CR_MECHANISM; String authSource = database; String gssapiServiceName = null; for (String key : authKeys) { String value = getLastValue(optionsMap, key); if (value == null) { continue; } if (key.equals("authmechanism")) { mechanism = value; } else if (key.equals("authsource")) { authSource = value; } else if (key.equals("gssapiservicename")) { gssapiServiceName = value; } } if (mechanism.equals(MongoCredential.GSSAPI_MECHANISM)) { MongoCredential gssapiCredential = MongoCredential.createGSSAPICredential(userName); if (gssapiServiceName != null) { gssapiCredential = gssapiCredential.withMechanismProperty("SERVICE_NAME", gssapiServiceName); } return gssapiCredential; } else if (mechanism.equals(MongoCredential.PLAIN_MECHANISM)) { return MongoCredential.createPlainCredential(userName, authSource, password); } else if (mechanism.equals(MongoCredential.MONGODB_CR_MECHANISM)) { return MongoCredential.createMongoCRCredential(userName, authSource, password); } else if (mechanism.equals(MongoCredential.MONGODB_X509_MECHANISM)) { return MongoCredential.createMongoX509Credential(userName); } else if (mechanism.equals(MongoCredential.SCRAM_SHA_1_MECHANISM)) { return MongoCredential.createScramSha1Credential(userName, authSource, password); } else { throw new IllegalArgumentException("Unsupported authMechanism: " + mechanism); } }
@Override @Bean public Mongo mongo() throws Exception { host = System.getenv("CU_DATABASE_DNS_MONGO_1"); port = 27017; username = System.getenv("CU_DATABASE_USER_MONGO_1"); database = System.getenv("CU_DATABASE_NAME"); password = System.getenv("CU_DATABASE_PASSWORD_MONGO_1"); log.info("CU_DATABASE_DNS_MONGO_1 : " + host); log.info("CU_DATABASE_USER_MONGO_1 : " + username); log.info("CU_DATABASE_NAME : " + database); log.info("CU_DATABASE_PASSWORD_MONGO_1 : " + password); log.info("MongoDB Initialization"); return new MongoClient( singletonList(new ServerAddress(host, port)), singletonList(MongoCredential.createCredential(username, "admin", password.toCharArray()))); }
private CommandResultPair authenticateCommandHelper(String username, char[] password) { MongoCredential credentials = MongoCredential.createMongoCRCredential(username, getName(), password); if (getAuthenticationCredentials() != null) { if (getAuthenticationCredentials().equals(credentials)) { if (authenticationTestCommandResult != null) { return new CommandResultPair(authenticationTestCommandResult); } } else { throw new IllegalStateException("can't authenticate twice on the same database"); } } try { authenticationTestCommandResult = doAuthenticate(credentials); return new CommandResultPair(authenticationTestCommandResult); } catch (CommandFailureException commandFailureException) { return new CommandResultPair(commandFailureException); } }
protected MongoClient createMongoClient(Collection<String> uris, MongoClientOptions options) { String currentURI = null; try { List<ServerAddress> serverAddresses = new ArrayList<>(uris.size()); List<MongoCredential> mongoCredentials = new ArrayList<>(); for (String uri : uris) { currentURI = uri; serverAddresses.add(createServerAddress(currentURI)); String[] segments = currentURI.split("/"); String host = segments[2]; int authIndex = host.indexOf('@'); if (segments.length == 4) databaseName = segments[3]; if (authIndex > 0) { String[] credentials = host.substring(0, authIndex).split(":"); mongoCredentials.add( MongoCredential.createCredential( credentials[0], databaseName, credentials[1].toCharArray())); } } if (serverAddresses.size() == 1) return new MongoClient(serverAddresses.get(0), mongoCredentials, options); else return new MongoClient(serverAddresses, mongoCredentials, options); } catch (UnknownHostException e) { handleConfigurationException("The URI: '" + currentURI + "' has a bad hostname", e); } catch (URISyntaxException e) { handleConfigurationException("The URI: '" + currentURI + "' is not a proper URI", e); } return null; }
/** * Factory method for creating a MongoDB provider within the plugin manager. * * @param collectionName The name of the MongoDB collection to which log events should be written. * @param writeConcernConstant The {@link WriteConcern} constant to control writing details, * defaults to {@link WriteConcern#ACKNOWLEDGED}. * @param writeConcernConstantClassName The name of a class containing the aforementioned static * WriteConcern constant. Defaults to {@link WriteConcern}. * @param databaseName The name of the MongoDB database containing the collection to which log * events should be written. Mutually exclusive with {@code * factoryClassName&factoryMethodName!=null}. * @param server The host name of the MongoDB server, defaults to localhost and mutually exclusive * with {@code factoryClassName&factoryMethodName!=null}. * @param port The port the MongoDB server is listening on, defaults to the default MongoDB port * and mutually exclusive with {@code factoryClassName&factoryMethodName!=null}. * @param userName The username to authenticate against the MongoDB server with. * @param password The password to authenticate against the MongoDB server with. * @param factoryClassName A fully qualified class name containing a static factory method capable * of returning a {@link DB} or a {@link MongoClient}. * @param factoryMethodName The name of the public static factory method belonging to the * aforementioned factory class. * @return a new MongoDB provider. */ @PluginFactory public static MongoDbProvider createNoSqlProvider( @PluginAttribute("collectionName") final String collectionName, @PluginAttribute("writeConcernConstant") final String writeConcernConstant, @PluginAttribute("writeConcernConstantClass") final String writeConcernConstantClassName, @PluginAttribute("databaseName") final String databaseName, @PluginAttribute(value = "server", defaultString = "localhost") @ValidHost final String server, @PluginAttribute(value = "port", defaultString = "" + DEFAULT_PORT) @ValidPort final String port, @PluginAttribute("userName") final String userName, @PluginAttribute(value = "password", sensitive = true) final String password, @PluginAttribute("factoryClassName") final String factoryClassName, @PluginAttribute("factoryMethodName") final String factoryMethodName) { DB database; String description; if (Strings.isNotEmpty(factoryClassName) && Strings.isNotEmpty(factoryMethodName)) { try { final Class<?> factoryClass = LoaderUtil.loadClass(factoryClassName); final Method method = factoryClass.getMethod(factoryMethodName); final Object object = method.invoke(null); if (object instanceof DB) { database = (DB) object; } else if (object instanceof MongoClient) { if (Strings.isNotEmpty(databaseName)) { database = ((MongoClient) object).getDB(databaseName); } else { LOGGER.error( "The factory method [{}.{}()] returned a MongoClient so the database name is " + "required.", factoryClassName, factoryMethodName); return null; } } else if (object == null) { LOGGER.error( "The factory method [{}.{}()] returned null.", factoryClassName, factoryMethodName); return null; } else { LOGGER.error( "The factory method [{}.{}()] returned an unsupported type [{}].", factoryClassName, factoryMethodName, object.getClass().getName()); return null; } description = "database=" + database.getName(); final List<ServerAddress> addresses = database.getMongo().getAllAddress(); if (addresses.size() == 1) { description += ", server=" + addresses.get(0).getHost() + ", port=" + addresses.get(0).getPort(); } else { description += ", servers=["; for (final ServerAddress address : addresses) { description += " { " + address.getHost() + ", " + address.getPort() + " } "; } description += "]"; } } catch (final ClassNotFoundException e) { LOGGER.error("The factory class [{}] could not be loaded.", factoryClassName, e); return null; } catch (final NoSuchMethodException e) { LOGGER.error( "The factory class [{}] does not have a no-arg method named [{}].", factoryClassName, factoryMethodName, e); return null; } catch (final Exception e) { LOGGER.error( "The factory method [{}.{}()] could not be invoked.", factoryClassName, factoryMethodName, e); return null; } } else if (Strings.isNotEmpty(databaseName)) { final List<MongoCredential> credentials = new ArrayList<>(); description = "database=" + databaseName; if (Strings.isNotEmpty(userName) && Strings.isNotEmpty(password)) { description += ", username="******", passwordHash=" + NameUtil.md5(password + MongoDbProvider.class.getName()); credentials.add( MongoCredential.createCredential(userName, databaseName, password.toCharArray())); } try { final int portInt = TypeConverters.convert(port, int.class, DEFAULT_PORT); description += ", server=" + server + ", port=" + portInt; database = new MongoClient(new ServerAddress(server, portInt), credentials).getDB(databaseName); } catch (final Exception e) { LOGGER.error( "Failed to obtain a database instance from the MongoClient at server [{}] and " + "port [{}].", server, port); return null; } } else { LOGGER.error("No factory method was provided so the database name is required."); return null; } try { database.getCollectionNames(); // Check if the database actually requires authentication } catch (final Exception e) { LOGGER.error( "The database is not up, or you are not authenticated, try supplying a username and password to the MongoDB provider.", e); return null; } final WriteConcern writeConcern = toWriteConcern(writeConcernConstant, writeConcernConstantClassName); return new MongoDbProvider(database, writeConcern, collectionName, description); }