Example usage for com.mongodb MongoClientOptions builder

List of usage examples for com.mongodb MongoClientOptions builder

Introduction

In this page you can find the example usage for com.mongodb MongoClientOptions builder.

Prototype

public static Builder builder() 

Source Link

Document

Creates a builder instance.

Usage

From source file:com.boulmier.machinelearning.jobexecutor.mongodb.Mongo.java

public static Mongo getInstance(MongoConfig wrapper) throws UnknownHostException {
    if (instance == null) {
        StringBuilder host = new StringBuilder();
        MongoClient client;/*  w  ww.  j  a v a  2 s. c  om*/
        for (Map.Entry<String, String> param : wrapper.entrySet()) {
            switch (param.getKey()) {
            case MongoConfig.IP_FIELD:
                host.append(param.getValue());
                break;
            case MongoConfig.PORT_FIELD:
                host.append(':').append(param.getValue());
                break;
            }
        }

        client = new MongoClient(host.toString(), MongoClientOptions.builder().connectTimeout(100).build());//new MongoClient(ip, port);
        try {
            client.getDB(JobExecutorConfig.OPTIONS.LOGGING.MONGO_DEFAULT_DATABASE).command("ping");
            instance = new Mongo(client);
            JobExecutor.logger.info("mongodb accessible at " + host);
        } catch (MongoTimeoutException e) {
            throw new UnknownHostException();
        }
    }
    return instance;
}

From source file:com.ca.apm.mongo.Collector.java

License:Open Source License

private MongoClient setupDbClient(final String dbHost, final int dbPort) {
    final boolean useSSL = getBooleanProp(USE_SSL_PROP);
    final String clientTrustStore = getOptionalStringProp(SSL_CLIENT_TRUST_STORE_FILE_PROP);
    final String clientPasswd = getOptionalStringProp(SSL_CLIENT_TRUST_STORE_PASSWD_PROP);

    try {/*from  w ww . j  a v a2 s.c  o  m*/
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();

        if (useSSL) {
            System.setProperty(SSL_CLIENT_TRUST_STORE_FILE_PROP, clientTrustStore);
            System.setProperty(SSL_CLIENT_TRUST_STORE_PASSWD_PROP, clientPasswd);
            builder = builder.socketFactory(SSLSocketFactory.getDefault());
        }

        final MongoClientOptions options = builder.build();
        return new MongoClient(new ServerAddress(dbHost, dbPort), mongoCreds, options);
    } catch (Exception ex) {
        throw new RuntimeException("Can't initialize mongo client", ex);
    }
}

From source file:com.ca.apm.mongo.test.MongoReplicaSetForTestFactory.java

License:Open Source License

private void initializeReplicaSet(Entry<String, List<IMongodConfig>> entry) throws Exception {
    String replicaName = entry.getKey();
    List<IMongodConfig> mongoConfigList = entry.getValue();

    if (mongoConfigList.size() < 3) {
        throw new Exception("A replica set must contain at least 3 members.");
    }/*from  w  w  w  . j av a 2  s  . c  o  m*/
    // Create 3 mongod processes
    for (IMongodConfig mongoConfig : mongoConfigList) {
        if (!mongoConfig.replication().getReplSetName().equals(replicaName)) {
            throw new Exception("Replica set name must match in mongo configuration");
        }
        MongodStarter starter = MongodStarter.getDefaultInstance();
        MongodExecutable mongodExe = starter.prepare(mongoConfig);
        MongodProcess process = mongodExe.start();
        mongodProcessList.add(process);
    }
    Thread.sleep(1000);
    MongoClientOptions mo = MongoClientOptions.builder().autoConnectRetry(true).build();
    MongoClient mongo = new MongoClient(
            new ServerAddress(mongoConfigList.get(0).net().getServerAddress().getHostName(),
                    mongoConfigList.get(0).net().getPort()),
            mo);
    DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME);

    CommandResult cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1));
    logger.info("isMaster: " + cr);

    // Build BSON object replica set settings
    DBObject replicaSetSetting = new BasicDBObject();
    replicaSetSetting.put("_id", replicaName);
    BasicDBList members = new BasicDBList();
    int i = 0;
    for (IMongodConfig mongoConfig : mongoConfigList) {
        DBObject host = new BasicDBObject();
        host.put("_id", i++);
        host.put("host",
                mongoConfig.net().getServerAddress().getHostName() + ":" + mongoConfig.net().getPort());
        members.add(host);
    }

    replicaSetSetting.put("members", members);
    logger.info(replicaSetSetting.toString());
    // Initialize replica set
    cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate", replicaSetSetting));
    logger.info("replSetInitiate: " + cr);

    Thread.sleep(5000);
    cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
    logger.info("replSetGetStatus: " + cr);

    // Check replica set status before to proceed
    while (!isReplicaSetStarted(cr)) {
        logger.info("Waiting for 3 seconds...");
        Thread.sleep(1000);
        cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
        logger.info("replSetGetStatus: " + cr);
    }

    mongo.close();
    mongo = null;
}

From source file:com.ca.apm.mongo.Topology.java

License:Open Source License

protected MongoClient setupDbClient(final String dbHost, final int dbPort) {
    final boolean useSSL = Collector.getBooleanProp(Collector.USE_SSL_PROP, props);
    final String clientTrustStore = Collector.getOptionalStringProp(Collector.SSL_CLIENT_TRUST_STORE_FILE_PROP,
            props);/*from w  w w . ja  va 2 s .c o m*/
    final String clientPasswd = Collector.getOptionalStringProp(Collector.SSL_CLIENT_TRUST_STORE_PASSWD_PROP,
            props);

    try {
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();

        if (useSSL) {
            System.setProperty(Collector.SSL_CLIENT_TRUST_STORE_FILE_PROP, clientTrustStore);
            System.setProperty(Collector.SSL_CLIENT_TRUST_STORE_PASSWD_PROP, clientPasswd);
            builder = builder.socketFactory(SSLSocketFactory.getDefault());
        }

        final MongoClientOptions options = builder.build();
        MongoClient dbClient = new MongoClient(new ServerAddress(dbHost, dbPort), mongoCreds, options);
        logger.log(Level.FINE, "Connected to mongo at {0}", dbClient.getConnectPoint());
        logger.log(Level.FINE, "Client options: " + dbClient.getMongoClientOptions());
        return dbClient;
    } catch (Exception ex) {
        throw new RuntimeException("Can't initialize mongo client", ex);
    }
}

From source file:com.card.loop.xyz.config.AppConfig.java

@Bean
public Mongo mongo() throws Exception {
    MongoClientFactoryBean mongo = new MongoClientFactoryBean();
    mongo.setSingleton(false);//from   w ww . j  a v a2s  .c o  m
    mongo.setHost(mongodb_host);
    mongo.setPort(mongodb_port);
    Builder builder = MongoClientOptions.builder();
    builder.connectionsPerHost(AppConfig.connectionsPerHost);
    builder.connectTimeout(AppConfig.connectionTimeOut);
    return mongo.getObject();
}

From source file:com.centurylink.mdw.dataaccess.DatabaseAccess.java

License:Apache License

private static synchronized void openMongoDbClient() {
    if (mongoClient == null) {
        String mongoHost = PropertyManager.getProperty(PropertyNames.MDW_MONGODB_HOST);
        int mongoPort = PropertyManager.getIntegerProperty(PropertyNames.MDW_MONGODB_PORT, 27017);
        int maxConnections = PropertyManager.getIntegerProperty(PropertyNames.MDW_MONGODB_POOLSIZE,
                PropertyManager.getIntegerProperty(PropertyNames.MDW_DB_POOLSIZE, 100));

        MongoClientOptions.Builder options = MongoClientOptions.builder();
        options.socketKeepAlive(true);//from ww  w.jav a 2s . co  m
        if (maxConnections > 100) // MongoClient default is 100 max connections per host
            options.connectionsPerHost(maxConnections);

        mongoClient = new MongoClient(new ServerAddress(mongoHost, mongoPort), options.build());
        LoggerUtil.getStandardLogger().info(mongoClient.getMongoClientOptions().toString());
    }
}

From source file:com.centurylink.mdw.mongo.MongoDocumentDb.java

License:Apache License

@Override
public void initializeDbClient() {
    if (mongoClient == null) {
        MongoClientOptions.Builder options = MongoClientOptions.builder();
        if (maxConnections > 100) // MongoClient default is 100 max connections per host
            options.connectionsPerHost(maxConnections);

        mongoClient = new MongoClient(new ServerAddress(dbHost, dbPort), options.build());

        for (String name : mongoClient.getDatabase("mdw").listCollectionNames()) {
            createMongoDocIdIndex(name);
        }/*  ww  w . jav a  2s  .  c o m*/
        LoggerUtil.getStandardLogger().info(mongoClient.getMongoClientOptions().toString());
    }
}

From source file:com.clavain.muninmxcd.java

License:Apache License

/**
 * @param args the command line arguments
 *//*from  w  ww .  ja va  2 s . c om*/
public static void main(String[] args) {

    if (args.length < 1) {
        System.err.println("Usage: java -jar MuninMXcd.jar <full path to config>");
        System.exit(1);
    }

    try {

        initialArgs = args;
        p = new Properties();
        FileInputStream propInFile = null;
        propInFile = new FileInputStream(args[0]);
        p.loadFromXML(propInFile);
        String logfile = p.getProperty("log.file");
        socketTimeout = Integer.parseInt(p.getProperty("socket.timeout"));

        PatternLayout layout = new PatternLayout("%d{ISO8601} %-5p %m%n");

        ConsoleAppender consoleAppender = new ConsoleAppender(layout);
        logger.addAppender(consoleAppender);
        FileAppender fileAppender = new FileAppender(layout, logfile, false);
        logger.addAppender(fileAppender);

        logger.info("MuninMX Collector Daemon - " + version + " starting up...");
        logger.info("Loading configuration from <" + args[0] + ">");

        String l_strLogLevel = p.getProperty("log.level");
        // ALL | DEBUG | INFO | WARN | ERROR | FATAL | OFF:
        if (l_strLogLevel.equals("ALL")) {
            logger.setLevel(Level.ALL);
        } else if (l_strLogLevel.equals("DEBUG")) {
            logger.setLevel(Level.DEBUG);
        } else if (l_strLogLevel.equals("INFO")) {
            logger.setLevel(Level.INFO);
        } else if (l_strLogLevel.equals("WARN")) {
            logger.setLevel(Level.WARN);
        } else if (l_strLogLevel.equals("ERROR")) {
            logger.setLevel(Level.ERROR);
        } else if (l_strLogLevel.equals("FATAL")) {
            logger.setLevel(Level.FATAL);
        } else {
            logger.setLevel(Level.OFF);
        }

        if (p.getProperty("log.more") != null) {
            if (p.getProperty("log.more").equals("true")) {
                logMore = true;
            }
        }

    } catch (Exception ex) {
        System.err.println("Failed to Init basic logging infastructure: " + ex.getLocalizedMessage());
        System.exit(1);
    }

    try {
        // connect to db
        logger.info("Connecting to TokuMX");
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(400);
        builder.autoConnectRetry(true);
        builder.threadsAllowedToBlockForConnectionMultiplier(10);

        // speed up inserts, we dont care if we miss some if the shit hits the fan
        builder.writeConcern(WriteConcern.NONE);
        m = new MongoClient(new ServerAddress(p.getProperty("mongo.host")), builder.build());

        // connect to mysql
        connectToDatabase(p);

        // PreFilling Nodes, max 100 in concurrent
        logger.info("Loading initial MuninNode details. This can take a few minutes...");
        v_munin_nodes = new CopyOnWriteArrayList<>();
        v_cinterval_plugins = new CopyOnWriteArrayList<>();
        v_sockets = new CopyOnWriteArrayList<>();

        java.sql.Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM nodes");
        while (rs.next()) {
            MuninNode mn = new MuninNode();
            mn.setHostname(rs.getString("hostname"));
            mn.setNodename(rs.getString("hostname"));
            mn.setNode_id(rs.getInt("id"));
            mn.setPort(rs.getInt("port"));
            mn.setUser_id(rs.getInt("user_id"));
            mn.setQueryInterval(rs.getInt("query_interval"));
            mn.setStr_via(rs.getString("via_host"));
            mn.setAuthpw(rs.getString("authpw"));
            mn.setGroup(rs.getString("groupname"));
            v_munin_nodes.add(mn);
            logger.info("* " + mn.getHostname() + " queued for pluginfetch");
        }

        // launching quartz scheduler
        logger.info("Launching Scheduler");
        SchedulerFactory sf = new StdSchedulerFactory("quartz.properties");
        sched = sf.getScheduler();
        sched.start();

        // launching quartz scheduler for custom interval
        logger.info("Launching Custom Interval Scheduler");
        SchedulerFactory sfc = new StdSchedulerFactory("customquartz.properties");
        sched_custom = sfc.getScheduler();
        sched_custom.start();

        // starting API server
        new Thread(new JettyLauncher()).start();

        int sleepTime = Integer.parseInt(p.getProperty("startup.sleeptime"));
        int startupIterations = Integer.parseInt(p.getProperty("startup.iterations"));
        // scheduling jobs
        int i = 0;
        for (MuninNode it_mn : v_munin_nodes) {
            if (i == startupIterations) {
                Thread.sleep(sleepTime);
                i = 0;
                logger.info("Waiting " + sleepTime + "ms for new scheduling slot");
            }
            scheduleJob(it_mn);
            i++;
        }

        // schedule custom interval jobs
        dbScheduleAllCustomJobs();

        // add all alerts
        dbAddAllAlerts();

        // Service Checks
        logger.info("Launching Service Check Scheduler");
        SchedulerFactory sfsc = new StdSchedulerFactory("checksquartz.properties");
        sched_checks = sfsc.getScheduler();
        sched_checks.start();
        // load service checks from database
        stmt = conn.createStatement();
        rs = stmt.executeQuery("SELECT * FROM service_checks");
        while (rs.next()) {
            Gson gson = new Gson();
            ServiceCheck tc = gson.fromJson(rs.getString("json"), ServiceCheck.class);
            tc.setCid(rs.getInt("id"));
            tc.setUser_id(rs.getInt("user_id"));
            v_serviceChecks.add(tc);
            logger.info("* " + tc.getCheckname() + " Service Check added");
        }
        // queue service checks
        for (ServiceCheck it_sc : v_serviceChecks) {
            scheduleServiceCheck(it_sc);
        }

        // starting MongoExecutor
        new Thread(new MongoExecutor()).start();

        // starting MongoExecutor for Package Tracking and Essential Informations
        new Thread(new MongoEssentialExecutor()).start();

        // starting MongoExecutor for Service Checks
        new Thread(new MongoCheckExecutor()).start();

        // starting newnodewatcher
        new Thread(new NewNodeWatcher()).start();

        // start pushover sending message
        new Thread(new PushOverLimiter()).start();

        // SMS Limiter
        new Thread(new SMSLimiter()).start();

        // TTS Limiter
        new Thread(new TTSLimiter()).start();

        // start DataRetention Worker
        new Thread(new DataRetentionWorker()).start();

        // start Error Notify Inspector
        new Thread(new ErrorNotifyExecutor()).start();

        int curTime;
        int toTime;
        int mb = 1024 * 1024;
        while (true) {
            Thread.sleep(5000);
            System.out.println("Mongo Queue Size: " + mongo_queue.size());
            System.out.println("Mongo Check Queue Size: " + mongo_check_queue.size());
            System.out.println("Mongo Essential Queue Size: " + mongo_essential_queue.size());

            Runtime runtime = Runtime.getRuntime();
            //Print used memory
            System.out.println("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);

            //Print free memory
            System.out.println("Free Memory:" + runtime.freeMemory() / mb);

            //Print total available memory
            System.out.println("Total Memory:" + runtime.totalMemory() / mb);

            //Print Maximum available memory
            System.out.println("Max Memory:" + runtime.maxMemory() / mb);
            System.out.println(" ");

            if (p.getProperty("kill.sockets").equals("true")) {
                System.out.println("Sockets: " + v_sockets.size());
                // check for sockets that we can kill
                curTime = getUnixtime();
                for (SocketCheck sc : v_sockets) {
                    toTime = curTime - 120;
                    if (sc.getSocketCreated() < toTime) {
                        if (!sc.getSocket().isClosed()) {
                            logger.info("timing out socket... from: " + sc.getHostname());
                            sc.closeSocket();
                            v_sockets.remove(sc);
                        } else {
                            v_sockets.remove(sc);
                        }
                    }
                }
            }

        }
    } catch (Exception ex) {
        System.err.println("Something went wrong as fuck: " + ex.getLocalizedMessage());
        logger.fatal("Something went wrong as fuck. exiting: " + ex.getLocalizedMessage());
        ex.printStackTrace();
        System.exit(1);
    }
}

From source file:com.dawsonsystems.session.MongoManager.java

License:Apache License

private void initDbConnection(String path) throws LifecycleException {
    try {/* w  ww . j  a  v  a2  s.  c om*/
        String[] hosts = getHost().split(",");

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

        for (String host : hosts) {
            addrs.add(new ServerAddress(host, getPort()));
        }

        mongo = new MongoClient(addrs,
                MongoClientOptions.builder().description("TomcatMongoSession[path=" + path + "]")
                        .alwaysUseMBeans(true).connectionsPerHost(connectionsPerHost).build());

        db = mongo.getDatabase(getDatabase());
        if (slaveOk) {
            db.withReadPreference(ReadPreference.secondaryPreferred());
        }
        db.withWriteConcern(WriteConcern.ACKNOWLEDGED);
        getCollection().createIndex(new BasicDBObject("lastmodified", 1));
        log.info("Connected to Mongo " + host + "/" + database + " for session storage, slaveOk=" + slaveOk
                + ", " + (getMaxInactiveInterval() * 1000) + " session live time");
    } catch (RuntimeException e) {
        e.printStackTrace();
        throw new LifecycleException("Error Connecting to Mongo", e);
    }
}

From source file:com.ebay.cloud.cms.mongo.MongoDataSource.java

License:Apache License

public MongoDataSource(String servers, int connectionsPerHost, ReadPreference readPreference,
        CMSDBConfig config) {//  www.ja v  a  2 s .c o m
    this.addrs = parseServerString(servers);

    Collections.sort(addrs, new Comparator<ServerAddress>() {

        @Override
        public int compare(ServerAddress s1, ServerAddress s2) {
            int result = s1.getHost().compareTo(s2.getHost());
            if (result != 0) {
                return result;
            } else {
                return s1.getPort() - s2.getPort();
            }
        }

    });

    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    builder.socketKeepAlive(false);
    builder.connectionsPerHost(connectionsPerHost);
    if (readPreference != null) {
        builder.readPreference(readPreference);
    }
    // set socket timeout
    if (config != null) {
        Integer socketTimeOut = (Integer) config.get(CMSDBConfig.MONGO_CONNECTION_SOCKET_TIMEOUT);
        builder.socketTimeout(socketTimeOut);
    }
    MongoClientOptions mongoOptions = builder.build();
    this.mongo = new MongoClient(addrs, mongoOptions);
}