List of usage examples for com.mongodb ServerAddress getPort
public int getPort()
From source file:me.konglong.momei.mongodb.core.MongoClientFactory.java
License:Apache License
private ServerAddress createConfiguredOrDefaultServerAddress() throws UnknownHostException { ServerAddress defaultAddress = new ServerAddress(); return new ServerAddress(StringUtils.hasText(host) ? host : defaultAddress.getHost(), port != null ? port.intValue() : defaultAddress.getPort()); }
From source file:org.alfresco.mongo.MongoDBForTestsFactory.java
License:Open Source License
/** * Utility method to build a MongoDB URI that references the {@link #getObject() DB} provided by this factory * //from www . j a va2s .c o m * @return a MongoDB URI that can be used to connect to the DB instance */ public String getMongoURI() { String dbName = db.getName(); ServerAddress mongoAddress = db.getMongo().getAddress(); String mongoUri = MONGO_PREFIX + mongoAddress.getHost() + ":" + mongoAddress.getPort() + "/" + dbName; return mongoUri; }
From source file:org.alfresco.mongo.MongoDBForTestsFactory.java
License:Open Source License
/** * Utility method to build a MongoDB URI that can be used to construct a {@link MongoClient mongo client}. * /*from w ww . j a va 2 s . c o m*/ * @return a MongoDB URI that can be used to connect to mongo */ public String getMongoURIWithoutDB() { ServerAddress mongoAddress = db.getMongo().getAddress(); String mongoUri = MONGO_PREFIX + mongoAddress.getHost() + ":" + mongoAddress.getPort(); return mongoUri; }
From source file:org.anyframe.logmanager.bundle.core.Activator.java
License:Apache License
/** * @param context//ww w. ja v a2 s . c om * @throws Exception */ private void initMongo(BundleContext context) throws Exception { if (context == null) { throw new LogManagerBundleException("Context is null."); } String mongoSvr = context.getProperty("mongo.host"); int mongoPort = Integer.parseInt(context.getProperty("mongo.port")); logger.info("MongoDB connect to - " + mongoSvr + ":" + mongoPort); MongoOptions options = new MongoOptions(); options.connectionsPerHost = Integer.parseInt(context.getProperty("mongo.connectionsPerHost")); options.autoConnectRetry = Boolean.parseBoolean(context.getProperty("mongo.autoConnectRetry")); options.connectTimeout = Integer.parseInt(context.getProperty("mongo.connectTimeout")); options.threadsAllowedToBlockForConnectionMultiplier = Integer .parseInt(context.getProperty("mongo.threadsAllowedToBlockForConnectionMultiplier")); options.maxWaitTime = Integer.parseInt(context.getProperty("mongo.maxWaitTime")); options.connectTimeout = Integer.parseInt(context.getProperty("mongo.connectTimeout")); options.socketKeepAlive = Boolean.parseBoolean(context.getProperty("mongo.socketKeepAlive")); options.socketTimeout = Integer.parseInt(context.getProperty("mongo.socketTimeout")); ServerAddress addr = new ServerAddress(mongoSvr, mongoPort); mongo = new Mongo(addr, options); if (mongo != null) { logger.info("MongoDB connected - " + addr.getHost() + ":" + addr.getPort()); } }
From source file:org.apache.hadoop.contrib.mongoreduce.MongoInputFormat.java
License:Apache License
public static String[] hostsForShard(String shardName, boolean primaryOk) throws UnknownHostException, MongoException { ArrayList<String> hosts = new ArrayList<String>(); String[] parts = shardName.split("/"); if (parts.length == 1) { // no replicas hosts.add(shardName);//from w w w .j a v a 2s .c o m } else { // replicas // get first or only host listed String host = parts[1].split(",")[0]; Mongo h = new Mongo(host); List<ServerAddress> addresses = h.getServerAddressList(); h.close(); h = null; // only one node in replica set ... - use it if (addresses.size() == 1) { ServerAddress addr = addresses.get(0); hosts.add(addr.getHost() + ":" + Integer.toString(addr.getPort())); } else { for (ServerAddress addr : addresses) { // use secondaries and primaries if (primaryOk) { hosts.add(addr.getHost() + ":" + Integer.toString(addr.getPort())); } // only use secondaries else { String haddr = addr.getHost() + ":" + Integer.toString(addr.getPort()); h = new Mongo(haddr); if (!(Boolean) h.getDB(h.getDatabaseNames().get(0)).command(cmd).get("ismaster")) { hosts.add(haddr); } } } } } return hosts.toArray(new String[0]); }
From source file:org.apache.logging.log4j.nosql.appender.mongodb.MongoDbProvider.java
License:Apache License
/** * Factory method for creating a MongoDB provider within the plugin manager. * * @param collectionName The name of the MongoDB collection to which log events should be written. * @param writeConcernConstant The {@link WriteConcern} constant to control writing details, defaults to * {@link WriteConcern#ACKNOWLEDGED}. * @param writeConcernConstantClassName The name of a class containing the aforementioned static WriteConcern * constant. Defaults to {@link WriteConcern}. * @param databaseName The name of the MongoDB database containing the collection to which log events should be * written. Mutually exclusive with {@code factoryClassName&factoryMethodName!=null}. * @param server The host name of the MongoDB server, defaults to localhost and mutually exclusive with * {@code factoryClassName&factoryMethodName!=null}. * @param port The port the MongoDB server is listening on, defaults to the default MongoDB port and mutually * exclusive with {@code factoryClassName&factoryMethodName!=null}. * @param userName The username to authenticate against the MongoDB server with. * @param password The password to authenticate against the MongoDB server with. * @param factoryClassName A fully qualified class name containing a static factory method capable of returning a * {@link DB} or a {@link MongoClient}. * @param factoryMethodName The name of the public static factory method belonging to the aforementioned factory * class./*from ww w . j a v a 2 s. c o m*/ * @return a new MongoDB provider. */ @PluginFactory public static MongoDbProvider createNoSqlProvider( @PluginAttribute("collectionName") final String collectionName, @PluginAttribute("writeConcernConstant") final String writeConcernConstant, @PluginAttribute("writeConcernConstantClass") final String writeConcernConstantClassName, @PluginAttribute("databaseName") final String databaseName, @PluginAttribute("server") final String server, @PluginAttribute("port") final String port, @PluginAttribute("userName") final String userName, @PluginAttribute(value = "password", sensitive = true) final String password, @PluginAttribute("factoryClassName") final String factoryClassName, @PluginAttribute("factoryMethodName") final String factoryMethodName) { DB database; String description; if (Strings.isNotEmpty(factoryClassName) && Strings.isNotEmpty(factoryMethodName)) { try { final Class<?> factoryClass = Loader.loadClass(factoryClassName); final Method method = factoryClass.getMethod(factoryMethodName); final Object object = method.invoke(null); if (object instanceof DB) { database = (DB) object; } else if (object instanceof MongoClient) { if (Strings.isNotEmpty(databaseName)) { database = ((MongoClient) object).getDB(databaseName); } else { LOGGER.error("The factory method [{}.{}()] returned a MongoClient so the database name is " + "required.", factoryClassName, factoryMethodName); return null; } } else if (object == null) { LOGGER.error("The factory method [{}.{}()] returned null.", factoryClassName, factoryMethodName); return null; } else { LOGGER.error("The factory method [{}.{}()] returned an unsupported type [{}].", factoryClassName, factoryMethodName, object.getClass().getName()); return null; } description = "database=" + database.getName(); final List<ServerAddress> addresses = database.getMongo().getAllAddress(); if (addresses.size() == 1) { description += ", server=" + addresses.get(0).getHost() + ", port=" + addresses.get(0).getPort(); } else { description += ", servers=["; for (final ServerAddress address : addresses) { description += " { " + address.getHost() + ", " + address.getPort() + " } "; } description += "]"; } } catch (final ClassNotFoundException e) { LOGGER.error("The factory class [{}] could not be loaded.", factoryClassName, e); return null; } catch (final NoSuchMethodException e) { LOGGER.error("The factory class [{}] does not have a no-arg method named [{}].", factoryClassName, factoryMethodName, e); return null; } catch (final Exception e) { LOGGER.error("The factory method [{}.{}()] could not be invoked.", factoryClassName, factoryMethodName, e); return null; } } else if (Strings.isNotEmpty(databaseName)) { List<MongoCredential> credentials = new ArrayList<>(); description = "database=" + databaseName; if (Strings.isNotEmpty(userName) && Strings.isNotEmpty(password)) { description += ", username=" + userName + ", passwordHash=" + NameUtil.md5(password + MongoDbProvider.class.getName()); credentials.add(MongoCredential.createCredential(userName, databaseName, password.toCharArray())); } try { if (Strings.isNotEmpty(server)) { final int portInt = AbstractAppender.parseInt(port, 0); description += ", server=" + server; if (portInt > 0) { description += ", port=" + portInt; database = new MongoClient(new ServerAddress(server, portInt), credentials) .getDB(databaseName); } else { database = new MongoClient(new ServerAddress(server), credentials).getDB(databaseName); } } else { database = new MongoClient(new ServerAddress(), credentials).getDB(databaseName); } } catch (final Exception e) { LOGGER.error("Failed to obtain a database instance from the MongoClient at server [{}] and " + "port [{}].", server, port); return null; } } else { LOGGER.error("No factory method was provided so the database name is required."); return null; } try { database.getCollectionNames(); // Check if the database actually requires authentication } catch (final Exception e) { LOGGER.error( "The database is not up, or you are not authenticated, try supplying a username and password to the MongoDB provider.", e); return null; } WriteConcern writeConcern = toWriteConcern(writeConcernConstant, writeConcernConstantClassName); return new MongoDbProvider(database, writeConcern, collectionName, description); }
From source file:org.apache.rya.indexing.geoExamples.RyaMongoGeoDirectExample.java
License:Apache License
private static Configuration getConf() throws IOException { MongoDBIndexingConfigBuilder builder = MongoIndexingConfiguration.builder().setUseMockMongo(USE_MOCK) .setUseInference(USE_INFER).setAuths("U"); if (USE_MOCK) { mock = EmbeddedMongoFactory.newFactory(); MongoClient c = mock.newMongoClient(); ServerAddress address = c.getAddress(); String url = address.getHost(); String port = Integer.toString(address.getPort()); c.close();// ww w .j ava 2s .c o m builder.setMongoHost(url).setMongoPort(port); } else { // User name and password must be filled in: builder = builder.setMongoUser("fill this in").setMongoPassword("fill this in") .setMongoHost(MONGO_INSTANCE_URL).setMongoPort(MONGO_INSTANCE_PORT); } return builder.setMongoDBName(MONGO_DB).setMongoCollectionPrefix(MONGO_COLL_PREFIX) .setUseMongoFreetextIndex(true).setMongoFreeTextPredicates(RDFS.LABEL.stringValue()).build(); }
From source file:org.apache.rya.indexing.mongodb.AbstractMongoIndexer.java
License:Apache License
@VisibleForTesting public void initIndexer(final Configuration conf, final MongoClient client) { setClient(client);/*w w w . j a v a 2 s . co m*/ final ServerAddress address = client.getAddress(); conf.set(MongoDBRdfConfiguration.MONGO_INSTANCE, address.getHost()); conf.set(MongoDBRdfConfiguration.MONGO_INSTANCE_PORT, Integer.toString(address.getPort())); setConf(conf); if (!isInit) { init(); isInit = true; } }
From source file:org.cloudfoundry.java.test.core.MongoDbUtils.java
License:Apache License
private String getServerString(DB mongoDb, ServerAddress serverAddress) { String host = serverAddress.getHost(); int port = serverAddress.getPort(); String name = mongoDb.getName(); return String.format("mongodb://%s:%d/%s", host, port, name); }
From source file:org.elasticsearch.river.mongodb.MongoDBRiver.java
License:Apache License
/** * Execute actions to (re-)start the river on this node. *//*from w w w . j a v a 2s . c om*/ void internalStartRiver() { if (startupThread != null) { // Already processing a request to start up the river, so ignore this call. return; } // Update the status: we're busy starting now. context.setStatus(Status.STARTING); // ES only starts one River at a time, so we start the river using a new thread so that // we don't block the startup of other rivers Runnable startupRunnable = new Runnable() { @Override public void run() { // Log some info about what we're about to do now. logger.info("Starting river {}", riverName.getName()); logger.info( "MongoDB options: secondaryreadpreference [{}], drop_collection [{}], include_collection [{}], throttlesize [{}], gridfs [{}], filter [{}], db [{}], collection [{}], script [{}], indexing to [{}]/[{}]", definition.isMongoSecondaryReadPreference(), definition.isDropCollection(), definition.getIncludeCollection(), definition.getThrottleSize(), definition.isMongoGridFS(), definition.getMongoOplogFilter(), definition.getMongoDb(), definition.getMongoCollection(), definition.getScript(), definition.getIndexName(), definition.getTypeName()); for (ServerAddress server : definition.getMongoServers()) { logger.debug("Using MongoDB server(s): host [{}], port [{}]", server.getHost(), server.getPort()); } try { // Create the index if it does not exist try { if (!esClient.admin().indices().prepareExists(definition.getIndexName()).get().isExists()) { esClient.admin().indices().prepareCreate(definition.getIndexName()).get(); } } catch (Exception e) { if (ExceptionsHelper.unwrapCause(e) instanceof IndexAlreadyExistsException) { // that's fine } else if (ExceptionsHelper.unwrapCause(e) instanceof ClusterBlockException) { // ok, not recovered yet..., lets start indexing and hope we // recover by the first bulk // TODO: a smarter logic can be to register for cluster // event // listener here, and only start sampling when the // block is removed... } else { logger.error("failed to create index [{}], disabling river...", e, definition.getIndexName()); return; } } // GridFS if (definition.isMongoGridFS()) { try { if (logger.isDebugEnabled()) { logger.debug("Set explicit attachment mapping."); } esClient.admin().indices().preparePutMapping(definition.getIndexName()) .setType(definition.getTypeName()).setSource(getGridFSMapping()).get(); } catch (Exception e) { logger.warn("Failed to set explicit mapping (attachment): {}", e); } } // Replicate data roughly the same way MongoDB does // https://groups.google.com/d/msg/mongodb-user/sOKlhD_E2ns/SvngoUHXtcAJ // // Steps: // Get oplog timestamp // Do the initial import // Sync from the oplog of each shard starting at timestamp // // Notes // Primary difference between river sync and MongoDB replica sync is that we ignore chunk migrations // We only need to know about CRUD commands. If data moves from one MongoDB shard to another // then we do not need to let ElasticSearch know that. MongoClient mongoClusterClient = mongoClientService.getMongoClusterClient(definition); MongoConfigProvider configProvider = new MongoConfigProvider(mongoClientService, definition); MongoConfig config; while (true) { try { config = configProvider.call(); break; } catch (MongoSocketException | MongoTimeoutException e) { Thread.sleep(MONGODB_RETRY_ERROR_DELAY_MS); } } Timestamp startTimestamp = null; if (definition.getInitialTimestamp() != null) { startTimestamp = definition.getInitialTimestamp(); } else if (getLastProcessedTimestamp() != null) { startTimestamp = getLastProcessedTimestamp(); } else { for (Shard shard : config.getShards()) { if (startTimestamp == null || shard.getLatestOplogTimestamp().compareTo(startTimestamp) < 1) { startTimestamp = shard.getLatestOplogTimestamp(); } } } // All good, mark the context as "running" now: this // status value is used as termination condition for the threads we're going to start now. context.setStatus(Status.RUNNING); indexerThread = EsExecutors .daemonThreadFactory(settings.globalSettings(), "mongodb_river_indexer:" + definition.getIndexName()) .newThread( new Indexer(MongoDBRiver.this, definition, context, esClient, scriptService)); indexerThread.start(); // Import in main thread to block tailing the oplog Timestamp slurperStartTimestamp = getLastProcessedTimestamp(); if (slurperStartTimestamp != null) { logger.trace("Initial import already completed."); // Start from where we last left of } else if (definition.isSkipInitialImport() || definition.getInitialTimestamp() != null) { logger.info("Skip initial import from collection {}", definition.getMongoCollection()); // Start from the point requested slurperStartTimestamp = definition.getInitialTimestamp(); } else { // Determine the timestamp to be used for all documents loaded as "initial import". Timestamp initialImportTimestamp = null; for (Shard shard : config.getShards()) { if (initialImportTimestamp == null || shard.getLatestOplogTimestamp().compareTo(initialImportTimestamp) < 1) { initialImportTimestamp = shard.getLatestOplogTimestamp(); } } CollectionSlurper importer = new CollectionSlurper(mongoClusterClient, definition, context, esClient); importer.importInitial(initialImportTimestamp); // Start slurping from the shard's oplog time slurperStartTimestamp = null; } // Tail the oplog // NB: In a non-mongos environment the config will report a single shard, with the servers used for the connection as the replicas. for (Shard shard : config.getShards()) { Timestamp shardSlurperStartTimestamp = slurperStartTimestamp != null ? slurperStartTimestamp : shard.getLatestOplogTimestamp(); MongoClient mongoClient = mongoClientService.getMongoShardClient(definition, shard.getReplicas()); Thread tailerThread = EsExecutors .daemonThreadFactory(settings.globalSettings(), "mongodb_river_slurper_" + shard.getName() + ":" + definition.getIndexName()) .newThread(new OplogSlurper(shardSlurperStartTimestamp, mongoClusterClient, mongoClient, definition, context, esClient)); tailerThreads.add(tailerThread); } for (Thread thread : tailerThreads) { thread.start(); } logger.info("Started river {}", riverName.getName()); } catch (Throwable t) { logger.warn("Failed to start river {}", t, riverName.getName()); MongoDBRiverHelper.setRiverStatus(esClient, definition.getRiverName(), Status.START_FAILED); context.setStatus(Status.START_FAILED); } finally { // Startup is fully done startupThread = null; } } }; startupThread = EsExecutors.daemonThreadFactory(settings.globalSettings(), "mongodb_river_startup:" + definition.getIndexName()).newThread(startupRunnable); startupThread.start(); }