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.fpt.xml.hth.db.lib.DAO.MovieDAO.java

private void connection() {
    try {/*w w w .  ja  va  2 s  .c om*/
        MongoCredential credential = MongoCredential.createMongoCRCredential(Config.USER_NAME,
                Config.DATABASE_NAME, Config.PASS_WORD.toCharArray());
        ServerAddress address = new ServerAddress(Config.getHost(), Config.getPort());
        List<MongoCredential> lst = new ArrayList<MongoCredential>();
        lst.add(credential);
        this.mongoClient = new MongoClient(address, lst);
        this.cinemaDB = mongoClient.getDB(Config.DATABASE_NAME);
        this.movieCollection = cinemaDB.getCollection(Config.MOVIE_COLLECTION);
        this.converter = new MovieTheaterSessionConverter();
    } catch (UnknownHostException ex) {
        Logger.getLogger(MovieDAO.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.garyclayburg.persistence.config.EmbeddedMongoConfig.java

License:Open Source License

/**
 * This is for a relset of db's/*  w w  w.  jav a2  s  . c  om*/
 */

//        return new MongoClient(new ArrayList<ServerAddress>() {{
//            add(new ServerAddress("127.0.0.1",27017));
//            add(new ServerAddress("127.0.0.1",27027));
//            add(new ServerAddress("127.0.0.1",27037));
//        }});

//    }
@Bean
@Override
public Mongo mongo() throws Exception {

    log.info("configuring embedded mongo");
    //Files that could be left over after a previous execution was (rudely) killed with kill -9

    try {
        DeletionFileVisitor.deletePath(Paths.get(System.getProperty("java.io.tmpdir")), "embedmongo-db-*");
        DeletionFileVisitor.deletePath(Paths.get(System.getProperty("java.io.tmpdir")), "extract-*-mongod*");
    } catch (IOException e) {
        log.warn(
                "could not delete temporary files from embedded mongod process.  Try manually stopping or killing mongod.exe process first.");
    }

    //        RuntimeConfig config = new RuntimeConfig();
    //        config.setExecutableNaming(new UserTempNaming());

    //        MongodStarter starter = MongodStarter.getInstance(config);

    //        MongodExecutable mongoExecutable = starter.prepare(new MongodConfig(Version.V2_2_0,MONGO_TEST_PORT,false));
    //        mongoExecutable.start();

    File storeFile = new File(System.getProperty("user.home"));
    IDirectory artifactStorePath;
    if (storeFile.exists() && storeFile.isDirectory() && storeFile.canWrite()) {
        artifactStorePath = new FixedPath(System.getProperty("user.home") + "/.embeddedmongo");
    } else {
        //use java tmp dir instead of the default user.home - cloudbees cannot write to user.home
        artifactStorePath = new FixedPath(System.getProperty("java.io.tmpdir") + "/.embeddedmongo");
    }
    ITempNaming executableNaming = new UUIDTempNaming();
    Command command = Command.MongoD;
    IRuntimeConfig runtimeConfig;

    if (!mongoDownloadServer.equals("none")) {
        log.debug("using custom download server: " + mongoDownloadServer);
        runtimeConfig = new RuntimeConfigBuilder().defaults(command)
                .artifactStore(new ArtifactStoreBuilder().defaults(command)
                        .download(new DownloadConfigBuilder().defaultsForCommand(command)
                                .downloadPath(mongoDownloadServer).artifactStorePath(artifactStorePath))
                        .executableNaming(executableNaming))
                .build();
    } else {
        log.debug("using standard download server: " + mongoDownloadServer);
        runtimeConfig = new RuntimeConfigBuilder().defaults(command)
                .artifactStore(new ArtifactStoreBuilder().defaults(command)
                        .download(new DownloadConfigBuilder().defaultsForCommand(command)
                                .artifactStorePath(artifactStorePath))
                        .executableNaming(executableNaming))
                .build();
    }
    MongodStarter runtime = MongodStarter.getInstance(runtimeConfig);
    MongodExecutable mongodExe = runtime.prepare(new MongodConfigBuilder().version(Version.Main.PRODUCTION)
            .timeout(new Timeout(60000)).net(new Net(MONGO_TEST_PORT, Network.localhostIsIPv6())).build());
    mongodExe.start();

    mongo = new MongoClient(LOCALHOST, MONGO_TEST_PORT);
    mongo.getDB(DB_NAME);

    return new MongoClient(new ArrayList<ServerAddress>() {
        {
            add(new ServerAddress(LOCALHOST, MONGO_TEST_PORT));
        }
    });
}

From source file:com.garyclayburg.persistence.config.LocalMongoClientConfig.java

License:Open Source License

@Override
@Bean//  w ww. j  a  v  a  2s .  com
public Mongo mongo() throws Exception {
    log.info("configuring local mongo bean: " + mongoHost + ":" + mongoPort);
    MongoClient mongoClient = null;
    try {
        log.debug("mongoHost: " + mongoHost);
        log.debug("mongoPort: " + mongoPort);
        log.debug("mongoUser: " + mongoUser);
        log.debug("mongoDatabase: " + mongoDatabase);

        if (mongoUser != null) {
            log.debug("using user/password authentication to mongodb");
            MongoCredential credential = MongoCredential.createCredential(mongoUser, getDatabaseName(),
                    mongoPassword.toCharArray());
            List<MongoCredential> credList = new ArrayList<MongoCredential>();
            credList.add(credential);
            mongoClient = new MongoClient(new ServerAddress(mongoHost, mongoPort), credList);
        } else {

            log.debug("attempting no authentication to mongodb");
            mongoClient = new MongoClient(mongoHost, mongoPort);

        }

    } catch (UnknownHostException e) {
        log.warn("kaboom", e);
    }
    return mongoClient;
}

From source file:com.gatf.executor.dataprovider.MongoDBTestDataSource.java

License:Apache License

public void init() {
    if (args == null || args.length == 0) {
        throw new AssertionError("No arguments passed to the MongoDBTestDataProvider");
    }//w w  w.  j  a v a  2s  .c  om

    if (args.length < 3) {
        throw new AssertionError("The arguments, namely mongodb-host, mongodb-port, mongodb-database are "
                + " mandatory for MongoDBTestDataProvider");
    }

    Assert.assertNotNull("mongodb-host cannot be empty", args[0]);
    Assert.assertNotNull("mongodb-port cannot be empty", args[1]);
    Assert.assertNotNull("mongodb-database cannot be empty", args[2]);

    String host = args[0].trim();
    String port = args[1].trim();
    String dbName = args[2].trim();

    Assert.assertFalse("mongodb-host cannot be empty", host.isEmpty());
    Assert.assertFalse("mongodb-port cannot be empty", port.isEmpty());
    Assert.assertFalse("mongodb-database cannot be empty", dbName.isEmpty());

    String username = null, password = "";
    if (args.length > 3) {
        Assert.assertNotNull("mongodb-user cannot be empty", args[3]);
        Assert.assertFalse("mongodb-user cannot be empty", args[3].isEmpty());

        username = args[3].trim();
        if (args.length > 4 && args[4] != null)
            password = args[4].trim();
    }

    StringBuilder build = new StringBuilder();
    build.append("MongoDBTestDataSource configuration [\n");
    build.append(String.format("mongodb-host is %s\n", host));
    build.append(String.format("mongodb-port is %s\n", port));
    build.append(String.format("mongodb-database is %s\n", dbName));
    if (username != null) {
        build.append(String.format("mongodb-user is %s\n", username));
        build.append(String.format("mongodb-password is %s\n", password));
    }
    logger.info(build.toString());

    try {
        String[] hosts = host.split(",");
        String[] ports = port.split(",");

        if (hosts.length > ports.length) {
            Assert.assertEquals(String.format("Port missing for host %s", hosts[ports.length - 1]),
                    hosts.length, ports.length);
        } else {
            Assert.assertEquals(String.format("Host missing for port %s", ports[hosts.length - 1]),
                    hosts.length, ports.length);
        }

        for (String portVal : ports) {
            try {
                Integer.valueOf(portVal);
            } catch (Exception e) {
                throw new AssertionError(String.format("Port value invalid - %s", portVal));
            }
        }

        for (int i = 0; i < hosts.length; i++) {
            ServerAddress address = new ServerAddress(hosts[i], Integer.valueOf(ports[i]));
            addresses.add(address);
        }

        for (int i = 0; i < poolSize; i++) {
            MongoClient mongoClient = null;
            //Now try connecting to the Database
            try {
                mongoClient = new MongoClient(addresses);
            } catch (Exception e) {
                throw new AssertionError(String.format("Connection to MongoDB failed with the error %s",
                        ExceptionUtils.getStackTrace(e)));
            }

            DB db = null;
            try {
                db = mongoClient.getDB(dbName);
                if (username != null && password != null) {
                    Assert.assertTrue(String.format("Authentication to the Mongo database %s failed with %s/%s",
                            dbName, username, password), db.authenticate(username, password.toCharArray()));
                }
            } catch (Exception e) {
                throw new AssertionError(String.format("Error during initialization of MongoDB connection %s",
                        ExceptionUtils.getStackTrace(e)));
            }

            addToPool(mongoClient, false);
        }
    } catch (Exception e) {
        throw new AssertionError(String.format("Error during initialization of MongoDB connection %s",
                ExceptionUtils.getStackTrace(e)));
    } finally {
    }

}

From source file:com.genius.admin.helper.MongoFactoryBean.java

License:Apache License

private void replSeeds(String... serverAddresses) {
    try {/*from   www.  j  av a 2 s. c o m*/
        replicaSetSeeds.clear();
        for (String addr : serverAddresses) {
            String[] a = addr.split(":");
            String host = a[0];
            if (a.length > 2) {
                throw new IllegalArgumentException("Invalid Server Address : " + addr);
            } else if (a.length == 2) {
                replicaSetSeeds.add(new ServerAddress(host, Integer.parseInt(a[1])));
            } else {
                replicaSetSeeds.add(new ServerAddress(host));
            }
        }
    } catch (Exception e) {
        throw new BeanCreationException("Error while creating replicaSetAddresses", e);
    }
}

From source file:com.github.bluetiger9.nosql.benchmarking.clients.document.mongodb.MongoDBClient.java

License:Open Source License

private static ServerAddress getServerAddress(String server) throws UnknownHostException {
    final String host = StringUtils.substringBefore(server, ":");
    final String port = StringUtils.substringAfter(server, ":");
    if (!StringUtils.isBlank(port)) {
        return new ServerAddress(host, Integer.parseInt(port));
    } else {/*from   w ww. ja va 2 s . c  o m*/
        return new ServerAddress(host);
    }
}

From source file:com.github.cherimojava.data.mongo.MongoBase.java

License:Apache License

@Before
public final void dbSetup() throws IOException {
    client = new MongoClient(new ServerAddress("localhost", Suite.getPort()));
    db = client.getDatabase(this.getClass().getSimpleName());
    collectionCleanUp = Lists.newArrayList();
}

From source file:com.github.cherimojava.orchidae.config.cfgMongo.java

License:Apache License

@Bean
MongoDatabase mongoDatabase() throws UnknownHostException {
    return new MongoClient(new ServerAddress("localhost", mongoPort())).getDatabase(mongoDBName);
}

From source file:com.github.danzx.zekke.mongo.config.MongoDbSettings.java

License:Apache License

private MongoDbSettings(Builder builder) {
    this.database = builder.database;
    address = new ServerAddress(builder.host, builder.port);
    if (!isNullOrBlank(builder.user)) {
        credential = builder.password == null
                ? MongoCredential.createCredential(builder.user, builder.database, Strings.EMPTY.toCharArray())
                : MongoCredential.createCredential(builder.user, builder.database,
                        builder.password.toCharArray());
    } else/*from   ww w  .  jav a 2  s. co m*/
        credential = null;
}

From source file:com.github.frapontillo.pulse.crowd.data.repository.DBConfig.java

License:Apache License

public ServerAddress getServerAddress() {
    return new ServerAddress(getHost(), getPort());
}