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:com.englishtown.vertx.GridFSModule.java

License:Open Source License

@Override
public void start() {
    eb = vertx.eventBus();/*from www . jav  a2 s.co  m*/
    logger = container.logger();

    JsonObject config = container.config();
    address = config.getString("address", DEFAULT_ADDRESS);

    host = config.getString("host", "localhost");
    port = config.getInteger("port", 27017);
    dbName = config.getString("db_name", "default_db");
    username = config.getString("username", null);
    password = config.getString("password", null);
    int poolSize = config.getInteger("pool_size", 10);

    JsonArray seedsProperty = config.getArray("seeds");

    try {
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(poolSize);
        if (seedsProperty == null) {
            ServerAddress address = new ServerAddress(host, port);
            mongo = new MongoClient(address, builder.build());
        } else {
            List<ServerAddress> seeds = makeSeeds(seedsProperty);
            mongo = new MongoClient(seeds, builder.build());
        }
        db = mongo.getDB(dbName);
        if (username != null && password != null) {
            db.authenticate(username, password.toCharArray());
        }
    } catch (UnknownHostException e) {
        logger.error("Failed to connect to mongo server", e);
    }

    // Main Message<JsonObject> handler that inspects an "action" field
    eb.registerHandler(address, this);

    // Message<byte[]> handler to save file chunks
    eb.registerHandler(address + "/saveChunk", new Handler<Message<Buffer>>() {
        @Override
        public void handle(Message<Buffer> message) {
            saveChunk(message);
        }
    });

}

From source file:com.englishtown.vertx.GridFSModule.java

License:Open Source License

private List<ServerAddress> makeSeeds(JsonArray seedsProperty) throws UnknownHostException {
    List<ServerAddress> seeds = new ArrayList<>();
    for (Object elem : seedsProperty) {
        JsonObject address = (JsonObject) elem;
        String host = address.getString("host");
        int port = address.getInteger("port");
        seeds.add(new ServerAddress(host, port));
    }/*from  w w w.  ja  v a2 s.c  o  m*/
    return seeds;
}

From source file:com.enitalk.configs.MongoConfig.java

@Override
@Bean//from w w w .  j  a v a  2s  . c  o  m
public Mongo mongo() throws Exception {
    return new MongoClient(singletonList(new ServerAddress(env.getProperty("mongo.host"), 27017)),
            singletonList(MongoCredential.createCredential(env.getProperty("mongo.user"), getDatabaseName(),
                    env.getProperty("mongo.pass").toCharArray())));
}

From source file:com.epam.dlab.billing.azure.MongoDbBillingClient.java

License:Apache License

public MongoDbBillingClient(String host, int port, String databaseName, String username, String password) {
    this.client = new MongoClient(new ServerAddress(host, port), Lists
            .newArrayList(MongoCredential.createCredential(username, databaseName, password.toCharArray())));

    this.database = client.getDatabase(databaseName);
}

From source file:com.epam.dlab.mongo.MongoDbConnection.java

License:Apache License

/**
 * Instantiate the helper for Mongo database adapter.
 *
 * @param host         the host name./*www.  j ava2s .  c o m*/
 * @param port         the port.
 * @param databaseName the name of database.
 * @param username     the name of user.
 * @param password     the password.
 * @throws AdapterException
 */
public MongoDbConnection(String host, int port, String databaseName, String username, String password)
        throws AdapterException {
    try {
        client = new MongoClient(new ServerAddress(host, port), Collections.singletonList(
                MongoCredential.createCredential(username, databaseName, password.toCharArray())));
        database = client.getDatabase(databaseName).withWriteConcern(WriteConcern.ACKNOWLEDGED);
    } catch (Exception e) {
        throw new AdapterException(
                "Cannot create connection to database " + databaseName + ". " + e.getLocalizedMessage(), e);
    }
}

From source file:com.epam.dlab.mongo.MongoServiceFactory.java

License:Apache License

public MongoService build(Environment environment) {
    MongoClient client = new MongoClient(new ServerAddress(host, port), Collections
            .singletonList(MongoCredential.createCredential(username, database, password.toCharArray())));
    environment.lifecycle().manage(new Managed() {
        @Override/*w w w. j  av a2  s  .  c  o  m*/
        public void start() {
        }

        @Override
        public void stop() {
            client.close();
        }
    });
    return new MongoService(client, database);
}

From source file:com.epam.ta.reportportal.config.MongodbConfiguration.java

License:Open Source License

@Bean
@Profile("!unittest")
MongoClient mongo() throws UnknownHostException {
    MongoClientOptions.Builder mongoClientBuilder = MongoClientOptions.builder();
    mongoClientBuilder.connectionsPerHost(mongoProperties.getConnectionsPerHost())
            .threadsAllowedToBlockForConnectionMultiplier(
                    mongoProperties.getThreadsAllowedToBlockForConnectionMultiplier())
            .connectTimeout(mongoProperties.getConnectTimeout())
            .socketTimeout(mongoProperties.getSocketTimeout()).maxWaitTime(mongoProperties.getMaxWaitTime())
            .socketKeepAlive(mongoProperties.getSocketKeepAlive());

    List<MongoCredential> credentials = Collections.emptyList();
    if (!Strings.isNullOrEmpty(mongoProperties.getUser())
            && !Strings.isNullOrEmpty(mongoProperties.getPassword())) {
        credentials = Collections.singletonList(MongoCredential.createCredential(mongoProperties.getUser(),
                mongoProperties.getDbName(), mongoProperties.getPassword().toCharArray()));
    }/*  ww  w .j a va 2 s .  c  o m*/

    return new MongoClient(new ServerAddress(mongoProperties.getHost(), mongoProperties.getPort()), credentials,
            mongoClientBuilder.build());
}

From source file:com.erudika.para.persistence.MongoDBUtils.java

License:Apache License

/**
 * Returns a client instance for MongoDB
 * @return a client that talks to MongoDB
 *//* w  ww .  j ava  2s  . c  o m*/
public static MongoDatabase getClient() {
    if (mongodb != null) {
        return mongodb;
    }

    logger.info("MongoDB host: " + DBHOST + ":" + DBPORT + ", database: " + DBNAME);
    ServerAddress s = new ServerAddress(DBHOST, DBPORT);
    if (!StringUtils.isBlank(DBUSER) && !StringUtils.isBlank(DBPASS)) {
        MongoCredential credential = MongoCredential.createCredential(DBUSER, DBNAME, DBPASS.toCharArray());
        mongodbClient = new MongoClient(s, Arrays.asList(credential));
    } else {
        mongodbClient = new MongoClient(s);
    }

    mongodb = mongodbClient.getDatabase(DBNAME);

    if (!existsTable(Config.APP_NAME_NS)) {
        createTable(Config.APP_NAME_NS);
    }

    // We don't have access to Para.addDestroyListener() here.
    // Users will be responsible for calling shutDownClient().

    return mongodb;
}

From source file:com.focusit.log4jmongo.appender.SimpleMongoDbAppender.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 ww  . j  a  v a2s. co  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(final String hostname, final String port) {
    final List<ServerAddress> addresses = new ArrayList<ServerAddress>();

    final String[] hosts = hostname.split(" ");
    final 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 {
        final 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 {
            final boolean onePort = (portNums.size() == 1);

            int i = 0;
            for (final String host : hosts) {
                final int portNum = (onePort) ? portNums.get(0) : portNums.get(i);
                addresses.add(new ServerAddress(host.trim(), portNum));
                i++;
            }
        }
    }
    return addresses;
}

From source file:com.foodtruckdata.mongodb.UsersInput.java

public UsersInput(String host, int port, String db, String userName, String passwd)
        throws UnknownHostException {
    MongoCredential credential = MongoCredential.createMongoCRCredential(userName, db, passwd.toCharArray());
    MongoClient mongoClient = new MongoClient(new ServerAddress(host, port), Arrays.asList(credential));
    mongoDB = mongoClient.getDB(db);/*from   w w  w  .j av a 2 s .c om*/
}