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.handu.open.dubbo.monitor.config.MongoConfig.java

License:Apache License

@Override
@Bean//  w  ww  . ja v a  2s .  co  m
public Mongo mongo() throws Exception {
    final String url = Preconditions.checkNotNull(env.getProperty(DB_URL));
    final int port = Integer.parseInt(env.getProperty(DB_PORT, "27017"));
    final String username = env.getProperty(DB_USERNAME);
    final String database = env.getProperty(DB_DATABASE);
    final String password = env.getProperty(DB_PASSWORD);

    return new MongoClient(singletonList(new ServerAddress(url, port)),
            singletonList(MongoCredential.createCredential(username, database, password.toCharArray())));
}

From source file:com.hangum.tadpole.mongodb.core.connection.MongoConnectionManager.java

License:Open Source License

/**
 * //from   ww  w .  jav  a 2 s .  c  o m
 * @param userDB
 * @return
 * @throws Exception
 */
public static DB getInstance(UserDBDAO userDB) throws MongoDBNotFoundException, Exception {
    DB db = null;

    synchronized (dbManager) {

        try {
            String searchKey = getKey(userDB);
            Mongo mongoDB = dbManager.get(searchKey);

            if (mongoDB == null) {
                final MongoOptions options = new MongoOptions();
                options.connectionsPerHost = 20;
                options.threadsAllowedToBlockForConnectionMultiplier = 5;
                options.maxWaitTime = 120000;
                options.autoConnectRetry = false;
                options.safe = true;

                String strReplcaSet = userDB.getExt1();
                if (strReplcaSet == null | "".equals(strReplcaSet)) {
                    mongoDB = new Mongo(new DBAddress(userDB.getUrl()), options);

                } else {
                    List<ServerAddress> listServerList = new ArrayList<ServerAddress>();
                    listServerList.add(new ServerAddress(userDB.getHost(), Integer.parseInt(userDB.getPort())));

                    String[] urls = StringUtils.split(strReplcaSet, ",");
                    for (String ipPort : urls) {
                        String[] strIpPort = StringUtils.split(ipPort, ":");

                        listServerList.add(new ServerAddress(strIpPort[0], Integer.parseInt(strIpPort[1])));
                    }
                    //                  options.setReadPreference(ReadPreference.primary());

                    mongoDB = new Mongo(listServerList, options);
                }

                // password ?.
                db = mongoDB.getDB(userDB.getDb());
                if (!"".equals(userDB.getUsers())) { //$NON-NLS-1$
                    // pass change
                    String passwdDecrypt = "";
                    try {
                        passwdDecrypt = CipherManager.getInstance().decryption(userDB.getPasswd());
                    } catch (Exception e) {
                        passwdDecrypt = userDB.getPasswd();
                    }

                    boolean auth = db.authenticate(userDB.getUsers(), passwdDecrypt.toCharArray());
                    if (!auth) {
                        throw new Exception(Messages.MongoDBConnection_3);
                    }
                }

                //               
                //                ?   ? ? .
                //               
                //               // db  .
                //               List<String> listDB = mongoDB.getDatabaseNames();
                //               boolean isDB = false;
                //               for (String dbName : listDB) if(userDB.getDb().equals(dbName)) isDB = true;                  
                //               if(!isDB) {
                //                  throw new MongoDBNotFoundException(userDB.getDb() + Messages.MongoDBConnection_0);
                //               }
                try {
                    // ? ? ?  ?    .
                    db.getCollectionNames();
                } catch (Exception e) {
                    logger.error("error", e);
                    throw new MongoDBNotFoundException(userDB.getDb() + " " + e.getMessage());//Messages.MongoDBConnection_0);
                }

                // db map? .
                dbManager.put(searchKey, mongoDB);

            } else {
                db = mongoDB.getDB(userDB.getDb());
            }

        } catch (Exception e) {
            logger.error("mongodb connection error", e);
            throw e;
        }
    }

    return db;

}

From source file:com.hangum.tadpole.mongodb.core.test.ReplicaSetConnnection.java

License:Open Source License

/**
 * mongo db .//  w  w w .  j a  v a 2  s  .c  o m
 * 
 * @return
 */
public Mongo connection(String uri, int port) throws Exception {
    List<ServerAddress> listServerList = new ArrayList<ServerAddress>();

    listServerList.add(new ServerAddress(serverurl, port));

    String[] urls = StringUtils.split(SERVER_URL, ",");
    for (String ipPort : urls) {
        String[] strIpPort = StringUtils.split(ipPort, ":");

        listServerList.add(new ServerAddress(strIpPort[0], Integer.parseInt(strIpPort[1])));
    }

    Mongo m = null;
    //      try {
    m = new Mongo(listServerList);//uri, port);
    //         List<String> listDB = m.getDatabaseNames();
    //         for (String dbName : listDB) {
    //            System.out.println(dbName);
    //         }

    // authentication(optional)
    // boolean auth = db.authenticate(myUserName, myPassword);

    //      } catch (UnknownHostException e) {
    //         e.printStackTrace();
    //      } catch (MongoException e) {
    //         e.printStackTrace();
    //      }

    return m;
}

From source file:com.health.smart.util.MongoC.java

private static synchronized MongoClient getClient() throws UnknownHostException {
    if (client == null) {
        MongoCredential credential = MongoCredential.createMongoCRCredential("m.smart.health", "comp5527",
                "comp5527g3".toCharArray());
        client = new MongoClient(new ServerAddress("ds031947.mongolab.com", 31947), Arrays.asList(credential));
    }/*from w  ww  . j  av a  2  s . co  m*/
    return client;
}

From source file:com.heisenberg.mongo.MongoWorkflowEngineConfiguration.java

License:Apache License

protected static ServerAddress createServerAddress(String host, Integer port) {
    try {/*from www. jav  a  2s . co m*/
        if (port != null) {
            return new ServerAddress(host, port);
        }
        return new ServerAddress(host);
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.ibm.haac.hx.engine.tool.mongodb.MongoDBAccess.java

License:Open Source License

public MongoDBAccess() throws Exception {

    try {/*from ww  w . j  av a  2  s .com*/

        if (mongoUri != null && !mongoUri.trim().equals("")) {
            System.out.println("Use mongo connection uri");
            mongoUri = mongoUri.trim();
            // http://stackoverflow.com/questions/15052074/connecting-a-mongodb-created-in-mongolab-through-a-java-application
            MongoClientURI uri = new MongoClientURI(mongoUri);
            this.mongoClient = new MongoClient(uri);
            int index = mongoUri.lastIndexOf("/");
            dbName = mongoUri.substring(index + 1);
        } else {
            System.out.println("Use mongo database connection properties");
            MongoCredential credential = MongoCredential.createMongoCRCredential(userName, dbName,
                    pwd.toCharArray());

            // connect to the server
            this.mongoClient = new MongoClient(new ServerAddress(serverIP, serverPort),
                    Arrays.asList(credential));
        }
        // attach to the database
        this.db = this.mongoClient.getDB(dbName);

        morphia = new Morphia();
        if (morphiaDatastore == null)
            morphiaDatastore = morphia.createDatastore(this.mongoClient, dbName);

        ensureEntities();

        this.mongoConnected = true;

    } catch (MongoException e) {
        throw new Exception("MongoDB exception: " + e.getMessage());
    } catch (UnknownHostException e) {
        throw new Exception("MongoDB UnknownHostException exception: " + e.getMessage());
    }
}

From source file:com.images3.data.impl.MongoDBAccessProvider.java

License:Apache License

private void initMongoClient() {
    String url = config.getProperty("mongodb.url");
    int port = Integer.valueOf(config.getProperty("mongodb.port"));
    String username = config.getProperty("mongodb.username");
    String password = config.getProperty("mongodb.password");
    try {//from  w  ww .j  a  v a 2s  .c  om
        if (username.trim().length() == 0) {
            this.mongoClient = new MongoClient(new ServerAddress(url, port));
        } else {
            MongoCredential credential = MongoCredential.createMongoCRCredential(username, DBNAME,
                    password.toCharArray());
            this.mongoClient = new MongoClient(new ServerAddress(url, port), Arrays.asList(credential));
        }
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.impetus.client.mongodb.MongoDBClientFactory.java

License:Apache License

/**
 * On set mongo server properties.//from w w  w. j  a va 2s  .co m
 * 
 * @param contactNode
 *            the contact node
 * @param defaultPort
 *            the default port
 * @param poolSize
 *            the pool size
 * @param addrs
 *            the addrs
 * @return the mongo client
 * @throws UnknownHostException
 *             the unknown host exception
 */
private MongoClient onSetMongoServerProperties(String contactNode, String defaultPort, String poolSize,
        List<ServerAddress> addrs) throws UnknownHostException {
    MongoClient mongo = null;
    MongoClientOptions mo = null;
    MongoDBSchemaMetadata metadata = MongoDBPropertyReader.msmd;
    ClientProperties cp = metadata != null ? metadata.getClientProperties() : null;
    Properties propsFromCp = null;
    if (cp != null) {
        DataStore dataStore = metadata != null ? metadata.getDataStore() : null;
        List<Server> servers = dataStore != null && dataStore.getConnection() != null
                ? dataStore.getConnection().getServers()
                : null;
        if (servers != null && !servers.isEmpty()) {
            for (Server server : servers) {
                addrs.add(
                        new ServerAddress(server.getHost().trim(), Integer.parseInt(server.getPort().trim())));
            }
        }

        propsFromCp = dataStore != null && dataStore.getConnection() != null
                ? dataStore.getConnection().getProperties()
                : null;
    } else {
        for (String node : contactNode.split(Constants.COMMA)) {
            if (StringUtils.countMatches(node, Constants.COLON) == 1) {
                // node is given with hostname and port
                // count == 1 is to exclude IPv6 addresses
                String host = node.split(":")[0];
                int port = Integer.parseInt(node.split(Constants.COLON)[1]);

                addrs.add(new ServerAddress(host.trim(), port));
            } else {
                addrs.add(new ServerAddress(node.trim(), Integer.parseInt(defaultPort.trim())));
            }
        }
    }

    MongoClientOptions.Builder b = new PopulateMongoOptions(propsFromCp, externalProperties).prepareBuilder();
    mo = b.build();

    if (mo.getConnectionsPerHost() <= 0 && !StringUtils.isEmpty(poolSize)) {
        mo = b.connectionsPerHost(Integer.parseInt(poolSize)).build();
    }

    mongo = new MongoClient(addrs, mo);

    return mongo;
}

From source file:com.ineunet.knife.persist.mongo.MongoDBServerImpl.java

License:Apache License

public MongoDBServerImpl() throws Exception {
    String url = ConfigFactory.getKnifeConfig().get(ConfigKeysDB.mongo_db_addr, "localhost");
    this.dbName = ConfigFactory.getKnifeConfig().get(ConfigKeysDB.mongo_db_defaultdb, "knife");
    String[] addrs = url.split(",");
    List<ServerAddress> sa = new ArrayList<ServerAddress>();
    for (String ad : addrs) {
        String[] tmp = ad.split(":");
        if (tmp.length == 1) {
            sa.add(new ServerAddress(tmp[0], defaultPort));
        } else {//  w ww.ja va 2  s.c  o m
            sa.add(new ServerAddress(tmp[0], Integer.parseInt(tmp[1])));
        }
    }

    this.mongo = new Mongo(sa);
    mongo.setWriteConcern(WriteConcern.SAFE);
}

From source file:com.jaeksoft.searchlib.crawler.database.DatabaseCrawlMongoDb.java

License:Open Source License

MongoClient getMongoClient() throws URISyntaxException, UnknownHostException {
    String user = getUser();/*from   ww w. ja  v  a2s .  c  o  m*/
    String password = getPassword();
    URI uri = new URI(getUrl());
    MongoCredential credential = null;
    if (!StringUtils.isEmpty(user) && !StringUtils.isEmpty(password)) {
        credential = MongoCredential.createMongoCRCredential(user, databaseName, password.toCharArray());
        return new MongoClient(new ServerAddress(uri.getHost(), uri.getPort()), Arrays.asList(credential));
    }
    return new MongoClient(new ServerAddress(uri.getHost(), uri.getPort()));
}