Example usage for com.mongodb MongoClient listDatabaseNames

List of usage examples for com.mongodb MongoClient listDatabaseNames

Introduction

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

Prototype

public MongoIterable<String> listDatabaseNames() 

Source Link

Document

Get a list of the database names

Usage

From source file:com.bluedragon.mongo.MongoCollectionList.java

License:Open Source License

public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
    MongoClient client = getMongoClient(_session, argStruct);

    try {/*from  w  ww . ja va 2s.  c o  m*/
        cfArrayData arr = cfArrayData.createArray(1);

        client.listDatabaseNames().forEach(new Block<String>() {

            @Override
            public void apply(String dbName) {
                try {
                    arr.addElement(new cfStringData(dbName));
                } catch (cfmRunTimeException e) {
                }
            }

        });

        return arr;
    } catch (MongoException me) {
        throwException(_session, me.getMessage());
        return null;
    }
}

From source file:com.bluedragon.mongo.MongoDatabaseList.java

License:Open Source License

public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
    MongoClient client = getMongoClient(_session, argStruct);

    try {//from www .j a v a2  s.c  om
        cfArrayData arr = cfArrayData.createArray(1);

        client.listDatabaseNames().forEach(new Block<String>() {

            @Override
            public void apply(final String st) {
                try {
                    arr.addElement(new cfStringData(st));
                } catch (cfmRunTimeException e) {
                }
            }
        });

        return arr;
    } catch (MongoException me) {
        throwException(_session, me.getMessage());
        return null;
    }
}

From source file:io.debezium.connector.mongodb.MongoUtil.java

License:Apache License

/**
 * Perform the given operation on each of the database names.
 * //from ww  w .ja v  a2 s  . c  om
 * @param client the MongoDB client; may not be null
 * @param operation the operation to perform; may not be null
 */
public static void forEachDatabaseName(MongoClient client, Consumer<String> operation) {
    forEach(client.listDatabaseNames(), operation);
}

From source file:io.debezium.connector.mongodb.MongoUtil.java

License:Apache License

/**
 * Perform the given operation on the database with the given name, only if that database exists.
 * /*from w w  w  .j av  a 2s  . com*/
 * @param client the MongoDB client; may not be null
 * @param dbName the name of the database; may not be null
 * @param dbOperation the operation to perform; may not be null
 */
public static void onDatabase(MongoClient client, String dbName, Consumer<MongoDatabase> dbOperation) {
    if (contains(client.listDatabaseNames(), dbName)) {
        dbOperation.accept(client.getDatabase(dbName));
    }
}

From source file:mongodb.QuickTourAdmin.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args/*from www .  j  a v  a  2 s  .  com*/
 *            takes an optional single argument for the connection string
 */
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the specified database server
        mongoClient = new MongoClient("10.9.17.105", 27017);
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }

    // get handle to "test" database
    MongoDatabase database = mongoClient.getDatabase("test");

    database.drop();

    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");

    // drop all the data in it
    collection.drop();

    // getting a list of databases
    for (String name : mongoClient.listDatabaseNames()) {
        System.out.println(name);
    }

    // drop a database
    mongoClient.getDatabase("databaseToBeDropped").drop();

    // create a collection
    database.createCollection("cappedCollection",
            new CreateCollectionOptions().capped(true).sizeInBytes(0x100000));

    for (String name : database.listCollectionNames()) {
        System.out.println(name);
    }

    // drop a collection:
    collection.drop();

    // create an ascending index on the "i" field
    // 1 ascending or -1 for descending
    collection.createIndex(new Document("i", 1));

    // list the indexes on the collection
    for (final Document index : collection.listIndexes()) {
        System.out.println(index.toJson());
    }

    // create a text index on the "content" field
    // text indexes to support text search of string content
    collection.createIndex(new Document("content", "text"));

    collection.insertOne(new Document("_id", 0).append("content", "textual content"));
    collection.insertOne(new Document("_id", 1).append("content", "additional content"));
    collection.insertOne(new Document("_id", 2).append("content", "irrelevant content"));

    // Find using the text index
    long matchCount = collection.count(text("textual content -irrelevant"));
    System.out.println("Text search matches: " + matchCount);

    // Find using the $language operator
    Bson textSearch = text("textual content -irrelevant", "english");
    matchCount = collection.count(textSearch);
    System.out.println("Text search matches (english): " + matchCount);

    // Find the highest scoring match
    Document projection = new Document("score", new Document("$meta", "textScore"));
    Document myDoc = collection.find(textSearch).projection(projection).first();
    System.out.println("Highest scoring document: " + myDoc.toJson());

    // Run a command
    Document buildInfo = database.runCommand(new Document("buildInfo", 1));
    System.out.println(buildInfo);

    // release resources
    database.drop();
    mongoClient.close();
}

From source file:org.codinjutsu.tools.nosql.mongo.logic.SingleMongoClient.java

License:Apache License

List<Database> loadDatabaseCollections(ServerConfiguration configuration) {
    MongoClient mongo = null;
    List<Database> mongoDatabases = new LinkedList<>();
    try {//from  www . ja  va  2 s . c om
        String userDatabase = configuration.getUserDatabase();

        mongo = createMongoClient(configuration);

        if (StringUtils.isNotEmpty(userDatabase)) {
            MongoDatabase database = mongo.getDatabase(userDatabase);
            mongoDatabases.add(createMongoDatabaseAndItsCollections(database));
        } else {
            MongoIterable<String> databaseNames = mongo.listDatabaseNames();
            for (String databaseName : databaseNames) {
                MongoDatabase database = mongo.getDatabase(databaseName);
                mongoDatabases.add(createMongoDatabaseAndItsCollections(database));
            }

            Collections.sort(mongoDatabases, new Comparator<Database>() {
                @Override
                public int compare(Database o1, Database o2) {
                    return o1.getName().compareTo(o2.getName());
                }
            });
        }

        return mongoDatabases;
    } catch (MongoException | UnknownHostException mongoEx) {
        throw new ConfigurationException(mongoEx);
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}

From source file:org.flywaydb.core.internal.dbsupport.mongo.MongoDatabaseUtil.java

License:Apache License

/**
 * Checks whether a Mongo database exists.
 *
 * @param client a MongoClient for connecting to the database.
 * @param dbName the database name./*  ww  w . j ava  2s .  c  o m*/
 * @return {@code true} if a database with the given name exists, {@code false} if not.
 * @throws FlywayException when the check fails.
 */
public static boolean exists(MongoClient client, String dbName) throws FlywayException {
    try {
        MongoCursor<String> dbNameIterator = client.listDatabaseNames().iterator();
        while (dbNameIterator.hasNext()) {
            if (dbNameIterator.next().equals(dbName))
                return true;
        }
        return false;
    } catch (MongoException e) {
        throw new FlywayException("Unable to check whether Mongo database" + dbName + " exists", e);
    }
}

From source file:org.immutables.mongo.fixture.MongoContext.java

License:Apache License

private MongoContext(final MongoClient client) {
    Preconditions.checkNotNull(client, "client");

    // allows to cleanup resources after each test
    final Closer closer = Closer.create();

    closer.register(new Closeable() {
        @Override/*from  w ww .  j  a va2  s .  c o m*/
        public void close() throws IOException {
            client.close();
        }
    });

    // drop database if exists (to have a clean test)
    if (Iterables.contains(client.listDatabaseNames(), DBNAME)) {
        client.getDatabase(DBNAME).drop();
    }

    this.database = client.getDatabase(DBNAME);

    closer.register(new Closeable() {
        @Override
        public void close() throws IOException {
            database.drop();
        }
    });

    final ListeningExecutorService executor = MoreExecutors
            .listeningDecorator(Executors.newSingleThreadExecutor());

    closer.register(new Closeable() {
        @Override
        public void close() throws IOException {
            MoreExecutors.shutdownAndAwaitTermination(executor, 100, TimeUnit.MILLISECONDS);
        }
    });

    this.setup = RepositorySetup.builder().gson(createGson()).executor(executor).database(database).build();

    this.closer = closer;
}

From source file:org.kiaan.Main.java

/**
public static class view_main extends JFrame {            
        /*from ww  w .ja  va  2  s .  c  om*/
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.netbeans.modules.mongodb.ui.explorer.DBNodesFactory.java

License:Open Source License

@Override
protected boolean createKeys(final List<DbInfo> list) {
    ConnectionInfo connectionInfo = lookup.lookup(ConnectionInfo.class);
    MongoConnection connection = lookup.lookup(MongoConnection.class);
    try {//w  ww.j a  v a2  s  . c  om
        if (connection.isConnected()) {
            MongoClient mongo = connection.getClient();
            final String connectionDBName = connectionInfo.getMongoURI().getDatabase();
            if (connectionDBName != null) {
                list.add(new DbInfo(connectionDBName, lookup));
            } else {
                for (String dbName : mongo.listDatabaseNames()) {
                    list.add(new DbInfo(dbName, lookup));
                }
            }
        }
    } catch (MongoSocketException ex) {
        connection.disconnect();
    }
    Collections.sort(list);
    return true;
}