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:org.audit4j.mongodb.MongoRepository.java

@Override
public void createDataStore(String dataStoreName) throws HandlerException {
    MongoClient client;//from ww  w .j  a v  a  2  s  . c  o m
    List<ServerAddress> mongoServerAddresses = null;
    ServerAddress mongoServerAddress = null;
    List<MongoCredential> mongoCredentials = null;
    MongoCredential mongoCredential = null;

    if (serverAddresses != null && !serverAddresses.isEmpty() && serverAddresses.size() == 1) {
        mongoServerAddress = new ServerAddress(serverAddresses.get(0).getHost(),
                serverAddresses.get(0).getPort());
    }
    if (serverAddresses != null && !serverAddresses.isEmpty()) {
        mongoServerAddresses = new ArrayList<>();
        for (StoreServerAddress address : serverAddresses) {
            mongoServerAddresses.add(new ServerAddress(address.getHost(), address.getPort()));
        }
    }
    if (credentials != null && !credentials.isEmpty() && credentials.size() == 1) {
        mongoCredential = MongoCredential.createCredential(credentials.get(0).getUsername(), dbName.getName(),
                credentials.get(0).getPassword().toCharArray());
    }

    if (credentials != null && !credentials.isEmpty()) {
        mongoCredentials = new ArrayList<>();
        for (StoreCredential storeCredential : credentials) {
            mongoCredentials.add(MongoCredential.createCredential(storeCredential.getUsername(),
                    dbName.getName(), storeCredential.getPassword().toCharArray()));
        }
    }

    if (mongoServerAddress != null && mongoCredential == null && mongoCredentials == null) {
        client = new MongoClient(mongoServerAddress);
    } else if (mongoServerAddress != null && mongoCredentials != null && !mongoCredentials.isEmpty()) {
        client = new MongoClient(mongoServerAddress, mongoCredentials);
    } else if (mongoServerAddresses != null && !mongoServerAddresses.isEmpty() && mongoCredential == null
            && mongoCredentials == null) {
        client = new MongoClient(mongoServerAddresses);
    } else if (mongoServerAddresses != null && !mongoServerAddresses.isEmpty() && mongoCredentials != null
            && !mongoCredentials.isEmpty()) {
        client = new MongoClient(mongoServerAddresses, mongoCredentials);
    }
}

From source file:org.axway.grapes.server.db.mongo.MongodbHandler.java

public MongodbHandler(final DataBaseConfig config) throws UnknownHostException {
    final ServerAddress address = new ServerAddress(config.getHost(), config.getPort());
    final MongoClient mongo = new MongoClient(address);
    db = mongo.getDB(config.getDatastore());

    if (config.getUser() != null && config.getPwd() != null) {
        db.authenticate(config.getUser(), config.getPwd());
    }//from   w  ww. j  a v  a  2 s . c o m

    // Init credentials' cache
    credentialCache = CacheBuilder.newBuilder().maximumSize(1000)
            .build(new CacheLoader<String, DbCredential>() {
                public DbCredential load(String user) {
                    return getCredential(user);
                }
            });
}

From source file:org.benjp.services.mongodb.MongoBootstrap.java

License:Open Source License

private Mongo mongo() {
    if (m == null) {
        try {//from w  w w. ja v a2s .  co m
            if (PropertyManager.PROPERTY_SERVER_TYPE_EMBED
                    .equals(PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_TYPE))) {
                log.warning("WE WILL NOW USE MONGODB IN EMBED MODE...");
                log.warning("BE AWARE...");
                log.warning("EMBED MODE SHOULD NEVER BE USED IN PRODUCTION!");
                setupEmbedMongo();
            }

            MongoOptions options = new MongoOptions();
            options.connectionsPerHost = 200;
            options.connectTimeout = 60000;
            options.threadsAllowedToBlockForConnectionMultiplier = 10;
            options.autoConnectRetry = true;
            String host = PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_HOST);
            int port = Integer.parseInt(PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_PORT));
            m = new Mongo(new ServerAddress(host, port), options);
            m.setWriteConcern(WriteConcern.SAFE);
        } catch (UnknownHostException e) {
        } catch (IOException e) {
        }
    }
    return m;
}

From source file:org.benjp.services.mongodb.MongoBootstrap.java

License:Open Source License

private static Mongo setupEmbedMongo() throws IOException {
    MongodStarter runtime = MongodStarter.getDefaultInstance();
    int port = Integer.parseInt(PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_PORT));
    mongodExe = runtime.prepare(new MongodConfig(Version.V2_3_0, port, Network.localhostIsIPv6()));
    mongod = mongodExe.start();//w  ww.  j a v a2 s .  com
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        log.info(e.getMessage());
    }
    String host = PropertyManager.getProperty(PropertyManager.PROPERTY_SERVER_HOST);

    return new Mongo(new ServerAddress(host, port));
}

From source file:org.chililog.server.data.MongoConnection.java

License:Apache License

/**
 * <p>/*w w  w  .  j a  v a2 s.c om*/
 * Loads our mongoDB connection pool
 * </p>
 * <p>
 * This is a package scope method so that we can use it within our junit test cases. It should not be called from
 * real code.
 * </p>
 * 
 * @throws MongoException
 * @throws UnknownHostException
 * 
 */
void loadMongo() throws UnknownHostException, MongoException {
    AppProperties appProperties = AppProperties.getInstance();
    ServerAddress addr = new ServerAddress(appProperties.getDbIpAddress(), appProperties.getDbIpPort());
    MongoOptions options = new MongoOptions();
    options.connectionsPerHost = appProperties.getDbConnectionsPerHost();
    _mongo = new Mongo(addr, options);
}

From source file:org.chimi.s4s.storage.mongofs.MongoFSFileStorage.java

License:Apache License

public MongoFSFileStorage(String mongoHost, int mongoPort, int poolSize)
        throws UnknownHostException, MongoException {
    MongoOptions options = new MongoOptions();
    options.connectionsPerHost = poolSize;
    mongo = new Mongo(new ServerAddress(mongoHost, mongoPort), options);
}

From source file:org.clevermore.monitor.server.mongodb.MongoSessionFactory.java

License:Apache License

@Inject
public MongoSessionFactory() {
    mongoConfig = ConfigurationService.getInstance().getMongoConfig();

    if (!mongoConfig.getEnabled()) {
        logger.info("Mongo DB is disabled.Skipping initialization");
        return;/* w  ww  .j  a  va  2  s  . c  o  m*/
    }

    List<HostAddress> hosts = mongoConfig.getHosts();
    if (hosts == null || hosts.isEmpty()) {
        throw new RuntimeException("Mongo DB  Initialization Error: hosts not configured");
    }

    if (mongoConfig.getDatabaseName() == null || mongoConfig.getDatabaseName().isEmpty()) {
        throw new RuntimeException("Mongo DB Initialization Error : database name not specified");
    }

    List<ServerAddress> mongoServers = new ArrayList<ServerAddress>();
    for (HostAddress host : hosts) {
        try {
            mongoServers.add(new ServerAddress(host.getHostName(), host.getPort()));
        } catch (UnknownHostException e) {
            throw new RuntimeException("Mongo DB  Initialization Error ", e);
        }
    }

    mongo = new Mongo(mongoServers);
    morphia = new Morphia();
}

From source file:org.codinjutsu.tools.mongo.logic.MongoManager.java

License:Apache License

private MongoClient createMongoClient(ServerConfiguration configuration) throws UnknownHostException {
    List<String> serverUrls = configuration.getServerUrls();
    String username = configuration.getUsername();
    String password = configuration.getPassword();
    String userDatabase = configuration.getUserDatabase();
    if (serverUrls.isEmpty()) {
        throw new ConfigurationException("server host is not set");
    }/*  w ww .j a v  a2s.  c o m*/

    List<ServerAddress> serverAddresses = new LinkedList<ServerAddress>();
    for (String serverUrl : serverUrls) {
        String[] host_port = serverUrl.split(":");
        serverAddresses.add(new ServerAddress(host_port[0], Integer.valueOf(host_port[1])));
    }

    MongoClientOptions.Builder optionBuilder = MongoClientOptions.builder();
    if (configuration.isSslConnection()) {
        optionBuilder.socketFactory(SSLSocketFactory.getDefault());
    }

    if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
        MongoCredential credential = MongoCredential.createMongoCRCredential(username, userDatabase,
                password.toCharArray());
        return new MongoClient(serverAddresses, Arrays.asList(credential), optionBuilder.build());
    }
    return new MongoClient(serverAddresses, optionBuilder.build());
}

From source file:org.craftercms.commons.mongo.MongoClientFactory.java

License:Open Source License

@Override
protected MongoClient createInstance() throws Exception {

    if (StringUtils.isBlank(connectionString)) {
        logger.info("No connection string specified, connecting to {}:{}", connectionString, DEFAULT_MONGO_HOST,
                DEFAULT_MONGO_PORT);// w w w . j  av  a 2 s .c  om

        return new MongoClient(new ServerAddress(DEFAULT_MONGO_HOST, DEFAULT_MONGO_PORT));
    }

    StringTokenizer st = new StringTokenizer(connectionString, ",");
    List<ServerAddress> addressList = new ArrayList<>();

    while (st.hasMoreElements()) {
        String server = st.nextElement().toString();

        logger.debug("Processing first server found with string {}", server);

        String[] serverAndPort = server.split(":");
        if (serverAndPort.length == 2) {
            logger.debug("Server string defines host {} and port {}", serverAndPort[0], serverAndPort[1]);

            if (StringUtils.isBlank(serverAndPort[0])) {
                throw new IllegalArgumentException("Given host can't be empty");
            }

            int portNumber = NumberUtils.toInt(serverAndPort[1]);
            if (portNumber == 0) {
                throw new IllegalArgumentException("Given port number " + portNumber + " is not valid");
            }

            addressList.add(new ServerAddress(serverAndPort[0], portNumber));
        } else if (serverAndPort.length == 1) {
            logger.debug("Server string defines host {} only. Using default port ", serverAndPort[0]);

            if (StringUtils.isBlank(serverAndPort[0])) {
                throw new IllegalArgumentException("Given host can't be empty");
            }

            addressList.add(new ServerAddress(serverAndPort[0], DEFAULT_MONGO_PORT));
        } else {
            throw new IllegalArgumentException("Given connection string is not valid");
        }
    }

    logger.debug("Creating MongoClient with addresses: {}", addressList);

    if (options != null) {
        return new MongoClient(addressList, options);
    } else {
        return new MongoClient(addressList);
    }
}

From source file:org.dizitart.no2.datagate.NitriteDataGate.java

License:Apache License

@Bean
public Jongo jongo() {
    MongoCredential credential = MongoCredential.createCredential(mongoUser, mongoDatabase,
            mongoPassword.toCharArray());
    ServerAddress serverAddress = new ServerAddress(mongoHost, mongoPort);
    MongoClient mongoClient = new MongoClient(serverAddress, new ArrayList<MongoCredential>() {
        {//from w w  w .j a v  a  2 s.c  o m
            add(credential);
        }
    });

    DB db = mongoClient.getDB(mongoDatabase);
    return new Jongo(db);
}