Example usage for com.mongodb MongoClientOptions.Builder writeConcern

List of usage examples for com.mongodb MongoClientOptions.Builder writeConcern

Introduction

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

Prototype

WriteConcern writeConcern

To view the source code for com.mongodb MongoClientOptions.Builder writeConcern.

Click Source Link

Usage

From source file:com.clavain.muninmxcd.java

License:Apache License

/**
 * @param args the command line arguments
 *///  www . j  av  a 2s.com
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.edgytech.umongo.ConnectDialog.java

License:Apache License

MongoClientOptions getMongoClientOptions() {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    //        moptions.connectionsPerHost = getIntFieldValue(Item.connectionsPerHost);
    //        moptions.threadsAllowedToBlockForConnectionMultiplier = getIntFieldValue(Item.blockingThreadMultiplier);
    //        moptions.maxWaitTime = getIntFieldValue(Item.maxWaitTime);
    builder.connectTimeout(getIntFieldValue(Item.connectTimeout));
    builder.socketTimeout(getIntFieldValue(Item.socketTimeout));
    //        moptions.autoConnectRetry = getBooleanFieldValue(Item.autoConnectRetry);
    if (!getBooleanFieldValue(Item.safeWrites)) {
        builder.writeConcern(WriteConcern.NONE);
    }//ww  w. j a v  a 2  s  .  c  o m

    //        moptions.slaveOk = getBooleanFieldValue(Item.secondaryReads);
    if (getBooleanFieldValue(Item.secondaryReads)) {
        builder.readPreference(ReadPreference.secondaryPreferred());
    }

    int stype = getIntFieldValue(Item.socketType);
    int proxy = getIntFieldValue(Item.proxyType);
    if (proxy == 1) {
        // SOCKS proxy
        final String host = getStringFieldValue(Item.proxyHost);
        final int port = getIntFieldValue(Item.proxyPort);
        builder.socketFactory(new SocketFactory() {

            @Override
            public Socket createSocket() throws IOException {
                SocketAddress addr = new InetSocketAddress(host, port);
                Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
                Socket socket = new Socket(proxy);
                return socket;
            }

            @Override
            public Socket createSocket(String string, int i) throws IOException, UnknownHostException {
                SocketAddress addr = new InetSocketAddress(host, port);
                Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
                Socket socket = new Socket(proxy);
                InetSocketAddress dest = new InetSocketAddress(string, i);
                socket.connect(dest);
                return socket;
            }

            @Override
            public Socket createSocket(String string, int i, InetAddress ia, int i1)
                    throws IOException, UnknownHostException {
                throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public Socket createSocket(InetAddress ia, int i) throws IOException {
                SocketAddress addr = new InetSocketAddress(host, port);
                Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
                Socket socket = new Socket(proxy);
                InetSocketAddress dest = new InetSocketAddress(ia, i);
                socket.connect(dest);
                return socket;
            }

            @Override
            public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });

        //            // authentication.. only supports 1 global for all proxies :(
        //            final String user = getStringFieldValue(Item.proxyUser);
        //            final String pwd = getStringFieldValue(Item.proxyPassword);
        //            if (!user.isEmpty()) {
        //                Authenticator.setDefault(new Authenticator() {
        //                    @Override
        //                    protected PasswordAuthentication getPasswordAuthentication() {
        //                        PasswordAuthentication p = new PasswordAuthentication(user, pwd.toCharArray());
        //                        return p;
        //                    }
        //                });
        //            }
    }

    if (stype == 1) {
        builder.socketFactory(SSLSocketFactory.getDefault());
    } else if (stype == 2) {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            builder.socketFactory(sc.getSocketFactory());
        } catch (Exception e) {
        }
    }

    return builder.build();
}

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

License:Apache License

/**
 * Utility method to configure Mongo connection options
 *
 * @param optsBuilder/*from w ww.  ja  va2s  . com*/
 *          an options builder
 * @param connTimeout
 *          the connection timeout to use (can be null)
 * @param socketTimeout
 *          the socket timeout to use (can be null)
 * @param readPreference
 *          the read preference to use (can be null)
 * @param writeConcern
 *          the writeConcern to use (can be null)
 * @param wTimeout
 *          the w timeout to use (can be null)
 * @param journaled
 *          whether to use journaled writes
 * @param tagSet
 *          the tag set to use in conjunction with the read preference (can be null)
 * @param vars
 *          variables to use
 * @param log
 *          for logging
 * @throws KettleException
 *           if a problem occurs
 */
private void configureConnectionOptions(MongoClientOptions.Builder optsBuilder, String connTimeout,
        String socketTimeout, String readPreference, String writeConcern, String wTimeout, boolean journaled,
        List<String> tagSet, VariableSpace vars, LogChannelInterface log) throws KettleException {

    // connection timeout
    if (!Const.isEmpty(connTimeout)) {
        String connS = vars.environmentSubstitute(connTimeout);
        try {
            int cTimeout = Integer.parseInt(connS);
            if (cTimeout > 0) {
                optsBuilder.connectTimeout(cTimeout);
            }
        } catch (NumberFormatException n) {
            throw new KettleException(n);
        }
    }

    // socket timeout
    if (!Const.isEmpty(socketTimeout)) {
        String sockS = vars.environmentSubstitute(socketTimeout);
        try {
            int sockTimeout = Integer.parseInt(sockS);
            if (sockTimeout > 0) {
                optsBuilder.socketTimeout(sockTimeout);
            }
        } catch (NumberFormatException n) {
            throw new KettleException(n);
        }
    }

    if (log != null) {
        String rpLogSetting = NamedReadPreference.PRIMARY.getName();

        if (!Const.isEmpty(readPreference)) {
            rpLogSetting = readPreference;
        }
        log.logBasic(
                BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.UsingReadPreference", rpLogSetting)); //$NON-NLS-1$
    }
    DBObject firstTagSet = null;
    DBObject[] remainingTagSets = new DBObject[0];
    if (tagSet != null && tagSet.size() > 0) {
        if (tagSet.size() > 1) {
            remainingTagSets = new DBObject[tagSet.size() - 1];
        }

        firstTagSet = (DBObject) JSON.parse(tagSet.get(0).trim());
        for (int i = 1; i < tagSet.size(); i++) {
            remainingTagSets[i - 1] = (DBObject) JSON.parse(tagSet.get(i).trim());
        }
        if (log != null && (!Const.isEmpty(readPreference)
                && !readPreference.equalsIgnoreCase(NamedReadPreference.PRIMARY.getName()))) {
            StringBuilder builder = new StringBuilder();
            for (String s : tagSet) {
                builder.append(s).append(" "); //$NON-NLS-1$
            }
            log.logBasic(BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.UsingReadPreferenceTagSets", //$NON-NLS-1$
                    builder.toString()));
        }
    } else {
        if (log != null) {
            log.logBasic(
                    BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.NoReadPreferenceTagSetsDefined")); //$NON-NLS-1$
        }
    }

    // read preference
    if (!Const.isEmpty(readPreference)) {

        String rp = vars.environmentSubstitute(readPreference);

        NamedReadPreference preference = NamedReadPreference.byName(rp);

        if ((firstTagSet != null) && (preference.getPreference() instanceof TaggableReadPreference)) {
            optsBuilder.readPreference(preference.getTaggableReadPreference(firstTagSet, remainingTagSets));
        } else {
            optsBuilder.readPreference(preference.getPreference());
        }

    }

    // write concern
    writeConcern = vars.environmentSubstitute(writeConcern);
    wTimeout = vars.environmentSubstitute(wTimeout);

    WriteConcern concern = null;

    if (Const.isEmpty(writeConcern) && Const.isEmpty(wTimeout) && !journaled) {
        // all defaults - timeout 0, journal = false, w = 1
        concern = new WriteConcern();
        concern.setWObject(new Integer(1));

        if (log != null) {
            log.logBasic(BaseMessages.getString(PKG,
                    "MongoNoAuthWrapper.Message.ConfiguringWithDefaultWriteConcern")); //$NON-NLS-1$
        }
    } else {
        int wt = 0;
        if (!Const.isEmpty(wTimeout)) {
            try {
                wt = Integer.parseInt(wTimeout);
            } catch (NumberFormatException n) {
                throw new KettleException(n);
            }
        }

        if (!Const.isEmpty(writeConcern)) {
            // try parsing as a number first
            try {
                int wc = Integer.parseInt(writeConcern);
                concern = new WriteConcern(wc, wt, false, journaled);
            } catch (NumberFormatException n) {
                // assume its a valid string - e.g. "majority" or a custom
                // getLastError label associated with a tag set
                concern = new WriteConcern(writeConcern, wt, false, journaled);
            }
        } else {
            concern = new WriteConcern(1, wt, false, journaled);
        }

        if (log != null) {
            String lwc = "w = " + concern.getW() + ", wTimeout = " + concern.getWtimeout() + ", journaled = "
                    + concern.getJ();
            log.logBasic(
                    BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.ConfiguringWithWriteConcern", lwc));
        }
    }
    optsBuilder.writeConcern(concern);
}

From source file:com.novemberain.quartz.mongodb.MongoDBJobStore.java

License:Open Source License

private Mongo connectToMongoDB() throws SchedulerConfigException {

    if (mongoUri != null) {
        return connectToMongoDB(mongoUri);
    }/*from   ww  w . ja  v a  2  s.co  m*/

    MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder();
    optionsBuilder.writeConcern(WriteConcern.SAFE);

    if (mongoOptionAutoConnectRetry != null)
        optionsBuilder.autoConnectRetry(mongoOptionAutoConnectRetry);
    if (mongoOptionMaxConnectionsPerHost != null)
        optionsBuilder.connectionsPerHost(mongoOptionMaxConnectionsPerHost);
    if (mongoOptionConnectTimeoutMillis != null)
        optionsBuilder.connectTimeout(mongoOptionConnectTimeoutMillis);
    if (mongoOptionSocketTimeoutMillis != null)
        optionsBuilder.socketTimeout(mongoOptionSocketTimeoutMillis);
    if (mongoOptionSocketKeepAlive != null)
        optionsBuilder.socketKeepAlive(mongoOptionSocketKeepAlive);
    if (mongoOptionThreadsAllowedToBlockForConnectionMultiplier != null)
        optionsBuilder.threadsAllowedToBlockForConnectionMultiplier(
                mongoOptionThreadsAllowedToBlockForConnectionMultiplier);

    MongoClientOptions options = optionsBuilder.build();

    try {
        ArrayList<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
        for (String a : addresses) {
            serverAddresses.add(new ServerAddress(a));
        }
        return new MongoClient(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);
    }
}

From source file:com.ricardolorenzo.identity.user.impl.UserIdentityManagerMongoDB.java

License:Open Source License

public UserIdentityManagerMongoDB(final Properties conf) throws UnknownHostException {
    this.properties = conf;

    this.databaseUsers = new Boolean(this.properties.getProperty("mongodb.databaseUsers", "true"));

    WriteConcern writeConcern = WriteConcern.MAJORITY;
    String writeConcernType = conf.getProperty("mongodb.writeConcern", "majority").toLowerCase();
    if ("majority".equals(writeConcernType)) {
        writeConcern = WriteConcern.UNACKNOWLEDGED;
    } else if ("unacknowledged".equals(writeConcernType)) {
        writeConcern = WriteConcern.UNACKNOWLEDGED;
    } else if ("acknowledged".equals(writeConcernType)) {
        writeConcern = WriteConcern.ACKNOWLEDGED;
    } else if ("journaled".equals(writeConcernType)) {
        writeConcern = WriteConcern.JOURNALED;
    } else if ("replica_acknowledged".equals(writeConcernType)) {
        writeConcern = WriteConcern.REPLICA_ACKNOWLEDGED;
    }//w w w . j a v a2s  .c  o  m

    ReadPreference readPreference = null;
    String readPreferenceType = conf.getProperty("mongodb.readPreference", "primary").toLowerCase();
    if ("primary".equals(readPreferenceType)) {
        readPreference = ReadPreference.primary();
    } else if ("primary_preferred".equals(readPreferenceType)) {
        readPreference = ReadPreference.primaryPreferred();
    } else if ("secondary".equals(readPreferenceType)) {
        readPreference = ReadPreference.secondary();
    } else if ("secondary_preferred".equals(readPreferenceType)) {
        readPreference = ReadPreference.secondaryPreferred();
    } else if ("nearest".equals(readPreferenceType)) {
        readPreference = ReadPreference.nearest();
    }

    MongoClientOptions.Builder options = MongoClientOptions.builder();
    options.writeConcern(writeConcern);
    options.readPreference(readPreference);
    try {
        options.connectionsPerHost(Integer.parseInt(conf.getProperty("mongodb.threads", "100")));
    } catch (NumberFormatException e) {
        options.connectionsPerHost(100);
    }

    MongoClientURI mongoClientURI = new MongoClientURI(
            conf.getProperty("mongodb.url", "mongodb://localhost:27017"), options);
    if (!this.properties.containsKey("mongodb.database")) {
        if (mongoClientURI.getDatabase() != null && !mongoClientURI.getDatabase().isEmpty()) {
            this.properties.setProperty("mongodb.database", mongoClientURI.getDatabase());
        } else {
            this.properties.setProperty("mongodb.database", DEFAULT_DATABASE);
        }
    }
    mongoClient = new MongoClient(mongoClientURI);
}

From source file:com.streamsets.pipeline.stage.common.mongodb.MongoDBConfig.java

License:Apache License

private MongoClient createClient(Stage.Context context, List<Stage.ConfigIssue> issues,
        ReadPreference readPreference, WriteConcern writeConcern) {
    MongoClientOptions.Builder optionBuilder = new MongoClientOptions.Builder()
            .connectionsPerHost(connectionsPerHost).connectTimeout(connectTimeout)
            .cursorFinalizerEnabled(cursorFinalizerEnabled).heartbeatConnectTimeout(heartbeatConnectTimeout)
            .heartbeatFrequency(heartbeatFrequency).heartbeatSocketTimeout(heartbeatSocketTimeout)
            .localThreshold(localThreshold).maxConnectionIdleTime(maxConnectionIdleTime)
            .maxConnectionLifeTime(maxConnectionLifeTime).maxWaitTime(maxWaitTime)
            .minConnectionsPerHost(minConnectionsPerHost).minHeartbeatFrequency(minHeartbeatFrequency)
            .serverSelectionTimeout(serverSelectionTimeout).socketKeepAlive(socketKeepAlive)
            .socketTimeout(socketTimeout).sslEnabled(sslEnabled)
            .sslInvalidHostNameAllowed(sslInvalidHostNameAllowed)
            .threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);

    // the default value of requiredReplicaSetName is null, so it should be set only if a non-empty string is provided
    if (!requiredReplicaSetName.isEmpty()) {
        optionBuilder = optionBuilder.requiredReplicaSetName(requiredReplicaSetName);
    }/*from w  ww .  java  2  s.c  o  m*/
    // read preference is only set by the source
    if (readPreference != null) {
        optionBuilder = optionBuilder.readPreference(readPreference);
    }
    // write concern is only set by the target
    if (writeConcern != null) {
        optionBuilder = optionBuilder.writeConcern(writeConcern);
    }

    MongoClientURI mongoURI;
    List<ServerAddress> servers = new ArrayList<>();
    try {
        mongoURI = new MongoClientURI(connectionString, optionBuilder);
    } catch (IllegalArgumentException e) {
        issues.add(context.createConfigIssue(Groups.MONGODB.name(), MONGO_CONFIG_PREFIX + "connectionString",
                Errors.MONGODB_00, e.toString()));
        return null;
    }

    validateServerList(context, mongoURI.getHosts(), servers, issues);
    if (!issues.isEmpty()) {
        return null;
    }

    MongoClient mongoClient = null;
    List<MongoCredential> credentials;
    try {
        credentials = createCredentials();
    } catch (StageException ex) {
        issues.add(context.createConfigIssue(Groups.MONGODB.name(), MONGO_CONFIG_PREFIX + "connectionString",
                Errors.MONGODB_34, ex.toString()));
        return null;
    }

    if (credentials.isEmpty()) {
        Optional.ofNullable(mongoURI.getCredentials()).ifPresent(credentials::add);
    }

    try {
        if (isSingleMode) {
            mongoClient = new MongoClient(servers.get(0), credentials, mongoURI.getOptions());
        } else {
            mongoClient = new MongoClient(servers, credentials, mongoURI.getOptions());
        }
    } catch (MongoException e) {
        issues.add(context.createConfigIssue(Groups.MONGODB.name(), MONGO_CONFIG_PREFIX + "connectionString",
                Errors.MONGODB_01, e.toString()));
    }

    return mongoClient;
}

From source file:fr.eolya.utils.nosql.mongodb.MongoDBConnection.java

License:Apache License

/**
 * @param hostName         The MongoDB server host name
 * @param hostPort         The MongoDB server host port
 * @return//from   w  w w .  j av  a 2 s .  c o  m
 * @throws UnknownHostException 
 */
public MongoDBConnection(String hostName, int hostPort, String userName, String userPassword)
        throws UnknownHostException {

    MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
    builder.autoConnectRetry(true);
    builder.socketKeepAlive(true);
    builder.writeConcern(WriteConcern.SAFE);

    if ("".equals(hostName))
        hostName = "localhost";
    if (hostPort > 0) {
        ServerAddress addr = new ServerAddress(hostName, hostPort);
        m = new MongoClient(addr, builder.build());
    } else {
        m = new MongoClient(hostName, builder.build());
    }
    this.hostName = hostName;
    this.hostPort = hostPort;
}

From source file:io.gravitee.repository.mongodb.common.MongoFactory.java

License:Apache License

private MongoClientOptions.Builder builder() {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();

    builder.writeConcern(WriteConcern.SAFE);

    Integer connectionsPerHost = readPropertyValue(propertyPrefix + "connectionsPerHost", Integer.class);
    Integer connectTimeout = readPropertyValue(propertyPrefix + "connectTimeout", Integer.class, 500);
    Integer maxWaitTime = readPropertyValue(propertyPrefix + "maxWaitTime", Integer.class);
    Integer socketTimeout = readPropertyValue(propertyPrefix + "socketTimeout", Integer.class, 500);
    Boolean socketKeepAlive = readPropertyValue(propertyPrefix + "socketKeepAlive", Boolean.class);
    Integer maxConnectionLifeTime = readPropertyValue(propertyPrefix + "maxConnectionLifeTime", Integer.class);
    Integer maxConnectionIdleTime = readPropertyValue(propertyPrefix + "maxConnectionIdleTime", Integer.class);

    // We do not want to wait for a server
    Integer serverSelectionTimeout = readPropertyValue(propertyPrefix + "serverSelectionTimeout", Integer.class,
            0);/*from w w  w  .j a  va2  s  .c  o  m*/
    Integer minHeartbeatFrequency = readPropertyValue(propertyPrefix + "minHeartbeatFrequency", Integer.class);
    String description = readPropertyValue(propertyPrefix + "description", String.class, "gravitee.io");
    Integer heartbeatConnectTimeout = readPropertyValue(propertyPrefix + "heartbeatConnectTimeout",
            Integer.class, 1000);
    Integer heartbeatFrequency = readPropertyValue(propertyPrefix + "heartbeatFrequency", Integer.class);
    Integer heartbeatSocketTimeout = readPropertyValue(propertyPrefix + "heartbeatSocketTimeout",
            Integer.class);
    Integer localThreshold = readPropertyValue(propertyPrefix + "localThreshold", Integer.class);
    Integer minConnectionsPerHost = readPropertyValue(propertyPrefix + "minConnectionsPerHost", Integer.class);
    Boolean sslEnabled = readPropertyValue(propertyPrefix + "sslEnabled", Boolean.class);
    Integer threadsAllowedToBlockForConnectionMultiplier = readPropertyValue(
            propertyPrefix + "threadsAllowedToBlockForConnectionMultiplier", Integer.class);
    Boolean cursorFinalizerEnabled = readPropertyValue(propertyPrefix + "cursorFinalizerEnabled",
            Boolean.class);

    if (connectionsPerHost != null)
        builder.connectionsPerHost(connectionsPerHost);
    if (maxWaitTime != null)
        builder.maxWaitTime(maxWaitTime);
    if (connectTimeout != null)
        builder.connectTimeout(connectTimeout);
    if (socketTimeout != null)
        builder.socketTimeout(socketTimeout);
    if (socketKeepAlive != null)
        builder.socketKeepAlive(socketKeepAlive);
    if (maxConnectionLifeTime != null)
        builder.maxConnectionLifeTime(maxConnectionLifeTime);
    if (maxConnectionIdleTime != null)
        builder.maxConnectionIdleTime(maxConnectionIdleTime);
    if (minHeartbeatFrequency != null)
        builder.minHeartbeatFrequency(minHeartbeatFrequency);
    if (description != null)
        builder.description(description);
    if (heartbeatConnectTimeout != null)
        builder.heartbeatConnectTimeout(heartbeatConnectTimeout);
    if (heartbeatFrequency != null)
        builder.heartbeatFrequency(heartbeatFrequency);
    if (heartbeatSocketTimeout != null)
        builder.heartbeatSocketTimeout(heartbeatSocketTimeout);
    if (localThreshold != null)
        builder.localThreshold(localThreshold);
    if (minConnectionsPerHost != null)
        builder.minConnectionsPerHost(minConnectionsPerHost);
    if (sslEnabled != null)
        builder.sslEnabled(sslEnabled);
    if (threadsAllowedToBlockForConnectionMultiplier != null)
        builder.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);
    if (cursorFinalizerEnabled != null)
        builder.cursorFinalizerEnabled(cursorFinalizerEnabled);
    if (serverSelectionTimeout != null)
        builder.serverSelectionTimeout(serverSelectionTimeout);

    return builder;
}

From source file:org.apache.gora.mongodb.store.MongoStore.java

License:Apache License

/**
 * Retrieve a client connected to the MongoDB server to be used.
 *
 * @param servers/* ww  w .jav  a2 s.c  o  m*/
 *          This value should specify the host:port (at least one) for
 *          connecting to remote MongoDB. Multiple values must be separated by
 *          coma.
 * @return a {@link Mongo} instance connected to the server
 * @throws UnknownHostException
 */
private MongoClient getClient(MongoStoreParameters params) throws UnknownHostException {
    // Configure options
    MongoClientOptions.Builder optBuilder = new MongoClientOptions.Builder()
            .dbEncoderFactory(GoraDBEncoder.FACTORY); // Utf8 serialization!
    if (params.getReadPreference() != null) {
        optBuilder.readPreference(ReadPreference.valueOf(params.getReadPreference()));
    }
    if (params.getWriteConcern() != null) {
        optBuilder.writeConcern(WriteConcern.valueOf(params.getWriteConcern()));
    }
    // If configuration contains a login + secret, try to authenticated with DB
    List<MongoCredential> credentials = null;
    if (params.getLogin() != null && params.getSecret() != null) {
        credentials = new ArrayList<MongoCredential>();
        credentials.add(MongoCredential.createCredential(params.getLogin(), params.getDbname(),
                params.getSecret().toCharArray()));
    }
    // Build server address
    List<ServerAddress> addrs = new ArrayList<ServerAddress>();
    Iterable<String> serversArray = Splitter.on(",").split(params.getServers());
    if (serversArray != null) {
        for (String server : serversArray) {
            Iterator<String> paramsIterator = Splitter.on(":").trimResults().split(server).iterator();
            if (!paramsIterator.hasNext()) {
                // No server, use default
                addrs.add(new ServerAddress());
            } else {
                String host = paramsIterator.next();
                if (paramsIterator.hasNext()) {
                    String port = paramsIterator.next();
                    addrs.add(new ServerAddress(host, Integer.parseInt(port)));
                } else {
                    addrs.add(new ServerAddress(host));
                }
            }
        }
    }
    // Connect to the Mongo server
    return new MongoClient(addrs, credentials, optBuilder.build());
}

From source file:org.apache.jackrabbit.oak.plugins.document.util.MongoConnection.java

License:Apache License

/**
 * Returns {@code true} if the given {@code uri} has a write concern set.
 * @param uri the URI to check.//from   w  ww  .j a v  a 2s  . c  om
 * @return {@code true} if the URI has a write concern set, {@code false}
 *      otherwise.
 */
public static boolean hasWriteConcern(@Nonnull String uri) {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    builder.writeConcern(WC_UNKNOWN);
    WriteConcern wc = new MongoClientURI(checkNotNull(uri), builder).getOptions().getWriteConcern();
    return !WC_UNKNOWN.equals(wc);
}