Example usage for com.mongodb MongoClient getDatabase

List of usage examples for com.mongodb MongoClient getDatabase

Introduction

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

Prototype

public MongoDatabase getDatabase(final String databaseName) 

Source Link

Usage

From source file:org.kiaan.Main.java

/**
public static class view_main extends JFrame {            
        //from  w  w w  . j a v  a2 s .  com
public view_main() throws HeadlessException, IOException {            
    //
            
    addKeyListener(getInputKey());
    //            
    getContentPane();
    setTitle(" ?  ");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setScreenSize();
//            add BorderLayout
    BorderLayout Layout = new BorderLayout();
    Layout.setHgap(3);Layout.setVgap(3);
    setLayout(Layout);
//        add Top
    JPanel pnlMainTop = new JPanel();
    pnlMainTop.setBackground(Color.LIGHT_GRAY);
    add(pnlMainTop, BorderLayout.PAGE_START);
    JButton btn = new JButton("change");
    pnlMainTop.add(btn);
//        add left
    JPanel pnlMainLeft = new JPanel();
    pnlMainLeft.setBackground(Color.LIGHT_GRAY);
    add(pnlMainLeft, BorderLayout.LINE_START);
//        add right
    JPanel pnlMainRight = new JPanel();
    pnlMainRight.setBackground(Color.LIGHT_GRAY);
    add(pnlMainRight, BorderLayout.LINE_END);
//        add Center
    JPanel pnlMainCenter = new JPanel();
    pnlMainCenter.setBackground(Color.GRAY);
    add(pnlMainCenter, BorderLayout.CENTER);
            
    CardLayout cardLayoutMain = new CardLayout();
    pnlMainCenter.setLayout(cardLayoutMain);
    JPanel subPanelMain = new JPanel(); 
    subPanelMain.setBackground(Color.white);
            
    myToggleButton tb_main = new myToggleButton("",false);            
    subPanelMain.add(tb_main);
            
//            JPanel subPanel2 = new JPanel(); subPanel2.setBackground(Color.blue);
    pnlMainCenter.add(subPanelMain, "1");
//            pnlMainCenter.add(subPanel2, "2");
    btn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
//                    cardLayoutMain.show(pnlMainCenter, "2");
            cardLayoutMain.next(pnlMainCenter);
        }
    });
        
            
//        add Bottom
    JPanel pnlMainBottom = new JPanel();
    pnlMainBottom.setBackground(Color.LIGHT_GRAY);
    add(pnlMainBottom, BorderLayout.PAGE_END);
            
            
            
//            JTable tbl = new JTable();
//            add(tbl, BorderLayout.CENTER);
            
            
            
        
}                            
        
private void setScreenSize() {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    setSize(screenSize.width, screenSize.height);
}
}
**/

public static void db() {
    try {
        //connect to db
        MongoClient MongoClient = new MongoClient("localhost", 27017);
        MongoIterable<String> databaseNames = MongoClient.listDatabaseNames();
        //            MongoDatabase kiaanDB = MongoClient.getDatabase("kiaan");            
        //check exists kiaan db
        Boolean blnDBExists = false;
        for (String DBName : databaseNames) {
            if (DBName.equals("kiaan")) {
                blnDBExists = true;
                System.out.println("kiaan database is exists.");
                break;
            }
        }
        if (blnDBExists == false)
            System.out.println("create kiaan database...");
        MongoDatabase mydb = MongoClient.getDatabase("kiaan");
        System.out.println("Connect to database successfully");
        //Check exist user collection
        Boolean blnCollectionName = false;
        for (String collectionName : mydb.listCollectionNames()) {
            if (collectionName.equals("user")) {
                blnCollectionName = true;
                break;
            }
        }
        if (!blnCollectionName) {
            //create users collection
            ObjectId user_id = new ObjectId();
            Document doc = new Document().append("name", "")
                    //.append("credit_limit", 0)
                    //                        .append("status", true)
                    .append("comment", " ? ( ?)")
                    .append("creator_id", user_id).append("users",
                            new Document("_id", user_id).append("id", 1)
                                    .append("first_name", " ")
                                    .append("last_name", "( ? )")
                                    .append("user_name", "admin").append("password", "1602")
                                    //.append("status", false)
                                    .append("creator_id", user_id));
            mydb.getCollection("user").insertOne(doc);
            System.out.println("user collection created...");
            doc.clear();
            //
            BasicDBList dbl = new BasicDBList();
            ObjectId branch_id = new ObjectId();
            dbl.add(new Document("_id", branch_id).append("id", 8561).append("name", " ")
                    .append("city", "").append("creator_id", user_id));
            dbl.add(new Document("_id", new ObjectId()).append("id", 8576).append("name", "")
                    .append("city", "").append("creator_id", user_id));
            ObjectId bank_id = new ObjectId();
            doc = new Document("_id", bank_id).append("name", "")
                    //                        .append("logo", "")
                    .append("creator_id", user_id).append("branches", dbl);
            mydb.getCollection("bank").insertOne(doc);

            dbl = new BasicDBList();
            dbl.add(new Document("_id", new ObjectId()).append("id", 3238).append("name", " ")
                    .append("city", "").append("creator_id", user_id));
            doc = new Document().append("name", "")
                    //                        .append("logo", "")
                    .append("creator_id", user_id).append("branches", dbl);
            mydb.getCollection("bank").insertOne(doc);
            //
            doc = new Document().append("name", "").append("creator_id", user_id).append("branches",
                    new BasicDBList());
            mydb.getCollection("bank").insertOne(doc);
            //add doc to array
            //                DBObject listItem = new BasicDBObject("branches", new BasicDBObject("_id", new ObjectId())
            //                        .append("branch_id",8576)
            //                        .append("name","")
            //                        .append("city","")
            //                );
            //                DBObject findQuery = new BasicDBObject("name", "");
            //                DBObject updateQuery = new BasicDBObject("$push", listItem);
            //                mydb.getCollection("banks").update(findQuery, updateQuery);                                
            //
            System.out.println("bank collection created...");

            //add person
            doc.clear();
            dbl.clear();
            ObjectId person_id1 = new ObjectId();
            ObjectId person_id2 = new ObjectId();
            dbl.add(new Document("_id", person_id1).append("id", 1).append("type", "")
                    .append("first_name", "").append("last_name", "")
                    .append("comment", "     ")
                    .append("creator_id", user_id));

            BasicDBList dbl_tel = new BasicDBList();
            BasicDBList dbl_bankAcc = new BasicDBList();
            dbl_tel.add(new Document("_id", new ObjectId()).append("type", "mobile")
                    .append("number", "09151213139").append("default", true));
            dbl_tel.add(new Document("_id", new ObjectId()).append("type", "mobile").append("number",
                    "09151112233"));
            dbl_tel.add(new Document("_id", new ObjectId()).append("type", "work")
                    .append("number", "05133661313").append("default", true));
            dbl_bankAcc.add(new Document("_id", new ObjectId()).append("type", "bank_acc")
                    .append("bank_id", bank_id).append("number", "4218504285")
                    .append("comment", "  ").append("default", true));
            dbl_bankAcc.add(new Document("_id", new ObjectId()).append("type", "sheba")
                    .append("bank_id", bank_id).append("number", "600120020000004218504285"));
            dbl.add(new Document("_id", person_id2).append("id", 2).append("type", "")
                    .append("first_name", "").append("last_name", "")
                    .append("gender", true).append("credit_limit", 10000000)
                    .append("address",
                            "  -    ?   -  2/716")
                    .append("creator_id", user_id).append("tel", dbl_tel).append("bank_account", dbl_bankAcc));
            doc = new Document("name", "").append("creator_id", user_id).append("persons", dbl);
            mydb.getCollection("person").insertOne(doc);

            mydb.getCollection("person").insertOne(new Document("name", "")
                    .append("creator_id", user_id).append("persons", new BasicDBList()));
            System.out.println("person collection created...");
            //
            doc = new Document("id", 1).append("account_no", "0205575259006")
                    .append("account_holder", "? ").append("bank_id", bank_id)
                    .append("branch_id", branch_id).append("type", 0).append("comment", " ")
                    .append("creator_id", user_id);
            mydb.getCollection("bank_account").insertOne(doc);
            doc = new Document("id", 2).append("account_no", "0207723518008")
                    .append("account_holder", "? ").append("bank_id", bank_id)
                    .append("branch_id", branch_id).append("type", 1).append("creator_id", user_id);
            mydb.getCollection("bank_account").insertOne(doc);

            System.out.println("bank_account collection created...");
            //add units
            ObjectId unit_id = new ObjectId();
            doc = new Document("_id", unit_id).append("name", "").append("creator_id", user_id);
            mydb.getCollection("unit").insertOne(doc);
            System.out.println("Unit collection created...");
            //add products
            dbl = new BasicDBList();
            ObjectId product_id = new ObjectId();
            dbl.add(new Document("_id", product_id).append("id", 1).append("name", "")
                    .append("unit_id", unit_id).append("min_stock", 1000).append("default_price", 8300)
                    .append("comment", " ").append("creator_id", user_id));
            dbl.add(new Document("_id", new ObjectId()).append("id", 2).append("name", "")
                    .append("unit_id", unit_id).append("min_stock", 10).append("default_price", 80000)
                    .append("comment", "  ").append("creator_id", user_id));
            doc = new Document("name", "").append("comment", "  ")
                    .append("creator_id", user_id).append("products", dbl);
            mydb.getCollection("product").insertOne(doc);
            //
            dbl.clear();
            dbl.add(new Document("_id", new ObjectId()).append("id", 3).append("name", "")
                    .append("unit_id", unit_id).append("min_stock", 100).append("default_price", 2500)
                    .append("comment", "   ").append("creator_id", user_id));
            doc = new Document("name", "").append("comment", "   ")
                    .append("creator_id", user_id).append("products", dbl);
            mydb.getCollection("product").insertOne(doc);
            //
            System.out.println("product Document created...");

            //add buy
            doc.clear();
            dbl.clear();
            dbl.add(new Document("_id", new ObjectId()).append("product_id", product_id).append("value", 100)
                    .append("price", 9250).append("comment", "   "));
            dbl.add(new Document("_id", new ObjectId()).append("product_id", product_id).append("value", 350)
                    .append("price", 9350).append("comment", "   "));
            doc = new Document("_id", new ObjectId()).append("type", "buy").append("id", 1)
                    .append("person_id", person_id1).append("by", "? ").append("discount", -1500)
                    //                        .append("increase", 0)
                    .append("tax", 4000)
                    //                        .append("fare", 0)
                    .append("comment", "  ?").append("creator_id", user_id)
                    .append("items", dbl);
            mydb.getCollection("buy").insertOne(doc);
            //                doc.clear(); dbl.clear();
            //                dbl.add(new BasicDBObject("_id",new ObjectId())
            //                        .append("product_id", 1)
            //                        .append("value", 1000)
            //                        .append("price", 9300)                        
            //                );
            //                doc = new BasicDBObject("num", 2)
            //                        .append("date", new Date())                        
            //                        .append("person_id", person_id2)
            //                        .append("by", "? ")
            //                        .append("discount", 0)
            //                        .append("increase", 0)
            //                        .append("user_id", user_id)
            //                        .append("items", dbl);
            //                mydb.getCollection("buy").insert(doc);         
            System.out.println("buy Document created...");

        }

        //            System.out.println("Collection created successfully");
        //            BasicDBObject doc = new BasicDBObject("name","mongoDB");
        //            coll.insert(doc);
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:org.lambdamatic.mongodb.internal.LambdamaticMongoCollectionImpl.java

License:Open Source License

/**
 * Constructor./*  w  ww .  j ava2 s .c  om*/
 * 
 * @param mongoClient the underlying MongoDB Client.
 * @param databaseName the name of the underlying {@link MongoDatabase} to use with the given
 *        client.
 * @param collectionName the name of the {@link MongoCollection} to use in the given database.
 * @param targetClass the Java type associated with the documents in the {@link MongoCollection}.
 */
public LambdamaticMongoCollectionImpl(final MongoClient mongoClient, final String databaseName,
        final String collectionName, final Class<DomainType> targetClass) {
    super(mongoClient.getDatabase(databaseName).withCodecRegistry(BsonUtils.codecRegistry)
            .getCollection(collectionName, targetClass));
    this.targetClass = targetClass;
    LOGGER.debug("Initialized MongoCollection for documents of class '{}'", targetClass);
}

From source file:org.log4mongo.MongoDbAppender.java

License:Apache License

protected MongoDatabase getDatabase(MongoClient mongo, String databaseName) {
    return mongo.getDatabase(databaseName);
}

From source file:org.mongodb.tse.tests.RunQueryThreadPool.java

public static void main(String[] args) {
    Option help = Option.builder("help").argName("help").desc("get help").build();
    Option ouri = Option.builder("uri").argName("uri").desc("mongodb uri, required").hasArg().type(String.class)
            .build();/*from   ww  w .java 2s . c o m*/
    Option odatabase = Option.builder("database").argName("database")
            .desc("mongodb database, default productpersistdb").hasArg().type(String.class).build();
    Option ocollection = Option.builder("collection").argName("collection")
            .desc("mongodb collection, default product").hasArg().type(String.class).build();
    Option osleep = Option.builder("sleep").argName("sleep").desc("sleep between runs, default 10 seconds")
            .hasArg().type(Integer.class).build();
    Option othreads = Option.builder("threads").argName("threads").desc("number of threads to run, default 5")
            .hasArg().type(Integer.class).build();
    Option readPreference = Option.builder("readPreference").argName("readPreference")
            .desc("read preference, default is secondaryPreferred").hasArg().type(String.class).build();
    Option oids = Option.builder("ids").argName("ids").desc("list of comma separated ids").hasArg()
            .type(String.class).build();
    Option oidFile = Option.builder("idFile").argName("idFile").desc("file containing ids per line").hasArg()
            .type(String.class).build();
    Option oincludeslow = Option.builder("includeslow").argName("includeslow")
            .desc("run slow query that will pause 1 second for every document in collection").build();
    Option oincreasethreads = Option.builder("increasethreads").argName("increasethreads")
            .desc("increase thread count every second until this number").hasArg().type(Integer.class).build();

    Options options = new Options();
    options.addOption(help);
    options.addOption(ouri);
    options.addOption(odatabase);
    options.addOption(ocollection);
    options.addOption(osleep);
    options.addOption(othreads);
    options.addOption(readPreference);
    options.addOption(oids);
    options.addOption(oidFile);
    options.addOption(oincludeslow);
    options.addOption(oincreasethreads);

    CommandLineParser parser = new DefaultParser();
    CommandLine cline = null;
    try {
        // parse the command line arguments
        cline = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }

    if (args.length == 0 || cline.hasOption("help") || !cline.hasOption("uri")) {
        printHelp(options);
    }

    final String[] ids = parseIdFile(cline);

    String uriParameter = cline.getOptionValue("uri");
    String databaseParameter = cline.getOptionValue("database", "productpersistdb");
    String collectionParameter = cline.getOptionValue("collection", "product");
    System.out.println("Using database: " + databaseParameter + " and collection: " + collectionParameter);

    MongoClientURI uri = new MongoClientURI(uriParameter);
    MongoClient mongoClient = new MongoClient(uri);

    MongoDatabase database = mongoClient.getDatabase(databaseParameter);
    final MongoCollection<Document> collection = getCollection(cline, database, collectionParameter);

    long tsleep = 10000;
    if (cline.hasOption("sleep"))
        tsleep = Integer.parseInt(cline.getOptionValue("sleep")) * 1000;
    final long sleep = tsleep;
    int threads = 5;
    if (cline.hasOption("threads"))
        threads = Integer.parseInt(cline.getOptionValue("threads"));

    int max = ids.length;
    boolean includeslow = cline.hasOption("includeslow");
    ExecutorService pool = Executors.newCachedThreadPool();
    for (int i = 0; i < threads; i++) {
        pool.execute(new Runnable() {
            public void run() {
                int count = 0;
                for (;;) {
                    String id = ids[(count % max)];
                    Document doc = null;
                    RawBsonDocument raw = null;

                    Date date = new Date();
                    long end = 0L;
                    long start = System.nanoTime();

                    try {
                        if (includeslow
                        //&& ( count % 2 ) == 0 
                        ) {
                            FindIterable<Document> fit = collection
                                    .find(where("function() { "
                                            + "var d = new Date((new Date()).getTime() + 1*1000); "
                                            + "while ( d > (new Date())) { }; " + "return true;" + "}"))
                                    .limit(100);
                            int dcount = 0;
                            for (Document d : fit) {
                                dcount++;
                            }
                            System.out.println(
                                    String.format("%s - slow query, count:%s, start: %s, elasped: %s ns",
                                            Thread.currentThread().getName(), dcount, date, (end - start)));
                        } else {
                            doc = collection
                                    .find(and(eq("_id", id), where("function() { "
                                            + "var d = new Date((new Date()).getTime() + 1*1000); "
                                            + "while ( d > (new Date())) { }; " + "return true;" + "}")))
                                    .first();
                            end = System.nanoTime();
                            if (doc == null)
                                System.out.println("Could not find " + id);
                            System.out.println(String.format("%s - id: %s, start: %s, elasped: %s ns",
                                    Thread.currentThread().getName(), id, date, (end - start)));
                        }
                    } catch (Exception e) {
                        System.out.println("Got an exception: " + e.getMessage());
                        e.printStackTrace();
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e2) {
                        }
                    }

                    //try { Thread.sleep(sleep); } catch ( InterruptedException e ) {}
                    count++;

                }

            }
        });
    }
    if (cline.hasOption("increasethreads")) {
        int increaseThreads = Integer.parseInt(cline.getOptionValue("increasethreads"));
        for (int i = threads; i < increaseThreads; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            pool.execute(new Runnable() {
                public void run() {
                    int count = 0;
                    for (;;) {
                        String id = ids[(count % max)];
                        Document doc = null;
                        RawBsonDocument raw = null;

                        Date date = new Date();
                        long end = 0L;
                        long start = System.nanoTime();

                        try {
                            if (includeslow
                            //&& ( count % 2 == 0 ) 
                            ) {
                                FindIterable<Document> fit = collection
                                        .find(where("function() { "
                                                + "var d = new Date((new Date()).getTime() + 1*1000); "
                                                + "while ( d > (new Date())) { }; " + "return true;" + "}"))
                                        .limit(100);
                                int dcount = 0;
                                for (Document d : fit) {
                                    dcount++;
                                }
                                System.out.println(
                                        String.format("%s - slow query, count:%s, start: %s, elasped: %s ns",
                                                Thread.currentThread().getName(), dcount, date, (end - start)));
                            } else {
                                doc = collection
                                        .find(and(eq("_id", id), where("function() { "
                                                + "var d = new Date((new Date()).getTime() + 1*1000); "
                                                + "while ( d > (new Date())) { }; " + "return true;" + "}")))
                                        .first();
                                end = System.nanoTime();
                                if (doc == null)
                                    System.out.println("Could not find " + id);
                                System.out.println(String.format("%s - id: %s, start: %s, elasped: %s ns",
                                        Thread.currentThread().getName(), id, date, (end - start)));
                            }
                        } catch (Exception e) {
                            System.out.println("Got an exception: " + e.getMessage());
                            e.printStackTrace();
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e2) {
                            }
                        }

                        //try { Thread.sleep(sleep); } catch ( InterruptedException e ) {}
                        count++;

                    }

                }
            });
        }
    }
}

From source file:org.mongodb.tse.tests.Timings.java

public static void main(String[] args) throws ParseException {

    Option help = Option.builder("help").argName("help").desc("get help").build();
    Option test = Option.builder("test").argName("test").desc("quick test").build();
    Option ouri = Option.builder("uri").argName("uri").desc("mongodb uri, required").hasArg().type(String.class)
            .build();//  w  ww  .  ja  v  a  2  s .  c o m
    Option odatabase = Option.builder("database").argName("database")
            .desc("mongodb database, default productpersistdb").hasArg().type(String.class).build();
    Option ocollection = Option.builder("collection").argName("collection")
            .desc("mongodb collection, default product").hasArg().type(String.class).build();
    Option osleep = Option.builder("sleep").argName("sleep").desc("sleep between runs, default 10 seconds")
            .hasArg().type(Integer.class).build();
    Option otimes = Option.builder("times").argName("times").desc("number of times to run, default 100")
            .hasArg().type(Integer.class).build();
    Option readPreference = Option.builder("readPreference").argName("readPreference")
            .desc("read preference, default is secondaryPreferred").hasArg().type(String.class).build();
    Option oids = Option.builder("ids").argName("ids").desc("list of comma separated ids").hasArg()
            .type(String.class).build();
    Option oidFile = Option.builder("idFile").argName("idFile").desc("file containing ids per line").hasArg()
            .type(String.class).build();
    Option odoc = Option.builder("doc").argName("doc")
            .desc("get a Document instead of RawBsonDocument, no size output with this option").build();

    Options options = new Options();
    options.addOption(help);
    options.addOption(test);
    options.addOption(ouri);
    options.addOption(odatabase);
    options.addOption(ocollection);
    options.addOption(osleep);
    options.addOption(otimes);
    options.addOption(readPreference);
    options.addOption(oids);
    options.addOption(oidFile);
    options.addOption(odoc);

    CommandLineParser parser = new DefaultParser();
    CommandLine cline = null;
    try {
        // parse the command line arguments
        cline = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }

    if (args.length == 0 || cline.hasOption("help") || !cline.hasOption("uri")) {
        printHelp(options);
    }

    if (cline.hasOption("test")) {
        List<Double> testList = new ArrayList<Double>();
        for (int i = 0; i < 100; i++) {
            testList.add(new Double(i));
        }
        Collections.sort(testList);
        System.out.println(String.format("P50: %.2f, P75: %.2f, P90: %.2f, P95: %.2f, P99: %.2f",
                percentile(testList, 0.50), percentile(testList, 0.75), percentile(testList, 0.90),
                percentile(testList, 0.95), percentile(testList, 0.99)));
        System.exit(0);
    }

    String[] ids = null;
    if (cline.hasOption("idFile")) {
        ids = parseIdFile(new File(cline.getOptionValue("idFile")));
    } else
        ids = cline.getOptionValue("ids", "517886481000").split(",");

    List<Double> timeList = new ArrayList<>();

    String uriParameter = cline.getOptionValue("uri");
    String databaseParameter = cline.getOptionValue("database", "productpersistdb");
    String collectionParameter = cline.getOptionValue("collection", "product");
    System.out.println("Using database: " + databaseParameter + " and collection: " + collectionParameter);

    MongoClientURI uri = new MongoClientURI(uriParameter);
    MongoClient mongoClient = new MongoClient(uri);

    MongoDatabase database = mongoClient.getDatabase(databaseParameter);
    MongoCollection<Document> collection = null;
    MongoCollection<RawBsonDocument> rawCollection = null;

    boolean doDoc = cline.hasOption("doc");
    if (doDoc) {
        if (cline.hasOption("readPreference")) {
            String p = cline.getOptionValue("readPreference");
            collection = database.getCollection(collectionParameter)
                    .withReadPreference(ReadPreference.valueOf(p));
        } else
            collection = database.getCollection(collectionParameter)
                    .withReadPreference(ReadPreference.secondaryPreferred());
    } else {
        if (cline.hasOption("readPreference")) {
            String p = cline.getOptionValue("readPreference");
            rawCollection = database.getCollection(collectionParameter, RawBsonDocument.class)
                    .withReadPreference(ReadPreference.valueOf(p));
        } else
            rawCollection = database.getCollection(collectionParameter, RawBsonDocument.class)
                    .withReadPreference(ReadPreference.secondaryPreferred());
    }

    long sleep = 10000;
    if (cline.hasOption("sleep"))
        sleep = Integer.parseInt(cline.getOptionValue("sleep")) * 1000;
    int times = 100;
    if (cline.hasOption("times"))
        times = Integer.parseInt(cline.getOptionValue("times"));

    int count = 0;
    int max = ids.length;
    while (count < times) {
        String id = ids[(count % max)];
        Document doc = null;
        RawBsonDocument raw = null;

        Date date = new Date();
        long end = 0L;
        long start = System.nanoTime();
        if (doDoc) {
            doc = collection.find(eq("_id", id)).first();
            end = System.nanoTime();
            if (doc == null)
                System.out.println("Could not find " + id);
        } else {
            raw = rawCollection.find(eq("_id", id)).first();
            end = System.nanoTime();
            if (raw == null)
                System.out.println("Could not find " + id);
        }

        int size = 0;
        if (raw != null)
            size = raw.getByteBuffer().capacity();

        if (raw != null) {
            System.out.println(String.format("id: %s, start: %s, elasped: %s ns, docSize: %s", id, date,
                    (end - start), size));
        } else {
            System.out.println(String.format("id: %s, start: %s, elasped: %s ns", id, date, (end - start)));
        }
        timeList.add(new Double(end - start));
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
        }
        count++;
    }

    Collections.sort(timeList);

    System.out.println(String.format("P50: %.2f, P75: %.2f, P90: %.2f, P95: %.2f, P99: %.2f",
            percentile(timeList, 0.50), percentile(timeList, 0.75), percentile(timeList, 0.90),
            percentile(timeList, 0.95), percentile(timeList, 0.99)));
}

From source file:org.nuxeo.directory.mongodb.MongoDBConnectionHelper.java

License:Apache License

/**
 * @return a database representing the specified database
 *///  w w  w .ja  v a2 s. c  o  m
public static MongoDatabase getDatabase(MongoClient mongoClient, String dbname) {
    if (StringUtils.isBlank(dbname)) {
        dbname = DB_DEFAULT;
    }
    return mongoClient.getDatabase(dbname);
}

From source file:org.nuxeo.ecm.core.storage.mongodb.MongoDBChecker.java

License:Apache License

@Override
public void check(ConfigurationGenerator cg) throws ConfigurationException {
    MongoClient ret = null;
    String serverName = cg.getUserConfig().getProperty(ConfigurationGenerator.PARAM_MONGODB_SERVER);
    String dbName = cg.getUserConfig().getProperty(ConfigurationGenerator.PARAM_MONGODB_NAME);

    MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder()
            .serverSelectionTimeout((int) TimeUnit.SECONDS.toMillis(1)).description("Nuxeo DB Check");
    if (serverName.startsWith("mongodb://")) {
        // allow mongodb:// URI syntax for the server, to pass everything in one string
        ret = new MongoClient(new MongoClientURI(serverName, optionsBuilder));
    } else {/*from ww w  .j  av a2s.co m*/
        ret = new MongoClient(new ServerAddress(serverName), optionsBuilder.build());
    }
    try {
        Document ping = new Document("ping", "1");
        ret.getDatabase(dbName).runCommand(ping);
    } catch (MongoTimeoutException e) {
        throw new ConfigurationException(
                String.format("Unable to connect to MongoDB at %s, please check your connection", serverName));
    } finally {
        ret.close();
    }
}

From source file:org.opencb.commons.datastore.mongodb.MongoDataStoreManager.java

License:Apache License

private MongoDataStore create(String database, MongoDBConfiguration mongoDBConfiguration) {
    MongoDataStore mongoDataStore = null;
    MongoClient mc = null;
    logger.debug(/*from w ww .ja  v  a2  s  .  co m*/
            "MongoDataStoreManager: creating a MongoDataStore object for database: '" + database + "' ...");
    long t0 = System.currentTimeMillis();
    if (database != null && !database.trim().equals("")) {
        // read DB configuration for that SPECIES.VERSION, by default
        // PRIMARY_DB is selected
        //            String dbPrefix = applicationProperties.getProperty(speciesVersionPrefix + ".DB", "PRIMARY_DB");
        // We create the MongoClientOptions
        MongoClientOptions mongoClientOptions;
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder()
                .connectionsPerHost(
                        mongoDBConfiguration.getInt(CONNECTIONS_PER_HOST, CONNECTIONS_PER_HOST_DEFAULT))
                .connectTimeout(mongoDBConfiguration.getInt(CONNECT_TIMEOUT, CONNECT_TIMEOUT_DEFAULT))
                .readPreference(ReadPreference.valueOf(
                        mongoDBConfiguration.getString(READ_PREFERENCE, READ_PREFERENCE_DEFAULT.getValue())));

        if (mongoDBConfiguration.getString(REPLICA_SET) != null
                && !mongoDBConfiguration.getString(REPLICA_SET).isEmpty()) {
            logger.debug("Setting replicaSet to " + mongoDBConfiguration.getString(REPLICA_SET));
            builder = builder.requiredReplicaSetName(mongoDBConfiguration.getString(REPLICA_SET));
        }

        if (mongoDBConfiguration.getBoolean(SSL_ENABLED)) {
            logger.debug("SSL connections enabled for " + database);
            builder = builder.sslEnabled(mongoDBConfiguration.getBoolean(SSL_ENABLED));
        }

        mongoClientOptions = builder.build();

        assert (dataStoreServerAddresses != null);

        // We create the MongoCredential object
        String user = mongoDBConfiguration.getString(USERNAME, "");
        String pass = mongoDBConfiguration.getString(PASSWORD, "");
        MongoCredential mongoCredential = null;
        if ((user != null && !user.equals("")) || (pass != null && !pass.equals(""))) {
            //                final DB authenticationDatabase;
            if (mongoDBConfiguration.get(AUTHENTICATION_DATABASE) != null
                    && !mongoDBConfiguration.getString(AUTHENTICATION_DATABASE).isEmpty()) {
                //                        authenticationDatabase = mc.getDB(mongoDBConfiguration.getString("authenticationDatabase"));
                mongoCredential = MongoCredential.createScramSha1Credential(user,
                        mongoDBConfiguration.getString(AUTHENTICATION_DATABASE), pass.toCharArray());
            } else {
                //                        authenticationDatabase = db;
                mongoCredential = MongoCredential.createScramSha1Credential(user, "", pass.toCharArray());
            }
            //                    authenticationDatabase.authenticate(user, pass.toCharArray());
        }

        mc = newMongoClient(mongoClientOptions, mongoCredential);

        //                mc.setReadPreference(ReadPreference.secondary(new BasicDBObject("dc", "PG")));
        //                mc.setReadPreference(ReadPreference.primary());
        //                System.out.println("Replica Status: "+mc.getReplicaSetStatus());
        logger.debug(mongoDBConfiguration.toString());
        MongoDatabase db = mc.getDatabase(database);
        //                db.setReadPreference(ReadPreference.secondary(new BasicDBObject("dc", "PG")));
        //                db.setReadPreference(ReadPreference.primary());

        long t1 = System.currentTimeMillis();
        logger.debug("MongoDataStoreManager: MongoDataStore object for database: '" + database + "' created in "
                + (t0 - t1) + "ms");
        mongoDataStore = new MongoDataStore(mc, db, mongoDBConfiguration);
    } else {
        logger.debug("MongoDB database is null or empty");
    }
    return mongoDataStore;
}

From source file:org.pac4j.mongo.test.tools.MongoServer.java

License:Apache License

public void start(final int port) {
    MongodStarter starter = MongodStarter.getDefaultInstance();

    try {/*  ww  w .  j  a  va  2  s.  co  m*/
        IMongodConfig mongodConfig = new MongodConfigBuilder().version(Version.Main.PRODUCTION)
                .net(new Net(port, Network.localhostIsIPv6())).build();

        mongodExecutable = starter.prepare(mongodConfig);
        MongodProcess mongod = mongodExecutable.start();

        // populate
        final MongoClient mongo = new MongoClient("localhost", port);
        final MongoDatabase db = mongo.getDatabase("users");
        db.createCollection("users");
        final MongoCollection<Document> collection = db.getCollection("users");
        final PasswordEncoder encoder = new BasicSaltedSha512PasswordEncoder(SALT);
        final String password = encoder.encode(PASSWORD);
        Map<String, Object> properties1 = new HashMap<>();
        properties1.put(USERNAME, GOOD_USERNAME);
        properties1.put(PASSWORD, password);
        properties1.put(FIRSTNAME, FIRSTNAME_VALUE);
        collection.insertOne(new Document(properties1));
        Map<String, Object> properties2 = new HashMap<>();
        properties2.put(USERNAME, MULTIPLE_USERNAME);
        properties2.put(PASSWORD, password);
        collection.insertOne(new Document(properties2));
        Map<String, Object> properties3 = new HashMap<>();
        properties3.put(USERNAME, MULTIPLE_USERNAME);
        properties3.put(PASSWORD, password);
        collection.insertOne(new Document(properties3));

    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.radarcns.mongo.util.MongoHelper.java

License:Apache License

/**
 * Returns the needed MongoDB collection.
 *
 * @param client the MongoDB client// ww w .j  a  va  2  s .  c om
 * @param collection is the name of the returned connection
 * @return the MongoDB collection named collection.
 */
public static MongoCollection<Document> getCollection(MongoClient client, String collection) {
    return client.getDatabase(Properties.getApiConfig().getMongoDbName()).getCollection(collection);
}