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.dawsonsystems.session.MongoManager.java

License:Apache License

private void initDbConnection(String path) throws LifecycleException {
    try {/*from  ww w.j  a  va 2s .  c  o m*/
        String[] hosts = getHost().split(",");

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

        for (String host : hosts) {
            addrs.add(new ServerAddress(host, getPort()));
        }

        mongo = new MongoClient(addrs,
                MongoClientOptions.builder().description("TomcatMongoSession[path=" + path + "]")
                        .alwaysUseMBeans(true).connectionsPerHost(connectionsPerHost).build());

        db = mongo.getDatabase(getDatabase());
        if (slaveOk) {
            db.withReadPreference(ReadPreference.secondaryPreferred());
        }
        db.withWriteConcern(WriteConcern.ACKNOWLEDGED);
        getCollection().createIndex(new BasicDBObject("lastmodified", 1));
        log.info("Connected to Mongo " + host + "/" + database + " for session storage, slaveOk=" + slaveOk
                + ", " + (getMaxInactiveInterval() * 1000) + " session live time");
    } catch (RuntimeException e) {
        e.printStackTrace();
        throw new LifecycleException("Error Connecting to Mongo", e);
    }
}

From source file:com.dawsonsystems.session.MongoSessionManager.java

License:Apache License

@SuppressWarnings("deprecation")
private void initDbConnection() throws LifecycleException {
    try {/*from   w w w.  j a  v a2  s  . c om*/
        String[] hosts = getHost().split(",");

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

        for (String host : hosts) {
            addrs.add(new ServerAddress(host, getPort()));
        }
        mongo = new MongoClient(addrs);
        db = mongo.getDB(getDatabase());
        if (slaveOk) {
            db.slaveOk();
        }
        getCollection().ensureIndex(new BasicDBObject("lastmodified", 1));
        log.info("Connected to Mongo " + host + "/" + database + " for session storage, slaveOk=" + slaveOk
                + ", " + (getMaxInactiveInterval() * 1000) + " session live time");
    } catch (IOException e) {
        e.printStackTrace();
        throw new LifecycleException("Error Connecting to Mongo", e);
    }
}

From source file:com.ebay.jetstream.config.mongo.MongoConnection.java

License:MIT License

public MongoConnection(MongoConfiguration mongoConfiguration) {

    List<ServerAddress> hosts = new ArrayList<ServerAddress>();
    for (String host : mongoConfiguration.getHosts()) {
        try {/* w  w w .j av a 2 s  .  c o m*/
            hosts.add(new ServerAddress(host, Integer.valueOf(mongoConfiguration.getPort())));
        } catch (UnknownHostException e) {
        }
    }

    Mongo mongo = null;
    mongo = new Mongo(hosts);
    db = mongo.getDB(mongoConfiguration.getDb());

    authenticate(mongoConfiguration);
}

From source file:com.ebay.jetstream.config.mongo.MongoConnection.java

License:MIT License

public MongoConnection(List<String> hostStrings, String port, String database) {

    List<ServerAddress> hosts = new ArrayList<ServerAddress>();
    for (String host : hostStrings) {
        try {/*from  w w w . j  a  va 2  s.c o  m*/
            hosts.add(new ServerAddress(host, Integer.valueOf(port)));
        } catch (UnknownHostException e) {
        }
    }

    Mongo mongo = null;
    mongo = new Mongo(hosts);
    db = mongo.getDB(database);

}

From source file:com.eclipsesource.connect.persistence.util.MongoDBClientFactory.java

License:Open Source License

private MongoDatabase doCreateDB(String host, String dbName, int port, String user, String password)
        throws UnknownHostException {
    if (client != null) {
        client.close();/*from ww  w .  j a  va2s  .  co  m*/
    }
    if (user != null && password != null) {
        MongoCredential credential = MongoCredential.createCredential(user, "admin", password.toCharArray());
        client = new MongoClient(new ServerAddress(host, port), Lists.newArrayList(credential));
    } else {
        client = new MongoClient(host, port);
    }
    return client.getDatabase(dbName);
}

From source file:com.edgytech.umongo.MainMenu.java

License:Apache License

public void connect() {
    try {/*from  w  w w. j  av a  2  s .  c  o  m*/
        ConnectDialog dialog = (ConnectDialog) getBoundUnit(Item.connectDialog);
        ProgressDialog progress = (ProgressDialog) getBoundUnit(Item.connectProgressDialog);
        MongoClient mongo = null;
        List<String> dbs = new ArrayList<String>();
        String uri = dialog.getStringFieldValue(ConnectDialog.Item.uri);
        if (!uri.trim().isEmpty()) {
            if (!uri.startsWith(MongoURI.MONGODB_PREFIX)) {
                uri = MongoURI.MONGODB_PREFIX + uri;
            }
            MongoClientURI muri = new MongoClientURI(uri);
            mongo = new MongoClient(muri);
            String db = muri.getDatabase();
            if (db != null && !db.trim().isEmpty()) {
                dbs.add(db.trim());
            }
        } else {
            String servers = dialog.getStringFieldValue(ConnectDialog.Item.servers);
            if (servers.trim().isEmpty()) {
                return;
            }
            String[] serverList = servers.split(",");
            ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
            for (String server : serverList) {
                String[] tmp = server.split(":");
                if (tmp.length > 1) {
                    addrs.add(new ServerAddress(tmp[0], Integer.valueOf(tmp[1]).intValue()));
                } else {
                    addrs.add(new ServerAddress(tmp[0]));
                }
            }
            if ("Direct".equals(dialog.getStringFieldValue(ConnectDialog.Item.connectionMode)))
                mongo = new MongoClient(addrs.get(0), dialog.getMongoClientOptions());
            else
                mongo = new MongoClient(addrs, dialog.getMongoClientOptions());

            String sdbs = dialog.getStringFieldValue(ConnectDialog.Item.databases);
            if (!sdbs.trim().isEmpty()) {
                for (String db : sdbs.split(",")) {
                    dbs.add(db.trim());
                }
            }
        }

        if (dbs.size() == 0) {
            dbs = null;
        }

        String user = dialog.getStringFieldValue(ConnectDialog.Item.user).trim();
        String password = dialog.getStringFieldValue(ConnectDialog.Item.password);
        if (!user.isEmpty()) {
            // authenticate against all dbs
            if (dbs != null) {
                for (String db : dbs) {
                    mongo.getDB(db).authenticate(user, password.toCharArray());
                }
            } else {
                mongo.getDB("admin").authenticate(user, password.toCharArray());
            }
        }

        final MongoClient fmongo = mongo;
        final List<String> fdbs = dbs;
        // doing in background can mean concurrent modification, but dialog is modal so unlikely
        progress.show(new ProgressDialogWorker(progress) {
            @Override
            protected void finished() {
            }

            @Override
            protected Object doInBackground() throws Exception {
                UMongo.instance.addMongoClient(fmongo, fdbs);
                return null;
            }
        });

    } catch (Exception ex) {
        UMongo.instance.showError(id, ex);
    }
}

From source file:com.edgytech.umongo.RouterNode.java

License:Apache License

@Override
protected void populateChildren() {
    CommandResult res = mongo.getDB("admin").command("listShards");
    shards = (BasicDBList) res.get("shards");
    if (shards == null) {
        return;/* w ww .  ja v  a2  s.  c  o  m*/
    }

    for (Object obj : shards) {
        try {
            DBObject shard = (DBObject) obj;
            String shardName = (String) shard.get("_id");
            String hosts = (String) shard.get("host");
            String repl = null;
            int slash = hosts.indexOf('/');
            if (slash >= 0) {
                repl = hosts.substring(0, slash);
                hosts = hosts.substring(slash + 1);
            }

            String[] hostList = hosts.split(",");
            ArrayList<ServerAddress> addrs = new ArrayList<ServerAddress>();
            for (String host : hostList) {
                int colon = host.indexOf(':');
                if (colon >= 0) {
                    addrs.add(new ServerAddress(host.substring(0, colon),
                            Integer.parseInt(host.substring(colon + 1))));
                } else {
                    addrs.add(new ServerAddress(host));
                }
            }

            if (repl != null || addrs.size() > 1) {
                addChild(new ReplSetNode(repl, addrs, mongo.getMongoClientOptions(), shardName));
            } else {
                addChild(new ServerNode(addrs.get(0), mongo.getMongoClientOptions(), false, false));
            }
        } catch (Exception e) {
            getLogger().log(Level.WARNING, null, e);
        }
    }

    // add config servers
    try {
        res = mongo.getDB("admin").command("getCmdLineOpts");
        String configStr = (String) ((BasicDBObject) res.get("parsed")).get("configdb");
        String[] configsvrs = configStr.split(",");
        for (String host : configsvrs) {
            int colon = host.indexOf(':');
            ServerAddress addr;
            if (colon >= 0) {
                addr = new ServerAddress(host.substring(0, colon), Integer.parseInt(host.substring(colon + 1)));
            } else {
                addr = new ServerAddress(host);
            }
            addChild(new ServerNode(addr, mongo.getMongoClientOptions(), false, true));
        }
    } catch (Exception e) {
        getLogger().log(Level.WARNING, null, e);
    }
}

From source file:com.effektif.mongo.MongoConfiguration.java

License:Apache License

protected static ServerAddress createServerAddress(String host, Integer port) {
    try {//from w w  w .  j  av  a  2s . c om
        if (port != null) {
            return new ServerAddress(host, port);
        }
        return new ServerAddress(host);
    } catch (IllegalArgumentException | MongoException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.eightkdata.mongowp.client.wrapper.MongoClientWrapper.java

License:Open Source License

@Inject
public MongoClientWrapper(MongoClientConfiguration configuration) throws UnreachableMongoServerException {
    try {//  w ww  . j a v a  2 s .  c om
        MongoClientOptions options = toMongoClientOptions(configuration);
        ImmutableList<MongoCredential> credentials = toMongoCredentials(configuration);

        testAddress(configuration.getHostAndPort(), options);

        this.configuration = configuration;

        this.driverClient = new com.mongodb.MongoClient(
                new ServerAddress(configuration.getHostAndPort().getHostText(),
                        configuration.getHostAndPort().getPort()),
                credentials, options);

        version = calculateVersion();
        codecRegistry = CodecRegistries.fromCodecs(new DocumentCodec());
        closed = false;
    } catch (com.mongodb.MongoException ex) {
        throw new UnreachableMongoServerException(configuration.getHostAndPort(), ex);
    }
}

From source file:com.emuneee.camerasyncmanager.util.DatabaseUtil.java

License:Apache License

private void initMongoClient() throws UnknownHostException {
    sLogger.info("Initializing MongoDB Client");
    String dbUrl = mProperties.getProperty("DATABASE_URL");
    int port = Integer.parseInt(mProperties.getProperty("DATABASE_PORT"));
    sLogger.debug("Database URL: " + dbUrl);
    sLogger.debug("Database Port: " + String.valueOf(port));

    // create the mongo client and connect
    ServerAddress serverAddr = new ServerAddress(mProperties.getProperty("DATABASE_URL"),
            Integer.parseInt(mProperties.getProperty("DATABASE_PORT")));
    MongoCredential credential = MongoCredential.createMongoCRCredential(
            mProperties.getProperty("DATABASE_USER"), mProperties.getProperty("DATABASE_NAME"),
            mProperties.getProperty("DATABASE_AUTH").toCharArray());
    mMongoClient = new MongoClient(serverAddr, Arrays.asList(credential));
}