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:fr.cnes.sitools.datasource.mongodb.business.SitoolsMongoDBDataSourceFactory.java

License:Open Source License

/**
 * Setup a dataSource for "users". Usage is for all users for consultation functions.
 * //from www.ja va2  s  .  c  o m
 * @param dataSource
 *          the DataSource to update
 * @return SitoolsDataSource the new DataSource
 */
public SitoolsMongoDBDataSource setupDataSourceForUsers(MongoDBDataSource dataSource) {
    String key = dataSource.getId();
    SitoolsMongoDBDataSource foundDatasource = dataSources.get(key);
    if (foundDatasource == null) {

        Mongo mongo = null;
        try {
            MongoOptions options = new MongoOptions();
            ServerAddress address = new ServerAddress(dataSource.getUrl(), dataSource.getPortNumber());
            options.setConnectionsPerHost(dataSource.getMaxActive());
            mongo = new Mongo(address, options);
        } catch (UnknownHostException e) {
            logger.log(Level.INFO, null, e);
        } catch (MongoException e) {
            logger.log(Level.INFO, null, e);
        }

        foundDatasource = new SitoolsMongoDBDataSource(dataSource, mongo);
        dataSources.put(key, foundDatasource);
    }
    return foundDatasource;
}

From source file:fr.eolya.utils.nosql.mongodb.MongoDBConnection.java

License:Apache License

/**
 * @param hostName         The MongoDB server host name
 * @param hostPort         The MongoDB server host port
 * @return//from w  w  w.j  ava  2s  .c  o m
 * @throws UnknownHostException 
 */
public MongoDBConnection(String hostName, int hostPort, String userName, String userPassword)
        throws UnknownHostException {

    MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
    builder.autoConnectRetry(true);
    builder.socketKeepAlive(true);
    builder.writeConcern(WriteConcern.SAFE);

    if ("".equals(hostName))
        hostName = "localhost";
    if (hostPort > 0) {
        ServerAddress addr = new ServerAddress(hostName, hostPort);
        m = new MongoClient(addr, builder.build());
    } else {
        m = new MongoClient(hostName, builder.build());
    }
    this.hostName = hostName;
    this.hostPort = hostPort;
}

From source file:fr.wseduc.gridfs.GridFSPersistor.java

License:Apache License

public void start() {
    super.start();

    address = getOptionalStringConfig("address", "vertx.gridfspersistor");

    host = getOptionalStringConfig("host", "localhost");
    port = getOptionalIntConfig("port", 27017);
    dbName = getOptionalStringConfig("db_name", "default_db");
    username = getOptionalStringConfig("username", null);
    password = getOptionalStringConfig("password", null);
    ReadPreference readPreference = ReadPreference
            .valueOf(getOptionalStringConfig("read_preference", "primary"));
    int poolSize = getOptionalIntConfig("pool_size", 10);
    boolean autoConnectRetry = getOptionalBooleanConfig("auto_connect_retry", true);
    int socketTimeout = getOptionalIntConfig("socket_timeout", 60000);
    boolean useSSL = getOptionalBooleanConfig("use_ssl", false);
    JsonArray seedsProperty = config.getArray("seeds");
    bucket = getOptionalStringConfig("bucket", "fs");

    try {/*from  ww  w  .  j a  va 2s  . com*/
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(poolSize);
        builder.autoConnectRetry(autoConnectRetry);
        builder.socketTimeout(socketTimeout);
        builder.readPreference(readPreference);

        if (useSSL) {
            builder.socketFactory(SSLSocketFactory.getDefault());
        }

        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);
    }
    eb.registerHandler(address, this);
    eb.registerHandler(address + ".json", new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> message) {
            String action = message.body().getString("action", "");
            switch (action) {
            case "write":
                writeTo(message);
                break;
            default:
                sendError(message, "Invalid action");
            }
        }
    });
}

From source file:fr.wseduc.resizer.GridFsFileAccess.java

License:Apache License

public GridFsFileAccess(String host, int port, String dbName, String username, String password, int poolSize)
        throws UnknownHostException {
    MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
    builder.connectionsPerHost(poolSize);
    ServerAddress address = new ServerAddress(host, port);
    mongo = new MongoClient(address, builder.build());
    db = mongo.getDB(dbName);/*from   w  w w.j  a v  a 2  s.co  m*/
    if (username != null && password != null) {
        db.authenticate(username, password.toCharArray());
    }
}

From source file:gov.llnl.iscr.iris.MongoInstance.java

License:Open Source License

/**
 * creates a MongoInstance instance and/*ww  w  .j  a  v  a2s  .c  o  m*/
 * calls {@link MongoInstance#getMongo(String)} with given host address and port number used to instantiate a
 * Mongo instance based on a (single) mongo node
 * @param host server to connect to
 * @param port the port on which the database is running
 */
public MongoInstance(String host, int port) {
    String hostAddress;
    try {
        hostAddress = (new ServerAddress(host, port)).toString();
        MongoInstance.getMongo(URIprefix + hostAddress);
    } catch (UnknownHostException e) {
        System.err.println("Host cannot be resolved: " + e);
    }

}

From source file:gov.llnl.iscr.iris.MongoInstance.java

License:Open Source License

/**
 * creates a MongoInstance instance,//  w  w  w  .  j a  va 2 s.  c  o  m
 * calls {@link MongoInstance#getMongo(String)} with given host address and port number used to instantiate a
 * Mongo instance based on a (single) mongo node, and
 * automatically connects to the given database name
 * @param host server to connect to
 * @param port the port on which the database is running
 * @param dbname the database name that specifies location for retrieving collections
 */
public MongoInstance(String host, int port, String dbname) {
    String hostAddress;
    try {
        hostAddress = (new ServerAddress(host, port)).toString();
        db = MongoInstance.getMongo(URIprefix + hostAddress).getDB(dbname);
    } catch (UnknownHostException e) {
        System.err.println("Could NOT connect to Mongo: check hostname provided");
        e.printStackTrace();
    }

}

From source file:HAL.libraries.blackboard_client.BlackboardClient.java

License:Open Source License

/**
 * Constructs a BlackboardClient for the server at the specified host and port.
 *
 * @param host The ip of the MongoDB host.
 * @param port The port of the MongoDB host.
 * @throws MongoConnectionException Connecting to the database failed.
 * @throws UnknownHostException The IP address of a host could not be determined.
 **//*ww w. j a  va2 s.  c o  m*/
public BlackboardClient(String host, int port) throws UnknownHostException, GeneralMongoException {
    this.subscriptions = new ArrayList<BlackboardSubscription>();
    this.mongo = MongoDBConnection.getInstanceForHost(new ServerAddress(host, port)).getMongoClient();
}

From source file:henu.util.NosqlDB.java

public static MongoDatabase getMongoDataBaseByAuth() {

    try {//from w  w w  .  jav a2s .c om

        //MongoDB? ??localhost??IP?  
        //ServerAddress()? ??  ? 
        ServerAddress serverAddress = new ServerAddress(ADDRESS, PORT);
        List<ServerAddress> addrs = new ArrayList<ServerAddress>();
        addrs.add(serverAddress);

        //MongoCredential.createScramSha1Credential()? ?? ??? ?  
        MongoCredential credential = MongoCredential.createScramSha1Credential(USERNAME, DBNAME,
                PASSWORD.toCharArray());
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();
        credentials.add(credential);

        //??MongoDB  
        MongoClient mongoClient = new MongoClient(addrs, credentials);

        // ?
        MongoDatabase mongoDatabase = mongoClient.getDatabase(DBNAME);
        System.out.println("Connect to database successfully");

        return mongoDatabase;
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }

    return null;
}

From source file:in.mtap.iincube.mongoser.config.MongoConfig.java

License:Apache License

private List<ServerAddress> toAddress(String servers) throws UnknownHostException {
    List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
    servers = servers.trim();/* w ww.j  a  v a 2 s  . c  om*/
    String[] arrServer = servers.split("[,]");
    for (String server : arrServer) {
        String[] hostPort = server.split("[:]");
        if (hostPort.length != 2) {
            throw new IllegalArgumentException("Mongo servers should be in `server:port` format");
        }
        try {
            int port = Integer.parseInt(hostPort[1]);
            serverAddresses.add(new ServerAddress(hostPort[0], port));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Cannot parse port: " + hostPort[1]);
        }
    }
    return serverAddresses;
}

From source file:io.awacs.repository.MongoRepository.java

License:Apache License

@Override
public void init(Configuration configuration) throws InitializationException {
    try {//from   w  w w  .j  a va  2 s.  co m
        String[] addrs = configuration.getString(ADDRESS, DEFAULT_ADDRESS).split(",");
        List<ServerAddress> addresses = new LinkedList<>();
        for (String addr : addrs) {
            String[] hostport = addr.split(":");
            addresses.add(new ServerAddress(hostport[0], Integer.valueOf(hostport[1])));
        }

        String db = configuration.getString(DB, DEFAULT_DB);

        List<MongoCredential> credentials = new LinkedList<>();
        String[] creds = configuration.getString(CREDENTIAL, DEFAULT_CREDENTIAL).split(",");
        if (!creds[0].equals("")) {
            for (String credential : creds) {
                int _1split = credential.indexOf(':');
                int _2split = credential.indexOf('@');
                if (_1split == -1 || _2split == -1) {
                    throw new MongoSecurityException(null, credential);
                }
                String username = credential.substring(0, _1split);
                String password = credential.substring(_1split + 1, _2split);
                String authDb = credential.substring(_2split + 1);
                credentials.add(MongoCredential.createCredential(username, authDb, password.toCharArray()));
            }
        }
        mongoConnection = new MongoConnection(addresses, credentials, db);
    } catch (Exception e) {
        e.printStackTrace();
        throw new InitializationException();
    }
}