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:soatreefinder.SOATreeFinder.java

public static void loadMongoFromSQL(String sqlQuery, String mongoDBName, String mongoCollName,
        String mongoCollPrimaryKey) throws SQLException, IOException, FileNotFoundException {
    propsFile.load(new FileInputStream(System.getProperty("user.dir") + "\\context.properties"));
    Statement stmt = null;/*from w ww  .  j  a v a  2 s  . co m*/
    String blobString;
    Map sqlMap = new HashMap();
    MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress(
            propsFile.getProperty("mongoHost"), Integer.parseInt(propsFile.getProperty("mongoPort")))));
    MongoDatabase db = mongoClient.getDatabase(mongoDBName);
    MongoCollection coll = db.getCollection(mongoCollName);
    UpdateOptions upsertOption = new UpdateOptions();
    upsertOption.upsert(true);
    Connection soadb_Connection = DriverManager
            .getConnection("jdbc:oracle:thin:" + propsFile.getProperty("user") + "/"
                    + propsFile.getProperty("password") + "@//" + propsFile.getProperty("host") + ":"
                    + propsFile.getProperty("port") + "/" + propsFile.getProperty("service"));

    stmt = soadb_Connection.createStatement();
    ResultSet rs = stmt.executeQuery(sqlQuery);
    ResultSetMetaData rsmd = rs.getMetaData();
    while (rs.next()) {
        for (int i = 1; i <= rsmd.getColumnCount(); i++) {
            /* The following block of switch statement checks for the sql data type of
            a given column and puts the appropriate object into the hash map*/
            switch (rsmd.getColumnType(i)) {
            case 12:
                sqlMap.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case -9:
                sqlMap.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case -15:
                sqlMap.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case 16:
                sqlMap.put(rsmd.getColumnName(i), rs.getBoolean(i));
                break;
            case -7:
                sqlMap.put(rsmd.getColumnName(i), rs.getByte(i));
                break;
            case 2:
                sqlMap.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case 4:
                sqlMap.put(rsmd.getColumnName(i), rs.getInt(i));
                break;
            case 6:
                sqlMap.put(rsmd.getColumnName(i), rs.getFloat(i));
                break;
            case 8:
                sqlMap.put(rsmd.getColumnName(i), rs.getDouble(i));
                break;
            case 3:
                sqlMap.put(rsmd.getColumnName(i), rs.getBigDecimal(i));
                break;
            case 1:
                sqlMap.put(rsmd.getColumnName(i), rs.getString(i));
                break;
            case 91:
                sqlMap.put(rsmd.getColumnName(i), rs.getDate(i).toString());
                break;
            case 92:
                sqlMap.put(rsmd.getColumnName(i), rs.getTime(i).toString());
                break;
            case 93:
                sqlMap.put(rsmd.getColumnName(i), rs.getTimestamp(i).toString());
                break;
            case 2003:
                sqlMap.put(rsmd.getColumnName(i), rs.getArray(i));
                break;
            case 2004: {
                Blob blob = rs.getBlob(i);
                byte[] bdata = blob.getBytes(1, (int) blob.length());
                blobString = new String(bdata);
                sqlMap.put(rsmd.getColumnName(i), blobString);
            }
                break;
            case 2005:
                sqlMap.put(rsmd.getColumnName(i), rs.getClob(i));
                break;
            default:
                sqlMap.put(rsmd.getColumnName(i), rs.getString(i));
            }
        }

        // Upsert sql record into mongo collection
        coll.updateOne(eq(mongoCollPrimaryKey, sqlMap.get(mongoCollPrimaryKey)),
                new Document("$set", new Document(sqlMap)), upsertOption);
    }
}

From source file:sockslib.utils.mongo.MongoDBUtil.java

License:Apache License

private MongoClient getConnectedClient() {
    if (Strings.isEmpty(username)) {
        return new MongoClient(host, port);
    } else {/*  w ww.ja va2 s.c  o  m*/
        MongoCredential credential = MongoCredential.createCredential(username, databaseName,
                password.toCharArray());
        return new MongoClient(new ServerAddress(host, port), Lists.newArrayList(credential));
    }
}

From source file:streamflow.datastore.mongodb.config.MongoDatastoreModule.java

License:Apache License

@Provides
public Mongo providesMongoClient(DatastoreConfig datastoreConfig) {
    MongoClient mongoClient = null;//from   w ww . j a  va2s . c o  m
    MongoClientOptions.Builder clientOptions = MongoClientOptions.builder();

    String serverAddressHost = datastoreConfig.getProperty("host", String.class);
    if (serverAddressHost == null) {
        serverAddressHost = "localhost";
    }

    Integer serverAddressPort = datastoreConfig.getProperty("port", Integer.class);
    if (serverAddressPort == null) {
        serverAddressPort = 27017;
    }

    Integer acceptableLatencyDifference = datastoreConfig.getProperty("acceptableLatencyDifference",
            Integer.class);
    if (acceptableLatencyDifference != null) {
        clientOptions.acceptableLatencyDifference(acceptableLatencyDifference);
    }

    Integer connectTimeout = datastoreConfig.getProperty("connectTimeout", Integer.class);
    if (connectTimeout != null) {
        clientOptions.connectTimeout(connectTimeout);
    }

    Integer connectionsPerHost = datastoreConfig.getProperty("connectionsPerHost", Integer.class);
    if (connectionsPerHost != null) {
        clientOptions.connectionsPerHost(connectionsPerHost);
    }

    Boolean cursorFinalizerEnabled = datastoreConfig.getProperty("acceptableLatencyDifference", Boolean.class);
    if (cursorFinalizerEnabled != null) {
        clientOptions.cursorFinalizerEnabled(cursorFinalizerEnabled);
    }

    Integer heartbeatConnectRetryFrequency = datastoreConfig.getProperty("heartbeatConnectRetryFrequency",
            Integer.class);
    if (heartbeatConnectRetryFrequency != null) {
        clientOptions.heartbeatConnectRetryFrequency(heartbeatConnectRetryFrequency);
    }

    Integer heartbeatConnectTimeout = datastoreConfig.getProperty("heartbeatConnectTimeout", Integer.class);
    if (heartbeatConnectTimeout != null) {
        clientOptions.heartbeatConnectTimeout(heartbeatConnectTimeout);
    }

    Integer heartbeatFrequency = datastoreConfig.getProperty("heartbeatFrequency", Integer.class);
    if (heartbeatFrequency != null) {
        clientOptions.heartbeatFrequency(heartbeatFrequency);
    }

    Integer heartbeatSocketTimeout = datastoreConfig.getProperty("heartbeatSocketTimeout", Integer.class);
    if (heartbeatSocketTimeout != null) {
        clientOptions.heartbeatSocketTimeout(heartbeatSocketTimeout);
    }

    Integer heartbeatThreadCount = datastoreConfig.getProperty("heartbeatThreadCount", Integer.class);
    if (heartbeatThreadCount != null) {
        clientOptions.heartbeatThreadCount(heartbeatThreadCount);
    }

    Integer maxConnectionIdleTime = datastoreConfig.getProperty("maxConnectionIdleTime", Integer.class);
    if (maxConnectionIdleTime != null) {
        clientOptions.maxConnectionIdleTime(maxConnectionIdleTime);
    }

    Integer maxConnectionLifeTime = datastoreConfig.getProperty("maxConnectionLifeTime", Integer.class);
    if (maxConnectionLifeTime != null) {
        clientOptions.maxConnectionLifeTime(maxConnectionLifeTime);
    }

    Integer maxWaitTime = datastoreConfig.getProperty("maxWaitTime", Integer.class);
    if (maxWaitTime != null) {
        clientOptions.maxWaitTime(maxWaitTime);
    }

    Integer minConnectionsPerHost = datastoreConfig.getProperty("minConnectionsPerHost", Integer.class);
    if (minConnectionsPerHost != null) {
        clientOptions.minConnectionsPerHost(minConnectionsPerHost);
    }

    Boolean socketKeepAlive = datastoreConfig.getProperty("socketKeepAlive", Boolean.class);
    if (socketKeepAlive != null) {
        clientOptions.socketKeepAlive(socketKeepAlive);
    }

    Integer socketTimeout = datastoreConfig.getProperty("socketTimeout", Integer.class);
    if (socketTimeout != null) {
        clientOptions.socketTimeout(socketTimeout);
    }

    Integer threadsAllowedToBlockForConnectionMultiplier = datastoreConfig
            .getProperty("threadsAllowedToBlockForConnectionMultiplier", Integer.class);
    if (threadsAllowedToBlockForConnectionMultiplier != null) {
        clientOptions
                .threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);
    }

    try {
        ServerAddress serverAddress = new ServerAddress(serverAddressHost, serverAddressPort);

        // Initialize the Mongo connection with the specified address and options
        mongoClient = new MongoClient(serverAddress, clientOptions.build());
    } catch (UnknownHostException ex) {
        LOG.error("Exception occurred while building Mongo client connection", ex);
    }

    return mongoClient;
}

From source file:test.elasticsearch.plugin.river.mongodb.RiverMongoDBTestAsbtract.java

License:Apache License

private void initMongoInstances() throws Exception {
    logger.debug("*** initMongoInstances ***");
    CommandResult cr;// ww w.  jav a  2 s .  c  o  m

    // Create 3 mongod processes
    mongodConfig1 = new MongodConfig(new GenericVersion(mongoVersion),
            new Net(mongoPort1, Network.localhostIsIPv6()), new Storage(null, REPLICA_SET_NAME, 20),
            new Timeout());
    MongodStarter starter = MongodStarter.getDefaultInstance();
    mongodExe1 = starter.prepare(mongodConfig1);
    mongod1 = mongodExe1.start();
    mongodConfig2 = new MongodConfig(new GenericVersion(mongoVersion),
            new Net(mongoPort2, Network.localhostIsIPv6()), new Storage(null, REPLICA_SET_NAME, 20),
            new Timeout());
    mongodExe2 = starter.prepare(mongodConfig2);
    mongod2 = mongodExe2.start();
    mongodConfig3 = new MongodConfig(new GenericVersion(mongoVersion),
            new Net(mongoPort3, Network.localhostIsIPv6()), new Storage(null, REPLICA_SET_NAME, 20),
            new Timeout());
    mongodExe3 = starter.prepare(mongodConfig3);
    mongod3 = mongodExe3.start();
    String server1 = Network.getLocalHost().getHostName() + ":" + mongodConfig1.net().getPort();
    String server2 = Network.getLocalHost().getHostName() + ":" + mongodConfig2.net().getPort();
    String server3 = Network.getLocalHost().getHostName() + ":" + mongodConfig3.net().getPort();
    logger.debug("Server #1: {}", server1);
    logger.debug("Server #2: {}", server2);
    logger.debug("Server #3: {}", server3);
    Thread.sleep(2000);
    MongoClientOptions mco = MongoClientOptions.builder().autoConnectRetry(true).connectTimeout(15000)
            .socketTimeout(60000).build();
    mongo = new MongoClient(
            new ServerAddress(Network.getLocalHost().getHostName(), mongodConfig1.net().getPort()), mco);
    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': '" + REPLICA_SET_NAME + "', 'members': [{'_id': 0, 'host': '"
                    + server1 + "'}, {'_id': 1, 'host': '" + server2 + "'}, {'_id': 2, 'host': '" + server3
                    + "', 'arbiterOnly' : true}]} }")));
    logger.debug("replSetInitiate: " + cr);

    Thread.sleep(5000);
    cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
    logger.info("replSetGetStatus: " + cr);

    // Check replica set status before to proceed
    while (!isReplicaSetStarted(cr)) {
        logger.debug("Waiting for 3 seconds...");
        Thread.sleep(1000);
        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>();
    mongoServers.add(new ServerAddress(Network.getLocalHost().getHostName(), mongodConfig1.net().getPort()));
    mongoServers.add(new ServerAddress(Network.getLocalHost().getHostName(), mongodConfig2.net().getPort()));
    mongoServers.add(new ServerAddress(Network.getLocalHost().getHostName(), mongodConfig3.net().getPort()));
    mongo = new MongoClient(mongoServers, mco);
    Assert.assertNotNull(mongo);
    mongo.setReadPreference(ReadPreference.secondaryPreferred());
    mongo.setWriteConcern(WriteConcern.REPLICAS_SAFE);
}

From source file:thingynet.mongo.MongoConfig.java

License:Apache License

@Bean
MongoClient mongoClient() throws IOException {
    ArrayList<ServerAddress> servers = new ArrayList<>();
    for (int i = 0; i < mongoHosts.length; i++) {
        servers.add(new ServerAddress(mongoHosts[i], mongoPorts[i]));
    }//from  w  w  w  .ja  va2  s  .com
    WriteConcern writeConcern = WriteConcern.valueOf(mongoWriteConcern);
    ReadPreference readPreference = ReadPreference.valueOf(mongoReadPreference);

    MongoClientOptions options = new MongoClientOptions.Builder().connectionsPerHost(mongoConnectionsPerHost)
            .writeConcern(writeConcern).readPreference(readPreference).build();

    return new MongoClient(servers, options);
}

From source file:ua.serhuz.dropwizard_morphia.mongo.MongoClientBuilder.java

License:Apache License

/**
 * Builds {@link MongoClient} instance and registers {@link MongoHealthCheck} in application environment.
 *
 * @return {@link MongoClient} instance//  w  w w.  j av  a  2  s  .  co m
 * @throws UnknownHostException thrown if connection to Mongo could not be determined
 */
public MongoClient build() throws UnknownHostException {
    List<MongoConnection> connections = configuration.getConnections();
    List<ServerAddress> addrs = new LinkedList<ServerAddress>();

    for (MongoConnection connection : connections) {
        addrs.add(new ServerAddress(connection.getHost(), connection.getPort()));
    }

    MongoClient mongoClient = new MongoClient(addrs);

    environment.lifecycle().manage(mongoClient);
    environment.jersey().register(new MongoHealthCheck(mongoClient));

    return mongoClient;
}

From source file:uk.ac.ebi.eva.dbmigration.mongodb.MongobeeHelper.java

License:Apache License

private static List<ServerAddress> getServers(DatabaseParameters databaseParameters) {
    List<ServerAddress> addresses = new ArrayList<>();

    int port = ServerAddress.defaultPort();
    if (hasText(databaseParameters.getDbPort())) {
        port = Integer.parseInt(databaseParameters.getDbPort());
    }/*from   w  w w . j av a  2  s  .c om*/

    String hosts = databaseParameters.getDbHosts();
    if (!hasText(hosts)) {
        hosts = ServerAddress.defaultHost();
    }

    for (String host : hosts.split(",")) {
        addresses.add(new ServerAddress(host, port));
    }

    return addresses;
}

From source file:uk.ac.ebi.eva.lib.datastore.DBAdaptorConnector.java

License:Apache License

/**
 * Get a MongoClient using the configuration (credentials) in a given Properties.
 *
 * @param properties can have the next values:
 *                   - eva.mongo.auth.db authentication database
 *                   - eva.mongo.host comma-separated strings of colon-separated host and port strings: host_1:port_1,host_2:port_2
 *                   - eva.mongo.user/*from   w  w  w .j  av  a  2s. c o m*/
 *                   - eva.mongo.passwd
 *                   - eva.mongo.read-preference string, "secondaryPreferred" if unspecified. one of:
 *                          [primary, primaryPreferred, secondary, secondaryPreferred, nearest]
 * @return MongoClient with given credentials
 * @throws UnknownHostException
 */
public static MongoClient getMongoClient(Properties properties) throws UnknownHostException {

    String[] hosts = properties.getProperty("eva.mongo.host").split(",");
    List<ServerAddress> servers = new ArrayList<>();

    // Get the list of hosts (optionally including the port number)
    for (String host : hosts) {
        String[] params = host.split(":");
        if (params.length > 1) {
            servers.add(new ServerAddress(params[0], Integer.parseInt(params[1])));
        } else {
            servers.add(new ServerAddress(params[0], 27017));
        }
    }

    List<MongoCredential> mongoCredentialList = null;
    String authenticationDb = properties.getProperty("eva.mongo.auth.db", null);
    if (authenticationDb != null && !authenticationDb.isEmpty()) {
        mongoCredentialList = Collections
                .singletonList(MongoCredential.createCredential(properties.getProperty("eva.mongo.user"),
                        authenticationDb, properties.getProperty("eva.mongo.passwd").toCharArray()));
    }

    String readPreference = properties.getProperty("eva.mongo.read-preference");
    readPreference = readPreference == null || readPreference.isEmpty() ? "secondaryPreferred" : readPreference;

    MongoClientOptions options = MongoClientOptions.builder()
            .readPreference(ReadPreference.valueOf(readPreference)).build();

    return new MongoClient(servers, mongoCredentialList, options);
}

From source file:uk.ac.ebi.eva.utils.ConnectionHelper.java

License:Apache License

public static List<ServerAddress> parseServerAddresses(String hosts) throws UnknownHostException {
    List<ServerAddress> serverAddresses = new LinkedList<>();
    for (String hostPort : hosts.split(",")) {
        if (hostPort.contains(":")) {
            String[] split = hostPort.split(":");
            Integer port = Integer.valueOf(split[1]);
            serverAddresses.add(new ServerAddress(split[0], port));
        } else {// ww w  .j  a  v  a 2 s .  co m
            serverAddresses.add(new ServerAddress(hostPort, 27017));
        }
    }
    return serverAddresses;
}

From source file:uk.ac.ebi.eva.vcfdump.server.configuration.DBAdaptorConnector.java

License:Apache License

/**
 * Get a MongoClient using the configuration (credentials) in a given Properties.
 *
 * @param springDataMongoDbProperties can have the next values:
 *                   - eva.mongo.auth.db authentication database
 *                   - eva.mongo.host comma-separated strings of colon-separated host and port strings: host_1:port_1,host_2:port_2
 *                   - eva.mongo.user/*www  .j  av  a 2 s . co m*/
 *                   - eva.mongo.passwd
 *                   - eva.mongo.read-preference string, "secondaryPreferred" if unspecified. one of:
 *                          [primary, primaryPreferred, secondary, secondaryPreferred, nearest]
 * @return MongoClient with given credentials
 * @throws UnknownHostException
 */
public static MongoClient getMongoClient(SpringDataMongoDbProperties springDataMongoDbProperties)
        throws UnknownHostException {

    String[] hosts = springDataMongoDbProperties.getHost().split(",");
    List<ServerAddress> servers = new ArrayList<>();

    // Get the list of hosts (optionally including the port number)
    for (String host : hosts) {
        String[] params = host.split(":");
        if (params.length > 1) {
            servers.add(new ServerAddress(params[0], Integer.parseInt(params[1])));
        } else {
            servers.add(new ServerAddress(params[0], 27017));
        }
    }

    List<MongoCredential> mongoCredentialList = new ArrayList<>();
    String authenticationDb = springDataMongoDbProperties.getAuthenticationDatabase();
    if (authenticationDb != null && !authenticationDb.isEmpty()) {
        mongoCredentialList = Collections
                .singletonList(MongoCredential.createCredential(springDataMongoDbProperties.getUsername(),
                        authenticationDb, springDataMongoDbProperties.getPassword().toCharArray()));
    }

    String readPreference = springDataMongoDbProperties.getReadPreference();
    readPreference = readPreference == null || readPreference.isEmpty() ? "secondaryPreferred" : readPreference;

    MongoClientOptions options = MongoClientOptions.builder()
            .readPreference(ReadPreference.valueOf(readPreference)).build();

    return new MongoClient(servers, mongoCredentialList, options);
}