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.streamsets.pipeline.stage.common.mongodb.MongoDBConfig.java

License:Apache License

private void validateServerList(Stage.Context context, List<String> hosts, List<ServerAddress> servers,
        List<Stage.ConfigIssue> issues) {
    // Validate each host in the connection string is valid. MongoClient will not tell us
    // if something is wrong when we try to open it.
    for (String host : hosts) {
        String[] hostport = host.split(":");
        if (hostport.length != 2) {
            issues.add(context.createConfigIssue(Groups.MONGODB.name(),
                    MONGO_CONFIG_PREFIX + "connectionString", Errors.MONGODB_07, host));
        } else {//  w ww.  j a  v a2 s . c om
            try {
                InetAddress.getByName(hostport[0]);
                servers.add(new ServerAddress(hostport[0], Integer.parseInt(hostport[1])));
            } catch (UnknownHostException e) {
                issues.add(context.createConfigIssue(Groups.MONGODB.name(),
                        MONGO_CONFIG_PREFIX + "connectionString", Errors.MONGODB_09, hostport[0]));
            } catch (NumberFormatException e) {
                issues.add(context.createConfigIssue(Groups.MONGODB.name(),
                        MONGO_CONFIG_PREFIX + "connectionString", Errors.MONGODB_08, hostport[1]));
            }
        }
    }
}

From source file:com.streamsets.pipeline.stage.origin.mongodb.MongoDBSource.java

License:Apache License

private boolean parseServerList(String mongoConnectionString, List<ServerAddress> servers,
        List<ConfigIssue> issues) {
    boolean isOk = true;
    MongoClientURI mongoURI = new MongoClientURI(mongoConnectionString);
    List<String> hosts = mongoURI.getHosts();

    // Validate each host in the connection string is valid. MongoClient will not tell us
    // if something is wrong when we try to open it.
    for (String host : hosts) {
        String[] hostport = host.split(":");
        if (hostport.length != 2) {
            issues.add(getContext().createConfigIssue(Groups.MONGODB.name(), "mongoConnectionString",
                    Errors.MONGODB_07, host));
            isOk = false;//from w w w .ja  va2 s .  c  om
        } else {
            try {
                InetAddress.getByName(hostport[0]);
                servers.add(new ServerAddress(hostport[0], Integer.parseInt(hostport[1])));
            } catch (UnknownHostException e) {
                issues.add(getContext().createConfigIssue(Groups.MONGODB.name(), "mongoConnectionString",
                        Errors.MONGODB_09, hostport[0]));
                isOk = false;
            } catch (NumberFormatException e) {
                issues.add(getContext().createConfigIssue(Groups.MONGODB.name(), "mongoConnectionString",
                        Errors.MONGODB_08, hostport[1]));
                isOk = false;
            }
        }
    }
    return isOk;
}

From source file:com.telefonica.iot.cygnus.backends.mongo.MongoBackend.java

License:Open Source License

/**
 * Gets a Mongo database./*from w  ww .  java2  s .c  o  m*/
 * @param dbName
 * @return
 */
private MongoDatabase getDatabase(String dbName) {
    // create a ServerAddress object for each configured URI
    List<ServerAddress> servers = new ArrayList<ServerAddress>();
    String[] uris = mongoHosts.split(",");

    for (String uri : uris) {
        String[] uriParts = uri.split(":");
        servers.add(new ServerAddress(uriParts[0], new Integer(uriParts[1])));
    } // for

    // create a Mongo client

    if (client == null) {
        if (mongoUsername.length() != 0) {
            MongoCredential credential = MongoCredential.createCredential(mongoUsername, dbName,
                    mongoPassword.toCharArray());
            client = new MongoClient(servers, Arrays.asList(credential));
        } else {
            client = new MongoClient(servers);
        } // if else
    } // if

    // get the database
    return client.getDatabase(dbName);
}

From source file:com.tengen.helloworld.HelloWorldMongoDBSparkFreemarkerStyle.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(HelloWorldSparkFreemarkerStyle.class, "/");

    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));

    DB database = client.getDB("course");
    final DBCollection collection = database.getCollection("hello");

    Spark.get(new Route("/") {
        @Override//  w w w .  ja v  a2s.  c  om
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template helloTemplate = configuration.getTemplate("hello.ftl");

                DBObject document = collection.findOne();

                helloTemplate.process(document, writer);
            } catch (Exception e) {
                halt(500);
                e.printStackTrace();
            }
            return writer;
        }
    });
}

From source file:com.tengen.helloworld.HelloWorldMongoDBStyle.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));

    DB database = client.getDB("course");
    DBCollection collection = database.getCollection("hello");

    DBObject document = collection.findOne();
    System.out.println(document);
}

From source file:com.tengen.home.Week1Homework4.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(Week1Homework4.class, "/");

    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));

    DB database = client.getDB("m101");
    final DBCollection collection = database.getCollection("funnynumbers");

    Spark.get(new Route("/") {
        @Override//from   w  ww  . j a  v a2  s  . c o m
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template helloTemplate = configuration.getTemplate("answer.ftl");

                // Not necessary yet to understand this.  It's just to prove that you
                // are able to run a command on a mongod server
                AggregationOutput output = collection.aggregate(
                        new BasicDBObject("$group",
                                new BasicDBObject("_id", "$value").append("count",
                                        new BasicDBObject("$sum", 1))),
                        new BasicDBObject("$match", new BasicDBObject("count", new BasicDBObject("$lte", 2))),
                        new BasicDBObject("$sort", new BasicDBObject("_id", 1)));

                int answer = 0;
                for (DBObject doc : output.results()) {
                    answer += (Double) doc.get("_id");
                }

                Map<String, String> answerMap = new HashMap<String, String>();
                answerMap.put("answer", Integer.toString(answer));

                helloTemplate.process(answerMap, writer);
            } catch (Exception e) {
                logger.error("Failed", e);
                halt(500);
            }
            return writer;
        }
    });
}

From source file:com.themodernway.server.mongodb.support.spring.MongoDBDescriptor.java

License:Open Source License

private final boolean init() {
    if (null == m_baseprop) {
        m_baseprop = MongoDBContextInstance.getMongoDBContextInstance().getMongoDBProvider()
                .getMongoDBDefaultPropertiesBase();
    }/*from w w  w. j a  v a  2 s  .com*/
    final IPropertiesResolver prop = ServerContextInstance.getServerContextInstance().getPropertiesResolver();

    setName(prop.getPropertyByName(m_baseprop + ".name"));

    setDefaultDB(prop.getPropertyByName(m_baseprop + ".db"));

    setReplicas(Boolean.valueOf(prop.getPropertyByName(m_baseprop + ".replicas", "false")));

    setCreateID(Boolean.valueOf(prop.getPropertyByName(m_baseprop + ".createid", "false")));

    final ArrayList<ServerAddress> addrlist = new ArrayList<>();

    for (String name : StringOps.requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".host.list"))
            .split(",")) {
        name = StringOps.toTrimOrNull(name);

        if (null != name) {
            final String addr = StringOps
                    .requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".host." + name + ".addr"));

            final String port = StringOps
                    .requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".host." + name + ".port"));

            addrlist.add(new ServerAddress(addr, Integer.parseInt(port)));
        }
    }
    if (addrlist.isEmpty()) {
        throw new IllegalArgumentException("no MongoDB server address");
    }
    m_addrlist = addrlist;

    m_authlist = new ArrayList<>();

    final String temp = StringOps.toTrimOrNull(prop.getPropertyByName(m_baseprop + ".auth.list"));

    if (null != temp) {
        for (String name : temp.split(",")) {
            name = StringOps.toTrimOrNull(name);

            if (null != name) {
                final String user = StringOps
                        .requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".auth." + name + ".user"));

                final String pass = StringOps
                        .requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".auth." + name + ".pass"));

                final String data = StringOps
                        .requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".auth." + name + ".db"));

                m_authlist.add(MongoCredential.createCredential(user, data, pass.toCharArray()));
            }
        }
    }
    if (null == getClientOptions()) {
        setClientOptions(MongoClientOptions.builder().connectionsPerHost(getConnectionPoolSize())
                .threadsAllowedToBlockForConnectionMultiplier(getConnectionMultiplier())
                .connectTimeout(getConnectionTimeout()).build());
    }
    m_doptions = new LinkedHashMap<>();

    final String conf = StringOps.toTrimOrNull(prop.getPropertyByName(m_baseprop + ".dbconfig.list"));

    if (null != conf) {
        for (String name : conf.split(",")) {
            name = StringOps.toTrimOrNull(name);

            if ((null != name) && (null == m_doptions.get(name))) {
                boolean doid = isCreateID();

                final ArrayList<IMongoDBCollectionOptions> list = new ArrayList<>();

                final String dbid = StringOps
                        .toTrimOrNull(prop.getPropertyByName(m_baseprop + ".dbconfig." + name + ".createid"));

                if (null != dbid) {
                    doid = Boolean.valueOf(dbid);
                }
                final String base = m_baseprop + ".dbconfig." + name + ".collections";

                final String cols = StringOps.toTrimOrNull(prop.getPropertyByName(base));

                if (null != cols) {
                    for (String coln : cols.split(",")) {
                        coln = StringOps.toTrimOrNull(coln);

                        if (null != coln) {
                            final String icid = StringOps
                                    .toTrimOrNull(prop.getPropertyByName(base + "." + coln + ".createid"));

                            if (null != icid) {
                                list.add(new MongoDBCollectionOptions(coln, Boolean.valueOf(icid)));
                            } else {
                                list.add(new MongoDBCollectionOptions(coln, doid));
                            }
                        }
                    }
                }
                m_doptions.put(name, new MongoDBOptions(name, doid, list));
            }
        }
    }
    return true;
}

From source file:com.tilab.fiware.metaware.dao.impls.mongodb.core.DataSourceProvider.java

License:Open Source License

/**
 * Initializes the datasource provider.// w w w .  j a v a  2s.  co  m
 *
 * @param props
 * @throws UnknownHostException
 */
DataSourceProvider(Properties props) throws UnknownHostException { // opening mongodb connection
    log.info(MSG_OPENING_DB_CONNECTION);

    serverAddress = new ServerAddress(props.getProperty(KEY_DB_HOST),
            Integer.parseInt(props.getProperty(KEY_DB_PORT)));
    //        mongoCredential = new MongoCredential.createCredential(KEY_DB_USERNAME, KEY_DB_NAME,
    //                KEY_DB_PASSWORD.toCharArray());
    //        mongoClient = new MongoClient(serverAddress, Arrays.asList(mongoCredential));
    mongoClient = new MongoClient(serverAddress);
    db = mongoClient.getDB(props.getProperty(KEY_DB_NAME));

    try {
        db.getCollectionNames();
    } catch (MongoException e) {
        log.error(MSG_ERR_DB_CONNECTION, e);
        throw new DBConnectionException();
    }

    log.info(MSG_DB_CONNECTION_OPENED);

    // Specify additional unique fields
    db.getCollection(USERS_COLLECTION_NAME).createIndex(new BasicDBObject("username", 1),
            new BasicDBObject("unique", true));
}

From source file:com.tomtom.speedtools.mongodb.MongoConnectionCache.java

License:Apache License

/**
 * From a string list of hostname:port tuples, create a list of MongoDB server addresses.
 *
 * @param servers String of host names and port numbers.
 * @return List of MongoDB server addresses.
 * @throws UnknownHostException     If the MongoDB server cannot be found.
 * @throws IllegalArgumentException If a value is incorrect.
 *///from  w  w  w.  j  a v  a  2s. c o m
@Nonnull
public static List<ServerAddress> getMongoDBServerAddresses(@Nonnull final String servers)
        throws UnknownHostException {
    final String[] serversArray = servers.split(HOSTNAME_SEPARATOR);
    final List<ServerAddress> replicaSetSeeds = new ArrayList<>(serversArray.length);
    for (final String server : serversArray) {
        final int sep = server.indexOf(PORTNAME_SEPARATOR);
        if ((sep <= 0) || (sep >= (server.length() - 1))) {
            throw new IllegalArgumentException(
                    "Expected format <hostname>" + PORTNAME_SEPARATOR + "<port>, but was " + server);
        }
        final String host = server.substring(0, sep).trim();
        final int port = Integer.valueOf(server.substring(sep + 1));
        if ((port < 1) || (port > 65535)) {
            throw new IllegalArgumentException("Port number must be in [1, 65535], but was " + port);
        }
        final ServerAddress address = new ServerAddress(host, port);
        replicaSetSeeds.add(address);
    }
    return replicaSetSeeds;
}

From source file:com.torodb.testing.mongodb.docker.AbstractMongod.java

License:Apache License

@Override
protected void afterStarted(DockerClient client, String containerId)
        throws DockerException, InterruptedException {
    this.address = HostAndPort.fromParts(getIp(), MONGOD_PORT);
    mongoClient = new MongoClient(new ServerAddress(address.getHost(), address.getPort()), clientOptions);
}