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.ebaysf.ostara.telemetry.mongodb.Database.java

License:Apache License

public Datastore getMongoDatastore(String mongoHostOverride)
        throws UnknownHostException, MongoException, NamingException, SQLException {

    Mongo mongoClient;//from   www.j  a  v a2s  .  c  o  m

    String tmpOverride = System.getenv("RMIGWEB_MONGO_HOST");

    if (tmpOverride != null) {
        LoggerFactory.getLogger(Database.class)
                .info("Using mongo host overridden by system property: " + tmpOverride);
        mongoHostOverride = tmpOverride;
    }

    if (mongoHostOverride == null) {
        mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", DEFAULT_MONGO_PORT)));
    } else {
        mongoClient = new MongoClient(new ServerAddress(mongoHostOverride, DEFAULT_MONGO_PORT));
    }
    Morphia morphia = new Morphia();
    Datastore ds = morphia.createDatastore(mongoClient, "UpdateLog");
    ds.ensureIndexes();
    return ds;
}

From source file:org.eclipse.birt.data.oda.mongodb.impl.MongoDBDriver.java

License:Open Source License

private static Mongo createMongoNode(ServerNodeKey serverNodeKey) throws OdaException {
    /* NOTE: Not able to use the new 2.10 MongoClient classes directly,
     *  as their public methods, as of 2.10.1, do not allow merging options of
     *  MongoClientURL and MongoClientOptions
     *//*w  w w.  j a v a  2 s.  c o m*/
    List<String> hosts = serverNodeKey.getServerHosts();
    String standaloneHost = hosts.size() == 1 ? hosts.get(0) : null;
    Integer port = serverNodeKey.getServerPort();
    MongoOptions options = serverNodeKey.getOptions();
    if (options == null)
        options = sm_defaultClientOptions;

    try {
        if (standaloneHost != null) {
            ServerAddress serverAddr = port != null ? new ServerAddress(standaloneHost, port)
                    : new ServerAddress(standaloneHost);
            return new Mongo(serverAddr, options);
        } else {
            List<ServerAddress> serverSeeds = new ArrayList<ServerAddress>(hosts.size());
            for (String host : hosts)
                serverSeeds.add(new ServerAddress(host));
            return new Mongo(serverSeeds, options);
        }
    } catch (Exception ex) {
        throw new OdaException(ex);
    }
}

From source file:org.edgexfoundry.AppConfig.java

License:Apache License

private ServerAddress getServerAddress() throws UnknownHostException {
    return new ServerAddress(host, port);
}

From source file:org.edgexfoundry.MongoConfig.java

License:Apache License

private ServerAddress getServerAddress() {
    return new ServerAddress(host, port);
}

From source file:org.elasticsearch.river.mongodb.RiverMongoDBTestAbstract.java

License:Apache License

private void initMongoInstances(ExecutableType type) throws Exception {
    logger.debug("*** initMongoInstances(" + type + ") ***");
    CommandResult cr;//from  w  ww . j  a v a 2s.  c  o  m
    Settings rsSettings = settings.getByPrefix(type.configKey + '.');
    int[] ports;
    if (rsSettings.getAsBoolean("useDynamicPorts", false)) {
        ports = new int[] { Network.getFreeServerPort(), Network.getFreeServerPort(),
                Network.getFreeServerPort() };
    } else {
        int start = 37017 + 10 * type.ordinal();
        ports = new int[] { start, start + 1, start + 2 };
    }
    String replicaSetName = "es-test-" + type.configKey;
    // Create 3 mongod processes
    Starter<IMongodConfig, MongodExecutable, MongodProcess> starter = type.newStarter();
    ImmutableList.Builder<MongoReplicaSet.Member> builder = ImmutableList.builder();
    for (int i = 1; i <= 3; ++i) {
        Storage storage = new Storage("target/" + replicaSetName + '/' + i, replicaSetName, 20);
        MongoReplicaSet.Member member = new MongoReplicaSet.Member();
        member.config = new MongodConfigBuilder()
                .version(Versions.withFeatures(new GenericVersion(rsSettings.get("version"))))
                .net(new de.flapdoodle.embed.mongo.config.Net(ports[i - 1], Network.localhostIsIPv6()))
                .replication(storage).build();
        logger.trace("replSetName in config: {}", member.config.replication().getReplSetName());
        member.executable = starter.prepare(member.config);
        member.process = member.executable.start();
        member.address = new ServerAddress(Network.getLocalHost().getHostName(), member.config.net().getPort());
        logger.debug("Server #" + i + ": {}", member.address);
        builder.add(member);
    }
    ImmutableList<MongoReplicaSet.Member> members = builder.build();
    Thread.sleep(2000);
    MongoClientOptions mco = MongoClientOptions.builder().autoConnectRetry(true).connectTimeout(15000)
            .socketTimeout(60000).build();
    Mongo mongo = new MongoClient(new ServerAddress(Network.getLocalHost().getHostName(), ports[0]), mco);
    DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME);

    cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1));
    logger.debug("isMaster: " + cr);

    // Initialize replica set
    cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate",
            (DBObject) JSON.parse("{'_id': '" + replicaSetName + "', 'members': [" + "{'_id': 0, 'host': '"
                    + members.get(0).address.getHost() + ':' + members.get(0).address.getPort() + "'}, "
                    + "{'_id': 1, 'host': '" + members.get(1).address.getHost() + ':'
                    + members.get(1).address.getPort() + "'}, " + "{'_id': 2, 'host': '"
                    + members.get(2).address.getHost() + ':' + members.get(2).address.getPort()
                    + "', 'arbiterOnly' : true}]} }")));
    logger.debug("replSetInitiate result: " + cr);

    Thread.sleep(5000);
    cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
    logger.trace("replSetGetStatus result: {}", cr);

    // Check replica set status before to proceed
    while (!isReplicaSetStarted(cr)) {
        logger.debug("Waiting 3 seconds for replicaset to change status...");
        Thread.sleep(3000);
        cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
        // logger.debug("replSetGetStatus: " + cr);
    }

    mongo.close();
    mongo = null;

    // Initialize a new client using all instances.
    List<ServerAddress> mongoServers = new ArrayList<ServerAddress>();
    for (MongoReplicaSet.Member member : members) {
        mongoServers.add(member.address);
    }
    mongo = new MongoClient(mongoServers, mco);
    Assert.assertNotNull(mongo);
    mongo.setReadPreference(ReadPreference.secondaryPreferred());
    mongo.setWriteConcern(WriteConcern.REPLICAS_SAFE);
    replicaSets.put(type, new MongoReplicaSet(type, rsSettings.get("version"), mongo, mongoAdminDB, members));
}

From source file:org.envirocar.server.mongo.MongoDB.java

License:Open Source License

@Inject
public MongoDB(Injector injector, Set<TypeConverter> converters,
        @Named(MAPPED_CLASSES) Set<Class<?>> mappedClasses, @Named(HOST_PROPERTY) String host,
        @Named(PORT_PROPERTY) int port, @Named(DATABASE_PROPERTY) String database,
        @Nullable @Named(USER_PROPERTY) String username, @Nullable @Named(PASS_PROPERTY) char[] password) {
    try {//from w ww.j  av a2 s . c  om
        MorphiaLoggerFactory.registerLogger(SLF4JLogrImplFactory.class);
        mongo = new MongoClient(new ServerAddress(host, port));
        morphia = new Morphia();
        morphia.getMapper().getOptions().objectFactory = new CustomGuiceObjectFactory(new DefaultCreator(),
                injector);
        addConverters(converters);
        addMappedClasses(mappedClasses);
        datastore = morphia.createDatastore(mongo, database, username, password);
        datastore.ensureIndexes();
        ensureIndexes();
        datastore.ensureCaps();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.exoplatform.addons.persistence.services.mongodb.MongoBootstrap.java

License:Open Source License

private Mongo mongo() {
    if (m == null) {
        try {//from  w  w w. jav a 2  s  .  c  o m
            if (PropertyManager.PROPERTY_DB_SERVER_TYPE_EMBED
                    .equals(PropertyManager.getProperty(PropertyManager.PROPERTY_DB_SERVER_TYPE))) {
                log.warning("WE WILL NOW USE MONGODB IN EMBED MODE...");
                log.warning("BE AWARE...");
                log.warning("EMBED MODE SHOULD NEVER BE USED IN PRODUCTION!");
                setupEmbedMongo();
            }

            MongoOptions options = new MongoOptions();
            options.connectionsPerHost = 200;
            options.connectTimeout = 60000;
            options.threadsAllowedToBlockForConnectionMultiplier = 10;
            options.autoConnectRetry = true;
            String host = PropertyManager.getProperty(PropertyManager.PROPERTY_DB_SERVER_HOST);
            int port = Integer.parseInt(PropertyManager.getProperty(PropertyManager.PROPERTY_DB_SERVER_PORT));
            m = new Mongo(new ServerAddress(host, port), options);
            m.setWriteConcern(WriteConcern.SAFE);
        } catch (UnknownHostException e) {
        } catch (IOException e) {
        }
    }
    return m;
}

From source file:org.exoplatform.addons.persistence.services.mongodb.MongoBootstrap.java

License:Open Source License

private static Mongo setupEmbedMongo() throws IOException {
    MongodStarter runtime = MongodStarter.getDefaultInstance();
    int port = Integer.parseInt(PropertyManager.getProperty(PropertyManager.PROPERTY_DB_SERVER_PORT));
    mongodExe = runtime.prepare(new MongodConfig(Version.V2_3_0, port, Network.localhostIsIPv6()));
    mongod = mongodExe.start();/*from ww w  . j  a v a 2 s. c om*/
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        log.info(e.getMessage());
    }
    String host = PropertyManager.getProperty(PropertyManager.PROPERTY_DB_SERVER_HOST);

    return new Mongo(new ServerAddress(host, port));
}

From source file:org.exoplatform.addons.storage.services.mongodb.MongoBootstrap.java

License:Open Source License

private Mongo mongo() {
    if (m == null) {
        try {/*from ww  w  .ja v a 2  s . co  m*/
            MongoOptions options = new MongoOptions();
            options.connectionsPerHost = 200;
            options.connectTimeout = 60000;
            options.threadsAllowedToBlockForConnectionMultiplier = 10;
            options.autoConnectRetry = true;
            String host = PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_HOST);
            int port = Integer.parseInt(PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_PORT));
            m = new Mongo(new ServerAddress(host, port), options);
            m.setWriteConcern(WriteConcern.SAFE);
        } catch (UnknownHostException e) {

        } catch (IOException e) {

        }
    }
    return m;
}

From source file:org.exoplatform.chat.services.mongodb.MongoBootstrap.java

License:Open Source License

private Mongo mongo() {
    if (m == null) {
        try {//from ww w .  j a v a 2  s . c  o m
            if (PropertyManager.PROPERTY_SERVER_TYPE_EMBED
                    .equals(PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_TYPE))) {
                LOG.warning("WE WILL NOW USE MONGODB IN EMBED MODE...");
                LOG.warning("BE AWARE...");
                LOG.warning("EMBED MODE SHOULD NEVER BE USED IN PRODUCTION!");
                setupEmbedMongo();
            }

            MongoOptions options = new MongoOptions();
            options.connectionsPerHost = 200;
            options.connectTimeout = 60000;
            options.threadsAllowedToBlockForConnectionMultiplier = 10;
            options.autoConnectRetry = true;
            String host = PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_HOST);
            int port = Integer.parseInt(PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_PORT));
            m = new Mongo(new ServerAddress(host, port), options);
            m.setWriteConcern(WriteConcern.SAFE);
        } catch (UnknownHostException e) {
            LOG.warning(e.getMessage());
        } catch (IOException e) {
            LOG.warning(e.getMessage());
        }
    }
    return m;
}