List of usage examples for com.mongodb ServerAddress ServerAddress
public ServerAddress(@Nullable final String host, final int port)
From source file:edu.uniandes.ecos.codeaholics.config.DatabaseConfig.java
/** * Configuracion de la base de datos/*ww w . j ava 2 s.com*/ * @param pConfig ruta del archivo de configuracion */ public DatabaseConfig(String pConfig) { Properties prop = new Properties(); InputStream input = null; try { input = new FileInputStream(pConfig); // load a properties file prop.load(input); // get the property value and print it out dbEnv = prop.getProperty("mongo.env"); dbServerUrl = prop.getProperty("mongo.url"); dbPort = prop.getProperty("mongo.port"); dbName = prop.getProperty("mongo.db.name"); dbReplicaSetIPs = prop.getProperty("mongo.db.replicasetips").split(","); dbServerAdresses = new ArrayList<ServerAddress>(); for (String ips : dbReplicaSetIPs) { dbServerAdresses.add(new ServerAddress(ips, 27017)); } } catch (IOException ex) { ex.printStackTrace(); dbEnv = "local"; dbServerUrl = "localhost"; dbPort = "27017"; dbName = "factory"; } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java
License:EUPL
private MongoClient client() { mutex.lock();//from www . ja v a 2 s . com try { if (__client == null) { final MongoClientOptions options = MongoClientOptions.builder() .readPreference(ReadPreference.nearest()).writeConcern(WriteConcern.ACKNOWLEDGED).build(); final Splitter splitter = on(':').trimResults().omitEmptyStrings().limit(2); final List<ServerAddress> seeds = from(CONFIG_MANAGER.getDbHosts()) .transform(new Function<String, ServerAddress>() { @Override public ServerAddress apply(final String entry) { ServerAddress seed = null; try { final List<String> tokens = splitter.splitToList(entry); switch (tokens.size()) { case 1: seed = new ServerAddress(tokens.get(0), 27017); break; case 2: int port = parseInt(tokens.get(1)); seed = new ServerAddress(tokens.get(0), port); break; default: break; } } catch (Exception e) { LOGGER.error("Invalid host", e); } return seed; } }).filter(notNull()).toList(); // enable/disable authentication (requires MongoDB server to be configured to support authentication) final List<MongoCredential> credentials = newArrayList(); if (!CONFIG_MANAGER.isAnonymousDbAccess()) { credentials.add(createMongoCRCredential(CONFIG_MANAGER.getDbUsername(), CONFIG_MANAGER.getDbName(), CONFIG_MANAGER.getDbPassword().toCharArray())); } __client = new MongoClient(seeds, credentials, options); // check class attributes accessed by reflection try { final Field metadataField = BaseFile.class.getDeclaredField(METADATA_ATTR); checkNotNull(metadataField, "Metadata property (" + METADATA_ATTR + ") not found in file base: " + BaseFile.class.getCanonicalName()); final Class<?> metadataType = metadataField.getType(); checkState(Versionable.class.isAssignableFrom(metadataType), "Metadata does not implements versionable: " + metadataType.getCanonicalName()); checkNotNull(Versionable.class.getDeclaredField(IS_LATEST_VERSION_ATTR), "Version property (" + IS_LATEST_VERSION_ATTR + ") not found in versionable: " + Versionable.class.getCanonicalName()); checkNotNull(metadataType.getDeclaredField(OPEN_ACCESS_LINK_ATTR), "Open access link property (" + OPEN_ACCESS_LINK_ATTR + ") not found in metadata: " + metadataType.getCanonicalName()); checkNotNull(metadataType.getDeclaredField(OPEN_ACCESS_DATE_ATTR), "Open access date property (" + OPEN_ACCESS_DATE_ATTR + ") not found in metadata: " + metadataType.getCanonicalName()); } catch (Exception e) { throw new IllegalStateException( "Object versioning needs a compatible version of the LVL core library, but none is available", e); } } return __client; } finally { mutex.unlock(); } }
From source file:example.springdata.mongodb.util.MongosSystemForTestFactory.java
License:Apache License
private void initializeReplicaSet(Entry<String, List<IMongodConfig>> entry) throws Exception { String replicaName = entry.getKey(); List<IMongodConfig> mongoConfigList = entry.getValue(); if (mongoConfigList.size() < 3) { throw new Exception("A replica set must contain at least 3 members."); }//www . j av a 2s. c o m // Create 3 mongod processes for (IMongodConfig mongoConfig : mongoConfigList) { if (!mongoConfig.replication().getReplSetName().equals(replicaName)) { throw new Exception("Replica set name must match in mongo configuration"); } IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaultsWithLogger(Command.MongoD, logger) .processOutput(outputFunction.apply(Command.MongoD)).build(); MongodStarter starter = MongodStarter.getInstance(runtimeConfig); MongodExecutable mongodExe = starter.prepare(mongoConfig); MongodProcess process = mongodExe.start(); mongodProcessList.add(process); } Thread.sleep(1000); MongoClientOptions mo = MongoClientOptions.builder().connectTimeout(10).build(); MongoClient mongo = new MongoClient( new ServerAddress(mongoConfigList.get(0).net().getServerAddress().getHostName(), mongoConfigList.get(0).net().getPort()), mo); DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME); CommandResult cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1)); logger.info("isMaster: {}", cr); // Build BSON object replica set settings DBObject replicaSetSetting = new BasicDBObject(); replicaSetSetting.put("_id", replicaName); BasicDBList members = new BasicDBList(); int i = 0; for (IMongodConfig mongoConfig : mongoConfigList) { DBObject host = new BasicDBObject(); host.put("_id", i++); host.put("host", mongoConfig.net().getServerAddress().getHostName() + ":" + mongoConfig.net().getPort()); members.add(host); } replicaSetSetting.put("members", members); logger.info(replicaSetSetting.toString()); // Initialize replica set cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate", replicaSetSetting)); logger.info("replSetInitiate: {}", cr); Thread.sleep(5000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); logger.info("replSetGetStatus: {}", cr); // Check replica set status before to proceed while (!isReplicaSetStarted(cr)) { logger.info("Waiting for 3 seconds..."); Thread.sleep(1000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); logger.info("replSetGetStatus: {}", cr); } mongo.close(); mongo = null; }
From source file:example.springdata.mongodb.util.MongosSystemForTestFactory.java
License:Apache License
private void configureMongos() throws Exception { CommandResult cr;/*from w w w . jav a 2s . co m*/ MongoClientOptions options = MongoClientOptions.builder().connectTimeout(10).build(); try (MongoClient mongo = new MongoClient( new ServerAddress(this.config.net().getServerAddress().getHostName(), this.config.net().getPort()), options)) { DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME); // Add shard from the replica set list for (Entry<String, List<IMongodConfig>> entry : this.replicaSets.entrySet()) { String replicaName = entry.getKey(); String command = ""; for (IMongodConfig mongodConfig : entry.getValue()) { if (command.isEmpty()) { command = replicaName + "/"; } else { command += ","; } command += mongodConfig.net().getServerAddress().getHostName() + ":" + mongodConfig.net().getPort(); } logger.info("Execute add shard command: {}", command); cr = mongoAdminDB.command(new BasicDBObject("addShard", command)); logger.info(cr.toString()); } logger.info("Execute list shards."); cr = mongoAdminDB.command(new BasicDBObject("listShards", 1)); logger.info(cr.toString()); // Enabled sharding at database level logger.info("Enabled sharding at database level"); cr = mongoAdminDB.command(new BasicDBObject("enableSharding", this.shardDatabase)); logger.info(cr.toString()); // Create index in sharded collection logger.info("Create index in sharded collection"); DB db = mongo.getDB(this.shardDatabase); db.getCollection(this.shardCollection).createIndex(this.shardKey); // Shard the collection logger.info("Shard the collection: {}.{}", this.shardDatabase, this.shardCollection); DBObject cmd = new BasicDBObject(); cmd.put("shardCollection", this.shardDatabase + "." + this.shardCollection); cmd.put("key", new BasicDBObject(this.shardKey, 1)); cr = mongoAdminDB.command(cmd); logger.info(cr.toString()); logger.info("Get info from config/shards"); DBCursor cursor = mongo.getDB("config").getCollection("shards").find(); while (cursor.hasNext()) { DBObject item = cursor.next(); logger.info(item.toString()); } } }
From source file:example.springdata.mongodb.util.MongosSystemForTestFactory.java
License:Apache License
public Mongo getMongo() throws UnknownHostException, MongoException { return new MongoClient(new ServerAddress(mongosProcess.getConfig().net().getServerAddress(), mongosProcess.getConfig().net().getPort())); }
From source file:exifIndexer.MongoHandler.java
public DB connect() { MongoCredential credential = MongoCredential.createMongoCRCredential(user, bdname, password); MongoClient Client;//from w w w. j a va 2 s . c om try { Client = new MongoClient(new ServerAddress(host, port), Arrays.asList(credential)); } catch (UnknownHostException ex) { System.err.println("Error creating Mongo DB Client"); } try { Client = new MongoClient(host, port); DB db = Client.getDB(bdname); //Elimino la bd por si hubiera datos mongoClient = Client; //db = deletedb(bdname); // mongoClient.getDB(bdname).dropDatabase(); return db; } catch (UnknownHostException ex) { Logger.getLogger(MongoHandler.class.getName()).log(Level.SEVERE, null, ex); return null; } }
From source file:ezbake.data.mongo.EzMongoHandler.java
License:Apache License
private List<ServerAddress> parseMongoServerString(String mongoServers) { final List<ServerAddress> servers = new ArrayList<ServerAddress>(); for (final String server : mongoServers.split(",")) { final String[] tokens = server.split(":"); final String host = tokens[0]; int port = DEFAULT_MONGODB_PORT; try {// w w w . j a v a2 s. c o m if (tokens.length == 2) { port = Integer.parseInt(tokens[1]); } servers.add(new ServerAddress(host, port)); } catch (final NumberFormatException e) { appLog.error("Unable to parse port number from server string({})", server); } catch (final java.net.UnknownHostException e) { appLog.error("Unknown host exception when parsing server string({})", server); } } return servers; }
From source file:ezbakehelpers.mongoutils.MongoHelper.java
License:Apache License
public List<ServerAddress> getMongoServerAddress() throws UnknownHostException { List<ServerAddress> serverAddresses = Lists.newArrayList(); for (String hostname : mongoConfigurationHelper.getMongoDBHostNames()) { serverAddresses.add(new ServerAddress(hostname, mongoConfigurationHelper.getMongoDBPort())); }//from w w w .ja v a2 s . c o m return serverAddresses; }
From source file:flipkart.mongo.node.discovery.MongoConnector.java
License:Apache License
public static synchronized MongoClient getMongoClient(List<Node> mongoNodes) { int nodeHashCode = mongoNodes.hashCode(); if (MONGO_CONNECTION_POOL.containsKey(nodeHashCode)) { return MONGO_CONNECTION_POOL.get(nodeHashCode); }/* ww w. ja va 2 s .co m*/ List<ServerAddress> serverAddresses = Lists.newArrayList(); for (Node node : mongoNodes) { ServerAddress serverAddress = new ServerAddress(node.host, node.port); serverAddresses.add(serverAddress); } MongoConnectorConfigs connectorConfigs = MongoConnectorConfigs.getInstance(); MongoClient mongoClient = new MongoClient(serverAddresses, connectorConfigs.mongoCredentials); MONGO_CONNECTION_POOL.put(nodeHashCode, mongoClient); return mongoClient; }
From source file:foam.dao.MongoDAO.java
License:Open Source License
public MongoDAO(String host, int port, String dbName, String collectionName, String username, String password) { if (SafetyUtil.isEmpty(dbName) || SafetyUtil.isEmpty(collectionName)) { throw new IllegalArgumentException("Illegal arguments"); }/*w w w . j av a 2 s.c o m*/ host = (host != null) ? host : "localhost"; MongoClient mongoClient; if (isUserPassProvided(username, password)) { MongoCredential credential = MongoCredential.createCredential(username, dbName, password.toCharArray()); mongoClient = new MongoClient(new ServerAddress(host, port), Arrays.asList(credential)); } else { mongoClient = new MongoClient(host, port); } this.database = mongoClient.getDatabase(dbName); this.collectionName = collectionName; }