List of usage examples for com.mongodb ServerAddress ServerAddress
public ServerAddress(@Nullable final String host, final int port)
From source file:mongodb.tedc.Week1Homework4.java
License:Apache License
public static void main(String[] args) throws IOException { /* ------------------------------------------------------------------------ */ /* You should do this ONLY ONCE in the whole application life-cycle: */ /* Create and adjust the configuration singleton */ Configuration cfg = new Configuration(Configuration.VERSION_2_3_21); cfg.setDirectoryForTemplateLoading(new File("src/main/resources")); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER); MongoClient client = new MongoClient(new ServerAddress("localhost", 27017)); DB database = client.getDB("m101"); final DBCollection collection = database.getCollection("funnynumbers"); get("/", (req, res) -> { StringWriter writer = new StringWriter(); try {/* w w w .ja va 2 s . com*/ // Not necessary yet to understand this. It's just to prove that you // are able to run a command on a mongod server DBObject groupFields = new BasicDBObject("_id", "$value"); groupFields.put("count", new BasicDBObject("$sum", 1)); DBObject group = new BasicDBObject("$group", groupFields); DBObject match = new BasicDBObject("$match", new BasicDBObject("count", new BasicDBObject("$lte", 2))); DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1)); // run aggregation List<DBObject> pipeline = Arrays.asList(group, match, sort); AggregationOutput output = collection.aggregate(pipeline); int answer = 0; for (DBObject doc : output.results()) { answer += (Double) doc.get("_id"); } /* Create a data-model */ Map<String, String> answerMap = new HashMap<>(); answerMap.put("answer", Integer.toString(answer)); /* Get the template (uses cache internally) */ Template helloTemplate = cfg.getTemplate("answer.ftl"); /* Merge data-model with template */ helloTemplate.process(answerMap, writer); } catch (Exception e) { logger.error("Failed", e); halt(500); } return writer; }); }
From source file:mongodbutils.MongodbConnection.java
public boolean connect(String host, int portNo, String dbName, String username, String password, boolean authenticate) { try {//w w w. java 2 s . c o 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:mvm.rya.indexing.mongodb.MongoGeoIndexer.java
License:Apache License
private void init() throws NumberFormatException, IOException { boolean useMongoTest = conf.getBoolean(MongoDBRdfConfiguration.USE_TEST_MONGO, false); if (useMongoTest) { testsFactory = MongodForTestsFactory.with(Version.Main.PRODUCTION); mongoClient = testsFactory.newMongo(); int port = mongoClient.getServerAddressList().get(0).getPort(); conf.set(MongoDBRdfConfiguration.MONGO_INSTANCE_PORT, Integer.toString(port)); } else {//from w w w.ja v a2 s . c o m ServerAddress server = new ServerAddress(conf.get(MongoDBRdfConfiguration.MONGO_INSTANCE), Integer.valueOf(conf.get(MongoDBRdfConfiguration.MONGO_INSTANCE_PORT))); if (conf.get(MongoDBRdfConfiguration.MONGO_USER) != null) { MongoCredential cred = MongoCredential.createCredential( conf.get(MongoDBRdfConfiguration.MONGO_USER), conf.get(MongoDBRdfConfiguration.MONGO_DB_NAME), conf.get(MongoDBRdfConfiguration.MONGO_USER_PASSWORD).toCharArray()); mongoClient = new MongoClient(server, Arrays.asList(cred)); } else { mongoClient = new MongoClient(server); } } predicates = ConfigUtils.getGeoPredicates(conf); tableName = conf.get(MongoDBRdfConfiguration.MONGO_DB_NAME); db = mongoClient.getDB(tableName); coll = db.getCollection(conf.get(MongoDBRdfConfiguration.MONGO_COLLECTION_PREFIX, "rya")); storageStrategy = new GeoMongoDBStorageStrategy( Double.valueOf(conf.get(MongoDBRdfConfiguration.MONGO_GEO_MAXDISTANCE, "1e-10"))); }
From source file:mvm.rya.mongodb.MongoDBRyaDAO.java
License:Apache License
public void initConnection() throws RyaDAOException { try {/*from ww w . ja va 2s .c om*/ boolean useMongoTest = conf.getUseTestMongo(); if (useMongoTest) { testsFactory = MongodForTestsFactory.with(Version.Main.PRODUCTION); mongoClient = testsFactory.newMongo(); int port = mongoClient.getServerAddressList().get(0).getPort(); conf.set(MongoDBRdfConfiguration.MONGO_INSTANCE_PORT, Integer.toString(port)); } else { ServerAddress server = new ServerAddress(conf.get(MongoDBRdfConfiguration.MONGO_INSTANCE), Integer.valueOf(conf.get(MongoDBRdfConfiguration.MONGO_INSTANCE_PORT))); if (conf.get(MongoDBRdfConfiguration.MONGO_USER) != null) { MongoCredential cred = MongoCredential.createCredential( conf.get(MongoDBRdfConfiguration.MONGO_USER), conf.get(MongoDBRdfConfiguration.MONGO_DB_NAME), conf.get(MongoDBRdfConfiguration.MONGO_USER_PASSWORD).toCharArray()); mongoClient = new MongoClient(server, Arrays.asList(cred)); } else { mongoClient = new MongoClient(server); } } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:mx.iteso.msc.bda.banksimulator.dbaccess.DbClient.java
License:Apache License
public static MongoClient openConnection() { // Random r = new Random(); // if (r.nextInt(101) < DB_SUCCESS_RATE) { MongoCredential credential = MongoCredential.createCredential(USERNAME, DATABASE, PASSWORD.toCharArray()); MongoClient client = new MongoClient(new ServerAddress(SERVER, PORT), Arrays.asList(credential)); // try { // Thread.sleep(DB_DELAY); // } catch (InterruptedException ex) { // Logger.getLogger(DbClient.class.getName()).log(Level.SEVERE, null, ex); // } return client; // }//from w ww. ja va2s . co m // else { // System.out.println("Simulated database error"); // return null; // } }
From source file:net.cellcloud.storage.mongodb.MongoDBProperties.java
License:Open Source License
/** ??? *//*w w w.jav a2 s . co m*/ @SuppressWarnings("unchecked") public void addServerAddress(String host, int port) { List<ServerAddress> list = null; if (this.hasProperty(SERVER_ADDRESS)) { list = ((ListProperty<ServerAddress>) this.getProperty(SERVER_ADDRESS)).getValueAsList(); } else { list = new ArrayList<ServerAddress>(); ListProperty<ServerAddress> prop = new ListProperty<ServerAddress>(SERVER_ADDRESS, list); this.addProperty(prop); } try { list.add(new ServerAddress(host, port)); } catch (UnknownHostException e) { e.printStackTrace(); } }
From source file:net.es.netshell.mongodb.MongoDBProvider.java
License:Open Source License
public MongoDBProvider(String host, int port, String dbName, String mongoUser, String password) { this.serverAddress = new ServerAddress(host, port); ArrayList<MongoCredential> creds = new ArrayList<MongoCredential>(); MongoCredential enosCred = MongoCredential.createCredential(mongoUser, dbName, password.toCharArray()); creds.add(enosCred);//from ww w .j a va2 s.c om this.client = new MongoClient(this.serverAddress, creds); this.db = client.getDatabase(dbName); }
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 w w. java 2s . c o 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.tooan.ynpay.third.mongodb.BuguConnection.java
License:Apache License
private void doConnect() throws UnknownHostException, DBConnectionException { if (host != null && port != 0) { ServerAddress sa = new ServerAddress(host, port); if (options != null) { mc = new MongoClient(sa, options); } else {// ww w .ja v a2s.co m mc = new MongoClient(sa); } } else if (replicaSet != null) { if (options != null) { mc = new MongoClient(replicaSet, options); } else { mc = new MongoClient(replicaSet); } if (readPreference != null) { mc.setReadPreference(readPreference); } } if (mc != null) { if (!StringUtil.isEmpty(database)) { db = mc.getDB(database); } } else { throw new DBConnectionException( "Can not get database instance! Please ensure connected to mongoDB correctly."); } }
From source file:net.ymate.platform.persistence.mongodb.impl.MongoModuleCfg.java
License:Apache License
@SuppressWarnings("unchecked") protected MongoDataSourceCfgMeta __doParserDataSourceCfgMeta(String dsName, Map<String, String> _moduleCfgs) throws Exception { MongoDataSourceCfgMeta _meta = null; ////from w ww . ja v a 2s . c o m Map<String, String> _dataSourceCfgs = new HashMap<String, String>(); for (Map.Entry<String, String> _cfgEntry : _moduleCfgs.entrySet()) { String _key = _cfgEntry.getKey(); String _prefix = "ds." + dsName + "."; if (StringUtils.startsWith(_key, _prefix)) { String _cfgKey = StringUtils.substring(_key, _prefix.length()); _dataSourceCfgs.put(_cfgKey, _cfgEntry.getValue()); } } // if (!_dataSourceCfgs.isEmpty()) { String _connectionUrl = StringUtils.trimToNull(_dataSourceCfgs.get("connection_url")); if (_connectionUrl != null) { _meta = new MongoDataSourceCfgMeta(dsName, _dataSourceCfgs.get("collection_prefix"), _connectionUrl, _dataSourceCfgs.get("database_name")); } else { List<ServerAddress> _servers = new ArrayList<ServerAddress>(); String[] _serversArr = StringUtils.split(_dataSourceCfgs.get("servers"), "|"); if (_serversArr != null) { for (String _serverStr : _serversArr) { String[] _server = StringUtils.split(_serverStr, ":"); if (_server.length > 1) { _servers.add(new ServerAddress(_server[0], Integer.parseInt(_server[1]))); } else { _servers.add(new ServerAddress(_server[0])); } } } // boolean _isPwdEncrypted = new BlurObject(_dataSourceCfgs.get("password_encrypted")) .toBooleanValue(); Class<? extends IPasswordProcessor> _passwordClass = null; if (_isPwdEncrypted) { _passwordClass = (Class<? extends IPasswordProcessor>) ClassUtils .loadClass(_dataSourceCfgs.get("password_class"), this.getClass()); } _meta = new MongoDataSourceCfgMeta(dsName, _dataSourceCfgs.get("collection_prefix"), _servers, _dataSourceCfgs.get("username"), _dataSourceCfgs.get("password"), _dataSourceCfgs.get("database_name"), _isPwdEncrypted, _passwordClass); } } return _meta; }