List of usage examples for com.mongodb ServerAddress ServerAddress
public ServerAddress(@Nullable final String host, final int port)
From source file:org.apache.deltaspike.example.mongo.MongoProducer.java
License:Apache License
@PostConstruct public void start() { List<ServerAddress> serverAddressList = new ArrayList<>(); Arrays.stream(mongoConnectionInfo.split(";")).forEach(s -> { String[] hostAndPort = s.split(":"); String host = hostAndPort[0]; int port = Integer.parseInt(hostAndPort[1]); try {/* w w w . ja va2 s . c o m*/ serverAddressList.add(new ServerAddress(host, port)); } catch (UnknownHostException e) { e.printStackTrace(); } }); this.mongoClient = new MongoClient(serverAddressList); }
From source file:org.apache.felix.useradmin.mongodb.MongoDB.java
License:Apache License
/** * Parses the space separated list of server names. * /*from w w w . ja va 2 s . c o m*/ * @param serverNames the server names, cannot be <code>null</code>. * @return a list of {@link ServerAddress}es to connect to, never <code>null</code>. * @throws IllegalArgumentException in case the given server names was invalid. */ private static List<ServerAddress> parseServers(String serverNames) { String[] parts = serverNames.split("\\s+"); List<ServerAddress> servers = new ArrayList<ServerAddress>(); for (int i = 0; i < parts.length; i++) { String part = parts[i]; try { int colonPos = part.indexOf(":"); if (colonPos > 0 && (colonPos < part.length() - 1)) { String name = part.substring(0, colonPos); String portStr = part.substring(colonPos + 1); servers.add(new ServerAddress(name, Integer.valueOf(portStr))); } } catch (NumberFormatException e) { throw new IllegalArgumentException("Illegal port number in: " + part); } catch (UnknownHostException e) { throw new IllegalArgumentException("Unknown host: " + part); } } if (servers.isEmpty()) { throw new IllegalArgumentException("No (valid) servers defined!"); } return servers; }
From source file:org.apache.jackrabbit.oak.plugins.document.mongo.replica.NodeCollectionProvider.java
License:Apache License
private MongoClient prepareClientForHostname(String hostname) throws UnknownHostException { ServerAddress address;/*from ww w . j a va 2 s . c o m*/ if (hostname.contains(":")) { String[] hostSplit = hostname.split(":"); if (hostSplit.length != 2) { throw new IllegalArgumentException("Not a valid hostname: " + hostname); } address = new ServerAddress(hostSplit[0], Integer.parseInt(hostSplit[1])); } else { address = new ServerAddress(hostname); } MongoClientURI originalUri = new MongoClientURI(originalMongoUri); List<MongoCredential> credentialList = new ArrayList<MongoCredential>(1); if (originalUri.getCredentials() != null) { credentialList.add(originalUri.getCredentials()); } return new MongoClient(address, credentialList, originalUri.getOptions()); }
From source file:org.apache.jmeter.protocol.mongodb.mongo.MongoUtils.java
License:Apache License
public static List<ServerAddress> toServerAddresses(String connections) throws UnknownHostException { List<ServerAddress> addresses = new ArrayList<>(); for (String connection : Arrays.asList(connections.split(","))) { int port = DEFAULT_PORT; String[] hostPort = connection.split(":"); if (hostPort.length > 1 && !StringUtils.isEmpty(hostPort[1])) { port = Integer.parseInt(hostPort[1].trim()); }//from www . j a v a 2 s. c o m addresses.add(new ServerAddress(hostPort[0], port)); } return addresses; }
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.// w ww .j a va 2 s . c om * @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.kafka.connect.mongo.MongoRyaSinkTask.java
License:Apache License
@Override protected void checkRyaInstanceExists(final Map<String, String> taskConfig) throws IllegalStateException { requireNonNull(taskConfig);//from w w w.j a va 2 s. c om // Parse the configuration object. final MongoRyaSinkConfig config = new MongoRyaSinkConfig(taskConfig); @Nullable final String username = Strings.isNullOrEmpty(config.getUsername()) ? null : config.getUsername(); @Nullable final char[] password = Strings.isNullOrEmpty(config.getPassword()) ? null : config.getPassword().toCharArray(); // Connect a Mongo Client to the configured Mongo DB instance. final ServerAddress serverAddr = new ServerAddress(config.getHostname(), config.getPort()); final boolean hasCredentials = username != null && password != null; try (MongoClient mongoClient = hasCredentials ? new MongoClient(serverAddr, Arrays.asList( MongoCredential.createCredential(username, config.getRyaInstanceName(), password))) : new MongoClient(serverAddr)) { // Use a RyaClient to see if the configured instance exists. // Create the Mongo Connection Details that describe the Mongo DB Server we are interacting with. final MongoConnectionDetails connectionDetails = new MongoConnectionDetails(config.getHostname(), config.getPort(), Optional.ofNullable(username), Optional.ofNullable(password)); final RyaClient client = MongoRyaClientFactory.build(connectionDetails, mongoClient); if (!client.getInstanceExists().exists(config.getRyaInstanceName())) { throw new ConnectException("The Rya Instance named " + LogUtils.clean(config.getRyaInstanceName()) + " has not been installed."); } } catch (final RyaClientException e) { throw new ConnectException("Unable to determine if the Rya Instance named " + LogUtils.clean(config.getRyaInstanceName()) + " has been installed.", e); } }
From source file:org.apache.rya.mongodb.EmbeddedMongoFactory.java
License:Apache License
/** * Creates a new Mongo connection./*from ww w. j a va 2 s. c o m*/ * * @throws MongoException * @throws UnknownHostException */ public MongoClient newMongoClient() throws UnknownHostException, MongoException { return new MongoClient(new ServerAddress(mongodProcess.getConfig().net().getServerAddress(), mongodProcess.getConfig().net().getPort())); }
From source file:org.apache.rya.mongodb.MongoConnectorFactory.java
License:Apache License
/** * Create a MongoDB client object and assign it to this class's static mongoClient * @param conf configuration containing connection parameters * @throws ConfigurationRuntimeException - Thrown if the configured server, port, user, or others are missing. * @throws MongoException if can't connect despite conf parameters are given *///w w w. ja v a 2s.c o m private static void createMongoClientForServer(final Configuration conf) throws ConfigurationRuntimeException, MongoException { // Connect to a running Mongo server final String host = requireNonNull(conf.get(MongoDBRdfConfiguration.MONGO_INSTANCE), MSG_INTRO + "host name is required"); final int port = requireNonNullInt(conf.get(MongoDBRdfConfiguration.MONGO_INSTANCE_PORT), MSG_INTRO + "Port number is required."); final ServerAddress server = new ServerAddress(host, port); // check for authentication credentials if (conf.get(MongoDBRdfConfiguration.MONGO_USER) != null) { final String username = conf.get(MongoDBRdfConfiguration.MONGO_USER); final String dbName = requireNonNull(conf.get(MongoDBRdfConfiguration.MONGO_DB_NAME), MSG_INTRO + MongoDBRdfConfiguration.MONGO_DB_NAME + " is null but required configuration if " + MongoDBRdfConfiguration.MONGO_USER + " is configured."); final char[] pswd = requireNonNull(conf.get(MongoDBRdfConfiguration.MONGO_USER_PASSWORD), MSG_INTRO + MongoDBRdfConfiguration.MONGO_USER_PASSWORD + " is null but required configuration if " + MongoDBRdfConfiguration.MONGO_USER + " is configured.").toCharArray(); final MongoCredential cred = MongoCredential.createCredential(username, dbName, pswd); mongoClient = new MongoClient(server, Arrays.asList(cred)); } else { // No user was configured: mongoClient = new MongoClient(server); } }
From source file:org.araqne.logdb.mongo.MongoProfile.java
License:Apache License
public ServerAddress getAddress() throws UnknownHostException { return new ServerAddress(host, port); }
From source file:org.atlasapi.AtlasModule.java
License:Apache License
private List<ServerAddress> mongoHosts() { Splitter splitter = Splitter.on(",").omitEmptyStrings().trimResults(); return ImmutableList.copyOf(Iterables .filter(Iterables.transform(splitter.split(mongoHost), new Function<String, ServerAddress>() { @Override// w w w .j ava2 s .c o m public ServerAddress apply(String input) { try { return new ServerAddress(input, 27017); } catch (UnknownHostException e) { return null; } } }), Predicates.notNull())); }