Example usage for com.mongodb ServerAddress ServerAddress

List of usage examples for com.mongodb ServerAddress ServerAddress

Introduction

In this page you can find the example usage for com.mongodb ServerAddress ServerAddress.

Prototype

public ServerAddress(@Nullable final String host, final int port) 

Source Link

Document

Creates a ServerAddress

Usage

From source file:org.pentaho.mongo.wrapper.NoAuthMongoClientWrapper.java

License:Open Source License

private List<ServerAddress> getServerAddressList() throws MongoDbException {
    String hostsPorts = props.get(MongoProp.HOST);
    String singlePort = props.get(MongoProp.PORT);

    int singlePortI = -1;

    try {/*from w  ww  . jav a 2  s . c om*/
        singlePortI = Integer.parseInt(singlePort);
    } catch (NumberFormatException n) {
        // don't complain
    }

    if (Util.isEmpty(hostsPorts)) {
        throw new MongoDbException(
                BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.Error.EmptyHostsString")); //$NON-NLS-1$
    }

    List<ServerAddress> serverList = new ArrayList<ServerAddress>();

    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 MongoDbException(
                    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 MongoDbException(BaseMessages.getString(PKG,
                        "MongoNoAuthWrapper.Message.Error.UnableToParsePortNumber", hp[1])); //$NON-NLS-1$
            }
        }

        try {
            ServerAddress s = new ServerAddress(host, port);
            serverList.add(s);
        } catch (UnknownHostException u) {
            throw new MongoDbException(u);
        }
    }
    return serverList;
}

From source file:org.perfcake.message.sender.MongoDBSender.java

License:Apache License

@Override
public void doInit(final Properties messageAttributes) throws PerfCakeException {
    final String t = getTarget(messageAttributes);
    final ServerAddress a;

    if (t.contains(":")) {
        final String[] addr = t.split(":", 2);
        final String host = addr[0];
        final int port = Integer.valueOf(addr[1]);
        a = new ServerAddress(host, port);
    } else {/*from  ww  w  .jav  a  2s  .  co m*/
        a = new ServerAddress(t);
    }

    if (dbUsername != null) {
        final MongoCredential c = MongoCredential.createScramSha1Credential(dbUsername, dbName,
                dbPassword.toCharArray());
        mongoClient = new MongoClient(a, Collections.singletonList(c),
                MongoClientOptions.builder().connectionsPerHost(connectionPoolSize).build());
    } else {
        mongoClient = new MongoClient(a,
                MongoClientOptions.builder().connectionsPerHost(connectionPoolSize).build());
    }

    db = mongoClient.getDatabase(dbName);
}

From source file:org.qi4j.entitystore.mongodb.MongoMapEntityStoreAssembler.java

License:Apache License

/**
 * Add a MongoDB node's hostname and port.
 *
 * Calling this method once disable the default behavior that use the MongoDB defaults: 127.0.0.1 27017
 *///from w  w  w  .  ja  va2s . c o  m
public MongoMapEntityStoreAssembler addHostnameAndPort(String hostname, Integer port)
        throws UnknownHostException {
    this.hostname = null;
    this.port = null;
    if (serverAddresses == null) {
        serverAddresses = new ArrayList<ServerAddress>();
    }
    serverAddresses.add(new ServerAddress(hostname, port));
    return this;
}

From source file:org.qi4j.entitystore.mongodb.MongoMapEntityStoreMixin.java

License:Apache License

private void loadConfiguration() throws UnknownHostException {
    configuration.refresh();//from  w  w  w .  java2s  .  c o  m
    MongoEntityStoreConfiguration config = configuration.get();

    // Combine hostname, port and nodes configuration properties
    serverAddresses = new ArrayList<ServerAddress>();
    if (config.hostname().get() != null && !config.hostname().get().isEmpty()) {
        serverAddresses.add(new ServerAddress(config.hostname().get(), config.port().get()));
    }
    serverAddresses.addAll(config.nodes().get());

    // If database name not configured, set it to qi4j:entitystore
    databaseName = config.database().get();
    if (databaseName == null) {
        databaseName = DEFAULT_DATABASE_NAME;
    }

    // If collection name not configured, set it to qi4j:entitystore:entities
    collectionName = config.collection().get();
    if (collectionName == null) {
        collectionName = DEFAULT_COLLECTION_NAME;
    }

    // If write concern not configured, set it to normal
    switch (config.writeConcern().get()) {
    case FSYNC_SAFE:
        writeConcern = WriteConcern.FSYNC_SAFE;
        break;
    case JOURNAL_SAFE:
        writeConcern = WriteConcern.JOURNAL_SAFE;
        break;
    case MAJORITY:
        writeConcern = WriteConcern.MAJORITY;
        break;
    case NONE:
        writeConcern = WriteConcern.NONE;
        break;
    case REPLICAS_SAFE:
        writeConcern = WriteConcern.REPLICAS_SAFE;
        break;
    case SAFE:
        writeConcern = WriteConcern.SAFE;
        break;
    case NORMAL:
    default:
        writeConcern = WriteConcern.NORMAL;
    }

    // Username and password are defaulted to empty strings
    username = config.username().get();
    password = config.password().get().toCharArray();
}

From source file:org.radarcns.config.ApplicationConfig.java

License:Apache License

/**
 * Returns the list of all known MongoDB instances.
 *
 * @return MongoDB instances as List//from  www .j  ava 2  s. c  o  m
 */
public List<ServerAddress> getMongoDbHosts() {

    final List<ServerAddress> mongoHostsTemp = new LinkedList<>();
    for (final String key : mongoHosts.keySet()) {
        mongoHostsTemp.add(new ServerAddress(key, Integer.valueOf(mongoHosts.get(key))));
    }

    return mongoHostsTemp;
}

From source file:org.radarcns.connect.mongodb.MongoWrapper.java

License:Apache License

private MongoClient createClient(AbstractConfig config, MongoClientOptions options) {
    String host = config.getString(MONGO_HOST);
    int port = config.getInt(MONGO_PORT);

    try {//from  w  ww .  j  av a 2  s .com
        MongoClientOptions actualOptions;
        if (options != null) {
            actualOptions = options;
        } else {
            actualOptions = new MongoClientOptions.Builder().build();
        }
        ServerAddress server = new ServerAddress(host, port);
        if (credentials != null) {
            return new MongoClient(server, credentials, actualOptions);
        } else {
            return new MongoClient(server, actualOptions);
        }
    } catch (MongoException ex) {
        log.error("Failed to create MongoDB client to {}:{} with credentials {}", host, port, credentials, ex);
        throw new ConnectException("MongoDb client cannot be created.", ex);
    }
}

From source file:org.radarcns.mongodb.MongoWrapper.java

License:Apache License

private MongoClient createClient(AbstractConfig config, MongoClientOptions options) {
    String host = config.getString(MONGO_HOST);
    int port = config.getInt(MONGO_PORT);

    try {/*from w  w w  . ja  v a2s  .  c  om*/
        if (options == null) {
            options = new MongoClientOptions.Builder().build();
        }
        return new MongoClient(new ServerAddress(host, port), credentials, options);
    } catch (com.mongodb.MongoSocketOpenException e) {
        log.error("Failed to create MongoDB client to {}:{} with credentials {}", host, port, credentials, e);
        throw new ConnectException("MongoDb client cannot be created.", e);
    }
}

From source file:org.rnott.places.MongoDB.java

License:Apache License

public MongoDB() {
    // TODO: look into 'strict' write setting

    /*/*w ww . java  2 s. c  o m*/
     * http://stackoverflow.com/questions/6520439/how-to-configure-mongodb-java-driver-mongooptions-for-production-use
     * 
     * autoConnectRetry 
     * Simply means the driver will automatically attempt to reconnect to the server(s) after unexpected disconnects. 
     * In production environments you usually want this set to true.
     * 
     * connectionsPerHost
     * the amount of physical connections a single Mongo instance (it's singleton so you usually have one per application)
     * can establish to a mongod/mongos process. At time of writing the java driver will establish this amount of connections eventually even if the
     * actual query throughput is low (in order words you will see the "conn" statistic in mongostat rise until it hits this number per app server).
     * There is no need to set this higher than 100 in most cases but this setting is one of those "test it and see" things. Do note that you will have 
     * to make sure you set this low enough so that the total amount of connections to your server do not exceed db.serverStatus().connections.available.
     * In production we currently have this at 40.
     * 
     * connectTimeout
     * As the name suggest number of milliseconds the driver will wait before a connection attempt is aborted. Keep the default unless there's a 
     * realistic, expected change this will be in the way of otherwise successful connection attempts.
     * 
     * maxWaitTime
     * Number of ms a thread will wait for a connection to become available on the connection pool, and raises an exception if this does not happen
     * in time. Keep default.
     * 
     * socketTimeout
     * Standard socket timeout value. Keep default.
     * 
     * threadsAllowedToBlockForConnectionMultiplier
     * Number of threads that are allowed to wait for connections to become available if the pool is currently exhausted. This is the setting that will
     * cause the "com.mongodb.DBPortPool$SemaphoresOut: Out of semaphores to get db connection" exception. It will throw this exception once this thread
     * queue exceeds the threadsAllowedToBlockForConnectionMultiplier value. If you expect big peaks in throughput that could case large queues temporarily
     * increase this value. We have it at 1500 at the moment for exactly that reason. If your query load consistently outpaces the server you should just
     * improve your hardware/scaling situation accordingly.
     * 
     * slaveOk
     * Very important for increased read performance if you use replica sets. This basically allows mongo to direct reads to non-primary replica members,
     * spreading the read load. Note that this can also be configured per query in your code. If you use replica sets (and you should) and you can live 
     * with eventual consistency issues (meaning your secondaries might be slightly behind the primary's state) enable this.
     * 
     * safe
     * When enabled the driver is forced to send a getLastError() command to the server after every write operation. This ensures that any possible problems
     * (unique constraint violations, query issues, etc.) are noticed on the client side and possibly throw an error. It defaults to false but you should set
     * this to true and change the WriteConcern of your updates if, and only if, you know you will not care about the result of the update and/or desperately
     * require additional performance.
     * 
     * w
     * Oddly named parameter ;). If safe = true and w > 0 it determines the amount of replica set members a write has to be propogated to before considering
     * it successful. Use this for increased durability at the (considerable) expense of throughput.
     * 
     * fsync
     * Durability option that forces mongo to flush to disk after each write when enabled. I've never had any durability issues related to a write backlog so
     * we have this on false (the default) in production.
     */
    MongoOptions options = new MongoOptions();
    options.autoConnectRetry = true;
    //options.slaveOk = true;  see ReadPreference.SECONDARY
    options.safe = true;
    options.fsync = true; // durability is a must

    if (env == null) {
        //throw new RuntimeException( "Runtime environment is not injected" );
        // TODO: runtime environment bean is not being injected
        env = new Environment();
        env.initialize();
    }
    try {
        ServerAddress addr = new ServerAddress(env.getDatabaseHost(), env.getDatabasePort());
        mongo = new Mongo(addr, options);
    } catch (UnknownHostException e) {
        throw new RuntimeException("Failed to locate MongoDB", e);
    } catch (MongoException e) {
        throw new RuntimeException("Failed MongoDB initialization", e);
    }

    // authenticate
    logger.info("Initializing database: {}", env.getDatabaseName());
    logger.info(env.toString());
    mongo.getDB(env.getDatabaseName()).authenticate(env.getDatabaseUser(),
            env.getDatabasePassword().toCharArray());

    // initialize Morphia
    morphia = new Morphia();

    // set up mapping for entity types
    for (Class<?> c : MAPPED_CLASSES) {
        morphia.map(c);
    }

    // enable JSR303 Validation
    // this is extended so that it can respond to dynamic validation groups
    // TODO: re-enable validation after figuring out how to deal with Address issues (when embedded in Place, city and postal code may be null)
    //new DynamicValidationExtension( morphia );
}

From source file:org.s1.mongodb.MongoDBConnectionHelper.java

License:Apache License

/**
 *
 * @param instance/*from  ww  w.j  a  va2s . c  o  m*/
 */
private static synchronized void initialize(String instance) {
    if (!connections.containsKey(instance)) {

        Map<String, Object> mopt = Options.getStorage().getMap(OPTIONS);
        Map<String, Object> m = Objects.get(mopt, "connections." + instance);
        if (Objects.isNullOrEmpty(m)) {
            m = Objects.get(mopt, "connections." + DEFAULT_INSTANCE);
        }

        MongoClientOptions.Builder b = MongoClientOptions.builder();
        MongoClientOptions def_opt = MongoClientOptions.builder().build();
        b.connectionsPerHost(Objects.get(m, "connectionsPerHost", def_opt.getConnectionsPerHost()));
        b.autoConnectRetry(Objects.get(m, "autoConnectRetry", def_opt.isAutoConnectRetry()));
        b.connectTimeout(Objects.get(m, "connectTimeout", def_opt.getConnectTimeout()));
        b.socketKeepAlive(Objects.get(m, "socketKeepAlive", def_opt.isSocketKeepAlive()));
        b.socketTimeout(Objects.get(m, "socketTimeout", def_opt.getSocketTimeout()));
        b.maxAutoConnectRetryTime(
                Objects.get(m, "maxAutoConnectRetryTime", def_opt.getMaxAutoConnectRetryTime()));
        b.maxWaitTime(Objects.get(m, "maxWaitTime", def_opt.getMaxWaitTime()));
        b.threadsAllowedToBlockForConnectionMultiplier(
                Objects.get(m, "threadsAllowedToBlockForConnectionMultiplier",
                        def_opt.getThreadsAllowedToBlockForConnectionMultiplier()));
        b.writeConcern(WriteConcern.FSYNC_SAFE);
        MongoClientOptions opt = b.build();

        MongoClient cl = null;
        try {
            cl = new MongoClient(
                    new ServerAddress(Objects.get(m, "host", "localhost"), Objects.get(m, "port", 27017)), opt);
        } catch (UnknownHostException e) {
            throw S1SystemError.wrap(e);
        }

        String dbName = Objects.get(m, "name");
        if (Objects.isNullOrEmpty(dbName))
            throw new S1SystemError("Cannot initialize MongoDB connection, because name is not set");

        DB db = cl.getDB(dbName);

        String user = Objects.get(m, "user");
        String password = Objects.get(m, "password");
        if (!Objects.isNullOrEmpty(user)) {
            if (!db.authenticate(user, password.toCharArray())) {
                throw new S1SystemError(
                        "Cannot authenticate MongoDB connection " + dbName + " with user " + user);
            }
        }
        LOG.info("MongoDB connected " + cl.getAddress().getHost() + ":" + cl.getAddress().getPort());

        connections.put(instance, db);
    }
}

From source file:org.sglover.alfrescoextensions.common.MongoDbFactory.java

License:Open Source License

private MongoClient newMongo() throws UnknownHostException, MongoException {
    return new MongoClient(new ServerAddress(mongodProcess.getConfig().net().getServerAddress(),
            mongodProcess.getConfig().net().getPort()));
}