@Override public CompletableFuture<SecurityDefinitionStore> open() { List<ServerAddress> hostList = Arrays.stream(hosts).map(h -> new ServerAddress(h)).collect(Collectors.toList()); ClusterSettings clusterSettings = ClusterSettings.builder().hosts(hostList).build(); MongoClientSettings settings = MongoClientSettings.builder().clusterSettings(clusterSettings).build(); mongoClient = MongoClients.create(settings); database = mongoClient.getDatabase(DATABASE_NAME); collection = database.getCollection(SECDEF_COLLECTION_NAME); // In the case of MongoDB, open is synchronous because it doesn't // actually communicate with the server until a query is invoked. return CompletableFuture.completedFuture(this); }
/** * Create an asynchronous MongoDB client * @return the client */ private com.mongodb.async.client.MongoClient createAsyncClient() { ClusterSettings clusterSettings = ClusterSettings.builder() .hosts(Arrays.asList(mongoConnector.serverAddress)) .build(); MongoClientSettings settings = MongoClientSettings.builder() .clusterSettings(clusterSettings).build(); return MongoClients.create(settings); }
/** * {@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; }
@Start public void start() { final ClusterSettings clusterSettings = ClusterSettings.builder().hosts(asList(new ServerAddress(host, port))).build(); final MongoClientSettings settings = MongoClientSettings.builder().clusterSettings(clusterSettings).build(); mongoClient = MongoClients.create(settings); db = mongoClient.getDatabase(this.database); launchConsumers(); }
/** * 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); }
private MongoClientSettings mongoSettings(String host, int port) { return MongoClientSettings.builder() .clusterSettings( ClusterSettings.builder().hosts(newArrayList(new ServerAddress(host, port))).build()) .build(); }
@Override public MongoClientSettings getSettings() { return wrapped.getSettings(); }
public MongoClientOptionsParser(JsonObject config) { Objects.requireNonNull(config); MongoClientSettings.Builder options = MongoClientSettings.builder(); options.codecRegistry(CodecRegistries.fromRegistries(commonCodecRegistry, CodecRegistries.fromCodecs(new JsonObjectCodec(config)))); // All parsers should support connection_string first String cs = config.getString("connection_string"); ConnectionString connectionString = (cs == null) ? null : new ConnectionString(cs); String csDatabase = (connectionString != null) ? connectionString.getDatabase() : null; this.database = csDatabase != null ? csDatabase : config.getString("db_name", MongoClient.DEFAULT_DB_NAME); // ClusterSettings ClusterSettings clusterSettings = new ClusterSettingsParser(connectionString, config).settings(); options.clusterSettings(clusterSettings); // ConnectionPoolSettings ConnectionPoolSettings connectionPoolSettings = new ConnectionPoolSettingsParser(connectionString, config).settings(); options.connectionPoolSettings(connectionPoolSettings); // Credentials List<MongoCredential> credentials = new CredentialListParser(connectionString, config).credentials(); options.credentialList(credentials); // SocketSettings SocketSettings socketSettings = new SocketSettingsParser(connectionString, config).settings(); options.socketSettings(socketSettings); // SSLSettings SslSettings sslSettings = new SSLSettingsParser(connectionString, config).settings(); options.sslSettings(sslSettings); // WriteConcern WriteConcern writeConcern = new WriteConcernParser(connectionString, config).writeConcern(); if (writeConcern != null) { options.writeConcern(writeConcern); } // ReadConcern maybeReadConcern(connectionString, config).ifPresent(options::readConcern); // ReadPreference ReadPreference readPreference = new ReadPreferenceParser(connectionString, config).readPreference(); if (readPreference != null) { options.readPreference(readPreference); } // Heartbeat SocketSettings JsonObject hbConfig = config.getJsonObject("heartbeat.socket"); if (hbConfig != null) { SocketSettings heartBeatSocketSettings = new SocketSettingsParser(null, hbConfig).settings(); options.heartbeatSocketSettings(heartBeatSocketSettings); } // ServerSettings ServerSettings serverSettings = new ServerSettingsParser(config).settings(); options.serverSettings(serverSettings); this.settings = options.build(); }
public MongoClientSettings settings() { return settings; }
@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); }); }
private void connect() throws ActivecheckReporterException { if (mongoClient == null) { logger.debug("Cannot run query. MongoDB is not connected. Trying to (re)connect."); try { // configure credentials List<MongoCredential> credentialsList = new ArrayList<MongoCredential>(); String username = properties .getString("mongodb.username", null); String password = properties .getString("mongodb.password", null); if (username != null && password != null) { credentialsList.add(MongoCredential.createPlainCredential( username, "*", password.toCharArray())); } // configure server addresses List<ServerAddress> addressList = new ArrayList<ServerAddress>(); String socketPath = properties.getString("socket", null); if (socketPath != null) { addressList.add(new ServerAddress(new AFUNIXSocketAddress( new File(socketPath)))); } else { String url = properties.getString("url", ServerAddress.defaultHost()); int port = ServerAddress.defaultPort(); String[] urlParts = url.split(":"); if (urlParts.length > 1) { port = Integer.parseInt(urlParts[1]); } addressList.add(new ServerAddress(urlParts[0], port)); } ServerSelector serverSelector = new ReadPreferenceServerSelector( MONGO_READ_PREFERENCE); ClusterSettings clusterSettings = ClusterSettings.builder() .hosts(addressList).serverSelector(serverSelector) .build(); // actually configure and (re)create mongoClient ConnectionPoolSettings connectionPoolSettings = ConnectionPoolSettings .builder().maxSize(MONGO_POOL_SIZE).build(); MongoClientSettings settings = MongoClientSettings.builder() .readPreference(MONGO_READ_PREFERENCE) .credentialList(credentialsList) .clusterSettings(clusterSettings) .connectionPoolSettings(connectionPoolSettings).build(); mongoClient = MongoClients.create(settings); } catch (Exception e) { mongoClient = null; String errorMessage = "MongodbReporter Configuration Error for service '" + getOverallServiceName() + "': " + e.getMessage(); logger.error(errorMessage); logger.trace(e.getMessage(), e); // set report and status setOverallServiceReport(NagiosServiceStatus.CRITICAL, errorMessage); throw new ActivecheckReporterException(e); } } }
/** * Gets the settings that this client uses to connect to server. * * <p>Note: {@link MongoClientSettings} is immutable.</p> * * @return the settings */ MongoClientSettings getSettings();
/** * Create a new client with the given client settings. * * @param settings the settings * @return the client */ public static MongoClient create(final MongoClientSettings settings) { return create(settings, new NoopObservableAdapter()); }
/** * Create a new client with the given client settings. * * @param settings the settings * @param observableAdapter the {@link ObservableAdapter} to adapt all {@code Observables} * @return the client * @since 1.2 */ public static MongoClient create(final MongoClientSettings settings, final ObservableAdapter observableAdapter) { return create(settings, observableAdapter, null); }
/** * Creates a new client with the given client settings. * * <p>Note: Intended for driver and library authors to associate extra driver metadata with the connections.</p> * * @param settings 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 MongoClientSettings settings, final ObservableAdapter observableAdapter, final MongoDriverInformation mongoDriverInformation) { return create(com.mongodb.async.client.MongoClients.create(settings, getMongoDriverInformation(mongoDriverInformation)), observableAdapter); }
/** * Create a new client with the given client settings. * * @param settings the settings * @return the client */ public static MongoClient create(final MongoClientSettings settings) { return create(settings, null); }
/** * Creates a new client with the given client settings. * * <p>Note: Intended for driver and library authors to associate extra driver metadata with the connections.</p> * * @param settings the settings * @param mongoDriverInformation any driver information to associate with the MongoClient * @return the client * @since 1.3 */ public static MongoClient create(final MongoClientSettings settings, final MongoDriverInformation mongoDriverInformation) { return create(com.mongodb.async.client.MongoClients.create(settings, getMongoDriverInformation(mongoDriverInformation))); }
/** * Allow further configuration on the {@link MongoClientSettings}. * * @param configurer Configurer callback. * @return This module. */ public MongoRx doWith(final BiConsumer<MongoClientSettings.Builder, Config> configurer) { this.configurer = requireNonNull(configurer, "Configurer is required."); return this; }
/** * Allow further configuration on the {@link MongoClientSettings}. * * @param configurer Configurer callback. * @return This module. */ public MongoRx doWith(final Consumer<MongoClientSettings.Builder> configurer) { requireNonNull(configurer, "Configurer is required."); return doWith((s, c) -> configurer.accept(s)); }