List of usage examples for com.mongodb MongoClientOptions builder
public static Builder builder()
From source file:me.konglong.momei.mongodb.core.MongoClientFactory.java
License:Apache License
private MongoClient createInstance() throws Exception { if (mongoClientOptions == null) { mongoClientOptions = MongoClientOptions.builder().build(); }/*w ww . j av a 2 s . c o m*/ if (credentials == null) { credentials = Collections.emptyList(); } return createMongoClient(); }
From source file:mongodbutils.MongodbConnection.java
public boolean connect(String host, int portNo, String dbName, String username, String password, boolean authenticate) { try {//from w w w .j a va2s .co m //System.out.println("mongo start connect"); MongoClientOptions options = MongoClientOptions.builder().connectTimeout(30000) //.socketTimeout(30000) .autoConnectRetry(true).build(); mongoClient = new MongoClient(new ServerAddress(host, portNo), options); //String dbURI = "mongodb://"+host+":27017/?ssl=true"; //mongoClient = new MongoClient(new MongoClientURI(dbURI)); //System.out.println("mongo get db:"+dbName); db = mongoClient.getDB(dbName); if (null == db) { return false; } //System.out.println("mongo authenticate"); boolean auth = false; if (authenticate) { auth = db.authenticate(username, password.toCharArray()); } else { auth = true; } return auth; } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } }
From source file:mongofx.service.MongoService.java
License:Open Source License
public MongoDbConnection connect(ConnectionSettings connectionSettings) { StringBuilder authString = new StringBuilder(); String user = connectionSettings.getUser(); if (user != null && !user.isEmpty()) { authString.append(user);// w w w . j ava2 s . c o m String password = connectionSettings.getPassword(); if (password != null && !password.isEmpty()) { authString.append(":").append(password); } authString.append("@"); } String uri = String.format("mongodb://%s%s", authString, connectionSettings.getHost()); Builder options = MongoClientOptions.builder().serverSelectionTimeout(10000); MongoClient client = new MongoClient(new MongoClientURI(uri, options)); MongoConnection mongoConnection = new MongoConnection(client); return new MongoDbConnection(mongoConnection, connectionSettings); }
From source file:net.handle.server.MongoDBHandleStorage.java
License:Open Source License
/** * Initialize the MongoDB storage object with the given settings. *//* w ww. ja v a 2s .co m*/ public void init(StreamTable config) throws Exception { // load the MongoDB driver, if configured. Otherwise this will throw a class not found exception. if (config.containsKey(DRIVER_CLASS)) { Class.forName(String.valueOf(config.get(DRIVER_CLASS))); } // get the database URL and other connection parameters this.username = (String) config.get(LOGIN); this.passwd = (String) config.get(PASSWD); setDatabase((String) config.get(DATABASE_NAME)); this.databaseURL = (StreamVector) config.get(URL); StreamVector indices = (StreamVector) config.get(COLLECTION_INDICES); if (indices == null) { indices = new StreamVector(); indices.add("handle"); } this.indices = indices.subList(0, indices.size()); this.collection_nas = (String) config.get(COLLECTION_NAS); final String c_s = ((String) config.get(CASE_SENSITIVE, "no")).toLowerCase(); this.case_sensitive = (c_s.equalsIgnoreCase("yes")); this.readOnly = config.getBoolean(READ_ONLY, false); if (mongo == null) { final MongoClientOptions.Builder builder = new MongoClientOptions.Builder() .description("Handle System driver " + getClass()) .writeConcern(new WriteConcern(config.getInt(WRITECONCERN, 1))) .connectionsPerHost(config.getInt(CONNECTIONS_PER_HOST, 11)) .readPreference(ReadPreference.nearest()); this.mongo = new MongoDBSingleton((String[]) databaseURL.toArray(new String[databaseURL.size()]), builder.build()).getInstance(); if (username != null && passwd != null) { final boolean authenticate = authenticate(database, username, passwd.toCharArray()); if (!authenticate) { throw new HandleException(HandleException.UNABLE_TO_AUTHENTICATE, "Access denied."); } } } }
From source file:net.netzgut.integral.mongo.configuration.MongoConfigurationBuilder.java
License:Apache License
/** * Builds a {@link net.netzgut.integral.mongo.servics.MongoService} instance * based on the provided arguments / with senseful fallbacks *///from w ww . j a v a 2 s. co m public MongoConfiguration build() { return new MongoConfiguration() { @Override public ServerAddress getServerAddress() { return new ServerAddress(MongoConfigurationBuilder.this.host, MongoConfigurationBuilder.this.port); } @Override public String getDatabaseName() { return MongoConfigurationBuilder.this.databaseName; } @Override public List<MongoCredential> getCredentials() { return MongoConfigurationBuilder.this.credentials; } @Override public MongoClientOptions getClientOptions() { if (MongoConfigurationBuilder.this.options == null) { Builder builder = MongoClientOptions.builder(); if (MongoConfigurationBuilder.this.serverMonitorListeners.isEmpty() == false) { MongoConfigurationBuilder.this.serverMonitorListeners .forEach(builder::addServerMonitorListener); } if (MongoConfigurationBuilder.this.codecs.isEmpty() == false) { CodecRegistry customRegistry = CodecRegistries .fromCodecs(MongoConfigurationBuilder.this.codecs); CodecRegistry defaultRegistry = MongoClient.getDefaultCodecRegistry(); CodecRegistry combinedRegistry = CodecRegistries.fromRegistries(customRegistry, defaultRegistry); builder.codecRegistry(combinedRegistry); } options(builder.build()); } return MongoConfigurationBuilder.this.options; } }; }
From source file:net.ymate.platform.persistence.mongodb.IMongoClientOptionsHandler.java
License:Apache License
MongoClientOptions.Builder handler(String dataSourceName);
From source file:net.ymate.platform.persistence.mongodb.impl.MongoDataSourceAdapter.java
License:Apache License
public void initialize(IMongoClientOptionsHandler optionsHandler, MongoDataSourceCfgMeta cfgMeta) throws Exception { __cfgMeta = cfgMeta;/*from www .j a va 2 s .c om*/ MongoClientOptions.Builder _builder = null; if (optionsHandler != null) { _builder = optionsHandler.handler(cfgMeta.getName()); } if (_builder == null) { _builder = MongoClientOptions.builder(); } if (StringUtils.isNotBlank(cfgMeta.getConnectionUrl())) { __mongoClient = new MongoClient(new MongoClientURI(cfgMeta.getConnectionUrl(), _builder)); } else { String _username = StringUtils.trimToNull(cfgMeta.getUserName()); String _password = StringUtils.trimToNull(cfgMeta.getPassword()); if (_username != null && _password != null) { if (__cfgMeta.isPasswordEncrypted() && __cfgMeta.getPasswordClass() != null) { _password = __cfgMeta.getPasswordClass().newInstance().decrypt(_password); } MongoCredential _credential = MongoCredential.createCredential(cfgMeta.getUserName(), cfgMeta.getDatabaseName(), _password == null ? null : _password.toCharArray()); __mongoClient = new MongoClient(cfgMeta.getServers(), Collections.singletonList(_credential), _builder.build()); } else { __mongoClient = new MongoClient(cfgMeta.getServers(), _builder.build()); } } }
From source file:net.ymate.platform.persistence.mongodb.MongoDB.java
License:Apache License
/** * ?MongoDB?//from w w w .j ava 2s . co m * * @param config */ public static void initialize(IMongoConfig config) throws ConnectionException { if (!isInited) { __config = config; DATASOURCE_DEFAULT_NAME = StringUtils.defaultIfEmpty(config.getDefaultDataSourceName(), "default"); COLLECTION_PREFIX = StringUtils.trimToEmpty(config.getCollectionPrefix()); // try { for (DataSourceCfgMeta _cfgMeta : config.getDataSourceCfgMetas()) { List<ServerAddress> _addrs = new ArrayList<ServerAddress>(); String[] _hosts = StringUtils.split(_cfgMeta.getConnectionUrl(), "|"); if (_hosts == null || _hosts.length == 0) { _addrs.add(new ServerAddress(DEFAULT_MONGODB_HOST, DEFAULT_MONGODB_PORT)); } else { for (String _host : _hosts) { String[] _tmpAddr = StringUtils.split(_host, ":"); if (_tmpAddr.length == 1) { _addrs.add(new ServerAddress(_tmpAddr[0], DEFAULT_MONGODB_PORT)); } else { _addrs.add(new ServerAddress(_tmpAddr[0], Integer.valueOf(_tmpAddr[1]))); } } } // MongoClientOptions.Builder _builder = new MongoClientOptions.Builder(); // TODO ?Meta? _builder.connectionsPerHost(200); MongoClient _client = new MongoClient(_addrs, _builder.build()); // TODO ? // _client.setReadPreference(...); // __DATASOURCE_CACHE.put(_cfgMeta.getName(), _client); __DATASOURCE_CFG_METAS.put(_cfgMeta.getName(), _cfgMeta); } // __REPOSTORY_BEAN_FACTORY = new RepositoryBeanFactory(config.getRepositoryPackages()); isInited = true; } catch (Exception e) { throw new ConnectionException(RuntimeUtils.unwrapThrow(e)); } } }
From source file:nopaper.Server.java
License:Apache License
public static void main(String[] args) throws UnknownHostException { String databaseHostname = System.getProperty("database.hostname"); if (null == databaseHostname) databaseHostname = "localhost"; logger.info("Using {}", databaseHostname); Route.client = new MongoClient(new ServerAddress(databaseHostname), new MongoClientOptions.Builder().connectionsPerHost(2).build()); Spark.options(new Route("/*") { @Override//from w w w . jav a 2s .c o m public Object handle(final Request request, final Response response) { setCORSResponseHeader(response); response.status(200); return new StringWriter(); } @Override public Object myHandle(Request request, Response response, DBCollection collection) { return null; } }); Spark.get(new Route("/system/:command") { @Override public Object myHandle(final Request request, final Response response, DBCollection collection) { String command = request.params(":command"); System.out.println("system command:" + command); if (command.equals("shutdown")) { System.exit(0); } if (command.equals("ls")) { String path = request.queryParams("path"); if (null == path) { path = "/"; } return Files.list(path); } if (command.equals("sleep")) { String seconds = request.queryParams("seconds"); if (null == seconds) { seconds = "1"; } int i = Integer.parseInt(seconds); try { Thread.sleep(i * 1000); } catch (InterruptedException e) { e.printStackTrace(); } return System.currentTimeMillis(); } return null; } }); PDF pdf = new PDF(); pdf.setDatabase(Route.client.getDB("test")); pdf.addRoutes(); controller.DB db = new controller.DB(); db.addRoutes(); Spark.get(new Route("/") { @Override public Object myHandle(final Request request, final Response response, DBCollection collection) { try { return new BasicDBObject( dict("status", "ok", "hostname", InetAddress.getLocalHost().getHostName())); } catch (UnknownHostException e) { throw new RuntimeException(e); } } }); controller.Convert convert = new controller.Convert(); convert.setDatabase(Route.client.getDB("test")); convert.addRoutes(); controller.Map map = new controller.Map(); map.addRoutes(); }
From source file:org.apache.beam.sdk.io.mongodb.MongoDbIO.java
License:Apache License
private static MongoClientOptions.Builder getOptions(int maxConnectionIdleTime, boolean sslEnabled, boolean sslInvalidHostNameAllowed) { MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder(); optionsBuilder.maxConnectionIdleTime(maxConnectionIdleTime); if (sslEnabled) { optionsBuilder.sslEnabled(sslEnabled).sslInvalidHostNameAllowed(sslInvalidHostNameAllowed) .sslContext(SSLUtils.ignoreSSLCertificate()); }//from ww w. j a va2 s .c o m return optionsBuilder; }