public MongoSongStore() { String connectionString = System.getProperty(CONNECTION_STRING_PROPERTY, "mongodb://localhost"); String databaseName = System.getProperty(DATABASE_NAME_PROPERTY, "default"); String collectionName = System.getProperty(COLLECTION_NAME_PROPERTY, "default"); mongoClient = MongoClients.create(new ConnectionString(connectionString)); mongoDatabase = mongoClient.getDatabase(databaseName); mongoCollection = mongoDatabase.getCollection(collectionName); logger.info("Initialized Mongo Driver with databaseName=" + databaseName + " collectionName=" + collectionName); }
private List<MongoClientWrapper> getMongoClient(List<ConnectionString> shardSet) { mongoClients = new ArrayList<>(); try { for (ConnectionString address : shardSet) { com.mongodb.reactivestreams.client.MongoClient client = MongoClients.create(address); mongoClients.add(new MongoClientWrapper(address.getConnectionString(), client)); Thread.sleep(100); // allow the client to establish prior to being } } catch (InterruptedException e) { e.printStackTrace(); } return mongoClients; }
private List<ConnectionString> buildServerAddressList(DBObject next) { List<ConnectionString> hosts = new ArrayList<>(); for (String host : Arrays.asList(((String) next.get("host")).split("/")[1].split(","))) { hosts.add(new ConnectionString("mongodb://" + host)); } return hosts; }
/** * {@inheritDoc} */ @Override public void onEnable() { saveDefaultConfig(); CodecRegistry codecRegistry = createCodecRegistry(); MongoClientSettings settings = MongoClientSettings.builder() .clusterSettings(ClusterSettings.builder().applyConnectionString(new ConnectionString(getConfig().getString("mongodb.uri"))).build()) .codecRegistry(codecRegistry) .build(); client = MongoClients.create(settings); MongoDatabase database = client.getDatabase(getConfig().getString("mongodb.database")); if (!testConnection(database)) return; RegionStorageAdapter storageAdapter = new RegionStorageAdapter(database); MongoRegionDriver driver = new MongoRegionDriver(getServer(), storageAdapter); WorldGuardPlugin wgPlugin = WorldGuardPlugin.inst(); if (getConfig().getBoolean("mongodb.use_oplog")) { getLogger().info("OpLog usage enabled."); WorldGuardOpLogHandler opLogHandler = new WorldGuardOpLogHandler(codecRegistry.get(ProcessingProtectedRegion.class), storageAdapter, wgPlugin); getServer().getScheduler().runTaskAsynchronously(this, new OpLogRetriever( OpLogUtils.getCollection(client), new OpLogParser(opLogHandler), getConfig().getString("mongodb.database") + "." + RegionStorageAdapter.COLLECTION_NAME )); storageAdapter.setListener(opLogHandler); } ConfigurationManager config = wgPlugin.getGlobalStateManager(); RegionContainer container = wgPlugin.getRegionContainer(); InjectionUtils.injectRegionDriver(container, driver); InjectionUtils.callUnload(container); InjectionUtils.callLoadWorlds(container); config.selectedRegionStoreDriver = driver; }
public ClusterSettingsParser(ConnectionString connectionString, JsonObject config) { ClusterSettings.Builder settings = ClusterSettings.builder(); // ConnectionString takes precedence if (connectionString != null) { settings.applyConnectionString(connectionString); } else { // hosts List<ServerAddress> hosts = parseHosts(config); settings.hosts(hosts); // replica set / mode String replicaSet = config.getString("replicaSet"); if (hosts.size() == 1 && replicaSet == null) { settings.mode(ClusterConnectionMode.SINGLE); } else { settings.mode(ClusterConnectionMode.MULTIPLE); } if (replicaSet != null) { settings.requiredReplicaSetName(replicaSet); } // serverSelectionTimeoutMS Long serverSelectionTimeoutMS = config.getLong("serverSelectionTimeoutMS"); if(serverSelectionTimeoutMS != null) { settings.serverSelectionTimeout(serverSelectionTimeoutMS, MILLISECONDS); } Integer waitQueueMultiple = config.getInteger("waitQueueMultiple"); if (waitQueueMultiple != null) { Integer waitQueueSize = waitQueueMultiple * DEFAULT_MONGO_DRIVER_WAIT_Q_SIZE; settings.maxWaitQueueSize(waitQueueSize); } } this.settings = settings.build(); }
ReadPreferenceParser(ConnectionString connectionString, JsonObject config) { ReadPreference connStringReadPreference = connectionString != null ? connectionString.getReadPreference() : null; if (connStringReadPreference != null) { // Prefer connection string's read preference readPreference = connStringReadPreference; } else { ReadPreference rp; String rps = config.getString("readPreference"); if (rps != null) { JsonArray readPreferenceTags = config.getJsonArray("readPreferenceTags"); if (readPreferenceTags == null) { rp = ReadPreference.valueOf(rps); if (rp == null) throw new IllegalArgumentException("Invalid ReadPreference " + rps); } else { // Support advanced ReadPreference Tags List<TagSet> tagSet = new ArrayList<>(); readPreferenceTags.forEach(o -> { String tagString = (String) o; List<Tag> tags = Stream.of(tagString.trim().split(",")) .map(s -> s.split(":")) .filter(array -> { if (array.length != 2) { throw new IllegalArgumentException("Invalid readPreferenceTags value '" + tagString + "'"); } return true; }).map(array -> new Tag(array[0], array[1])).collect(Collectors.toList()); tagSet.add(new TagSet(tags)); }); rp = ReadPreference.valueOf(rps, tagSet); } } else { rp = null; } readPreference = rp; } }
public SocketSettingsParser(ConnectionString connectionString, JsonObject config) { SocketSettings.Builder settings = SocketSettings.builder(); if (connectionString != null) { settings.applyConnectionString(connectionString); } else { Integer connectTimeoutMS = config.getInteger("connectTimeoutMS"); if (connectTimeoutMS != null) { settings.connectTimeout(connectTimeoutMS, MILLISECONDS); } Integer socketTimeoutMS = config.getInteger("socketTimeoutMS"); if (socketTimeoutMS != null) { settings.readTimeout(socketTimeoutMS, MILLISECONDS); } Boolean keepAlive = config.getBoolean("keepAlive"); if (keepAlive != null) { settings.keepAlive(keepAlive); } Integer receiveBufferSize = config.getInteger("receiveBufferSize"); if (receiveBufferSize != null) { settings.receiveBufferSize(receiveBufferSize); } Integer sendBufferSize = config.getInteger("sendBufferSize"); if (sendBufferSize != null) { settings.sendBufferSize(sendBufferSize); } } this.settings = settings.build(); }
public SSLSettingsParser(ConnectionString connectionString, JsonObject config) { SslSettings.Builder settings = SslSettings.builder(); Boolean ssl; if (connectionString != null) { ssl = connectionString.getSslEnabled(); } else { ssl = config.getBoolean("ssl"); } if (ssl != null) { settings.enabled(ssl); } this.settings = settings.build(); }
@Test public void testConnStringWriteConcern() { final ConnectionString connString = new ConnectionString("mongodb://localhost:27017/mydb?replicaSet=myapp&safe=true"); WriteConcern wc = new WriteConcernParser(connString, new JsonObject()).writeConcern(); assertNotNull(wc); assertEquals(WriteConcern.ACKNOWLEDGED, wc); }
@Test public void testConnStringSimpleAndAdvancedWriteConcern() { final ConnectionString connString = new ConnectionString("mongodb://localhost:27017/mydb?replicaSet=myapp" + "&w=majority&wtimeoutms=20&journal=false"); WriteConcern expected = new WriteConcern("majority").withWTimeout(20, TimeUnit.MILLISECONDS).withJournal(false); WriteConcern wc = new WriteConcernParser(connString, new JsonObject()).writeConcern(); assertNotNull(wc); assertEquals(expected, wc); }
static SocketSettings socket(final String path, final ConnectionString cstr, final Config dbconf) { SocketSettings.Builder settings = SocketSettings.builder().applyConnectionString(cstr); withConf(path, dbconf, c -> { withMs("connectTimeout", c, s -> settings.connectTimeout(s.intValue(), TimeUnit.MILLISECONDS)); withBool("keepAlive", c, settings::keepAlive); withMs("readTimeout", c, s -> settings.readTimeout(s.intValue(), TimeUnit.MILLISECONDS)); withInt("receiveBufferSize", c, settings::receiveBufferSize); withInt("sendBufferSize", c, settings::sendBufferSize); }); return settings.build(); }
private Block cluster(final String db) { return unit -> { ClusterSettings settings = unit.mock(ClusterSettings.class); unit.registerMock(ClusterSettings.class, settings); ClusterSettings.Builder builder = unit.mock(ClusterSettings.Builder.class); expect(builder.applyConnectionString(new ConnectionString(db))).andReturn(builder); expect(builder.build()).andReturn(settings); unit.mockStatic(ClusterSettings.class); expect(ClusterSettings.builder()).andReturn(builder); }; }
private Block pool(final String db) { return unit -> { ConnectionPoolSettings settings = unit.mock(ConnectionPoolSettings.class); unit.registerMock(ConnectionPoolSettings.class, settings); ConnectionPoolSettings.Builder builder = unit.mock(ConnectionPoolSettings.Builder.class); expect(builder.applyConnectionString(new ConnectionString(db))).andReturn(builder); expect(builder.build()).andReturn(settings); unit.mockStatic(ConnectionPoolSettings.class); expect(ConnectionPoolSettings.builder()).andReturn(builder); }; }
private Block socket(final String db) { return unit -> { SocketSettings settings = Try.apply(() -> unit.get(SocketSettings.class)) .orElseGet(() -> unit.mock(SocketSettings.class)); unit.registerMock(SocketSettings.class, settings); SocketSettings.Builder builder = Try.apply(() -> unit.get(SocketSettings.Builder.class)) .orElseGet(() -> unit.mock(SocketSettings.Builder.class)); expect(builder.applyConnectionString(new ConnectionString(db))).andReturn(builder).times(2); expect(builder.build()).andReturn(settings).times(2); expect(SocketSettings.builder()).andReturn(builder).times(2); }; }
private Block ssl(final String db) { return unit -> { SslSettings settings = unit.mock(SslSettings.class); unit.registerMock(SslSettings.class, settings); SslSettings.Builder builder = unit.mock(SslSettings.Builder.class); expect(builder.applyConnectionString(new ConnectionString(db))).andReturn(builder); expect(builder.build()).andReturn(settings); unit.mockStatic(SslSettings.class); expect(SslSettings.builder()).andReturn(builder); }; }
@Test(expected = IllegalArgumentException.class) public void wrongReadConcern() { MongoRx.settings(new ConnectionString("mongodb://localhost"), conf(null, "readConcern", "Xxx", "readPreference", "primary", "writeConcern", "w3")) .build(); }
@Test(expected = IllegalArgumentException.class) public void wrongWriteConcern() { MongoRx.settings(new ConnectionString("mongodb://localhost"), conf(null, "readPreference", "primary", "writeConcern", "Xqw")) .build(); }
/** * Lazily instantiate the {@link MongoClient} instance. * * @return */ private MongoClient createMongoClient() { String host = applicationConfiguration.getMongoHost(); int port = applicationConfiguration.getMongoPort(); ConnectionString connectionString = new ConnectionString("mongodb://" + host + ":" + port); logger.info("Creating Mongo client for: {}:{}", host, port); MongoClientSettings mongoClientSettings = MongoClientSettings.builder() .applicationName("dragoman") .serverSettings( ServerSettings.builder() .applyConnectionString(connectionString) .addServerMonitorListener(new LoggingServerMonitorListener()) .addServerListener(new LoggingServerListener()) .build()) .clusterSettings( ClusterSettings.builder() .applyConnectionString(connectionString) .serverSelectionTimeout( applicationConfiguration.getMongoServerSelectionTimeout(), MILLISECONDS) .addClusterListener(new LoggingClusterListener()) .build()) .connectionPoolSettings( ConnectionPoolSettings.builder() .applyConnectionString(connectionString) .maxWaitTime( applicationConfiguration.getConnectionPoolMaxWaitTime(), MILLISECONDS) .minSize(applicationConfiguration.getConnectionPoolMinSize()) .maxSize(applicationConfiguration.getConnectionPoolMaxSize()) .addConnectionPoolListener(new LoggingConnectionPoolListener()) .build()) .socketSettings( SocketSettings.builder() .applyConnectionString(connectionString) .connectTimeout( applicationConfiguration.getMongoSocketConnectionTimeout(), MILLISECONDS) .readTimeout(applicationConfiguration.getMongoReadTimeout(), MILLISECONDS) .build()) .build(); return MongoClients.create(mongoClientSettings); }
public CredentialListParser(ConnectionString connectionString, JsonObject config) { List<MongoCredential> connStringCredentials = null; if (connectionString != null) { connStringCredentials = connectionString.getCredentialList(); } if (connStringCredentials != null && !connStringCredentials.isEmpty()) { credentials = connStringCredentials; } else { String username = config.getString("username"); if (username == null) { credentials = Collections.emptyList(); } else { credentials = new ArrayList<>(); String passwd = config.getString("password"); char[] password = (passwd == null) ? null : passwd.toCharArray(); // See https://github.com/vert-x3/vertx-mongo-client/issues/46 - 'admin' as default is a security // concern, use the 'db_name' if none is set. String authSource = config.getString("authSource", config.getString("db_name", MongoClientImpl.DEFAULT_DB_NAME)); // AuthMechanism AuthenticationMechanism mechanism = null; String authMechanism = config.getString("authMechanism"); if (authMechanism != null) { mechanism = getAuthenticationMechanism(authMechanism); } // MongoCredential String gssapiServiceName = config.getString("gssapiServiceName"); MongoCredential credential; if (mechanism == GSSAPI) { credential = MongoCredential.createGSSAPICredential(username); credential = getMongoCredential(gssapiServiceName, credential); } else if (mechanism == PLAIN) { credential = MongoCredential.createPlainCredential(username, authSource, password); } else if (mechanism == MONGODB_CR) { credential = MongoCredential.createMongoCRCredential(username, authSource, password); } else if (mechanism == MONGODB_X509) { credential = MongoCredential.createMongoX509Credential(username); } else if (mechanism == SCRAM_SHA_1) { credential = MongoCredential.createScramSha1Credential(username, authSource, password); } else if (mechanism == null) { credential = MongoCredential.createCredential(username, authSource, password); } else { throw new IllegalArgumentException("Unsupported authentication mechanism " + mechanism); } credentials.add(credential); } } }
ReadConcernLevelParser(ConnectionString connectionString, JsonObject config) { this.connectionString = connectionString; this.config = config; }
public ConnectionPoolSettingsParser(ConnectionString connectionString, JsonObject config) { ConnectionPoolSettings.Builder settings = ConnectionPoolSettings.builder(); if (connectionString != null) { settings.applyConnectionString(connectionString); } else { Integer maxPoolSize = config.getInteger("maxPoolSize"); if (maxPoolSize != null) { settings.maxSize(maxPoolSize); } Integer minPoolSize = config.getInteger("minPoolSize"); if (minPoolSize != null) { settings.minSize(minPoolSize); } Long maxIdleTimeMS = config.getLong("maxIdleTimeMS"); if (maxIdleTimeMS != null) { settings.maxConnectionIdleTime(maxIdleTimeMS, MILLISECONDS); } Long maxLifeTimeMS = config.getLong("maxLifeTimeMS"); if (maxLifeTimeMS != null) { settings.maxConnectionLifeTime(maxLifeTimeMS, MILLISECONDS); } Integer waitQueueMultiple = config.getInteger("waitQueueMultiple"); if (waitQueueMultiple != null) { Integer waitQueueSize = waitQueueMultiple * DEFAULT_MONGO_DRIVER_WAIT_Q_SIZE; settings.maxWaitQueueSize(waitQueueSize); } Long waitQueueTimeoutMS = config.getLong("waitQueueTimeoutMS"); if (waitQueueTimeoutMS != null) { settings.maxWaitTime(waitQueueTimeoutMS, MILLISECONDS); } Long maintenanceInitialDelayMS = config.getLong("maintenanceInitialDelayMS"); if (maintenanceInitialDelayMS != null) { settings.maintenanceInitialDelay(maintenanceInitialDelayMS, MILLISECONDS); } Long maintenanceFrequencyMS = config.getLong("maintenanceFrequencyMS"); if (maintenanceFrequencyMS != null) { settings.maintenanceFrequency(maintenanceFrequencyMS, MILLISECONDS); } } this.settings = settings.build(); }
@Test public void testConnStringNoWriteConcern() { final ConnectionString connString = new ConnectionString("mongodb://localhost:27017/mydb?replicaSet=myapp"); WriteConcern rp = new WriteConcernParser(connString, new JsonObject()).writeConcern(); assertNull(rp); }
@SuppressWarnings({"rawtypes", "unchecked"}) @Override public void configure(final Env env, final Config conf, final Binder binder) { /** connection string */ ConnectionString cstr = Try.apply(() -> new ConnectionString(db)) .orElseGet(() -> new ConnectionString(conf.getString(db))); log.debug("Starting {}", cstr); boolean first = instances.getAndIncrement() == 0; Throwing.Function3<Class, String, Object, Void> bind = (type, name, value) -> { binder.bind(Key.get(type, Names.named(name))).toInstance(value); if (first) { binder.bind(Key.get(type)).toInstance(value); } return null; }; /** settings */ MongoClientSettings.Builder settings = settings(cstr, dbconf(db, conf)); if (configurer != null) { configurer.accept(settings, conf); } MongoClient client = MongoClients.create(settings.build()); bind.apply(MongoClient.class, db, client); /** bind database */ Optional.ofNullable(cstr.getDatabase()).ifPresent(dbname -> { // observable adapter MongoDatabase predb = adapter .map(a -> client.getDatabase(dbname).withObservableAdapter(a)) .orElseGet(() -> client.getDatabase(dbname)); // codec registry MongoDatabase database = codecRegistry .map(predb::withCodecRegistry) .orElse(predb); bind.apply(MongoDatabase.class, dbname, database); /** bind collection */ Optional.ofNullable(cstr.getCollection()).ifPresent(cname -> { MongoCollection<Document> collection = database.getCollection(cname); bind.apply(MongoCollection.class, cname, collection); }); }); /** mapper */ env.router() .map(mapper()); log.info("Started {}", cstr); env.onStop(() -> { log.debug("Stopping {}", cstr); client.close(); log.info("Stopped {}", cstr); }); }
/** * Creates a new client with the default connection string "mongodb://localhost". * * @return the client */ public static MongoClient create() { return create(new ConnectionString("mongodb://localhost")); }
/** * Create a new client with the given connection string. * * @param connectionString the connection * @return the client */ public static MongoClient create(final String connectionString) { return create(new ConnectionString(connectionString)); }
/** * Create a new client with the given connection string. * * @param connectionString the connection * @param observableAdapter the {@link ObservableAdapter} to adapt all {@code Observables} * @return the client * @since 1.2 */ public static MongoClient create(final String connectionString, final ObservableAdapter observableAdapter) { return create(new ConnectionString(connectionString), observableAdapter); }
/** * Create a new client with the given connection string. * * @param connectionString the settings * @return the client */ public static MongoClient create(final ConnectionString connectionString) { return create(connectionString, new NoopObservableAdapter()); }
/** * Create a new client with the given connection string. * * @param connectionString the settings * @param observableAdapter the {@link ObservableAdapter} to adapt all {@code Observables}. * @return the client * @since 1.2 */ public static MongoClient create(final ConnectionString connectionString, final ObservableAdapter observableAdapter) { return create(connectionString, observableAdapter, null); }
/** * Create a new client with the given connection string. * * <p>Note: Intended for driver and library authors to associate extra driver metadata with the connections.</p> * * @param connectionString the settings * @param observableAdapter the {@link ObservableAdapter} to adapt all {@code Observables}. * @param mongoDriverInformation any driver information to associate with the MongoClient * @return the client * @since 1.3 */ public static MongoClient create(final ConnectionString connectionString, final ObservableAdapter observableAdapter, final MongoDriverInformation mongoDriverInformation) { return create(com.mongodb.async.client.MongoClients.create(connectionString, getMongoDriverInformation(mongoDriverInformation)), observableAdapter); }
/** * Create a new client with the given connection string. * * @param connectionString the settings * @return the client */ public static MongoClient create(final ConnectionString connectionString) { return create(connectionString, null); }
/** * Create a new client with the given connection string. * * <p>Note: Intended for driver and library authors to associate extra driver metadata with the connections.</p> * * @param connectionString the settings * @param mongoDriverInformation any driver information to associate with the MongoClient * @return the client * @since 1.3 */ public static MongoClient create(final ConnectionString connectionString, final MongoDriverInformation mongoDriverInformation) { return create(com.mongodb.async.client.MongoClients.create(connectionString, getMongoDriverInformation(mongoDriverInformation))); }