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:RemoteDatabaseConfigurationExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    List<ServerAddress> seeds = Arrays.asList(new ServerAddress("localhost", 27017));

    Injector injector = Guice.createInjector(
            // create a connection to localhost:13731 that can be used by databases
            GuiceyMongo.configureConnection(Connections.Primary).port(13731),

            // create a connection to a ReplicatSet that can be used by databases
            GuiceyMongo.configureConnection(Connections.ReplicaSet).seeds(seeds),

            // create the production configuration
            GuiceyMongo.configure(Configurations.Production)
                    // configure the Main database to use the Primary connection (localhost:13731)
                    .mapDatabase(Databases.Main).to("prod_db").overConnection(Connections.ReplicaSet)
                    .mapDatabase(Databases.Search).to("prod_search_db"),

            // create the test configuration
            GuiceyMongo.configure(Configurations.Test)
                    // configure the Main database to use the Primary connection (localhost:13731)
                    .mapDatabase(Databases.Main).to("test_db").overConnection(Connections.ReplicaSet),

            // configurations can be augmented in separate modules
            GuiceyMongo.configure(Configurations.Test).mapDatabase(Databases.Search).to("test_search_db"),

            // choose the configuration to use
            GuiceyMongo.chooseConfiguration(Configurations.Test));

    injector.getInstance(RemoteDatabaseConfigurationExample.class);
}

From source file:act.installer.reachablesexplorer.FreemarkerRenderer.java

License:Open Source License

private void init(String dbHost, Integer dbPort, String dbName, String dnaCollection, String pathwayCollection)
        throws IOException {
    cfg = new Configuration(Configuration.VERSION_2_3_23);

    cfg.setClassLoaderForTemplateLoading(this.getClass().getClassLoader(),
            "/act/installer/reachablesexplorer/templates");
    cfg.setDefaultEncoding("UTF-8");

    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(true);//from   w  w  w .  j  a  v a2s.  c  om

    reachableTemplate = cfg.getTemplate(reachableTemplateName);
    pathwayTemplate = cfg.getTemplate(pathwayTemplateName);

    // TODO: move this elsewhere.
    MongoClient client = new MongoClient(new ServerAddress(dbHost, dbPort));
    DB db = client.getDB(dbName);

    dnaDesignCollection = JacksonDBCollection.wrap(db.getCollection(dnaCollection), DNADesign.class,
            String.class);
    Cascade.setCollectionName(pathwayCollection);
}

From source file:act.installer.reachablesexplorer.Loader.java

License:Open Source License

/**
 * Constructor for Loader. Instantiates connexions to Mongo databases
 * and Virtuoso triple store (Pubchem synonyms only)
 * @param host The host for the target Reachables MongoDB
 * @param port The port for the target Reachables MongoDB
 * @param targetDB The database for the target Reachables MongoDB
 * @param targetCollection The collection for the target Reachables MongoDB
 * @param targetSequenceCollection The collection for the target SequenceData MongoDB
 * @param renderingCache A directory where rendered images should live
 *//*from w w  w. java 2  s. c o m*/
public Loader(String host, Integer port, String sourceDB, String targetDB, String targetCollection,
        String targetSequenceCollection, String renderingCache) {
    // when the caller does not intend to touch the sourceDB, it can pass null as a param and we
    // won't setup a "source" connection. Creating a connection with "dummy" params leads mongod
    // to create (!) those dummy collections, mucking up our database with empty dbs/collections
    if (sourceDB != null) {
        sourceDBconn = new MongoDB(host, port, sourceDB);
        wordCloudGenerator = new WordCloudGenerator(host, port, sourceDB, renderingCache);
    }
    pubchemSynonymsDriver = new PubchemMeshSynonyms();
    moleculeRenderer = new MoleculeRenderer(new File(renderingCache));

    MongoClient mongoClient;
    try {
        mongoClient = new MongoClient(new ServerAddress(host, port));
    } catch (UnknownHostException e) {
        LOGGER.error(
                "Connection to MongoClient failed. Please double check the target database's host and port.");
        throw new RuntimeException(e);
    }
    DB reachables = mongoClient.getDB(targetDB);

    // TODO: this unsafe initialization does not belong in the constructor.
    try {
        calculator = new PhysiochemicalPropertiesCalculator.Factory().build();
    } catch (PluginException e) {
        LOGGER.error("Unable to initialize physiochemical calculator: %s", e.getMessage());
        throw new RuntimeException(e);
    }

    if (targetCollection != null) {
        jacksonReachablesCollection = JacksonDBCollection.wrap(reachables.getCollection(targetCollection),
                Reachable.class, String.class);
        jacksonReachablesCollection.ensureIndex(new BasicDBObject(Reachable.INCHI_FIELD_NAME, "hashed"));
    }

    if (targetSequenceCollection != null) {
        jacksonSequenceCollection = JacksonDBCollection.wrap(reachables.getCollection(targetSequenceCollection),
                SequenceData.class, String.class);
        jacksonSequenceCollection.createIndex(new BasicDBObject(SequenceData.SEQUENCE_FIELD_NAME, "hashed"));
        jacksonSequenceCollection.createIndex(new BasicDBObject(SequenceData.ORGANISM_FIELD_NAME, 1));
    }
}

From source file:AdminServer.ServiceS.java

private void DBConnect() {
    try {/*from w ww. ja  v  a 2s.  c  o  m*/
        mongo = new Mongo(new ServerAddress("", 27017));
        db = mongo.getDB("bank");
        admins = db.getCollection("admins");
        users = db.getCollection("users");
        clients = db.getCollection("clients");
        records = db.getCollection("records");
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (MongoException e) {
        e.printStackTrace();
    }
}

From source file:brooklyn.entity.nosql.mongodb.MongoDBClientSupport.java

License:Apache License

/**
 * Creates a {@link MongoDBClientSupport} instance in standalone mode.
 * Returns {@link com.google.common.base.Optional#absent} if the server's host and port are unknown.
 *///from  w  w  w. j a  v  a  2  s  .c  o  m
public static MongoDBClientSupport forServer(AbstractMongoDBServer standalone) throws UnknownHostException {
    String hostname = standalone.getAttribute(MongoDBServer.HOSTNAME);
    Integer port = standalone.getAttribute(MongoDBServer.PORT);
    ServerAddress address = new ServerAddress(hostname, port);
    return new MongoDBClientSupport(address);
}

From source file:ch.bfh.uniboard.persistence.mongodb.ConnectionManagerImpl.java

License:GNU General Public License

@PostConstruct
private void init() {

    Properties props = cm.getConfiguration(CONFIG_NAME);

    if (props == null) {
        logger.log(Level.SEVERE, "Configuration could not be loaded.");
        return;//  www .j  a  va  2s . c om
    }
    //DB Connection Information
    String host;
    String dbName;
    String collectionName;
    int port;
    String username;
    String password;
    boolean authentication;
    //Check if values are set or use defaults
    if (props.containsKey(HOST_KEY)) {
        host = props.getProperty(HOST_KEY);
    } else {
        host = "localhost";
    }
    if (props.containsKey(DBNAME_KEY)) {
        dbName = props.getProperty(DBNAME_KEY);
    } else {
        dbName = "uniboard";
    }
    if (props.containsKey(COLLECTION_KEY)) {
        collectionName = props.getProperty(COLLECTION_KEY);
    } else {
        collectionName = "default";
    }
    if (props.containsKey(PORT_KEY)) {
        port = Integer.parseInt(props.getProperty(PORT_KEY));
    } else {
        port = 27017;
    }
    if (props.containsKey(USERNAME_KEY)) {
        username = props.getProperty(USERNAME_KEY);
    } else {
        username = "admin";
    }
    if (props.containsKey(PASSWORD_KEY)) {
        password = props.getProperty(PASSWORD_KEY);
    } else {
        password = "password";
    }
    if (props.containsKey(AUTH_KEY)) {
        authentication = Boolean.parseBoolean(props.getProperty(AUTH_KEY));
    } else {
        authentication = false;
    }

    try {
        if (authentication) {
            MongoCredential credential = MongoCredential.createMongoCRCredential(username, dbName,
                    password.toCharArray());
            //MongoClient already works as a pool if only one instance is used (http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/)
            mongoClient = new MongoClient(new ServerAddress(host, port), Arrays.asList(credential));
        } else {
            mongoClient = new MongoClient(host, port);
        }
        this.connected = true;
    } catch (UnknownHostException ex) {
        logger.log(Level.SEVERE, "DB creation error", ex);
        return;
    }

    //Create or load the database
    DB db = mongoClient.getDB(dbName);

    //create the collection if it does not exist
    if (!db.collectionExists(collectionName)) {
        collection = db.createCollection(collectionName, null);
    }
    //load the collection
    collection = db.getCollection(collectionName);
}

From source file:cloud.simple.RuleEngineApplication.java

@Bean
public MongoDatabase dataSource() {
    String servers = env.getProperty("spring.data.mongodb.custom.service");
    String databaseName = env.getProperty("spring.data.mongodb.database");

    List<ServerAddress> seeds = new ArrayList<ServerAddress>();
    String[] servers1 = servers.split(",");
    for (String server : servers1) {
        String[] server1 = server.split(":");
        seeds.add(new ServerAddress(server1[0], Integer.parseInt(server1[1])));
    }/*from w w  w .  j  a v  a2  s .c o m*/

    Builder builder = MongoClientOptions.builder();
    builder.socketKeepAlive(true);
    builder.readPreference(ReadPreference.secondaryPreferred());
    MongoClientOptions options = builder.build();

    @SuppressWarnings("resource")
    MongoClient mongoClient = new MongoClient(seeds, options);
    return mongoClient.getDatabase(databaseName);
}

From source file:co.mcme.statistician.database.MongoDBUtil.java

License:Open Source License

public MongoDBUtil(String hostname, int port, String username, char[] password, String database,
        boolean tryAuth, String collection) throws UnknownHostException {
    if (tryAuth) {
        this.client = new MongoClient(Arrays.asList(new ServerAddress(hostname, port)),
                Arrays.asList(MongoCredential.createPlainCredential(username, database, password)));
    } else {// w w  w  .jav  a  2 s .  c om
        this.client = new MongoClient(Arrays.asList(new ServerAddress(hostname, port)));
    }
    this.database = client.getDB(database);
    if (client != null) {
        if (!this.database.collectionExists(collection)) {
            statsCollection = this.database.createCollection(collection, new BasicDBObject());
        } else {
            statsCollection = this.database.getCollection(collection);
        }
    } else {
        StatisticianLogger.severe(
                "Could not authenticate to '" + hostname + ":" + port + "/" + database + "' disabling plugin.");
        Statistician.getServerInstance().getPluginManager().disablePlugin(Statistician.getPluginInstance());
    }
}

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

License:Open Source License

private final boolean init() {
    try {//from   w  w w .  j a v a  2s  .  c  o  m
        if (null == m_baseprop) {
            m_baseprop = MongoDBContextInstance.getMongoDBContextInstance().getMongoDBProvider()
                    .getMongoDBDefaultPropertiesBase();
        }
        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<ServerAddress>();

        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.valueOf(port)));
            }
        }
        if (addrlist.isEmpty()) {
            throw new IllegalArgumentException("no MongoDB server address");
        }
        m_addrlist = addrlist;

        m_authlist = new ArrayList<MongoCredential>();

        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<String, IMongoDBOptions>();

        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) {
                    if (null == m_doptions.get(name)) {
                        boolean doid = isCreateID();

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

                        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;
    } catch (Exception e) {
        logger.error("error initializing MongoDBDescriptor", e);

        return false;
    }
}

From source file:com.Aleksandar.Zoric.MongoMain.java

public String mapReduceFunction() {
    MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
    DB db = mongoClient.getDB("amarokforumdb");
    DBCollection collection = db.getCollection("comments");
    long count = db.getCollection("comments").count();

    System.out.println("Current amount of documents: " + count);

    String map = "function() { " + "var category; " + "var numOfDocuments = " + count + ";"
            + "for(i = 0; i < numOfDocuments; i++){ " + "if (numOfDocuments <= 100) {"
            + "category = 'New Comments'; }" + "else if(numOfDocuments > 100){"
            + "category = 'Old Comments'; }}" + "emit(category,1);};";

    String reduce = "function(key, values) { " + "var sum = 0; " + "values.forEach(function(doc) { "
            + "sum += 1; " + "}); " + "return {comments: sum};} ";

    MapReduceCommand cmd = new MapReduceCommand(collection, map, reduce, null,
            MapReduceCommand.OutputType.INLINE, null);

    MapReduceOutput out = collection.mapReduce(cmd);

    System.out.println("Mapreduce results");

    String result = null;/* w w w .j a v a 2  s  . c om*/

    for (DBObject o : out.results()) {
        result += o;

    }
    return result;
}