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:rmi_video.VideoServer.java

@Override
public VideoData getVideo(String id) throws RemoteException {
    try {/*w ww  . j a  v  a 2  s. c o  m*/
        //Cria conexao com MongoDB
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("VideoDatabase");

        //Recupera o video atraves do ID
        GridFS gfsVideo = new GridFS(db, "video");
        BasicDBObject whereQuery = new BasicDBObject();
        whereQuery.put("videoId", id);
        GridFSDBFile videoForOutput = gfsVideo.findOne(whereQuery);

        String filename = videoForOutput.getFilename();

        try (FileOutputStream fos = new FileOutputStream("/Users/philcr/Documents/" + filename)) {
            videoForOutput.writeTo(fos);
        }

        Path path = Paths.get("/Users/philcr/Documents/" + filename);
        byte[] data = Files.readAllBytes(path);

        File videoFile = new File("/Users/philcr/Documents/" + filename);

        //Exclui o arquivo local
        boolean deletedFlag = videoFile.delete();
        if (!deletedFlag) {
            System.err.println("Video could not be deleted!");
        }

        mongoClient.close();
        return new VideoData(data, filename, id);
    } catch (UnknownHostException ex) {
        Logger.getLogger(VideoServer.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    } catch (FileNotFoundException ex) {
        Logger.getLogger(VideoServer.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    } catch (IOException ex) {
        Logger.getLogger(VideoServer.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:rocks.teammolise.myunimol.webapp.issues.SendAdvice.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w w  w  .  j a va 2  s  .c o m
 * 
 * @param request
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();

    MongoClient mongoClient = null;
    try {
        if (request.getSession().getAttribute("userInfo") == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }

        UserInfo userInfo = (UserInfo) request.getSession().getAttribute("userInfo");

        String username = userInfo.getUsername();
        String password = userInfo.getPassword();

        String type = request.getParameter("type");
        String other = request.getParameter("other");
        String details = request.getParameter("details");

        ConfigurationManager confMgr = ConfigurationManagerHandler.getInstance();
        String mdburi = confMgr.getMongoDbUri();
        int pos = mdburi.lastIndexOf("/");
        String dbName = mdburi.substring(pos + 1, mdburi.length());
        MongoClientURI uri = new MongoClientURI(mdburi);
        mongoClient = new MongoClient(uri);
        MongoDatabase db = mongoClient.getDatabase(dbName);

        MongoCollection<Document> collection = db.getCollection("advices");
        Map<String, Object> userinfo = new HashMap<String, Object>();
        userinfo.put("name", userInfo.getName());
        userinfo.put("surname", userInfo.getSurname());
        userinfo.put("course", userInfo.getCourse());
        userinfo.put("department", userInfo.getDepartment());
        userinfo.put("totalCFU", userInfo.getTotalCFU());
        userinfo.put("username", userInfo.getUsername());
        userinfo.put("studentId", userInfo.getStudentId());
        userinfo.put("enrolledExams", userInfo.getEnrolledExams());
        userinfo.put("registrationDate", userInfo.getRegistrationDate());
        userinfo.put("studentClass", userInfo.getStudentClass());
        userinfo.put("coursePath", userInfo.getCoursePath());
        userinfo.put("courseLength", userInfo.getCourseLength());
        Document userInfoDoc = new Document(userinfo);
        Map<String, Object> advice = new HashMap<String, Object>();
        advice.put("type", type);
        if (other != null)
            advice.put("other", other);
        advice.put("details", details);
        advice.put("userInfo", userInfoDoc);
        collection.insertOne(new Document(advice));

        out.println("{\"result\":\"success\"}");
    } catch (Exception ex) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
    } finally {
        out.close();
        mongoClient.close();
    }
}

From source file:shionn.hexas.mongo.MongoClientFactory.java

License:GNU General Public License

public void close(@Disposes MongoClient client) {
    logger.info("Close Mongo Client");
    client.close();
}

From source file:sockslib.utils.mongo.MongoDBUtil.java

License:Apache License

/**
 * Connect MongoDB and call callback, close connection at last.
 *
 * @param collectionName Collection name.
 * @param callback       Callback//from  w w w .j av a2  s . c  o  m
 * @param <T>            The type of value which you want to return.
 * @return The value which callback returned.
 */
public <T> T connect(String collectionName, CollectionCallback<T> callback) {
    MongoClient client = null;
    T t = null;
    try {
        client = getConnectedClient();
        MongoDatabase database = client.getDatabase(databaseName);
        MongoCollection<Document> collection = database.getCollection(collectionName);
        t = callback.doInCollection(collection);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return t;
}

From source file:softcons.lab10citysearchv3.MongoDBExamples.java

public static void main(final String[] args) throws ClassNotFoundException, SQLException, IOException {

    //      /* ww  w.  j  a v  a  2 s  .co  m*/
    CSVParser csv = new CSVParser();
    dao mydao = new dao();
    csv.insertData();
    List<Country> coun = csv.getRecord();

    //            for (Country region:coun){
    //                if (region.getClass().toString().contains("entities.Region")){
    //                    Region reg=(Region)region;
    //                    System.out.println(reg.getCityName());
    //                }
    //                System.out.println(region.getClass());
    //            }
    // 1. Connect to MongoDB instance running on localhost
    MongoClient mongoClient = Connection.getMongoClient();

    // Access database named 'test'
    MongoDatabase database = mongoClient.getDatabase("citySearchV3");

    // Access collection named 'restaurants'
    MongoCollection collection = database.getCollection("locations");

    //mydao.addData(coun, collection);
    //        FindIterable<Document> docList = mydao.findCityByName("\"Vail\"", collection);
    //        FindIterable<Document> docList = mydao.findCityByCoordinates(0, 0, collection);
    System.out.println("Select An Option");
    System.out.println("1: Find Neigbhour cities based on Name");
    System.out.println("2: Find Neigbhour cities based on Longtitude and Latitude");
    System.out.println("3: Distance between Cities using Longitudes and Latitudes");
    System.out.println("4: Exit The Program");
    Scanner sc = new Scanner(System.in);
    int val = sc.nextInt();

    switch (val) {

    case 4:
        System.exit(0);
        break;

    case 3:
        float longi1, longi2, lati1, lati2;

        System.out.println("Enter Longitude of First City");
        longi1 = sc.nextFloat();
        while (Math.abs(longi1) > 180) {
            System.out.println("Enter the Value Again [-180,180]");
            longi1 = sc.nextFloat();

        }

        System.out.println("Enter Latitude of First City");
        lati1 = sc.nextFloat();
        while (Math.abs(lati1) > 90) {
            System.out.println("Enter the Value Again [-90,90]");
            lati1 = sc.nextFloat();

        }

        System.out.println("Enter Longitude of Second City");
        longi2 = sc.nextFloat();
        while (Math.abs(longi2) > 180) {
            System.out.println("Enter the Value Again [-180,180]");
            longi2 = sc.nextFloat();

        }

        System.out.println("Enter Latitude of Second City");
        lati2 = sc.nextFloat();
        while (Math.abs(lati2) > 90) {
            System.out.println("Enter the Value Again [-90,90]");
            lati2 = sc.nextFloat();

        }

        System.out.println("Distance is:");
        System.out.println(GreatDistance(longi1, longi2, lati1, lati2) * 6371000);

        break;

    case 1:
        String s;
        System.out.println("Enter the City Name");
        s = sc.nextLine(); // To avoid the empty line, caused by earlier use of Scanner
        String st = sc.nextLine();

        FindIterable<Document> docList = mydao.findCityByName(st, collection);

        System.out.println("Result Of Longitude and Latitude");

        Document tempDoc = docList.first();
        Double currentLongitude = tempDoc.getDouble("longitude");
        Double currentLatitude = tempDoc.getDouble("latitude");

        System.out.println("How Many Nearby locations should be checked?");
        int value = sc.nextInt();

        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("longitude", new BasicDBObject("$gt", currentLongitude));
        searchQuery.put("latitude", new BasicDBObject("$lt", currentLongitude));

        docList = collection.find(searchQuery).sort(new BasicDBObject("longitude", 1));

        int tempCount = 1;
        for (Document d : docList) {
            if (d.getDouble("longitude") < currentLongitude) {
                continue;
            }
            if (tempCount <= value) {
                System.out.println(d.getString("name"));
                System.out.println(d.getDouble("longitude"));
                System.out.println(d.getDouble("latitude"));
                System.out.print("Distance : ");
                System.out.println(GreatDistance(currentLongitude, d.getDouble("longitude"), currentLatitude,
                        d.getDouble("latitude")));
                tempCount++;

            }

        }

        break;

    case 2:
        System.out.println("Enter Longitude:");
        float f = sc.nextFloat();
        System.out.println("Enter Latitude:");
        float f2 = sc.nextFloat();

        FindIterable<Document> docListv2 = mydao.findCityByCoordinates(f, f2, collection);

        Document doc = docListv2.first();

        Double currentLongitudev2 = doc.getDouble("longitude");
        Double currentLatitudev2 = doc.getDouble("latitude");

        System.out.println("How Many Nearby locations should be checked?");
        int valuev2 = sc.nextInt();

        BasicDBObject searchQueryv2 = new BasicDBObject();
        searchQueryv2.put("longitude", new BasicDBObject("$gt", currentLongitudev2));
        searchQueryv2.put("longitude", new BasicDBObject("$lt", currentLongitudev2));

        docList = collection.find(searchQueryv2).sort(new BasicDBObject("longitude", 1));

        int tempCountv2 = 1;
        for (Document d : docList) {
            if ((d.getDouble("longitude") - currentLongitudev2) >= -1 && tempCountv2 <= valuev2) {
                System.out.println(d.getString("name"));
                System.out.println(d.getDouble("longitude"));
                System.out.println(d.getDouble("latitude"));
                System.out.print("Distance : ");
                System.out.println(GreatDistance(currentLongitudev2, d.getDouble("longitude"),
                        currentLatitudev2, d.getDouble("latitude")));
                tempCountv2++;

            }

        }

        break;
    }
    System.out.println("Done");
    System.exit(0);

    mongoClient.close();
    System.out.println("Done ");
}

From source file:teste.mongo.example.QuickTourAdmin.java

License:Apache License

public static void main(String[] args) throws Exception {

    // connect to the local database server 
    MongoClient mongoClient = new MongoClient();

    /*/*from   www.j a  v  a 2  s. c  o m*/
    // Authenticate - optional
    MongoCredential credential = MongoCredential.createMongoCRCredential(userName, database, password);
    MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential));
    */

    System.out.println("##### DataBaseInitial");
    // get db names
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }

    // get a db
    DB db = mongoClient.getDB("mydb");

    System.out.println("##### With new DataBase MYDB");
    // do an insert so that the db will really be created.  Calling getDB() doesn't really take any
    // action with the server 
    db.getCollection("testcollection").insert(new BasicDBObject("i", 1));
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }

    // drop a database
    mongoClient.dropDatabase("mydb");

    System.out.println("##### DataBase drop MYDB");
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }

    // create a collection
    db = mongoClient.getDB("mydb");
    db.createCollection("testCollection", new BasicDBObject("capped", true).append("size", 1048576));

    System.out.println("##### ListAllCollection MYDB");
    // List all collections
    for (String s : db.getCollectionNames()) {
        System.out.println(s);
    }

    // Dropping a collection
    DBCollection testCollection = db.getCollection("testCollection");
    testCollection.drop();
    System.out.println("##### ListAllCollection MYDB - Drop testCollection");
    System.out.println(db.getCollectionNames());

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

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

    // create an index on the "i" field
    coll.createIndex(new BasicDBObject("i", 1));

    // Geospatial query
    coll.createIndex(new BasicDBObject("loc", "2dsphere"));

    BasicDBList coordinates = new BasicDBList();
    coordinates.put(0, -73.97);
    coordinates.put(1, 40.77);
    coll.insert(new BasicDBObject("name", "Central Park")
            .append("loc", new BasicDBObject("type", "Point").append("coordinates", coordinates))
            .append("category", "Parks"));

    coordinates.put(0, -73.88);
    coordinates.put(1, 40.78);
    coll.insert(new BasicDBObject("name", "La Guardia Airport")
            .append("loc", new BasicDBObject("type", "Point").append("coordinates", coordinates))
            .append("category", "Airport"));

    // Find whats within 500m of my location
    BasicDBList myLocation = new BasicDBList();
    myLocation.put(0, -73.965);
    myLocation.put(1, 40.769);
    DBObject myDoc = coll.findOne(new BasicDBObject("loc", new BasicDBObject("$near",
            new BasicDBObject("$geometry", new BasicDBObject("type", "Point").append("coordinates", myLocation))
                    .append("$maxDistance", 500))));
    System.out.println(myDoc.get("name"));

    // create a text index on the "content" field
    coll.createIndex(new BasicDBObject("content", "text"));

    coll.insert(new BasicDBObject("_id", 0).append("content", "textual content"));
    coll.insert(new BasicDBObject("_id", 1).append("content", "additional content"));
    coll.insert(new BasicDBObject("_id", 2).append("content", "irrelevant content"));

    // Find using the text index
    BasicDBObject search = new BasicDBObject("$search", "textual content -irrelevant");
    BasicDBObject textSearch = new BasicDBObject("$text", search);
    int matchCount = coll.find(textSearch).count();
    System.out.println("Text search matches: " + matchCount);

    // Find using the $language operator
    textSearch = new BasicDBObject("$text", search.append("$language", "english"));
    matchCount = coll.find(textSearch).count();
    System.out.println("Text search matches (english): " + matchCount);

    // Find the highest scoring match
    BasicDBObject projection = new BasicDBObject("score", new BasicDBObject("$meta", "textScore"));
    myDoc = coll.findOne(textSearch, projection);
    System.out.println("Highest scoring document: " + myDoc);

    // list the indexes on the collection
    List<DBObject> list = coll.getIndexInfo();
    for (final DBObject o : list) {
        System.out.println(o);
    }

    // clean up
    mongoClient.dropDatabase("mydb");
    mongoClient.close();
}

From source file:Tests.AddElementToCollection.java

public void addToCollection(String jsonString) {
    MongoClient mongoClient = new MongoClient(new ServerAddress(),
            Arrays.asList(MongoCredential.createCredential("admin", "test", "password".toCharArray())));
    try {/*ww  w  .java  2  s . c om*/
        for (String databaseName : mongoClient.listDatabaseNames()) {
            System.out.println("Database: " + databaseName);
        }
        MongoDatabase db = mongoClient.getDatabase("test");
        MongoCollection coll = db.getCollection("test2");

        Document doc = Document.parse(jsonString);
        coll.insertOne(doc);
    } finally {
        mongoClient.close();
    }
}

From source file:Tests.PrintFristElementOfCollection.java

public static void main(String[] args) throws UnknownHostException {

    MongoClient mongoClient = new MongoClient(new ServerAddress(),
            Arrays.asList(MongoCredential.createCredential("admin", "test", "password".toCharArray())));
    try {//from www . ja v a2  s.  co  m
        for (String databaseName : mongoClient.listDatabaseNames()) {
            System.out.println("Database: " + databaseName);
        }
        MongoDatabase db = mongoClient.getDatabase("test");
        MongoCollection coll = db.getCollection("test");
        System.out.println(coll.find().first());
    } finally {
        mongoClient.close();
    }
}

From source file:thermostatapplication.TemperaturePersisterTimerTask.java

public synchronized void persistDataOnMongolab() {
    //disable console logging
    //Logger mongoLogger = Logger.getLogger("org.mongodb.driver"); 
    //mongoLogger.setLevel(Level.SEVERE);

    iStoredTemperatures = iTemperatureStore.getTemperatures();
    if (iStoredTemperatures.isEmpty()) {
        logger.info("Nothing to persist. Exiting");
        return;/*  w w  w .  j a  va  2 s. c  om*/
    }
    logger.info("Prepairing to persist [{}] Temps in the cloud", iStoredTemperatures.size());
    MongoCollection<Document> mongoCollection = null;
    MongoClient client = null;
    List<Document> documents = new ArrayList<>();

    for (TemperatureMeasure tTemp : iStoredTemperatures) { //Exception in thread "Timer-2" java.util.ConcurrentModificationException
        Document doc = new Document();
        doc.put("Location", tTemp.getLocation()); //Location
        doc.put("Group", tTemp.getGroup()); //Group
        doc.put("Date", Helper.getDateAsString(tTemp.getDate())); //Date
        doc.put("Day", Helper.getDayAsString(tTemp.getDate()));
        doc.put("Time", Helper.getTimeAsString(tTemp.getDate()));
        doc.put("Temp", Helper.getTempAsString(tTemp.getTemp())); //Temp
        documents.add(doc);
        iPersistedTemperatures.add(tTemp);
    }

    try {
        MongoClientURI uri = new MongoClientURI(ThermostatProperties.ML_URL);
        client = new MongoClient(uri);
        MongoDatabase database = (MongoDatabase) client.getDatabase(uri.getDatabase());
        mongoCollection = database.getCollection("dailytemps");
        mongoCollection.insertMany(documents);
        //eliminate stored Temps from the collection
        iTemperatureStore.removeAll(iPersistedTemperatures);
        client.close();
        logger.info("Temperatures persisted on mongolab: [{}]. Exiting.", iPersistedTemperatures.size());
        iPersistedTemperatures.clear();
    } catch (Throwable e) {
        logger.error("Failed to store Temps in the cloud. Stacktrace: [{}]. Exiting.", e);
        iPersistedTemperatures.clear();
        e.printStackTrace();
    } finally {
        if (client != null) {
            client.close();
        }
        iPersistedTemperatures.clear();
    }
}

From source file:tour.NewQuickTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 *///  ww  w .  j a v  a2 s  . c  o  m
public static void main(final String[] args) {
    MongoClient mongoClient;

    if (args.length == 0) {
        // connect to the local database server
        mongoClient = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }

    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb");

    database.drop();

    // get a list of the collections in this database and print them out
    List<String> collectionNames = database.listCollectionNames().into(new ArrayList<String>());
    for (final String s : collectionNames) {
        System.out.println(s);
    }

    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");

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

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

    collection.insertOne(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    Document myDoc = collection.find().first();
    System.out.println(myDoc);

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

    // lets get all the documents in the collection and print them out
    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    for (Document cur : collection.find()) {
        System.out.println(cur);
    }

    // now use a query to get 1 document out
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc);

    // now use a range query to get a larger subset
    cursor = collection.find(gt("i", 50)).iterator();

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

    // range query with multiple constraints
    cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator();

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

    // max time
    collection.find().maxTime(1, TimeUnit.SECONDS).first();

    collection.drop();

    // ordered bulk writes
    List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
    writes.add(new InsertOneModel<Document>(new Document("_id", 4)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 5)));
    writes.add(new InsertOneModel<Document>(new Document("_id", 6)));
    writes.add(
            new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2))));
    writes.add(new DeleteOneModel<Document>(new Document("_id", 2)));
    writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4)));

    collection.bulkWrite(writes);

    collection.drop();

    collection.bulkWrite(writes, new BulkWriteOptions().ordered(false));

    // getting a list of databases
    for (String name : mongoClient.listDatabaseNames()) {
        System.out.println(name);
    }

    // drop a database
    mongoClient.dropDatabase("databaseToBeDropped");

    // create a collection
    database.createCollection("cappedCollection",
            new CreateCollectionOptions().capped(true).sizeInBytes(0x100000));

    for (String name : database.listCollectionNames()) {
        System.out.println(name);
    }

    // create an ascending index on the "i" field
    collection.createIndex(new Document("i", 1));

    // list the indexes on the collection
    for (final Document index : collection.listIndexes()) {
        System.out.println(index);
    }

    // create a text index on the "content" field
    collection.createIndex(new Document("content", "text"));

    collection.insertOne(new Document("_id", 0).append("content", "textual content"));
    collection.insertOne(new Document("_id", 1).append("content", "additional content"));
    collection.insertOne(new Document("_id", 2).append("content", "irrelevant content"));

    // Find using the text index
    Document search = new Document("$search", "textual content -irrelevant");
    Document textSearch = new Document("$text", search);
    long matchCount = collection.count(textSearch);
    System.out.println("Text search matches: " + matchCount);

    // Find using the $language operator
    textSearch = new Document("$text", search.append("$language", "english"));
    matchCount = collection.count(textSearch);
    System.out.println("Text search matches (english): " + matchCount);

    // Find the highest scoring match
    Document projection = new Document("score", new Document("$meta", "textScore"));
    myDoc = collection.find(textSearch).projection(projection).first();
    System.out.println("Highest scoring document: " + myDoc);

    // release resources
    mongoClient.close();
}