Example usage for com.mongodb MongoClient close

List of usage examples for com.mongodb MongoClient close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes all resources associated with this instance, in particular any open network connections.

Usage

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  ww  .j ava 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.sitewhere.mongodb.MongoDbClient.java

License:Open Source License

/**
 * Detects whether a replica set is configured and creates one if not.
 * /*from w w w.j  av  a  2 s  .c  o  m*/
 * @param addresses
 */
protected void doAutoConfigureReplication(List<ServerAddress> addresses) throws SiteWhereException {
    // Only connect to primary for sending commands.
    MongoClient primary = getPrimaryConnection(addresses);

    // Check for existing replica set configuration.
    getLogger().info("Checking for existing replica set...");
    try {
        Document result = primary.getDatabase("admin").runCommand(new BasicDBObject("replSetGetStatus", 1));
        if (result.getDouble("ok") == 1) {
            getLogger().warn("Replica set already configured. Skipping auto-configuration.");
            return;
        }
    } catch (MongoCommandException e) {
        getLogger().info("Replica set was not configured.");
    }

    // Create configuration for new replica set.
    try {
        getLogger().info("Configuring new replica set '" + getConfiguration().getReplicaSetName() + "'.");
        BasicDBObject config = new BasicDBObject("_id", getConfiguration().getReplicaSetName());
        List<BasicDBObject> servers = new ArrayList<BasicDBObject>();

        // Create list of members in replica set.
        int index = 0;
        for (final ServerAddress address : addresses) {
            BasicDBObject server = new BasicDBObject("_id", index);
            server.put("host", (address.getHost() + ":" + address.getPort()));

            // First server in list is preferred primary.
            if (index == 0) {
                server.put("priority", 10);
            }

            servers.add(server);
            index++;
        }
        config.put("members", servers);

        // Send command.
        Document result = primary.getDatabase("admin").runCommand(new BasicDBObject("replSetInitiate", config));
        if (result.getDouble("ok") != 1) {
            throw new SiteWhereException("Unable to auto-configure replica set.\n" + result.toJson());
        }
        getLogger().info(
                "Replica set '" + getConfiguration().getReplicaSetName() + "' creation command successful.");
    } finally {
        primary.close();
    }
}

From source file:com.softinstigate.restheart.Bootstrapper.java

License:Open Source License

private static void stopServer() {
    logger.info("stopping RESTHeart");
    logger.info("waiting for pending request to complete (up to 1 minute)");

    try {/*w  w w .  j av  a  2  s. c  o  m*/
        hanldersPipe.shutdown();
        hanldersPipe.awaitShutdown(60 * 1000); // up to 1 minute
    } catch (InterruptedException ie) {
        logger.error("error while waiting for pending request to complete", ie);
    }

    if (server != null) {
        try {
            server.stop();
        } catch (Throwable t) {
            logger.error("error stopping undertow server", t);
        }
    }

    try {
        MongoClient client = MongoDBClientSingleton.getInstance().getClient();
        client.fsync(false);
        client.close();
    } catch (Throwable t) {
        logger.error("error flushing and clonsing the mongo cliet", t);
    }

    tmpExtractedFiles.keySet().forEach(k -> {
        try {
            ResourcesExtractor.deleteTempDir(k, tmpExtractedFiles.get(k));
        } catch (URISyntaxException | IOException ex) {
            logger.error("error cleaning up temporary directory {}", tmpExtractedFiles.get(k).toString(), ex);
        }
    });

    logger.info("RESTHeart stopped");
}

From source file:com.stratio.deep.mongodb.extractor.MongoNativeExtractor.java

License:Apache License

@Override
public Partition[] getPartitions(S config) {
    MongoClient mongoClient = null;

    try {/*w  w w.java 2  s .c  o  m*/

        mongoDeepJobConfig = initConfig(config, mongoDeepJobConfig);

        DBCollection collection;
        ServerAddress address = new ServerAddress(mongoDeepJobConfig.getHost());

        List<ServerAddress> addressList = new ArrayList<>();
        addressList.add(address);
        mongoClient = new MongoClient(addressList);

        mongoClient.setReadPreference(ReadPreference.nearest());
        DB db = mongoClient.getDB(mongoDeepJobConfig.getDatabase());
        collection = db.getCollection(mongoDeepJobConfig.getCollection());
        return isShardedCollection(collection) ? calculateShardChunks(collection) : calculateSplits(collection);
    } catch (UnknownHostException e) {

        throw new DeepGenericException(e);
    } finally {
        if (mongoClient != null) {
            mongoClient.close();
        }

    }
}

From source file:com.stratio.deep.mongodb.extractor.MongoNativeExtractor.java

License:Apache License

/**
 * Gets split data collection shard enviroment.
 *
 * @param shards         the shards// w w  w .j a  v  a2  s.c o  m
 * @param dbName         the db name
 * @param collectionName the collection name
 * @return the split data collection shard enviroment
 */
private Pair<BasicDBList, List<ServerAddress>> getSplitDataCollectionShardEnviroment(
        Map<String, String[]> shards, String dbName, String collectionName) {
    MongoClient mongoClient = null;
    try {
        Set<String> keys = shards.keySet();

        for (String key : keys) {

            List<ServerAddress> addressList = getServerAddressList(Arrays.asList(shards.get(key)));

            mongoClient = new MongoClient(addressList);

            BasicDBList dbList = getSplitData(mongoClient.getDB(dbName).getCollection(collectionName));

            if (dbList != null) {
                return Pair.create(dbList, addressList);
            }
        }
    } catch (UnknownHostException e) {
        throw new DeepGenericException(e);
    } finally {
        if (mongoClient != null) {
            mongoClient.close();
        }

    }

    return null;

}

From source file:com.stratio.tests.ATExampleMongoDB.java

License:Apache License

@BeforeClass
public void setUp() throws UnknownHostException {
    MongoClient mongoClient = new MongoClient(mongoHost, mongoPort);
    mongoClient.dropDatabase(dataBase);/*from  w  w  w .j  a  v  a 2 s .  com*/
    DB db = mongoClient.getDB(dataBase);
    DBCollection tabletest = db.getCollection("tabletest");
    // DBCollection tabletest = db.createCollection("tabletest");
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    format.setTimeZone(TimeZone.getTimeZone("CET"));
    for (int i = 0; i < 10; i++) {
        Date parsedDate = null;
        String fecha = i + "/" + i + "/200" + i;
        try {
            parsedDate = format.parse(fecha);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(new java.sql.Date(parsedDate.getTime()).toString());
        BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start().add("ident", i)
                .add("name", "name_" + i).add("money", 10.2 + i).add("new", true)
                .add("date", new java.sql.Date(parsedDate.getTime()));
        tabletest.insert(documentBuilder.get());
    }
    //   DBObject aux = tabletest.findOne();
    //  java.sql.Date aux1 = (java.sql.Date)aux.get("date");
    mongoClient.close();
    String connector = "Mongo";
    //Preparamos las cositas para compartir
    ThreadProperty.set("Host", "127.0.0.1");
    ThreadProperty.set("Connector", connector);

}

From source file:com.thaonedroid.mongodbexercise.MongoDB.java

public static void main(String[] args) {
    try {//from   w  w  w .  ja va2 s  . co m
        MongoClientURI connStr = new MongoClientURI("mongodb://localhost:27017");
        MongoClient mongoClient = new MongoClient(connStr);

        MongoDatabase db = mongoClient.getDatabase("twitter");
        MongoCollection<Document> collection = db.getCollection("tweets");

        Scanner scanner = new Scanner(System.in);
        int input;
        OUTER: do {
            start();
            input = scanner.nextInt();
            switch (input) {
            case 1:
                //System.out.println("Distinct Twitter users : " + query.totalUsers());
                System.out.println("Question : " + q1);
                execute(query.totalUsers());
                break;
            case 2:
                //execute(query.linkOthers());
                System.out.println("Question : " + q2);
                System.out.println("Answer : Query hasn't been properly figured out yet");
                break;
            case 3:
                //execute(query.mostMentioned());
                System.out.println("Question : " + q3);
                System.out.println("Answer : Query hasn't been properly figured out yet");
                break;
            case 4:
                System.out.println("Question : " + q4);
                execute(query.mostActive());
                //System.out.println("Most active users : " + query.mostActive());
                break;
            case 5:
                System.out.println("Question : " + q5);
                execute(query.mostGrumpy());
                //System.out.println("Most grumpy users : " + query.mostGrumpy());
                break;
            case 6:
                System.out.println("Question : " + q6);
                execute(query.mostHappy());
                //System.out.println("Most happy users : " + query.mostHappy());
                break;
            case 7:
                break OUTER;
            default:
                break;
            }
        } while (true);
        mongoClient.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ":" + e.getMessage());
    }
}

From source file:com.wincere.lamda.storm.bolt.CreateTable.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes no args//w  ww  . ja  v a  2s  .c  om
 * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017
 */
public void update(BasicDBObject doc, OutputCollector collector, Tuple input) throws UnknownHostException {
    // connect to the local database server
    MongoCredential credential = MongoCredential.createMongoCRCredential("superuser", "admin",
            "12345678".toCharArray());
    try {
        MongoClient mongoClient = new MongoClient(new ServerAddress("172.16.1.171", 27017),
                Arrays.asList(credential));

        // MongoClient mongoClient = new MongoClient("172.16.1.171",27017);

        /*
        // Authenticate - optional
        MongoCredential credential = MongoCredential.createMongoCRCredential(userName, database, password);
        MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential));
        */

        // get handle to "mydb"
        DB db = mongoClient.getDB("UCAPBatchTest");

        // get a collection object to work with
        DBCollection coll = db.getCollection("Queries1");
        //  DBCollection status = db.getCollection("statustest1");
        //DBCollection coll1 = db.getCollection("queryaudittest1");
        // drop all the data in it
        //coll.drop();
        //status.drop();
        //coll1.drop();

        /*  status.insert(new BasicDBObject().append("queryStatus", "Open").append("QueryStatusID","1"));
          status.insert(new BasicDBObject().append("queryStatus", "Answered").append("QueryStatusID","2"));
          status.insert(new BasicDBObject().append("queryStatus", "Closed").append("QueryStatusID","3"));
          status.insert(new BasicDBObject().append("queryStatus", "Cancelled").append("QueryStatusID","4")); */
        // make a document and insert it

        int count = 0;
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss");
        try {

            //.equals("Open")?"1":(splitValue[5].equals("Answered")?"2":"3")

            BasicDBObject searchQuery = new BasicDBObject().append("queryRepeatKey",
                    (String) doc.get("queryRepeatKey"));
            BasicDBObject newDocument = new BasicDBObject();

            DBCursor cursor = coll.find(searchQuery);
            //DBObject result = cursor.next();

            if (cursor.hasNext()) {
                DBObject result = cursor.next();

                String queryValue = (String) result.get("queryValue");
                String queryStatusID = (String) result.get("queryStatusID");
                String queryResponse = (String) result.get("queryResponse");
                String queryResolvedTimeStamp = (String) result.get("queryResolvedTimeStamp");
                String queryAnsweredTimeStamp = (String) result.get("queryAnsweredTimeStamp");
                String queryCreatedTimeStamp = (String) result.get("queryCreatedTimeStamp");

                if (doc.get("queryValue").equals("\\N")) {
                    doc.append("queryValue", queryValue);
                }
                if (doc.get("queryStatusID").equals("\\N")) {
                    doc.append("queryStatusID", queryStatusID);
                }
                if (doc.get("queryResponse").equals("\\N")) {
                    doc.append("queryResponse", queryResponse);
                }
                if (doc.get("queryResolvedTimeStamp").equals("\\N")) {
                    doc.append("queryResolvedTimeStamp", queryResolvedTimeStamp);
                }
                if (doc.get("queryAnsweredTimeStamp").equals("\\N")) {
                    doc.append("queryAnsweredTimeStamp", queryAnsweredTimeStamp);
                }
                doc.append("queryCreatedTimeStamp", queryCreatedTimeStamp);
            }
            if (doc.get("queryStatusID").equals("Open"))
                doc.append("queryCreatedTimeStamp", doc.get("queryCreatedTimeStamp"));

            //System.out.println(count);
            newDocument.append("$set", doc);
            try {
                coll.update(searchQuery, newDocument, true, true);
            } catch (MongoException me) {
                collector.fail(input);
            }
            // collector.ack(input);

            //coll.insert(doc);

        } catch (Exception e) {
            System.err.println("CSV file cannot be read : " + e);
        }

        //System.out.println(count);
        // lets get all the documents in the collection and print them out
        /*DBCursor cursor = coll1.find();
        try {
            while (cursor.hasNext()) {
        System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }*/

        /* // now use a query to get 1 document out
         BasicDBObject query = new BasicDBObject("i", 71);
         cursor = coll.find(query);
                
         try {
             while (cursor.hasNext()) {
        System.out.println(cursor.next());
             }
         } finally {
             cursor.close();
         }*/

        // release resources
        //db.dropDatabase();
        mongoClient.close();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.zjy.mongo.splitter.StandaloneMongoSplitter.java

License:Apache License

@Override
public List<InputSplit> calculateSplits() throws SplitFailedException {
    final DBObject splitKey = MongoConfigUtil.getInputSplitKey(getConfiguration());
    final DBObject splitKeyMax = MongoConfigUtil.getMaxSplitKey(getConfiguration());
    final DBObject splitKeyMin = MongoConfigUtil.getMinSplitKey(getConfiguration());
    final int splitSize = MongoConfigUtil.getSplitSize(getConfiguration());
    final MongoClientURI inputURI;
    DBCollection inputCollection = null;
    final ArrayList<InputSplit> returnVal;
    try {//from   www . j  av a  2  s . c  o  m
        inputURI = MongoConfigUtil.getInputURI(getConfiguration());
        MongoClientURI authURI = MongoConfigUtil.getAuthURI(getConfiguration());
        if (authURI != null) {
            inputCollection = MongoConfigUtil.getCollectionWithAuth(inputURI, authURI);
        } else {
            inputCollection = MongoConfigUtil.getCollection(inputURI);
        }

        returnVal = new ArrayList<InputSplit>();
        final String ns = inputCollection.getFullName();

        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Running splitVector on namespace: %s.%s; hosts: %s",
                    inputURI.getDatabase(), inputURI.getCollection(), inputURI.getHosts()));
        }
        final DBObject cmd = BasicDBObjectBuilder.start("splitVector", ns).add("keyPattern", splitKey)
                .add("min", splitKeyMin).add("max", splitKeyMax)
                // force:True is misbehaving it seems
                .add("force", false).add("maxChunkSize", splitSize).get();

        CommandResult data;
        boolean ok = true;
        try {
            data = inputCollection.getDB().getSisterDB(inputURI.getDatabase()).command(cmd,
                    ReadPreference.primary());
        } catch (final MongoException e) { // 2.0 servers throw exceptions rather than info in a CommandResult
            data = null;
            LOG.info(e.getMessage(), e);
            if (e.getMessage().contains("unrecognized command: splitVector")) {
                ok = false;
            } else {
                throw e;
            }
        }

        if (data != null) {
            if (data.containsField("$err")) {
                throw new SplitFailedException("Error calculating splits: " + data);
            } else if (!data.get("ok").equals(1.0)) {
                ok = false;
            }
        }

        if (!ok) {
            final CommandResult stats = inputCollection.getStats();
            if (stats.containsField("primary")) {
                final DBCursor shards = inputCollection.getDB().getSisterDB("config").getCollection("shards")
                        .find(new BasicDBObject("_id", stats.getString("primary")));
                try {
                    if (shards.hasNext()) {
                        final DBObject shard = shards.next();
                        final String host = ((String) shard.get("host")).replace(shard.get("_id") + "/", "");
                        final MongoClientURI shardHost;
                        if (authURI != null) {
                            shardHost = new MongoClientURIBuilder(authURI).host(host).build();
                        } else {
                            shardHost = new MongoClientURIBuilder(inputURI).host(host).build();
                        }
                        MongoClient shardClient = null;
                        try {
                            shardClient = new MongoClient(shardHost);
                            data = shardClient.getDB(shardHost.getDatabase()).command(cmd,
                                    ReadPreference.primary());
                        } catch (final Exception e) {
                            LOG.error(e.getMessage(), e);
                        } finally {
                            if (shardClient != null) {
                                shardClient.close();
                            }
                        }
                    }
                } finally {
                    shards.close();
                }
            }
            if (data != null && !data.get("ok").equals(1.0)) {
                throw new SplitFailedException("Unable to calculate input splits: " + data.get("errmsg"));
            }

        }

        // Comes in a format where "min" and "max" are implicit
        // and each entry is just a boundary key; not ranged
        final BasicDBList splitData = (BasicDBList) data.get("splitKeys");

        if (splitData.size() == 0) {
            LOG.warn(
                    "WARNING: No Input Splits were calculated by the split code. Proceeding with a *single* split. Data may be too"
                            + " small, try lowering 'mongo.input.split_size' if this is undesirable.");
        }

        BasicDBObject lastKey = null; // Lower boundary of the first min split

        // If splitKeyMin was given, use it as first boundary.
        if (!splitKeyMin.toMap().isEmpty()) {
            lastKey = new BasicDBObject(splitKeyMin.toMap());
        }
        for (final Object aSplitData : splitData) {
            final BasicDBObject currentKey = (BasicDBObject) aSplitData;
            returnVal.add(createSplitFromBounds(lastKey, currentKey));
            lastKey = currentKey;
        }

        BasicDBObject maxKey = null;
        // If splitKeyMax was given, use it as last boundary.
        if (!splitKeyMax.toMap().isEmpty()) {
            maxKey = new BasicDBObject(splitKeyMax.toMap());
        }
        // Last max split
        final MongoInputSplit lastSplit = createSplitFromBounds(lastKey, maxKey);
        returnVal.add(lastSplit);
    } finally {
        if (inputCollection != null) {
            MongoConfigUtil.close(inputCollection.getDB().getMongo());
        }
    }

    return returnVal;
}

From source file:com.zns.vehicles.service.dao.impl.VehicleDAOImpl.java

private void dbPostUtil(String collection, Document doc) {
    MongoClient mongoClient = null;
    try {/*  www  .  ja v a2 s.com*/
        mongoClient = new MongoClient(props.getProperty(HOST), PORT);
        MongoDatabase db = mongoClient.getDatabase("vehicleApp");

        db.getCollection(collection).insertOne(doc);

    } catch (MongoClientException e) {
        log.error("Error while connecting to DB...");
        e.printStackTrace();
    } catch (MongoException e) {
        log.error("General mongo error");
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        log.error("Illegal argument exception...");
        e.printStackTrace();
    } finally {
        log.info("submitted request has been persisted sucessfully");
        mongoClient.close();
    }
}