Example usage for com.mongodb DBAddress DBAddress

List of usage examples for com.mongodb DBAddress DBAddress

Introduction

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

Prototype

public DBAddress(final String urlFormat) 

Source Link

Document

Creates a new address.

Usage

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

License:Open Source License

/**
 * table?   ./*from  w ww  .j a v  a2s.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   w w w . jav  a2s .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  a  va2 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  v a 2  s.  c  om*/
 * @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.erd.core.dnd.TableTransferDropTargetListener.java

License:Open Source License

/**
 * table?   ./*  w  w  w .  j  a  v a  2  s.c  o m*/
 * 
 * @param strTBName
 * @return
 * @throws Exception
 */
public List<CollectionFieldDAO> getColumns(String strTBName) throws Exception {
    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());
}

From source file:com.hangum.tadpole.rdb.core.viewers.object.ExplorerViewer.java

License:Open Source License

/**
 * table   .//from   ww  w  . ja  v  a  2 s  . c  o m
 */
public void refreshTable(final String source) {

    try {
        if (DBDefine.getDBDefine(userDB.getTypes()) != DBDefine.MONGODB_DEFAULT) {

            SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB);
            showTables = sqlClient.queryForList("tableList", userDB.getDb()); //$NON-NLS-1$

            // mongo db
        } else if (DBDefine.getDBDefine(userDB.getTypes()) == DBDefine.MONGODB_DEFAULT) {

            Mongo mongo = new Mongo(new DBAddress(userDB.getUrl()));
            DB mongoDB = mongo.getDB(userDB.getDb());

            if (showTables != null)
                showTables.clear();
            else
                showTables = new ArrayList<TableDAO>();

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

                showTables.add(dao);
            }
        }

        tableListViewer.setInput(showTables);
        tableListViewer.refresh();

    } catch (Exception e) {
        logger.error(source + " Table Referesh", e);

        if (showTables != null)
            showTables.clear();
        tableListViewer.setInput(showTables);
        tableListViewer.refresh();

        Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); //$NON-NLS-1$
        if ("DB".equals(source)) //$NON-NLS-1$
            ExceptionDetailsErrorDialog.openError(getSite().getShell(), "Error", Messages.ExplorerViewer_4, //$NON-NLS-1$
                    errStatus);
        else
            ExceptionDetailsErrorDialog.openError(getSite().getShell(), "Error", Messages.ExplorerViewer_86, //$NON-NLS-1$
                    errStatus);
    }

}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

/**
 * Initialize any state for this DB. Called once per DB instance; there is
 * one DB instance per client thread./*from   www  .j  av  a  2s  .  c o  m*/
 */
public boolean init() throws DBException {
    // initialize MongoDb driver
    props = getProperties();
    String url = props.getProperty(MONGODB_URL_PROPERTY);
    database = props.getProperty(MONGODB_DB_PROPERTY);
    String writeConcernType = props.getProperty(MONGODB_WRITE_CONCERN_PROPERTY,
            MONGODB_WRITE_CONCERN_PROPERTY_DEFAULT);
    manipulationArray = Boolean.parseBoolean(props.getProperty(MONGODB_MANIPULATION_ARRAY_PROPERTY,
            MONGODB_MANIPULATION_ARRAY_PROPERTY_DEFAULT));
    friendListReq = Boolean.parseBoolean(
            props.getProperty(MONGODB_FRNDLIST_REQ_PROPERTY, MONGODB_FRNDLIST_REQ_PROPERTY_DEFAULT));
    scanResources = Boolean
            .parseBoolean(props.getProperty(MONGODB_SCANFORRES_PROPERTY, MONGODB_SCANFORRES_PROPERTY_DEFAULT));

    if ("none".equals(writeConcernType)) {
        // don't return error on writes
        writeConcern = WriteConcern.NONE;
    } else if ("strict".equals(writeConcernType)) {
        // The write will wait for a response from the server and raise an
        // exception on any error
        writeConcern = WriteConcern.SAFE;
    } else if ("normal".equals(writeConcernType)) {
        // normal error handling - just raise exceptions when problems, don
        // wait for response form servers
        writeConcern = WriteConcern.NORMAL;
    }

    try {
        // System.out.println("new database url = "+url);
        /*
         * MongoOptions mo = new MongoOptions(); mo.connectionsPerHost =
         * 100; mongo = new Mongo(new DBAddress(url), mo);
         */

        /*
         * List<ServerAddress> addrs = new ArrayList<ServerAddress>();
         * addrs.add( new ServerAddress( "10.0.0.122" , 27017 ) );
         * addrs.add( new ServerAddress( "10.0.0.122" , 10002 ) );
         * addrs.add( new ServerAddress( "10.0.0.120" , 10003 ) );
         * MongoOptions mongoOptions = new MongoOptions(); mongo = new
         * Mongo( addrs, mongoOptions);
         * mongo.setReadPreference(ReadPreference.SECONDARY);
         */
        // System.out.println("mongo connection created with "+url);
        try {
            crtcl.acquire();

            if (NumThreads == null) {
                NumThreads = new AtomicInteger();
                NumThreads.set(0);
                MongoOptions mo = new MongoOptions();
                mo.connectionsPerHost = 100;
                String urls[];
                if (!url.contains(";")) { //multiple mongos servers
                    url += "/" + database;
                    mongo = new Mongo(new DBAddress(url), mo);
                } /*else{ // need to append db to url.
                    urls = url.split(";");
                     List<ServerAddress> addrs = new ArrayList<ServerAddress>();
                     for(int i=0; i< urls.length; i++){
                        addrs.add( new ServerAddress(urls[i].split(":")[0] , Integer.parseInt(urls[i].split(":")[1]) ) );
                        //no need to add the database name here as each action does a mongo.getDB(database)
                     } 
                     mongo = new Mongo( addrs);
                  }*/
                else { // need to append db to url.
                    urls = url.split(";");
                    mo = new MongoOptions();
                    mo.connectionsPerHost = 100;
                    //trying to direct clients to different routers
                    url = urls[(Integer.parseInt(props.getProperty(Client.MACHINE_ID_PROPERTY, "0")))
                            % urls.length];
                    url += "/" + database;
                    mongo = new Mongo(new DBAddress(url), mo);
                }

                //mongo = new MongoClient(new DBAddress(url));
                // checking to see if the connection is established
                try {
                    Socket socket = mongo.getMongoOptions().socketFactory.createSocket();
                    socket.connect(mongo.getAddress().getSocketAddress());
                    socket.close();
                } catch (IOException ex) {
                    System.out.println("ERROR: Can't create connection, check if MongDB is running");
                    return false;
                }
            }
            incrementNumThreads();

        } catch (Exception e) {
            System.out.println("MongoDB init failed to acquire semaphore.");
            e.printStackTrace(System.out);
        } finally {
            crtcl.release();
        }
    } catch (Exception e1) {
        System.out.println("Could not initialize MongoDB connection pool for Loader: " + e1.toString());
        e1.printStackTrace(System.out);
        return false;
    }
    return true;
}

From source file:net.ion.framework.db.mongo.jdbc.MongoDriver.java

License:Apache License

public Connection connect(String url, Properties info) throws SQLException {
    if (info != null && info.size() > 0)
        throw new UnsupportedOperationException("properties not supported yet");

    if (url.startsWith(PREFIX))
        url = url.substring(PREFIX.length());
    if (url.indexOf("/") < 0)
        throw new MongoSQLException("bad url: " + url);

    try {/*  w w  w . java 2 s. c o m*/
        DBAddress addr = new DBAddress(url);
        return new MongoConnection(Mongo.connect(addr));
    } catch (java.net.UnknownHostException uh) {
        throw new MongoSQLException("bad url: " + uh);
    }
}

From source file:org.fornax.cartridges.sculptor.framework.accessimpl.mongodb.DbManager.java

License:Apache License

private synchronized void init() {
    if (initialized) {
        return;/*  ww  w.  ja v a  2 s.  co m*/
    }
    if (dbname == null) {
        throw new IllegalStateException("MongoDB dbname not defined");
    }
    try {
        if (dbUrl1 == null || dbUrl1.equals("")) {
            // default host/port, but with options
            mongo = new Mongo(new ServerAddress(), options);
        } else if (dbUrl2 != null && !dbUrl2.equals("")) {
            DBAddress left = new DBAddress(urlWithDbname(dbUrl1));
            DBAddress right = new DBAddress(urlWithDbname(dbUrl2));
            mongo = new Mongo(left, right, options);
        } else {
            DBAddress left = new DBAddress(urlWithDbname(dbUrl1));
            mongo = new Mongo(left, options);
        }
        db = mongo.getDB(dbname);
        initialized = true;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.sculptor.framework.accessimpl.mongodb.DbManager.java

License:Apache License

@SuppressWarnings("deprecation")
private synchronized void init() {
    if (initialized) {
        return;//from www  .j  a va2 s. c  o m
    }
    if (dbname == null) {
        throw new IllegalStateException("MongoDB dbname not defined");
    }
    try {
        if (dbUrl1 == null || dbUrl1.equals("")) {
            // default host/port, but with options
            mongo = new Mongo(new ServerAddress(), options);
        } else if (dbUrl2 != null && !dbUrl2.equals("")) {
            DBAddress left = new DBAddress(urlWithDbname(dbUrl1));
            DBAddress right = new DBAddress(urlWithDbname(dbUrl2));
            mongo = new Mongo(left, right, options);
        } else {
            DBAddress left = new DBAddress(urlWithDbname(dbUrl1));
            mongo = new Mongo(left, options);
        }
        db = mongo.getDB(dbname);
        initialized = true;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}