Example usage for com.mongodb Mongo getDB

List of usage examples for com.mongodb Mongo getDB

Introduction

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

Prototype

@Deprecated 
public DB getDB(final String dbName) 

Source Link

Document

Gets a database object.

Usage

From source file:com.fuction.MongoDB.java

public static void display() {
    try {/*www  .j  ava  2  s . c o  m*/
        Mongo mongo = new Mongo(HOST, PORT);
        DB db = mongo.getDB(DB);
        DBCollection collection = db.getCollection("Data");
        System.out.println("Collection mycol selected successfully");
        DBCursor cursor = collection.find();
        int i = 1;
        while (cursor.hasNext()) {
            System.out.println("Inserted Document: " + i);
            String jsonString = cursor.next().toString();
            System.out.println(jsonString);
            JSONObject jsonObject = parseJSONObject(jsonString);
            System.out.println(jsonObject.get("Area"));
            i++;
        }
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.fuction.MongoDB.java

public static ArrayList<InformationObj> getObj() {
    ArrayList<InformationObj> list = new ArrayList<>();
    try {//  www.  ja  v  a 2s.  c  o  m
        Mongo mongo = new Mongo(HOST, PORT);
        DB db = mongo.getDB(DB);
        DBCollection collection = db.getCollection("Data");
        System.out.println("Collection mycol selected successfully");
        DBCursor cursor = collection.find();
        while (cursor.hasNext()) {
            String jsonString = cursor.next().toString();
            //System.out.println(jsonString);
            JSONObject jsonObject = parseJSONObject(jsonString);

            String roomNumber = (String) jsonObject.get("RoomNumber");
            String area = (String) jsonObject.get("Area");
            String address = (String) jsonObject.get("Address");
            String direction = (String) jsonObject.get("Direction");
            String numberOfBedRooms = (String) jsonObject.get("NumberOfBedRooms");
            String numberOfBathRooms = (String) jsonObject.get("NumberOfBathRooms");
            String project = (String) jsonObject.get("Project");
            String floor = (String) jsonObject.get("Floor");
            String utilities = (String) jsonObject.get("Utilities");
            String environment = (String) jsonObject.get("Environment");
            String description = (String) jsonObject.get("Description");
            String pricePerMetreSquare = (String) jsonObject.get("PricePerMetreSquare");
            String price = (String) jsonObject.get("Price");
            String image = (String) jsonObject.get("Image");
            String city = (String) jsonObject.get("City");
            String district = (String) jsonObject.get("District");

            InformationObj iObj = new InformationObj(roomNumber, area, address, direction, numberOfBedRooms,
                    numberOfBathRooms, project, floor, utilities, environment, description, pricePerMetreSquare,
                    price, image, city, district);
            list.add(iObj);
        }
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        e.printStackTrace();
    }
    return list;
}

From source file:com.github.niltz.maven.plugins.mongodb.AbstractMongoDBMojo.java

License:Open Source License

/**
 * Returns a DB from the given settings and mongo.
 * //www .  j a  va2 s .  co  m
 * @param mongo
 *            the mongo
 * @param dbSettings
 *            the settings
 * @return the DB
 */
protected DB getDatabase(ConnectionSettings connectionSettings, Mongo mongo) {

    String username, password = null;

    // use settings to get authentication info for the given server
    if (!StringUtils.isEmpty(connectionSettings.getServerId())) {
        Server server = settings.getServer(connectionSettings.getServerId());
        username = server.getUsername();
        password = server.getPassword();

        // use settings in pom.xml
    } else {
        username = connectionSettings.getUserName();
        password = connectionSettings.getPassword();
    }

    // get the DB and optionaly authenticate
    DB db = mongo.getDB(connectionSettings.getDatabase());
    if (username != null && password != null) {
        db.authenticate(username, password.toCharArray());
    }
    return db;
}

From source file:com.hangum.tadpole.erd.core.dnd.TableTransferDropTargetListener.java

License:Open Source License

/**
 * table?   ./*  w w  w  .java 2s  .c  o  m*/
 * 
 * @param strTBName
 * @return
 * @throws Exception
 */
public List<TableColumnDAO> getColumns(String strTBName) throws Exception {
    if (DBDefine.getDBDefine(userDB.getTypes()) != DBDefine.MONGODB_DEFAULT) {
        SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB);

        Map<String, String> param = new HashMap<String, String>();
        param.put("db", userDB.getDb());
        param.put("table", strTBName);

        return sqlClient.queryForList("tableColumnList", param);
    } else if (DBDefine.getDBDefine(userDB.getTypes()) == DBDefine.MONGODB_DEFAULT) {

        Mongo mongo = new Mongo(new DBAddress(userDB.getUrl()));
        com.mongodb.DB mongoDB = mongo.getDB(userDB.getDb());
        DBCollection coll = mongoDB.getCollection(strTBName);

        return MongoDBTableColumn.tableColumnInfo(coll.getIndexInfo(), coll.findOne());
    }

    return null;
}

From source file:com.hangum.tadpole.erd.core.utils.TadpoleModelUtils.java

License:Open Source License

/**
 * table  ./*from   ww  w  . ja v a 2  s  .  c  o  m*/
 */
public List<TableDAO> getTables() throws Exception {
    List<TableDAO> showTables = new ArrayList<TableDAO>();

    if (DBDefine.getDBDefine(userDB.getTypes()) != DBDefine.MONGODB_DEFAULT) {
        SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB);
        return sqlClient.queryForList("tableList", userDB.getDb()); //$NON-NLS-1$

    } else if (DBDefine.getDBDefine(userDB.getTypes()) == DBDefine.MONGODB_DEFAULT) {
        Mongo mongo = new Mongo(new DBAddress(userDB.getUrl()));
        com.mongodb.DB mongoDB = mongo.getDB(userDB.getDb());

        for (String col : mongoDB.getCollectionNames()) {
            TableDAO dao = new TableDAO();
            dao.setName(col);

            showTables.add(dao);
        }

        return showTables;
    }

    return showTables;
}

From source file:com.hangum.tadpole.erd.core.utils.TadpoleModelUtils.java

License:Open Source License

/**
 * table?   ./*from   w  w  w  . j ava 2 s .  c o  m*/
 * 
 * @param strTBName
 * @return
 * @throws Exception
 */
public List<TableColumnDAO> getColumns(String db, String strTBName) throws Exception {
    if (DBDefine.getDBDefine(userDB.getTypes()) != DBDefine.MONGODB_DEFAULT) {
        SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB);

        Map<String, String> param = new HashMap<String, String>();
        param.put("db", db);
        param.put("table", strTBName);

        return sqlClient.queryForList("tableColumnList", param);
    } else if (DBDefine.getDBDefine(userDB.getTypes()) == DBDefine.MONGODB_DEFAULT) {

        Mongo mongo = new Mongo(new DBAddress(userDB.getUrl()));
        com.mongodb.DB mongoDB = mongo.getDB(userDB.getDb());
        DBCollection coll = mongoDB.getCollection(strTBName);

        return MongoDBTableColumn.tableColumnInfo(coll.getIndexInfo(), coll.findOne());
    }

    return null;
}

From source file:com.hangum.tadpole.mongodb.core.connection.MongoConnectionManager.java

License:Open Source License

/**
 * /*  ww  w .j  a  va  2 s  . co m*/
 * @param userDB
 * @return
 * @throws Exception
 */
public static DB getInstance(UserDBDAO userDB) throws MongoDBNotFoundException, Exception {
    DB db = null;

    synchronized (dbManager) {

        try {
            String searchKey = getKey(userDB);
            Mongo mongoDB = dbManager.get(searchKey);

            if (mongoDB == null) {
                final MongoOptions options = new MongoOptions();
                options.connectionsPerHost = 20;
                options.threadsAllowedToBlockForConnectionMultiplier = 5;
                options.maxWaitTime = 120000;
                options.autoConnectRetry = false;
                options.safe = true;

                String strReplcaSet = userDB.getExt1();
                if (strReplcaSet == null | "".equals(strReplcaSet)) {
                    mongoDB = new Mongo(new DBAddress(userDB.getUrl()), options);

                } else {
                    List<ServerAddress> listServerList = new ArrayList<ServerAddress>();
                    listServerList.add(new ServerAddress(userDB.getHost(), Integer.parseInt(userDB.getPort())));

                    String[] urls = StringUtils.split(strReplcaSet, ",");
                    for (String ipPort : urls) {
                        String[] strIpPort = StringUtils.split(ipPort, ":");

                        listServerList.add(new ServerAddress(strIpPort[0], Integer.parseInt(strIpPort[1])));
                    }
                    //                  options.setReadPreference(ReadPreference.primary());

                    mongoDB = new Mongo(listServerList, options);
                }

                // password ?.
                db = mongoDB.getDB(userDB.getDb());
                if (!"".equals(userDB.getUsers())) { //$NON-NLS-1$
                    // pass change
                    String passwdDecrypt = "";
                    try {
                        passwdDecrypt = CipherManager.getInstance().decryption(userDB.getPasswd());
                    } catch (Exception e) {
                        passwdDecrypt = userDB.getPasswd();
                    }

                    boolean auth = db.authenticate(userDB.getUsers(), passwdDecrypt.toCharArray());
                    if (!auth) {
                        throw new Exception(Messages.MongoDBConnection_3);
                    }
                }

                //               
                //                ?   ? ? .
                //               
                //               // db  .
                //               List<String> listDB = mongoDB.getDatabaseNames();
                //               boolean isDB = false;
                //               for (String dbName : listDB) if(userDB.getDb().equals(dbName)) isDB = true;                  
                //               if(!isDB) {
                //                  throw new MongoDBNotFoundException(userDB.getDb() + Messages.MongoDBConnection_0);
                //               }
                try {
                    // ? ? ?  ?    .
                    db.getCollectionNames();
                } catch (Exception e) {
                    logger.error("error", e);
                    throw new MongoDBNotFoundException(userDB.getDb() + " " + e.getMessage());//Messages.MongoDBConnection_0);
                }

                // db map? .
                dbManager.put(searchKey, mongoDB);

            } else {
                db = mongoDB.getDB(userDB.getDb());
            }

        } catch (Exception e) {
            logger.error("mongodb connection error", e);
            throw e;
        }
    }

    return db;

}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * create database//from   ww w. j a  va2s  .c o  m
 * 
 * @param userDB
 * @throws Exception
 */
public static void createDB(UserDBDAO userDB) throws Exception {
    MongoOptions options = new MongoOptions();
    options.connectionsPerHost = 20;
    Mongo mongo = new Mongo(userDB.getHost(), Integer.parseInt(userDB.getPort()));
    DB db = mongo.getDB(userDB.getDb());
    db.authenticate(userDB.getUsers(), userDB.getPasswd().toCharArray());

    // 
    //  ? ? ?    ?? .
    // 
    Set<String> listColNames = db.getCollectionNames();
    for (String stringColName : listColNames) {
    }
    //
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

License:Open Source License

/**
 * get admin mongodb/*from   w w  w .  j a  va 2s . co m*/
 * 
 * @param userDB
 * @return
 * @throws Exception
 */
public static DB getAdminMongoDB(UserDBDAO userDB) throws Exception {
    Mongo mongo = new Mongo(userDB.getHost(), Integer.parseInt(userDB.getPort()));
    return mongo.getDB("admin");
}

From source file:com.hangum.tadpole.mongodb.core.test.ConAndAuthentication.java

License:Open Source License

/**
 * db  ? //from w ww.j a  v a 2 s  . c om
 * 
 * @param args
 */
public static void main(String[] args) {
    ConAndAuthentication testMongoCls = new ConAndAuthentication();

    Mongo mongo = testMongoCls.connection(serverurl, port);
    if (mongo != null) {
        DB testDB = mongo.getDB("test");
        // Set<String> collectionNames =
        // testMongoCls.getCollectionNames(testDB);
        // for (String collection : collectionNames) {
        testMongoCls.getCollectionInfo(testDB, "store");
        // }
    }
    mongo.close();
}