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.forgerock.openidm.repo.mongodb.impl.MongoClientSingleton.java

License:Open Source License

private static List<ServerAddress> getReplicaSet(JsonValue config) {
    JsonValue replicas = config.get(MongoDBRepoService.CONFIG_REPLICASET);
    List<ServerAddress> list = new ArrayList<ServerAddress>();

    for (Iterator<JsonValue> ite = replicas.iterator(); ite.hasNext();) {
        JsonValue serverConf = ite.next();
        try {//from  w w  w. j ava  2 s . c om
            list.add(new ServerAddress(serverConf.get(MongoDBRepoService.CONFIG_HOST).asString(),
                    serverConf.get(MongoDBRepoService.CONFIG_PORT).asInteger()));
        } catch (UnknownHostException ex) {
            logger.warn("Can't connect to Server", ex);
            throw new InvalidException();
        }
    }
    if (list.isEmpty()) {
        logger.warn("No Replica Set configured.");
        throw new InvalidException();
    }
    return list;
}

From source file:org.geosdi.geoplatform.experimental.mongodb.spring.client.GPMongoClientConfig.java

License:Open Source License

@Bean(name = "gpSpringMongoClient")
public MongoClient gpMongoClient(@Qualifier(value = "gpSpringMongoProp") MongoProperties gpSpringMongoProp)
        throws Exception {
    logger.debug("###################### GeoPlatform Experimental Version ::== Building MongoClient.\n");

    return (gpSpringMongoProp.getMongoAuth().isMongoAuthEnabled()
            ? new MongoClient(
                    new ServerAddress(gpSpringMongoProp.getMongoHost(), gpSpringMongoProp.getMongoPort()),
                    Arrays.asList(MongoCredential.createCredential(
                            gpSpringMongoProp.getMongoAuth().getMongoUserName(),
                            gpSpringMongoProp.getMongoDatabaseName(),
                            gpSpringMongoProp.getMongoAuth().getMongoPassword().toCharArray())))
            : new MongoClient(
                    new ServerAddress(gpSpringMongoProp.getMongoHost(), gpSpringMongoProp.getMongoPort())));
}

From source file:org.graylog.plugins.metrics.mongodb.providers.MongoDBReporterProvider.java

License:Open Source License

private ServerAddress[] extractServerAddresses(MongoClientURI mongoClientURI) {
    final List<String> hosts = mongoClientURI.getHosts();
    final List<ServerAddress> serverAddresses = new ArrayList<>(hosts.size());
    for (String host : hosts) {
        final HostAndPort hostAndPort = HostAndPort.fromString(host)
                .withDefaultPort(ServerAddress.defaultPort());
        final ServerAddress serverAddress = new ServerAddress(hostAndPort.getHostText(), hostAndPort.getPort());
        serverAddresses.add(serverAddress);
    }/*from w  w w  .  j  ava2s . c om*/
    return serverAddresses.toArray(new ServerAddress[serverAddresses.size()]);
}

From source file:org.graylog2.configuration.MongoDbConfiguration.java

License:Open Source License

public List<ServerAddress> getReplicaSet() {
    if (replicaSet == null || replicaSet.isEmpty()) {
        return null;
    }//from ww  w  .  jav a 2  s .  com

    final List<ServerAddress> replicaServers = new ArrayList<>(replicaSet.size());
    for (String host : replicaSet) {
        try {
            final HostAndPort hostAndPort = HostAndPort.fromString(host).withDefaultPort(27017);
            replicaServers.add(
                    new ServerAddress(InetAddress.getByName(hostAndPort.getHostText()), hostAndPort.getPort()));
        } catch (IllegalArgumentException e) {
            LOG.error("Malformed mongodb_replica_set configuration.", e);
            return null;
        } catch (UnknownHostException e) {
            LOG.error("Unknown host in mongodb_replica_set", e);
            return null;
        }
    }

    return replicaServers;
}

From source file:org.graylog2.Configuration.java

License:Open Source License

public static List<ServerAddress> getMongoDBReplicaSetServers(Properties config) {
    List<ServerAddress> replicaServers = new ArrayList<ServerAddress>();

    String rawSet = config.getProperty("mongodb_replica_set");

    if (rawSet == null || rawSet.isEmpty()) {
        return null;
    }/*from  w  ww  .  j a va 2  s .  c o m*/

    // Get every host:port pair
    String[] hosts = rawSet.split(",");
    for (int i = 0; i < hosts.length; i++) {
        // Split host:port.
        String[] replicaTarget = hosts[i].split(":");

        // Check if valid.
        if (replicaTarget == null || replicaTarget.length != 2) {
            LOG.error("Malformed mongodb_replica_set configuration.");
            return null;
        }

        // Get host and port.
        try {
            replicaServers.add(new ServerAddress(replicaTarget[0], Integer.parseInt(replicaTarget[1])));
        } catch (UnknownHostException e) {
            LOG.error("Unknown host in mongodb_replica_set: " + e.getMessage(), e);
            return null;
        }
    }

    return replicaServers;
}

From source file:org.graylog2.database.MongoConnection.java

License:Open Source License

/**
 * Connect the instance./* ww  w .  java  2 s .  c o m*/
 */
public synchronized MongoClient connect() {
    if (m == null) {
        Builder options = new MongoClientOptions.Builder();
        options.connectionsPerHost(maxConnections);
        options.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockMultiplier);

        try {

            // Connect to replica servers if given. Else the standard way to one server.
            if (replicaServers != null && replicaServers.size() > 0) {
                m = new MongoClient(replicaServers, options.build());
            } else {
                ServerAddress address = new ServerAddress(host, port);
                m = new MongoClient(address, options.build());
            }
            db = m.getDB(database);
            db.setWriteConcern(WriteConcern.SAFE);

            // Try to authenticate if configured.
            if (useAuth) {
                if (!db.authenticate(username, password.toCharArray())) {
                    throw new RuntimeException("Could not authenticate to database '" + database
                            + "' with user '" + username + "'.");
                }
            }
        } catch (UnknownHostException e) {
            throw new RuntimeException("Cannot resolve host name for MongoDB", e);
        }
    }
    return m;
}

From source file:org.hbr.session.store.MongoStore.java

License:Apache License

/**
 * Create the {@link MongoClient}.//from  w w w .  j a v a2 s  .  co  m
 * @throws LifecycleException
 */
private void getConnection() throws LifecycleException {
    try {
        /* create our MongoClient */
        if (this.connectionUri != null) {
            manager.getContainer().getLogger().info(getStoreName() + "[" + this.getName()
                    + "]: Connecting to MongoDB [" + this.connectionUri + "]");
            this.mongoClient = new MongoClient(this.connectionUri);
        } else {
            /* create the client using the Mongo options */
            ReadPreference readPreference = ReadPreference.primaryPreferred();
            if (this.useSlaves) {
                readPreference = ReadPreference.secondaryPreferred();
            }
            MongoClientOptions options = MongoClientOptions.builder().connectTimeout(connectionTimeoutMs)
                    .maxWaitTime(connectionWaitTimeoutMs).connectionsPerHost(maxPoolSize)
                    .writeConcern(writeConcern).readPreference(readPreference).build();

            /* build up the host list */
            List<ServerAddress> hosts = new ArrayList<ServerAddress>();
            String[] dbHosts = this.hosts.split(",");
            for (String dbHost : dbHosts) {
                String[] hostInfo = dbHost.split(":");
                ServerAddress address = new ServerAddress(hostInfo[0], Integer.parseInt(hostInfo[1]));
                hosts.add(address);
            }

            this.manager.getContainer().getLogger().info(
                    getStoreName() + "[" + this.getName() + "]: Connecting to MongoDB [" + this.hosts + "]");

            /* connect */
            this.mongoClient = new MongoClient(hosts, options);
        }

        /* get a connection to our db */
        this.manager.getContainer().getLogger()
                .info(getStoreName() + "[" + this.getName() + "]: Using Database [" + this.dbName + "]");
        this.db = this.mongoClient.getDB(this.dbName);

        /* see if we need to authenticate */
        if (this.username != null || this.password != null) {
            this.manager.getContainer().getLogger().info(
                    getStoreName() + "[" + this.getName() + "]: Authenticating using [" + this.username + "]");
            if (!this.db.authenticate(this.username, this.password.toCharArray())) {
                throw new RuntimeException("MongoDB Authentication Failed");
            }
        }

        /* get a reference to the collection */
        this.collection = this.db.getCollection(this.collectionName);
        this.manager.getContainer().getLogger()
                .info(getStoreName() + "[" + this.getName() + "]: Preparing indexes");

        /* drop any existing indexes */
        try {
            this.collection.dropIndex(new BasicDBObject(lastModifiedProperty, 1));
            this.collection.dropIndex(new BasicDBObject(appContextProperty, 1));
        } catch (Exception e) {
            /* these indexes may not exist, so ignore */
        }

        /* make sure the last modified and app name indexes exists */
        this.collection.ensureIndex(new BasicDBObject(appContextProperty, 1));

        /* determine if we need to expire our db sessions */
        if (this.timeToLive != -1) {
            /* use the time to live set */
            this.collection.ensureIndex(new BasicDBObject(lastModifiedProperty, 1),
                    new BasicDBObject("lastModifiedProperty", this.timeToLive));
        } else {
            /* no custom time to live specified, use the manager's settings */
            if (this.manager.getMaxInactiveInterval() != -1) {
                /* create a ttl index on the app property */
                this.collection.ensureIndex(new BasicDBObject(lastModifiedProperty, 1),
                        new BasicDBObject("lastModifiedProperty", this.manager.getMaxInactiveInterval()));
            } else {
                /* create a regular index */
                this.collection.ensureIndex(new BasicDBObject(lastModifiedProperty, 1));
            }
        }

        this.manager.getContainer().getLogger().info(getStoreName() + "[" + this.getName() + "]: Store ready.");
    } catch (UnknownHostException uhe) {
        this.manager.getContainer().getLogger().error("Unable to Connect to MongoDB", uhe);
        throw new LifecycleException(uhe);
    } catch (MongoException me) {
        this.manager.getContainer().getLogger().error("Unable to Connect to MongoDB", me);
        throw new LifecycleException(me);
    }
}

From source file:org.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider.java

License:LGPL

protected MongoClient createMongoClient(MongoDBConfiguration config) {
    MongoClientOptions clientOptions = config.buildOptions();
    List<MongoCredential> credentials = config.buildCredentials();
    log.connectingToMongo(config.getHost(), config.getPort(), clientOptions.getConnectTimeout());
    try {/*from www  .  ja v  a  2  s.  c o  m*/
        ServerAddress serverAddress = new ServerAddress(config.getHost(), config.getPort());
        return credentials == null ? new MongoClient(serverAddress, clientOptions)
                : new MongoClient(serverAddress, credentials, clientOptions);
    } catch (UnknownHostException e) {
        throw log.mongoOnUnknownHost(config.getHost());
    } catch (RuntimeException e) {
        throw log.unableToInitializeMongoDB(e);
    }
}

From source file:org.hibernate.ogm.perftest.mongodb.nativeapi.NativeApiBenchmarkBase.java

License:LGPL

protected static MongoClient getMongoClient() throws UnknownHostException {
    ServerAddress serverAddress = new ServerAddress(properties.getProperty("host"), 27017);

    MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();

    optionsBuilder.connectTimeout(1000);
    optionsBuilder.writeConcern(WriteConcern.ACKNOWLEDGED);
    optionsBuilder.readPreference(ReadPreference.primary());

    MongoClientOptions clientOptions = optionsBuilder.build();

    MongoClient mongo = new MongoClient(serverAddress, clientOptions);

    return mongo;
}

From source file:org.hibernate.scenicview.mongodb.internal.MongoDbDenormalizationBackend.java

License:LGPL

private static Connection createConnection(String connectionUri) {
    Matcher matcher = CONNECTION.matcher(connectionUri);
    if (!matcher.matches()) {
        throw new IllegalArgumentException("Unexpected connection string: " + connectionUri);
    }//from w w  w. ja  va 2s .c o m

    ServerAddress address = new ServerAddress(matcher.group(1), Integer.valueOf(matcher.group(2)));
    return new Connection(new MongoClient(address), matcher.group(3));
}