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(final InetSocketAddress inetSocketAddress) 

Source Link

Document

Creates a ServerAddress

Usage

From source file:com.facebook.presto.mongodb.MongoQueryRunner.java

License:Apache License

private MongoQueryRunner(Session session, int workers) throws Exception {
    super(session, workers);

    server = new MongoServer(new SyncMemoryBackend());
    address = server.bind();/*  ww  w .ja va 2s . co m*/
    client = new MongoClient(new ServerAddress(address));
}

From source file:com.flyingdonut.implementation.persistence.MongoDBConnection.java

License:Apache License

private void simpleInit() throws UnknownHostException {
    List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
    String[] hostNames = getHosts().split(",");

    for (String host : hostNames) {
        String[] hostPort = host.split(":");
        String h = hostPort[0];// ww  w  .j  av a2s.  c  o  m
        Integer p = (hostPort.length == 2 ? Integer.parseInt(hostPort[1]) : null);
        ServerAddress serverAddress;
        if (p == null) {
            serverAddress = new ServerAddress(h);
        } else {
            serverAddress = new ServerAddress(h, p);
        }
        serverAddresses.add(serverAddress);
    }
    logger.info("Connecting to " + serverAddresses + "...");
    mongo = new Mongo(serverAddresses);
    logger.info("...success!");
    db = mongo.getDB(dbName);
}

From source file:com.github.dbourdette.otto.SpringConfig.java

License:Apache License

public List<ServerAddress> getMongoServerAdresses() throws UnknownHostException {
    List<ServerAddress> addresses = new ArrayList<ServerAddress>();

    for (String url : StringUtils.split(getMongoUrl(), ",")) {
        addresses.add(new ServerAddress(url));
    }// w  w w  . j av a2 s  .  c o m

    return addresses;
}

From source file:com.github.maasdi.mongo.wrapper.NoAuthMongoClientWrapper.java

License:Apache License

protected MongoClient getClient(MongoDbMeta meta, VariableSpace vars, LogChannelInterface log,
        List<ServerAddress> repSet, boolean useAllReplicaSetMembers, MongoClientOptions opts)
        throws KettleException {
    try {/*from w  w  w.j a  v a  2s .co  m*/
        // Mongo's java driver will discover all replica set or shard
        // members (Mongos) automatically when MongoClient is constructed
        // using a list of ServerAddresses. The javadocs state that MongoClient
        // should be constructed using a SingleServer address instance (rather
        // than a list) when connecting to a stand-alone host - this is why
        // we differentiate here between a list containing one ServerAddress
        // and a single ServerAddress instance via the useAllReplicaSetMembers
        // flag.
        return (repSet.size() > 1 || (useAllReplicaSetMembers && repSet.size() >= 1)
                ? new MongoClient(repSet, opts)
                : (repSet.size() == 1 ? new MongoClient(repSet.get(0), opts)
                        : new MongoClient(new ServerAddress("localhost"), opts))); //$NON-NLS-1$
    } catch (UnknownHostException u) {
        throw new KettleException(u);
    }
}

From source file:com.github.maasdi.mongo.wrapper.UsernamePasswordMongoClientWrapper.java

License:Apache License

@Override
protected MongoClient getClient(MongoDbMeta meta, VariableSpace vars, LogChannelInterface log,
        List<ServerAddress> repSet, boolean useAllReplicaSetMembers, MongoClientOptions opts)
        throws KettleException {
    try {/*from   www  .  ja  v a  2s.c  o  m*/
        List<MongoCredential> credList = new ArrayList<MongoCredential>();
        credList.add(getCredential(meta, vars));
        return (repSet.size() > 1 || (useAllReplicaSetMembers && repSet.size() >= 1)
                ? new MongoClient(repSet, credList, opts)
                : (repSet.size() == 1 ? new MongoClient(repSet.get(0), credList, opts)
                        : new MongoClient(new ServerAddress("localhost"), credList, opts))); //$NON-NLS-1$
    } catch (UnknownHostException u) {
        throw new KettleException(u);
    }
}

From source file:com.grallandco.util.MongoConnectionManager.java

License:Apache License

/**
 * Get the MongoDB client//from   www .j  a v a2  s.  c  o  m
 * @return
 */
public static MongoClient getMongoClient() {
    if (client == null) {

        // get the URU list form the configuration
        String mongoURIs = MongoDBCouchbaseReplicator.mongoUri;
        List<String> list = Arrays.asList(mongoURIs.split(","));

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

        try {
            for (String addr : list) {
                addressList.add(new ServerAddress(addr));
            }
            client = new MongoClient(addressList);

        } catch (UnknownHostException e) {
            logger.log(Level.SEVERE, e.getMessage());
            System.exit(1);
        }

        logger.log(Level.INFO, "MongoDB Replicator Connected to " + addressList);

    }
    return client;
}

From source file:com.hipstogram.rest.HistogramMongoDBResource.java

License:Apache License

/**
 * Create a new instance of this class/*from w  w  w  .j  a v a  2 s.  com*/
 */
public HistogramMongoDBResource() {
    // MongoDB
    MongoDBSection mongoDBSection = HipstogramContext.getInstance().getConfiguration().getMongoSection();

    try {
        mongo = new MongoClient(new ServerAddress(mongoDBSection.host));
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

    // Morphia
    Morphia morphia = new Morphia();
    morphia.map(TrackCount.class);
    ds = morphia.createDatastore(mongo, "test");

    // Gson
    gson = new Gson();
}

From source file:com.ibm.ws.lars.testutils.RepositoryFixture.java

License:Apache License

/**
 * Creates a test fixture for the repository server and corresponding mongo database
 *
 * @param serverUrl the URL of the repository server
 * @param dbHost the hostname and port number of the mongodb server to connect to
 * @param dbName the database name to access on the mongodb server
 * @param adminRoleUsername the name of a user who is granted the Administrator
 * @param adminRolePassword the password associated with adminRoleUserName
 * @param userRoleUsername the name of a user who is granted the User role
 * @param userRolePassword the password associated with useRoleUsername
 *///from  ww w .  j av  a2s . c om
public RepositoryFixture(String serverUrl, String dbHost, String dbName, String adminRoleUsername,
        String adminRolePassword, String userRoleUsername, String userRolePassword) {
    this.adminLoginInfoEntry = new LoginInfoEntry(adminRoleUsername, adminRolePassword, "1", serverUrl);
    this.adminLoginInfo = new LoginInfo(adminLoginInfoEntry);

    // If userRoleUsername and userRolePassword are null then this LoginInfo will access the
    // repository as the UNAUTHENTICATED user
    this.userLoginInfoEntry = new LoginInfoEntry(userRoleUsername, userRolePassword, "1", serverUrl);

    this.dbName = dbName;
    try {
        this.dbHost = new ServerAddress(dbHost);
    } catch (UnknownHostException e) {
        throw new AssertionError("The host " + dbHost + " is not known", e);
    }
}

From source file:com.ikanow.aleph2.shared.crud.mongodb.services.MongoDbCrudServiceFactory.java

License:Apache License

@Inject
public MongoDbCrudServiceFactory(MongoDbConfigurationBean config) throws UnknownHostException {
    String mongo_config = Optional.ofNullable(config.mongodb_connection()).orElse("localhost:27017");
    // Create a list of server addresses and connect      
    String[] servers = mongo_config.split("\\s*,\\s*");
    List<ServerAddress> server_list = Arrays.asList(servers).stream().map(a -> {
        try {/*from  w w w.  j  a  va  2 s  . c  om*/
            String[] server_and_port = a.split("\\s*:\\s*");
            if (1 == server_and_port.length) {
                return new ServerAddress(a);
            } else {
                return new ServerAddress(server_and_port[0], Integer.decode(server_and_port[1]));
            }
        } catch (Exception e) {
            return (ServerAddress) null;
        }
    }).filter(sa -> null != sa).collect(Collectors.toList());

    _mongo_client = new MongoClient(server_list);
}

From source file:com.mulesoft.quartz.mongo.MongoDBJobStore.java

License:Open Source License

public void initialize(ClassLoadHelper loadHelper, SchedulerSignaler signaler) throws SchedulerConfigException {
    this.loadHelper = loadHelper;
    this.signaler = signaler;

    if (addresses == null || addresses.length == 0) {
        throw new SchedulerConfigException("At least one MongoDB address must be specified.");
    }//from w w w  .j  a  v a  2 s .  c  om

    MongoOptions options = new MongoOptions();
    options.safe = true; // need to do this to ensure we get DuplicateKey exceptions

    try {
        ArrayList<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
        for (String a : addresses) {
            serverAddresses.add(new ServerAddress(a));
        }
        mongo = new Mongo(serverAddresses, options);

    } catch (UnknownHostException e) {
        throw new SchedulerConfigException("Could not connect to MongoDB.", e);
    } catch (MongoException e) {
        throw new SchedulerConfigException("Could not connect to MongoDB.", e);
    }

    DB db = mongo.getDB(dbName);
    if (username != null) {
        db.authenticate(username, password.toCharArray());
    }
    jobCollection = db.getCollection(collectionPrefix + "jobs");
    triggerCollection = db.getCollection(collectionPrefix + "triggers");
    calendarCollection = db.getCollection(collectionPrefix + "calendars");
    locksCollection = db.getCollection(collectionPrefix + "locks");

    BasicDBObject keys = new BasicDBObject();
    keys.put(JOB_KEY_NAME, 1);
    keys.put(JOB_KEY_GROUP, 1);
    jobCollection.ensureIndex(keys, null, true);

    keys = new BasicDBObject();
    keys.put(TRIGGER_KEY_NAME, 1);
    keys.put(TRIGGER_KEY_GROUP, 1);
    triggerCollection.ensureIndex(keys, null, true);

    keys = new BasicDBObject();
    keys.put(LOCK_KEY_NAME, 1);
    keys.put(LOCK_KEY_GROUP, 1);
    locksCollection.ensureIndex(keys, null, true);
    // remove all locks for this instance on startup
    locksCollection.remove(new BasicDBObject(LOCK_INSTANCE_ID, instanceId));

    keys = new BasicDBObject();
    keys.put(CALENDAR_NAME, 1);
    calendarCollection.ensureIndex(keys, null, true);
}