Example usage for com.mongodb MongoClient MongoClient

List of usage examples for com.mongodb MongoClient MongoClient

Introduction

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

Prototype

public MongoClient(final MongoClientURI uri, final MongoDriverInformation mongoDriverInformation) 

Source Link

Document

Creates a Mongo described by a URI.

Usage

From source file:com.clavain.muninmxcd.java

License:Apache License

/**
 * @param args the command line arguments
 *//*from www  . j a va  2s  .c o  m*/
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.company.Action.java

License:Apache License

public void run() throws NotFound, ResponseException, InterruptedException {
    Way2SMS way2SMS = new Way2SMS();
    way2SMS.Login(USERNAME, PASSWORD);//from  ww  w. j  a v  a2  s  .  c  o  m

    Set<User> hashset = new HashSet<>();
    Set<String> numbers = new HashSet<>();
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase database = mongoClient.getDatabase("Users");
    MongoCollection<Document> collection = database.getCollection("credenzappusers");
    //        System.out.println(collection.count());
    for (Document cur : collection.find()) {
        if (cur.get("Phone1") != null) {
            String value = String.valueOf(cur.get("Phone1"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    hashset.add(new User(((String) cur.get("Name1")).split(" ")[0], value));
                }
            }
        }
        if (cur.get("Phone2") != null) {
            String value = String.valueOf(cur.get("Phone2"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    hashset.add(new User(((String) cur.get("Name2")).split(" ")[0], value));
                }
            }
        }
        if (cur.get("Phone3") != null) {
            String value = String.valueOf(cur.get("Phone3"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    hashset.add(new User(((String) cur.get("Name3")).split(" ")[0], value));
                }
            }
        }
        //            System.out.println("Phone2 is"+cur.get("Phone2"));
    }

    System.out.println(hashset.size());

    collection = database.getCollection("credenzreceipt");
    System.out.println(collection.count());
    for (Document cur : collection.find()) {
        if (cur.get("Contact1") != null) {
            String value = String.valueOf(cur.get("Contact1"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    hashset.add(new User(((String) cur.get("Name1")).split(" ")[0], value));
                }
            }
        }
        if (cur.get("Contact2") != null) {
            String value = String.valueOf(cur.get("Contact2"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    hashset.add(new User(((String) cur.get("Name2")).split(" ")[0], value));
                }
            }
        }
        if (cur.get("Contact3") != null) {
            String value = String.valueOf(cur.get("Contact3"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    try {
                        hashset.add(new User(((String) cur.get("Name3")).split(" ")[0], value));
                    } catch (Exception e) {
                        System.out.println("cought exception");
                    }
                }
            }
        }
        //            System.out.println("Phone2 is"+cur.get("Phone2"));
    }

    collection = database.getCollection("droidfest_users");
    //        System.out.println(collection.count());
    for (Document cur : collection.find()) {
        if (cur.get("phone_no") != null) {
            String value = String.valueOf(cur.get("phone_no"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    hashset.add(new User(((String) cur.get("name")).split(" ")[0], value));
                }
            }
        }
    }

    collection = database.getCollection("hingemeetusers");
    //        System.out.println(collection.count());
    for (Document cur : collection.find()) {
        if (cur.get("Number") != null) {
            String value = String.valueOf(cur.get("Number"));
            if (value.length() == 10) {
                //                    System.out.println(value);
                if (!numbers.contains(value)) {
                    numbers.add(value);
                    hashset.add(new User(((String) cur.get("Name")).split(" ")[0], value));
                }
            }
        }
    }

    System.out.println(hashset.size());
    int i = 1;
    for (User user : hashset) {
        //            System.out.print(user.getName());
        //            System.out.println(user.getPhone_no());
        i++;
        if (i > 7) {
            way2SMS.SendSMS(user.getPhone_no(), "Hi " + user.getName()
                    + "! This is how you can build your Campus Startup: http://bit.ly/28Pa8aC FREE first lesson: http://bit.ly/28POhxJ Only for you:)");
            Thread.sleep(4000);
        } else {
            System.out.println("Interrupted for " + user.getPhone_no());
        }
        System.out.println(i);
    }
    //        List <User> number=new ArrayList<>();
    //        number.add(new User("lol","9819124829"));
    //        number.add(new User("lol","8446499908"));
    //        number.add(new User("lol","7709758284"));
    //        number.add(new User("lol","8956613425"));
    //        number.add(new User("lol","7276807536"));
    //        for (int i=0;i<number.size();i++) {
    //            way2SMS.SendSMS(number.get(i).getPhone_no(), "Hi "+number.get(i).getName()+"! This is how you can build your Campus Startup: http://bit.ly/28Pa8aC FREE first lesson: http://bit.ly/28POhxJ Only for you :)"); //args ; Phone no , Message
    //        }
}

From source file:com.conventus.mongodb.infrastructure.MongoResource.java

private MongoClient createClient() {
    try {/*  w  w  w . ja  v a2s.  c  o m*/
        String host = "localhost";//properties.getProperty("host");
        Integer primaryPort = 27017;//Integer.valueOf(properties.getProperty("primary-port"));

        return new MongoClient(host, primaryPort);
    } catch (UnknownHostException uh) {
        uh.printStackTrace();
    }

    return null;
}

From source file:com.daprota.m2.realm.MongoDBRealm.java

License:Apache License

/**
 * Open (if necessary) and return a database connection for use by
 * this Realm./*from w w w. j  a  v a  2s . c o  m*/
 *
 * @exception M2Exception if a database error occurs
 */
protected DbConnection open() {
    if (!((connectionURL.substring(0, 7)).equals("mongodb"))) {
        containerLog.error(sm.getString("MongoDBRealm.exception: connectionURL not properly set up"));
    }

    String dbName = null;

    String connectionURL2 = connectionURL.substring(10);
    if (connectionURL2.indexOf(',') == -1) {
        if (connectionURL2.indexOf("/") == -1) {
            containerLog.error("M2 ConnectionManager cannot be initialized. Database name is not provide.");
        } else {
            String host = connectionURL2.substring(0, connectionURL2.indexOf(":"));
            String port = connectionURL2.substring(connectionURL2.indexOf(":") + 1,
                    connectionURL2.indexOf("/"));
            dbName = connectionURL2.substring(connectionURL2.indexOf("/") + 1);

            try {
                MongoClient mongoClient = new MongoClient(host, Integer.parseInt(port));
                return (new DbConnection(mongoClient, dbName));
            } catch (UnknownHostException e) {
                containerLog.error(sm.getString("MongoDBRealm.exception"), e);
            }
        }
    } else {
        String[] hostArray = null;

        if (connectionURL2.indexOf('/') == -1) {
            containerLog.error("M2 ConnectionManager cannot be initialized. Database name is not provide.");
        } else {
            dbName = connectionURL2.substring(connectionURL2.indexOf("/") + 1);
            String hostString = connectionURL2.substring(0, connectionURL2.indexOf('/'));
            hostArray = hostString.split(",");
        }

        int length = hostArray.length;
        int idx = 0;
        List<ServerAddress> saList = new ArrayList<ServerAddress>();
        try {
            while (idx < length) {
                String host = hostArray[idx].substring(0, hostArray[idx].indexOf(':'));
                String port = hostArray[idx].substring(hostArray[idx].indexOf(':') + 1);
                saList.add(new ServerAddress(host, Integer.parseInt(port)));
                ++idx;
            }

            MongoClient mongoClient = new MongoClient(saList);
            return (new DbConnection(mongoClient, dbName));
        } catch (MongoException e) {
            containerLog.error(sm.getString("MongoDBRealm.exception"), e);
        } catch (UnknownHostException e) {
            containerLog.error(sm.getString("MongoDBRealm.exception"), e);
        }
    }

    return null;

}

From source file:com.data.DAO.MetodoPagoDAO.java

public static String crearRecibo(Integer idMetodoPago, String descripcion, Integer cuotas, float precio,
        Integer idReserva) {//from  www.  j  av a 2s .  c  om
    String reciboCreado = null;
    try {
        // To connect to mongo dbserver
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // Now connect to your databases
        DB db = mongoClient.getDB("hoex");
        System.out.println("Connect to database successfully");

        DBCollection coll = db.getCollection("Metodo_pago");
        System.out.println("Collection Metodo_pago selected successfully");

        BasicDBObject doc = new BasicDBObject("idMetodoPago", idMetodoPago).append("descripcion", descripcion)
                .append("cuotas", cuotas).append("precio", precio).append("idReserva", idReserva);

        coll.insert(doc);
        System.out.println("Document inserted successfully");
        reciboCreado = "Success";
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }

    if (reciboCreado != null) {
        return "El recibo fue creado satisfactoriamente!";
    } else {
        return "El recibo no ha sido creado!";
    }
}

From source file:com.data.DAO.MetodoPagoDAO.java

public static ArrayList consultarRecibo(Integer idMetodoPago) {
    ArrayList reciboConsulta = new ArrayList();
    try {/*from  w ww.j  a v  a  2 s.c o m*/
        // To connect to mongo dbserver
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // Now connect to your databases
        DB db = mongoClient.getDB("hoex");
        System.out.println("Connect to database successfully");

        // Use an especific collection
        DBCollection coll = db.getCollection("Metodo_pago");
        System.out.println("Collection Metodo_pago selected successfully");

        BasicDBObject whereQuery = new BasicDBObject();
        // Sentence to search one account number
        whereQuery.put("idMetodoPago", idMetodoPago);

        DBCursor cursor = coll.find(whereQuery);

        while (cursor.hasNext()) {
            DBObject consultDocument = cursor.next();
            reciboConsulta.add(consultDocument.get("descripcion"));
            reciboConsulta.add(consultDocument.get("cuotas"));
            reciboConsulta.add(consultDocument.get("precio"));
            reciboConsulta.add(consultDocument.get("idReserva"));
        }
        System.out.println("Document consulted successfully");
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    if (!reciboConsulta.isEmpty()) {
        return reciboConsulta;
    } else {
        return null;
    }
}

From source file:com.data.DAO.MetodoPagoDAO.java

public static String actualizarRecibo(Integer idMetodoPago, String descripcion, Integer cuotas, float precio,
        Integer idReserva) {/*w  w  w  .  ja va 2s.  c om*/
    String reciboActualizar = null;
    try {
        // To connect to mongo dbserver
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // Now connect to your databases
        DB db = mongoClient.getDB("hoex");
        System.out.println("Connect to database successfully");

        DBCollection coll = db.getCollection("Metodo_pago");
        System.out.println("Collection Metodo_pago selected successfully");

        BasicDBObject whereQuery = new BasicDBObject();
        whereQuery.put("idMetodoPago", idMetodoPago);

        DBCursor cursor = coll.find(whereQuery);

        while (cursor.hasNext()) {
            DBObject updateDocument = cursor.next();
            updateDocument.put("descripcion", descripcion);
            updateDocument.put("cuotas", cuotas);
            updateDocument.put("precio", precio);
            updateDocument.put("idReserva", idReserva);
            coll.update(whereQuery, updateDocument);
        }
        System.out.println("Document updated successfully");
        reciboActualizar = "Success";
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    if (reciboActualizar != null) {
        return "El recibo se ha actualizado correctamente!";
    } else {
        return "El recibo no se ha actualizado!";
    }
}

From source file:com.data.DAO.MetodoPagoDAO.java

public static String borrarRecibo(Integer idMetodoPago) {
    String reciboBorrar = null;/* w w  w  .  j a va2 s  .c o m*/
    try {
        // To connect to mongo dbserver
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // Now connect to your databases
        DB db = mongoClient.getDB("hoex");
        System.out.println("Connect to database successfully");

        DBCollection coll = db.getCollection("Metodo_pago");
        System.out.println("Collection Metodo_pago selected successfully");

        BasicDBObject whereQuery = new BasicDBObject();
        whereQuery.put("idMetodoPago", idMetodoPago);

        DBCursor cursor = coll.find(whereQuery);

        coll.remove(whereQuery);
        System.out.println("Documento elminado exitosamente");
        reciboBorrar = "Success";
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }

    if (reciboBorrar != null) {
        return "El recibo ha sido borrado exitosamente!";
    } else {
        return "El recibo no ha sido borrado!";
    }
}

From source file:com.datumbox.common.persistentstorage.factories.MongoDBStructureFactory.java

License:Open Source License

public MongoDBStructureFactory(String database) {
    dbName = database;/*from  w w  w .  j  av  a  2  s .c o  m*/

    if (connection == null) {
        connection = new MongoClient(StorageConfiguration.MongoDB.SERVER_LIST,
                StorageConfiguration.MongoDB.CREDENTIAL_LIST);
    }
    db = connection.getDB(database);
}

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

License:Apache License

private void initDbConnection(String path) throws LifecycleException {
    try {/*from ww  w  .ja v  a 2  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);
    }
}