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:datapreparation.MongoStatistics.java

public void usersOfUrl(String URL) {
    // TODO code application logic here

    // TODO code application logic here
    int limit = 0;
    String filename = "Users_Of_Url_" + URL + ".txt";

    // To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
    MongoClient mongoClient;

    try {/*from w  w w  .j av a2  s.  co m*/
        mongoClient = new MongoClient("localhost");

        //use database
        DB db = mongoClient.getDB("users");

        //get collection
        DBCollection coll = db.getCollection("urls");

        // build the $projection operation
        //            DBObject fields = new BasicDBObject("user", 1);
        //            fields.put("_id", 0);
        //            BasicDBObject project = new BasicDBObject("$project", fields);

        //build the match operation
        DBObject matchFields = new BasicDBObject("url", URL);
        DBObject match = new BasicDBObject("$match", matchFields);

        // Now the $group operation
        DBObject groupFields = new BasicDBObject("_id", "$user");
        groupFields.put("count", new BasicDBObject("$sum", 1));
        DBObject group = new BasicDBObject("$group", groupFields);

        // Finally the $sort operation
        BasicDBObject sort = new BasicDBObject("$sort", new BasicDBObject("count", -1));

        // run aggregation
        List<DBObject> pipeline;
        if (limit == 0) {// without limits!
            pipeline = Arrays.asList(match, group, sort);
        } else {
            // create new BasicDBObject that limit query result in only 100 rows
            DBObject limitRes = new BasicDBObject("$limit", limit);
            pipeline = Arrays.asList(match, group, sort, limitRes);
        }
        AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100)
                .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build();

        Cursor cursor = coll.aggregate(pipeline, aggregationOptions);

        writeToFile(cursor, filename, "User\t Count");

        cursor.close();
        mongoClient.close();

    } catch (IOException ex) {
        System.out.println("Something's Wrong! " + ex);
    }
}

From source file:datapreparation.MongoStatistics.java

public void topUrls() {
    // TODO code application logic here
    int limit = 0;
    String filename = "Top_Urls_More.txt";
    // To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
    MongoClient mongoClient;

    try {//from  w ww . j av a 2  s  .  co m
        mongoClient = new MongoClient("localhost");

        //use database
        DB db = mongoClient.getDB("users");

        //get collection
        DBCollection coll = db.getCollection("urls");

        // build the $projection operation
        DBObject fields = new BasicDBObject("url", 1);
        fields.put("_id", 0);
        BasicDBObject project = new BasicDBObject("$project", fields);

        // Now the $group operation
        DBObject groupFields = new BasicDBObject("_id", "$url");
        groupFields.put("count", new BasicDBObject("$sum", 1));
        DBObject group = new BasicDBObject("$group", groupFields);

        // Finally the $sort operation
        BasicDBObject sort = new BasicDBObject("$sort", new BasicDBObject("count", -1));

        // run aggregation
        List<DBObject> pipeline;
        if (limit == 0) {// without limits!
            pipeline = Arrays.asList(project, group, sort);
        } else {
            // create new BasicDBObject that limit query result in only 100 rows
            DBObject limitRes = new BasicDBObject("$limit", limit);
            pipeline = Arrays.asList(project, group, sort, limitRes);
        }
        AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100)
                .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build();

        Cursor cursor = coll.aggregate(pipeline, aggregationOptions);

        writeToFile2(cursor, filename, "URL\t Count");

        cursor.close();
        mongoClient.close();

    } catch (IOException ex) {
        System.out.println("Something's Wrong! " + ex);
    }
}

From source file:datapreparation.MongoStatistics.java

public void timeIntervals() {
    // TODO code application logic here
    int limit = 0;
    String filename = "Times.txt";
    // To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
    MongoClient mongoClient;

    try {/*from   w  ww  . j  av a 2  s.com*/
        mongoClient = new MongoClient("localhost");

        //use database
        DB db = mongoClient.getDB("users");

        //get collection
        DBCollection coll = db.getCollection("urls");

        // build the $projection operation
        DBObject fields = new BasicDBObject("time", 1);
        fields.put("_id", 0);
        BasicDBObject project = new BasicDBObject("$project", fields);

        // Now the $group operation
        DBObject groupFields = new BasicDBObject("_id", "$time");
        //groupFields.put("count", new BasicDBObject("$sum", 1));
        DBObject group = new BasicDBObject("$group", groupFields);

        // Finally the $sort operation
        //BasicDBObject sort = new BasicDBObject("$sort", new BasicDBObject("count", -1));

        // run aggregation
        List<DBObject> pipeline;
        if (limit == 0) {// without limits!
            pipeline = Arrays.asList(project, group);
        } else {
            // create new BasicDBObject that limit query result in only 100 rows
            DBObject limitRes = new BasicDBObject("$limit", limit);
            pipeline = Arrays.asList(project, group, limitRes);
        }
        AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100)
                .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build();

        Cursor cursor = coll.aggregate(pipeline, aggregationOptions);

        writeToFile3(cursor, filename, "Times");

        cursor.close();
        mongoClient.close();

    } catch (IOException ex) {
        System.out.println("Something's Wrong! " + ex);
    }
}

From source file:datapreparation.MongoStatistics.java

public void usersToUrls() {
    // To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
    MongoClient mongoClient;

    try {/*from w w  w . j av  a  2 s  . c  o  m*/
        mongoClient = new MongoClient("localhost");

        //use database
        DB db = mongoClient.getDB("users");

        //get collection
        DBCollection coll = db.getCollection("urls");

        //iterate with a cursor
        BasicDBObject query = new BasicDBObject("source", new BasicDBObject("$exists", true));

        DBCursor cursor = coll.find(query);

        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter("Users_To_Urls.txt"));
            writer.write("url,user,time\n");

            while (cursor.hasNext()) {
                BasicDBObject tweet = (BasicDBObject) cursor.next();

                String time = tweet.get("created_at").toString();
                String user = tweet.get("from_user").toString();
                String urls[] = tweet.get("source").toString().replaceAll("&quot", "").split(";");

                for (String url : urls) {
                    if (url.matches("http.*")) {
                        //The user posted one link, write it in the file!
                        writer.write(url + "," + user + "," + time + "\n");
                    }
                }
            }
        } finally {
            cursor.close();
            mongoClient.close();
            writer.close();
        }
    } catch (IOException ex) {
        System.out.println("Something's Wrong! " + ex);
    }
}

From source file:db.MongoManager.java

public static void closeConnection(MongoClient m) {
    m.close();
}

From source file:de.steilerdev.myVerein.server.controller.init.InitController.java

License:Open Source License

/**
 * This function is validating the provided information of the MongoDB server, by establishing a test connection.
 * @param databaseHost The hostname of the MongoDB server.
 * @param databasePort The port of the MongoDB server.
 * @param databaseUser The user used to authenticate against the MongoDB server (may be empty if not needed).
 * @param databasePassword The password used to authenticate against the MongoDB server (may be empty if not needed).
 * @param databaseCollection The name of the database collection.
 * @return True if the connection was successfully established, false otherwise.
 *//*from ww  w .  j a va2 s .  c  om*/
private boolean mongoIsAvailable(String databaseHost, int databasePort, String databaseUser,
        String databasePassword, String databaseCollection) {
    logger.trace("Testing MongoDB connection");

    if (!databaseUser.isEmpty() && !databasePassword.isEmpty()) {
        logger.debug("Credentials have been provided");
        mongoCredential = Arrays.asList(MongoCredential.createMongoCRCredential(databaseUser,
                databaseCollection, databasePassword.toCharArray()));
    }

    try {
        logger.debug("Creating server address");
        mongoAddress = new ServerAddress(databaseHost, databasePort);
    } catch (UnknownHostException e) {
        logger.warn("Unable to resolve server host: " + e.getMessage());
        return false;
    }

    logger.debug("Creating mongo client");
    MongoClient mongoClient = new MongoClient(mongoAddress, mongoCredential);
    try {
        //Checking if connection REALLY works
        logger.debug("Establishing connection now.");
        List<String> databases = mongoClient.getDatabaseNames();
        if (databases == null) {
            logger.warn("The returned list of databases is null");
            return false;
        } else if (databases.isEmpty()) {
            logger.info("The databases are empty");
            return true;
        } else {
            logger.debug("The database connection seems okay");
            return true;
        }
    } catch (MongoException e) {
        logger.warn("Unable to receive list of present databases: " + e.getMessage());
        return false;
    } finally {
        logger.debug("Closing mongo client");
        mongoClient.close();
    }
}

From source file:de.steilerdev.myVerein.server.controller.init.InitController.java

License:Open Source License

/**
 * This function is establishing a connection to the new database and storing the new super user as well as the new root division. To correctly execute this function the {@link #mongoIsAvailable} function should be called first.
 * @param user The new super admin./* www .j  av a  2 s  . c  o  m*/
 * @param division The new root division.
 * @return True if the operation was successfully, false otherwise.
 */
private boolean savingInitialSetup(User user, Division division, Settings settings) {
    if (mongoAddress != null && databaseName != null && !databaseName.isEmpty()) {
        logger.trace("Saving user and division using new MongoDB connection");

        MongoClient mongoClient = new MongoClient(mongoAddress, mongoCredential);

        DB mongoDB = mongoClient.getDB(databaseName);
        if (mongoClient.getDatabaseNames().contains(databaseName)) {
            logger.warn("The database already contains the defined collection, dropping content.");
            mongoDB.dropDatabase();
        }

        try {
            if (user != null) {
                logger.debug("Storing user");
                DBObject userObject = (DBObject) mappingMongoConverter.convertToMongoType(user);
                userObject.put("_class", user.getClass().getCanonicalName());
                mongoDB.getCollection(user.getClass().getSimpleName().toLowerCase()).insert(userObject);
            }

            if (division != null) {
                logger.debug("Storing division");
                DBObject divisionObject = (DBObject) mappingMongoConverter.convertToMongoType(division);
                divisionObject.put("_class", division.getClass().getCanonicalName());
                mongoDB.getCollection(division.getClass().getSimpleName().toLowerCase()).insert(divisionObject);
            }

            if (settings != null) {
                logger.debug("Storing settings");
                settings.saveSettings(user, null);
                DBObject settingsObject = (DBObject) mappingMongoConverter.convertToMongoType(settings);
                settingsObject.put("_class", settings.getClass().getCanonicalName());
                mongoDB.getCollection(settings.getClass().getSimpleName().toLowerCase()).insert(settingsObject);
            }

            logger.info("Successfully saved root division and super admin");
            return true;
        } catch (MongoException e) {
            logger.warn("Unable to store root division and super admin in database");
            return false;
        } finally {
            mongoClient.close();
        }
    } else {
        logger.warn(
                "Unable to save super admin and new root division, because the new MongoDB connection is not available");
        return false;
    }
}

From source file:edu.csulaerp.db.ReferenceMongo.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes no args//from   ww w.j a  va  2s  .  c om
 * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017
 */
public static void main(final String[] args) throws UnknownHostException {
    // connect to the local database server
    MongoClient mongoClient = new MongoClient();

    /*
    // 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("mydb");

    // get a list of the collections in this database and print them out
    Set<String> collectionNames = db.getCollectionNames();
    for (final String s : collectionNames) {
        System.out.println(s);
    }

    // get a collection object to work with
    DBCollection coll = db.getCollection("testCollection");

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

    // make a document and insert it
    BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1)
            .append("info", new BasicDBObject("x", 203).append("y", 102));

    coll.insert(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    DBObject myDoc = coll.findOne();
    System.out.println(myDoc);

    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    for (int i = 0; i < 100; i++) {
        coll.insert(new BasicDBObject().append("i", i));
    }
    System.out
            .println("total # of documents after inserting 100 small ones (should be 101) " + coll.getCount());

    // lets get all the documents in the collection and print them out
    DBCursor cursor = coll.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();
    }

    // $ Operators are represented as strings
    query = new BasicDBObject("j", new BasicDBObject("$ne", 3)).append("k", new BasicDBObject("$gt", 10));

    cursor = coll.find(query);

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // now use a range query to get a larger subset
    // find all where i > 50
    query = new BasicDBObject("i", new BasicDBObject("$gt", 50));
    cursor = coll.find(query);

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // range query with multiple constraints
    query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30));
    cursor = coll.find(query);

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // Count all documents in a collection but take a maximum second to do so
    coll.find().maxTime(1, SECONDS).count();

    // Bulk operations
    BulkWriteOperation builder = coll.initializeOrderedBulkOperation();
    builder.insert(new BasicDBObject("_id", 1));
    builder.insert(new BasicDBObject("_id", 2));
    builder.insert(new BasicDBObject("_id", 3));

    builder.find(new BasicDBObject("_id", 1)).updateOne(new BasicDBObject("$set", new BasicDBObject("x", 2)));
    builder.find(new BasicDBObject("_id", 2)).removeOne();
    builder.find(new BasicDBObject("_id", 3)).replaceOne(new BasicDBObject("_id", 3).append("x", 4));

    BulkWriteResult result = builder.execute();
    System.out.println("Ordered bulk write result : " + result);

    // Unordered bulk operation - no guarantee of order of operation
    builder = coll.initializeUnorderedBulkOperation();
    builder.find(new BasicDBObject("_id", 1)).removeOne();
    builder.find(new BasicDBObject("_id", 2)).removeOne();

    result = builder.execute();
    System.out.println("Ordered bulk write result : " + result);

    // parallelScan
    ParallelScanOptions parallelScanOptions = ParallelScanOptions.builder().numCursors(3).batchSize(300)
            .build();

    List<Cursor> cursors = coll.parallelScan(parallelScanOptions);
    for (Cursor pCursor : cursors) {
        while (pCursor.hasNext()) {
            System.out.println(pCursor.next());
        }
    }

    // release resources
    db.dropDatabase();
    mongoClient.close();
}

From source file:embl.ebi.variation.eva.vcfdump.VariantExporterTestDB.java

License:Apache License

public static void cleanDBs() throws UnknownHostException {
    logger.info("Cleaning test DBs ...");
    MongoClient mongoClient = new MongoClient("localhost");
    List<String> dbs = Arrays.asList(TEST_DB_NAME, COW_TEST_DB_NAME);
    for (String dbName : dbs) {
        DB db = mongoClient.getDB(dbName);
        db.dropDatabase();//from w w w . java  2  s .c o  m
    }
    mongoClient.close();
}

From source file:es.upv.dsic.elp.iJulienne.MongoDB.java

License:Open Source License

public static String loadData(String maudeInput) {
    String res = null;//from ww  w .  j ava 2s.  co  m
    MongoClient mongo;
    DB db;

    //WARNING: Configure with your own data
    try {
        mongo = new MongoClient("YOUR_SERVER_ADDRESS", YOUR_SERVER_PORT);
    } catch (UnknownHostException e) {
        return null;
    }

    db = mongo.getDB("ijulienne");
    //WARNING: Configure with your own data
    boolean auth = db.authenticate("YOUR_USER", "YOUR_PASSWORD".toCharArray());
    if (auth) {
        DBCollection table = db.getCollection("ijulienne");
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("input", maudeInput);

        DBCursor cursor = table.find(searchQuery);
        if (cursor.hasNext())
            res = cursor.next().get("output").toString();
    }
    mongo.close();
    return res;
}