Example usage for com.mongodb MongoClient getDB

List of usage examples for com.mongodb MongoClient getDB

Introduction

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

Prototype

@Deprecated 
public DB getDB(final String dbName) 

Source Link

Document

Gets a database object.

Usage

From source file:com.norconex.collector.core.data.store.impl.mongo.MongoCrawlDataStore.java

License:Apache License

protected static DB buildMongoDB(String crawlerId, MongoConnectionDetails connDetails) {

    String dbName = MongoUtil.getDbNameOrGenerate(connDetails.getDatabaseName(), crawlerId);

    int port = connDetails.getPort();
    if (port <= 0) {
        port = ServerAddress.defaultPort();
    }//from  www .  jav a2s  .com

    try {
        ServerAddress server = new ServerAddress(connDetails.getHost(), port);
        List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
        if (StringUtils.isNoneBlank(connDetails.getUsername())) {
            MongoCredential credential = MongoCredential.createMongoCRCredential(connDetails.getUsername(),
                    dbName, connDetails.getPassword().toCharArray());
            credentialsList.add(credential);
        }
        MongoClient client = new MongoClient(server, credentialsList);
        return client.getDB(dbName);
    } catch (UnknownHostException e) {
        throw new CrawlDataStoreException(e);
    }
}

From source file:com.opengamma.util.mongo.MongoConnectorFactoryBean.java

License:Open Source License

/**
 * Creates the database./*ww  w.  jav a2s.  com*/
 * 
 * @param mongo  the Mongo instance, not null
 * @return the database, may be null
 */
protected DB createDatabase(MongoClient mongo) {
    final DB db = getDB();
    if (db != null) {
        return db;
    }
    final String databaseName = getDatabaseName(); // store in variable to protect against change by subclass
    ArgumentChecker.notNull(databaseName, "databaseName");
    return mongo.getDB(databaseName);
}

From source file:com.ovrhere.android.morseflash.ui.fragments.MainFragment.java

License:Apache License

private void insertIntoDB() {
    MongoClientURI URI = new MongoClientURI("mongodb://zaid:zaid@ds047802.mongolab.com:47802/aadhar");
    MongoClient client = null;
    try {/*from   www  .j  a v  a  2s .  c o m*/
        client = new MongoClient(URI);
        DB db = client.getDB("aadhar");
        DBCollection collection = db.getCollection("Sender");

        BasicDBObject document = new BasicDBObject();
        document.put("database", "aadhar");
        document.put("table", "Sender");

        BasicDBObject documentDetail = new BasicDBObject();
        documentDetail.put("Uid", "103");
        documentDetail.put("Amount", "1010");
        documentDetail.put("Pin", "" + UniqueCode);
        documentDetail.put("Status", "send");

        document.put("detail", documentDetail);

        collection.insert(document);

    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

}

From source file:com.owly.srv.config.ApplicationListener.java

License:Apache License

/**
 * This methond checks status of the stadistics server database
 * /*from w ww .  j  a  v a  2  s .  c  o m*/
 * @param StadisticsServer
 * @param listInitRemoteServer
 * @return a bolean true in case parameters of database are OK, and database
 *         is up.
 */
public boolean checkDatabaseStatus(StatsServer StadisticsServer, ArrayList<RemoteServer> listInitRemoteServer) {

    final String CollectionDB = "StatsSrvCfg";

    // logger.debug("Configuration of the Stats Server : " +
    // StadisticsServer.toString());

    if (!StadisticsServer.isEnabled()) {
        logger.error("Statistics server is disabled, check configuration file");
        RuntimeException ex = new RuntimeException("Error starting the Application ");
        throw ex;

    } else {
        if (!StadisticsServer.getStatsDatabaseType().equals("MONGODB")) {
            logger.error(
                    "Statistics server database should be MongoDB (others not implemented), check configuration file");
            RuntimeException ex = new RuntimeException("Error starting the Application ");
            throw ex;
        } else {
            if (!StadisticsServer.getStatsIpAddress().equals("127.0.0.1")) {
                logger.info("Statistics server IP is not 127.0.0.1 --> Database is a remote server");
            } else {
                logger.info("Statistics server IP is  127.0.0.1 --> Database is local server");
            }

            logger.debug("Checking if MongoDB is up and running for IP : "
                    + StadisticsServer.getStatsIpAddress() + " and port : " + StadisticsServer.getStatsPort());
            try {

                /**** Connect to MongoDB ****/
                // Since 2.10.0, uses MongoClient
                MongoClient mongoClient = new MongoClient(StadisticsServer.getStatsIpAddress(),
                        StadisticsServer.getStatsPort());

                try {
                    Socket socket = mongoClient.getMongoOptions().socketFactory.createSocket();
                    socket.connect(mongoClient.getAddress().getSocketAddress());
                    socket.close();
                } catch (IOException e) {
                    logger.error("mongoDB Error : " + e.getMessage());
                    logger.error("Exception ::", e);
                    RuntimeException ex = new RuntimeException("Error starting the Application ");
                    throw ex;

                }

                /**** Get database ****/
                // if database doesn't exists, MongoDB will create it
                // for you
                DB statsDB = mongoClient.getDB(StadisticsServer.getStatsDatabase());

                StatsServerMongoDAOImpl statServerCfg = new StatsServerMongoDAOImpl(statsDB);

                RemoteServerMongoDAOImpl remoteServerCfg = new RemoteServerMongoDAOImpl(statsDB);

                // Drop all previous configuration in the database

                statServerCfg.deleteAllStatsServer();
                //remoteServerCfg.deleteAllRemoteServer();

                // Create new configuration in database
                int numberStats = statServerCfg.numberStatsServer();

                if (numberStats == 0) {
                    logger.debug("Actual Server Stats configuration NOT in database");
                    logger.debug("Insert configuration in Database");

                    // Insert Stats Server in Database
                    statServerCfg.insertStatsServer(StadisticsServer);

                    // Insert Remote Servers in the Database
                    for (int srv = 0; srv < listInitRemoteServer.size(); srv++) {
                        logger.debug("Remote Server to Insert in database (" + srv + ") : "
                                + listInitRemoteServer.get(srv).toString());
                        RemoteServer remoteServer = listInitRemoteServer.get(srv);
                        String nameSrv = remoteServer.getName();
                        String ipSrv = remoteServer.getNodeIPAddress();

                        // Drop the server from database is already exists
                        remoteServerCfg.deleteRemoteServer(nameSrv, ipSrv);

                        // Insert the remote server. 
                        remoteServerCfg.insertRemoteServer(listInitRemoteServer.get(srv));
                        logger.debug("Remote Serverinserted");

                    }

                    // Add a unique index based on IP and name
                    remoteServerCfg.addUniqueIndex("NodeIPAddress", "Name");

                } else {
                    logger.error("Configuration in database " + CollectionDB
                            + " is not OK, manual action is required");
                    // Close the conection to database
                    logger.info("Closing MongoClient");
                    mongoClient.close();
                    RuntimeException ex = new RuntimeException("Error starting the Application ");
                    throw ex;
                }

                // Close the conection to database
                logger.info("Closing MongoClient");
                mongoClient.close();

            } catch (UnknownHostException e) {
                logger.error("mongoDB Error : " + e.getMessage());
                logger.error("Exception ::", e);
                RuntimeException ex = new RuntimeException("Error starting the Application ");
                throw ex;
            }

        }
    }

    return true;

}

From source file:com.owly.srv.Job.OwlySrvCleanJob.java

License:Apache License

void CleanStats(String dbName, String ipServer, int portServer, String typeDatabase) {

    //Get date for this executin
    GregorianCalendar cal = new GregorianCalendar();
    Date nowDate = cal.getTime();

    SimpleDateFormat actualDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    logger.debug("Actual date is " + actualDateFormat.format(nowDate));

    TimeZone tz = TimeZone.getDefault();
    int offset = tz.getOffset(new Date().getTime());

    logger.debug("This is my offset " + offset);

    /**** Connect to MongoDB ****/
    // Since 2.10.0, uses MongoClient
    try {//from   w  ww .jav a2 s . co m
        MongoClient mongoClient = new MongoClient(ipServer, portServer);
        /**** Get database ****/
        logger.info("MONGODB : Start MongoClient");
        DB statsDB = mongoClient.getDB(dbName);

        // Object to get the stats server in database
        StatsServerMongoDAOImpl statsServerDAO = new StatsServerMongoDAOImpl(statsDB);
        StatsServer srv = new StatsServer();
        srv = statsServerDAO.getStatsServer(dbName, ipServer, portServer, typeDatabase);

        //Number of days to keep in database 
        int number_days_to_save = srv.getSavedDays();
        logger.debug("Days to save in database = " + number_days_to_save);

        //GEt the past date
        cal.add(Calendar.DAY_OF_MONTH, -number_days_to_save);
        cal.add(Calendar.MILLISECOND, +offset);
        Date pastDate = cal.getTime();

        logger.debug("Date to drop before = " + pastDate);

        String StatsCollection = srv.getStatsCollect();
        logger.debug("Collection is  = " + StatsCollection);

        //Get an instance of the stadistics dao 
        RemoteBasicStatMongoDAOImpl basicStatDAO = new RemoteBasicStatMongoDAOImpl(statsDB, StatsCollection);

        //Get number of stats in databe for this condition
        long nb_stats = basicStatDAO.getNumberStatsBefore(pastDate);

        logger.info("Number of stats to drop = " + nb_stats);

        if (nb_stats > 0) {
            basicStatDAO.cleanStatsbefore(pastDate);
        }

        // Close the connection to database
        logger.info("MONGODB : Closing MongoClient");
        mongoClient.close();

    } catch (UnknownHostException e) {
        logger.error("mongoDB Error : " + e.getMessage());
        logger.error("Exception ::", e);

    }

}

From source file:com.owly.srv.Job.OwlySrvMainJob.java

License:Apache License

/**
 * This method is executed by Scheduler Job in order to get Stadistics from
 * a remote server, based in the information saved in Database related to
 * Remote Server configuration./*from w  w w .  j  a v  a  2s .  co  m*/
 * 
 * @param dbName
 *            is the DataBase Name
 * @param ipServer
 *            is the IP address for Stat Server ( normally 127.0.0.1)
 * @param portServer
 *            in port where is running the MongoDatabase
 */
void BasicStatsPerfMainJob(String dbName, String ipServer, int portServer) {

    //Get date for this executin
    GregorianCalendar currentDate = new GregorianCalendar();
    Date actualDate = currentDate.getTime();

    SimpleDateFormat actualDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    logger.debug("Actual date is " + actualDateFormat.format(actualDate));

    // Class for executing tasks in the remote server
    RemoteBasicStatItfImpl remoteExec = new RemoteBasicStatItfImpl();

    /**** Connect to MongoDB ****/
    // Since 2.10.0, uses MongoClient
    try {
        MongoClient mongoClient = new MongoClient(ipServer, portServer);
        /**** Get database ****/
        logger.info("MONGODB : Start MongoClient");
        DB statsDB = mongoClient.getDB(dbName);
        // Class for managing the remote server object.
        remoteServer = new RemoteServerMongoDAOImpl(statsDB);
        // Object to get the stats server in database
        StatsServerMongoDAOImpl statsServerDAO = new StatsServerMongoDAOImpl(statsDB);

        // Get the name of collection where stats are going to be saved.
        String StatsCollection = statsServerDAO.getStatCollectStatsServer();

        // Check is Stat Server is enabled
        Boolean statusServer = statsServerDAO.getMonitoringEnabledStatsServer();

        if (statusServer) {
            // Status Server is enabled for Monitoring

            // Get the list of IP of all remote Servers
            srvIP = remoteServer.listIPRemoteServer();

            Iterator<String> it = srvIP.iterator();

            while (it.hasNext()) {

                String valueIP = it.next();
                logger.debug("Ip of server to analyze :" + valueIP);
                rmtServer = remoteServer.getRemoteServerbyIP(valueIP);
                logger.debug("Remote Server Readed = " + rmtServer.toString());

                //Check if server is enabled
                boolean srvEnabled = rmtServer.isEnabled();

                // Check if Server is accessible
                boolean status = remoteExec.getStatusRemoteServer(valueIP, rmtServer.getClientPort());

                logger.debug("Status of server received = " + status);
                logger.debug("Update Status in remote Server = " + status);
                remoteServer.updateStatus(status, rmtServer);

                // If the remote server it is not accesible or it is not eanbled do not continue
                // asking for further statistics.
                if (status && srvEnabled) {

                    // For each server ( IP address) get the list of Stats
                    // to get.

                    listStats = rmtServer.getListTypeOfStats();

                    Iterator<String> it2 = listStats.iterator();
                    while (it2.hasNext()) {
                        String typeStat = it2.next();
                        logger.debug("Executing remote Stadistics for type  = " + typeStat);
                        // Execute a Remote Execution to the the Stadistic
                        // on the
                        // remote server, based on IP, server type and type
                        // of
                        // stadistic.

                        // Statistic received from remote server
                        RemoteBasicStat basicStat = remoteExec.getRemoteStatistic(rmtServer.getName(), valueIP,
                                rmtServer.getSrvType(), typeStat, rmtServer.getClientPort());

                        if (basicStat.getTypeOfStat().equals("NOK")) {
                            logger.error("Metric received is not OK, not save to database");
                        } else {
                            //Setup the date when this metric is executed.
                            basicStat.setstatServerDate(actualDate);
                            // Save statistic in Database
                            RemoteBasicStatMongoDAOImpl basicStatDAO = new RemoteBasicStatMongoDAOImpl(statsDB,
                                    StatsCollection);

                            basicStatDAO.insertRemoteBasicStat(basicStat);
                        }

                    }
                } else {
                    // remote server is disabled becosue not access to HTTP
                    logger.info("Remote Server is not accesible for getting stadistics");

                }

            }

        } else {
            // Stadistic server is disabled for monitoring
            logger.info("Stadistics Server is disabled for Monitoring");
        }

        // Close the connection to database
        logger.info("MONGODB : Closing MongoClient");
        mongoClient.close();

    } catch (UnknownHostException e) {
        logger.error("mongoDB Error : " + e.getMessage());
        logger.error("Exception ::", e);

    }

}

From source file:com.packages.mongodb.dao.automobilsdao.java

public automobilsdao(MongoClient mongo) {
    this.col = mongo.getDB("project").getCollection("automobile");
}

From source file:com.packages.mongodb.dao.hoteldao.java

public hoteldao(MongoClient mongo) {
    this.col = mongo.getDB("project").getCollection("hotel");
}

From source file:com.packages.mongodb.dao.individualdao.java

public individualdao(MongoClient mongo) {
    this.col = mongo.getDB("project").getCollection("individual");
}

From source file:com.packtpub.mongo.chapter2.ArrayInsert.java

public static void main(String args[]) {
    try {// w  w  w .j av a 2  s .co m
        // To connect to mongodb server
        MongoClient mongoClient = new MongoClient(HOST, PORT);

        DB db = mongoClient.getDB("semaine09");

        DBCollection coll = db.getCollection("contacts");

        List<DBObject> kids = new ArrayList<>();
        kids.add(new BasicDBObject("name", "mike"));
        kids.add(new BasicDBObject("name", "faye"));

        DBObject doc = new BasicDBObject("name", "john").append("age", 35).append("kids", kids).append("info",
                new BasicDBObject("email", "john@mail.com").append("phone", "876-134-667"));
        coll.insert(doc);

    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}