List of usage examples for com.mongodb ServerAddress ServerAddress
public ServerAddress(@Nullable final String host, final int port)
From source file:com.github.krr.mongodb.aggregate.support.config.MongoClientTestConfiguration.java
License:Apache License
private MongoClient getMongoClient() throws IOException { return new MongoClient(new ServerAddress(mongodProcess.getConfig().net().getServerAddress(), mongodProcess.getConfig().net().getPort())); }
From source file:com.github.krr.mongodb.aggregate.support.config.NonReactiveMongoClientTestConfiguration.java
License:Apache License
private ServerAddress getServerAddress() throws UnknownHostException { return new ServerAddress(mongodProcess.getConfig().net().getServerAddress(), mongodProcess.getConfig().net().getPort()); }
From source file:com.github.maasdi.mongo.wrapper.NoAuthMongoClientWrapper.java
License:Apache License
private MongoClient initConnection(MongoDbMeta meta, VariableSpace vars, LogChannelInterface log) throws KettleException { String hostsPorts = vars.environmentSubstitute(meta.getHostnames()); String singlePort = vars.environmentSubstitute(meta.getPort()); String connTimeout = meta.getConnectTimeout(); String socketTimeout = meta.getSocketTimeout(); String readPreference = meta.getReadPreference(); String writeConcern = meta.getWriteConcern(); String wTimeout = meta.getWTimeout(); boolean journaled = meta.getJournal(); List<String> tagSet = meta.getReadPrefTagSets(); boolean useAllReplicaSetMembers = meta.getUseAllReplicaSetMembers(); int singlePortI = -1; try {/*from w ww. ja v a 2s .com*/ singlePortI = Integer.parseInt(singlePort); } catch (NumberFormatException n) { // don't complain } if (Const.isEmpty(hostsPorts)) { throw new KettleException( BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.Error.EmptyHostsString")); //$NON-NLS-1$ } List<ServerAddress> repSet = new ArrayList<ServerAddress>(); // if (useAllReplicaSetMembers) { // repSet = getReplicaSetMembers(hostsPorts, singlePort, cred, vars, log); // // if (repSet.size() == 0) { // useAllReplicaSetMembers = false; // drop back and just configure using // // what we've been given // } else { // if (log != null) { // StringBuilder builder = new StringBuilder(); // for (ServerAddress s : repSet) { // builder.append(s.toString()).append(" "); // } // log.logBasic(BaseMessages.getString(PKG, // "MongoUtils.Message.UsingTheFollowingReplicaSetMembers") // + " " // + builder.toString()); // } // } // } // if (!useAllReplicaSetMembers) { String[] parts = hostsPorts.trim().split(","); //$NON-NLS-1$ for (String part : parts) { // host:port? int port = singlePortI != -1 ? singlePortI : MONGO_DEFAULT_PORT; String[] hp = part.split(":"); //$NON-NLS-1$ if (hp.length > 2) { throw new KettleException( BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.Error.MalformedHost", part)); //$NON-NLS-1$ } String host = hp[0]; if (hp.length == 2) { // non-default port try { port = Integer.parseInt(hp[1].trim()); } catch (NumberFormatException n) { throw new KettleException(BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.Error.UnableToParsePortNumber", hp[1])); //$NON-NLS-1$ } } try { ServerAddress s = new ServerAddress(host, port); repSet.add(s); } catch (UnknownHostException u) { throw new KettleException(u); } } // } MongoClientOptions.Builder mongoOptsBuilder = new MongoClientOptions.Builder(); configureConnectionOptions(mongoOptsBuilder, connTimeout, socketTimeout, readPreference, writeConcern, wTimeout, journaled, tagSet, vars, log); MongoClientOptions opts = mongoOptsBuilder.build(); return getClient(meta, vars, log, repSet, useAllReplicaSetMembers, opts); }
From source file:com.github.niltz.maven.plugins.mongodb.AbstractMongoDBMojo.java
License:Open Source License
/** * Opens a connection using the given settings. * //from www. ja va 2 s . co m * @param dbSettings * the connection settings * @return the Connection * @throws MojoFailureException * on error * @throws UnknownHostException */ protected Mongo openConnection(ConnectionSettings connectionSettings) throws MojoFailureException, UnknownHostException { // get server address ServerAddress serverAddr = (connectionSettings.getPort() != null) ? new ServerAddress(connectionSettings.getHostname(), connectionSettings.getPort().intValue()) : new ServerAddress(connectionSettings.getHostname()); // get Mongo Mongo mongo = (connectionSettings.getOptions() != null) ? new Mongo(serverAddr, connectionSettings.getOptions()) : new Mongo(serverAddr); // we're good :) return mongo; }
From source file:com.github.nlloyd.hornofmongo.adaptor.Mongo.java
License:Open Source License
@SuppressWarnings("unchecked") @JSConstructor//from w ww . j a va2s . co m public Mongo(final Object host) throws UnknownHostException { super(); if (host instanceof Undefined) this.hosts = Collections.singletonList(new ServerAddress("localhost", ServerAddress.defaultPort())); else if (host instanceof com.mongodb.Mongo) { this.innerMongo = (com.mongodb.Mongo) host; this.hosts = this.innerMongo.getAllAddress(); this.mongoOptions = this.innerMongo.getMongoOptions(); // now get the query options, not same as MongoOptions this.options = this.innerMongo.getOptions(); } else if (host instanceof List<?>) // TODO check if we get a list of ServerAddresses or something else this.hosts = (List<ServerAddress>) host; else { String hostsString = Context.toString(host); if (hostsString.startsWith(MONGO_CLIENT_URI_PREFIX)) hostsString = hostsString.substring(MONGO_CLIENT_URI_PREFIX.length()); String[] hostStrings = hostsString.split(","); this.hosts = new ArrayList<ServerAddress>(hostStrings.length); for (String hostString : hostStrings) { if (hostString.indexOf(':') > -1) { String[] hostBits = hostString.split(":"); this.hosts.add(new ServerAddress(hostBits[0], Integer.valueOf(hostBits[1]))); } else this.hosts.add(new ServerAddress(hostString, ServerAddress.defaultPort())); } } StringBuilder hostStringBuilder = new StringBuilder(); if (!(host instanceof Undefined)) { for (ServerAddress serverAddress : this.hosts) { if (hostStringBuilder.length() > 0) hostStringBuilder.append(","); hostStringBuilder.append(serverAddress.getHost()).append(":").append(serverAddress.getPort()); } } else hostStringBuilder.append("127.0.0.1"); put("host", this, hostStringBuilder.toString()); }
From source file:com.github.stephenc.mongodb.maven.StartMongoMojo.java
License:Apache License
public void execute() throws MojoExecutionException, MojoFailureException { if (skip) {//from w w w . j a v a2 s . com getLog().info("Skipping mongodb: mongodb.skip==true"); return; } if (installation == null) { getLog().info("Using mongod from PATH"); } else { getLog().info("Using mongod installed in " + installation); } getLog().info("Using database root of " + databaseRoot); final Logger mongoLogger = Logger.getLogger("com.mongodb"); Level mongoLevel = mongoLogger.getLevel(); try { mongoLogger.setLevel(Level.SEVERE); MongoOptions opts = new MongoOptions(); opts.autoConnectRetry = false; opts.connectionsPerHost = 1; opts.connectTimeout = 50; opts.socketTimeout = 50; Mongo instance; try { instance = new Mongo(new ServerAddress("localhost", port), opts); List<String> databaseNames = instance.getDatabaseNames(); throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance with the following databases " + databaseNames); } catch (MongoException.Network e) { // fine... no instance running } catch (MongoException e) { throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance"); } catch (UnknownHostException e) { // ignore... localhost is always known! } } finally { mongoLogger.setLevel(mongoLevel); } CommandLine commandLine = null; if (installation != null && installation.isDirectory()) { File bin = new File(installation, "bin"); File exe = new File(bin, Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod"); if (exe.isFile()) { commandLine = new CommandLine(exe); } else { throw new MojoExecutionException("Could not find mongo executables in specified installation: " + installation + " expected to find " + exe + " but it does not exist."); } } if (commandLine == null) { commandLine = new CommandLine(Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod"); } if (databaseRoot.isFile()) { throw new MojoExecutionException("Database root " + databaseRoot + " is a file and not a directory"); } if (databaseRoot.isDirectory() && cleanDatabaseRoot) { getLog().info("Cleaning database root directory: " + databaseRoot); try { FileUtils.deleteDirectory(databaseRoot); } catch (IOException e) { throw new MojoExecutionException("Could not clean database root directory " + databaseRoot, e); } } if (!databaseRoot.isDirectory()) { getLog().debug("Creating database root directory: " + databaseRoot); if (!databaseRoot.mkdirs()) { throw new MojoExecutionException("Could not create database root directory " + databaseRoot); } } if (!verbose) { commandLine.addArgument("--quiet"); } commandLine.addArgument("--logpath"); commandLine.addArgument(logPath.getAbsolutePath()); if (logAppend) { commandLine.addArgument("--logappend"); } commandLine.addArgument(auth ? "--auth" : "--noauth"); commandLine.addArgument("--port"); try { // this is a hack to force mongo to use a project property // that we are randomly setting at run-time (reserve-network-port) port = Integer.parseInt(project.getProperties().getProperty("mongodb.port")); } catch (NumberFormatException e) { // no or bad project property } commandLine.addArgument(Integer.toString(port)); commandLine.addArgument("--dbpath"); commandLine.addArgument(databaseRoot.getAbsolutePath()); if (additionalArguments != null) { for (String aa : additionalArguments) { commandLine.addArgument(aa); } } Executor exec = new DefaultExecutor(); DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler(); exec.setWorkingDirectory(databaseRoot); ProcessObserver processObserver = new ProcessObserver(new ShutdownHookProcessDestroyer()); exec.setProcessDestroyer(processObserver); LogOutputStream stdout = new MavenLogOutputStream(getLog()); LogOutputStream stderr = new MavenLogOutputStream(getLog()); getLog().info("Executing command line: " + commandLine); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr)); try { exec.execute(commandLine, execHandler); getLog().info("Waiting for MongoDB to start..."); long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(120); mongoLevel = mongoLogger.getLevel(); try { mongoLogger.setLevel(Level.SEVERE); while (System.currentTimeMillis() < timeout && !execHandler.hasResult()) { MongoOptions opts = new MongoOptions(); opts.autoConnectRetry = false; opts.connectionsPerHost = 1; opts.connectTimeout = 250; opts.socketTimeout = 250; Mongo instance; try { instance = new Mongo(new ServerAddress("localhost", port), opts); List<String> databaseNames = instance.getDatabaseNames(); getLog().info("MongoDb started."); getLog().info("Databases: " + databaseNames); } catch (MongoException.Network e) { // ignore, wait and try again try { Thread.sleep(50); } catch (InterruptedException e1) { // ignore } continue; } catch (MongoException e) { getLog().info("MongoDb started."); getLog().info("Unable to list databases due to " + e.getMessage()); } break; } } finally { mongoLogger.setLevel(mongoLevel); } if (execHandler.hasResult()) { ExecuteException exception = execHandler.getException(); if (exception != null) { throw new MojoFailureException(exception.getMessage(), exception); } throw new MojoFailureException( "Command " + commandLine + " exited with exit code " + execHandler.getExitValue()); } Map pluginContext = session.getPluginContext(getPluginDescriptor(), project); pluginContext.put(ProcessObserver.class.getName() + ":" + Integer.toString(port), processObserver); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } }
From source file:com.glaf.core.container.MongodbContainer.java
License:Apache License
private synchronized void init() { if (mongoClient == null) { String servers = getString("servers"); if (servers == null) { servers = "127.0.0.1:27017"; }/*from w w w . j a va 2s .c om*/ List<String> list = StringTools.split(servers, ","); List<ServerAddress> addrList = new ArrayList<ServerAddress>(); for (String server : list) { String host = server.substring(0, server.indexOf(":")); int port = Integer.parseInt(server.substring(server.indexOf(":") + 1, server.length())); try { ServerAddress addr = new ServerAddress(host, port); addrList.add(addr); } catch (Exception ex) { ex.printStackTrace(); } } mongoClient = new MongoClient(addrList); mongoClient.setWriteConcern(WriteConcern.JOURNALED); Runnable shutdownHook = new MongodbShutdownHook(mongoClient); ShutdownHookManager.get().addShutdownHook(shutdownHook, Thread.NORM_PRIORITY); } }
From source file:com.globocom.grou.configurations.MongoConfiguration.java
License:Open Source License
@Override public Mongo mongo() throws Exception { if ("".equals(MONGO_URI.getValue())) { LOGGER.info("MONGO_HOST: {}, MONGO_PORT: {}, MONGO_DB: {}", MONGO_HOST.getValue(), MONGO_PORT.getValue(), MONGO_DB.getValue()); final List<MongoCredential> credentialsList = "".equals(MONGO_USER.getValue()) || "".equals(MONGO_PASS.getValue()) ? Collections.emptyList() : singletonList(MongoCredential.createCredential(MONGO_USER.getValue(), MONGO_DB.getValue(), MONGO_PASS.getValue().toCharArray())); return new MongoClient( singletonList(/*from www .j a v a2 s . co m*/ new ServerAddress(MONGO_HOST.getValue(), Integer.parseInt(MONGO_PORT.getValue()))), credentialsList); } else { LOGGER.info("MONGO_URI: {}", MONGO_URI.getValue().replaceAll("([/,]).*@", "$1xxxx:xxxx@")); return new MongoClient(getMongoClientUri()); } }
From source file:com.google.code.log4mongo.MongoDbAppender.java
License:Apache License
/** * Returns a List of ServerAddress objects for each host specified in the hostname * property. Returns an empty list if configuration is detected to be invalid, e.g.: * <ul>//from w w w. j a v a 2 s.c o m * <li>Port property doesn't contain either one port or one port per host</li> * <li>After parsing port property to integers, there isn't either one port or one port per host</li> * </ul> * * @param hostname Blank space delimited hostnames * @param port Blank space delimited ports. Must specify one port for all hosts or a port per host. * @return List of ServerAddresses to connect to */ private List<ServerAddress> getServerAddresses(String hostname, String port) { List<ServerAddress> addresses = new ArrayList<ServerAddress>(); String[] hosts = hostname.split(" "); String[] ports = port.split(" "); if (ports.length != 1 && ports.length != hosts.length) { errorHandler.error("MongoDB appender port property must contain one port or a port per host", null, ErrorCode.ADDRESS_PARSE_FAILURE); } else { List<Integer> portNums = getPortNums(ports); // Validate number of ports again after parsing if (portNums.size() != 1 && portNums.size() != hosts.length) { errorHandler.error("MongoDB appender port property must contain one port or a valid port per host", null, ErrorCode.ADDRESS_PARSE_FAILURE); } else { boolean onePort = (portNums.size() == 1); int i = 0; for (String host : hosts) { int portNum = (onePort) ? portNums.get(0) : portNums.get(i); try { addresses.add(new ServerAddress(host.trim(), portNum)); } catch (UnknownHostException e) { errorHandler.error("MongoDB appender hostname property contains unknown host", e, ErrorCode.ADDRESS_PARSE_FAILURE); } i++; } } } return addresses; }
From source file:com.groupon.jenkins.SetupConfig.java
License:Open Source License
public List<ServerAddress> getMongoServerAddresses() throws UnknownHostException { final List<ServerAddress> serverAddresses = new ArrayList<>(); for (final String dbHost : getDbHost().split(",")) { final String[] hostPort = dbHost.split(":"); final int port = hostPort.length == 1 ? getDbPort() : Integer.parseInt(hostPort[1]); serverAddresses.add(new ServerAddress(hostPort[0], port)); }//from w w w .j av a 2 s .co m return serverAddresses; }