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:example.QuickTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes no args/*from  w  w  w  .j a  v a  2 s .c o m*/
 * @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();

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

    // Authenticate - optional
    // boolean auth = db.authenticate("foo", "bar");

    // 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 testCollection = db.getCollection("testCollection");

    // drop all the data in it
    testCollection.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));

    testCollection.insert(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    DBObject myDoc = testCollection.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++) {
        testCollection.insert(new BasicDBObject().append("i", i));
    }
    System.out.println(
            "total # of documents after inserting 100 small ones (should be 101) " + testCollection.getCount());

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

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

    // now use a range query to get a larger subset
    query = new BasicDBObject("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50
    cursor = testCollection.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)); // i.e.   20 < i <= 30
    cursor = testCollection.find(query);

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

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

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

    // See if the last operation had an error
    System.out.println("Last error : " + db.getLastError());

    // see if any previous operation had an error
    System.out.println("Previous error : " + db.getPreviousError());

    // force an error
    db.forceError();

    // See if the last operation had an error
    System.out.println("Last error : " + db.getLastError());

    db.resetError();

    // release resources
    mongoClient.close();
}

From source file:example.springdata.mongodb.util.MongosSystemForTestFactory.java

License:Apache License

private void initializeReplicaSet(Entry<String, List<IMongodConfig>> entry) throws Exception {
    String replicaName = entry.getKey();
    List<IMongodConfig> mongoConfigList = entry.getValue();

    if (mongoConfigList.size() < 3) {
        throw new Exception("A replica set must contain at least 3 members.");
    }//from  w  w  w .j  a  v a  2 s  .  c  om
    // Create 3 mongod processes
    for (IMongodConfig mongoConfig : mongoConfigList) {
        if (!mongoConfig.replication().getReplSetName().equals(replicaName)) {
            throw new Exception("Replica set name must match in mongo configuration");
        }
        IRuntimeConfig runtimeConfig = new RuntimeConfigBuilder().defaultsWithLogger(Command.MongoD, logger)
                .processOutput(outputFunction.apply(Command.MongoD)).build();
        MongodStarter starter = MongodStarter.getInstance(runtimeConfig);
        MongodExecutable mongodExe = starter.prepare(mongoConfig);
        MongodProcess process = mongodExe.start();
        mongodProcessList.add(process);
    }
    Thread.sleep(1000);
    MongoClientOptions mo = MongoClientOptions.builder().connectTimeout(10).build();
    MongoClient mongo = new MongoClient(
            new ServerAddress(mongoConfigList.get(0).net().getServerAddress().getHostName(),
                    mongoConfigList.get(0).net().getPort()),
            mo);
    DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME);

    CommandResult cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1));
    logger.info("isMaster: {}", cr);

    // Build BSON object replica set settings
    DBObject replicaSetSetting = new BasicDBObject();
    replicaSetSetting.put("_id", replicaName);
    BasicDBList members = new BasicDBList();
    int i = 0;
    for (IMongodConfig mongoConfig : mongoConfigList) {
        DBObject host = new BasicDBObject();
        host.put("_id", i++);
        host.put("host",
                mongoConfig.net().getServerAddress().getHostName() + ":" + mongoConfig.net().getPort());
        members.add(host);
    }

    replicaSetSetting.put("members", members);
    logger.info(replicaSetSetting.toString());
    // Initialize replica set
    cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate", replicaSetSetting));
    logger.info("replSetInitiate: {}", cr);

    Thread.sleep(5000);
    cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
    logger.info("replSetGetStatus: {}", cr);

    // Check replica set status before to proceed
    while (!isReplicaSetStarted(cr)) {
        logger.info("Waiting for 3 seconds...");
        Thread.sleep(1000);
        cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
        logger.info("replSetGetStatus: {}", cr);
    }

    mongo.close();
    mongo = null;
}

From source file:examples.tour.QuickTour.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
 *//*from  ww  w  .  java2 s .  c  om*/
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");

    // 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.toJson());

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

    // find first
    myDoc = collection.find().first();
    System.out.println(myDoc.toJson());

    // 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().toJson());
        }
    } finally {
        cursor.close();
    }

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

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

    // 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().toJson());
        }
    } 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().toJson());
        }
    } finally {
        cursor.close();
    }

    // Query Filters
    myDoc = collection.find(eq("i", 71)).first();
    System.out.println(myDoc.toJson());

    // now use a range query to get a larger subset
    Block<Document> printBlock = new Block<Document>() {

        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
    };
    collection.find(gt("i", 50)).forEach(printBlock);

    // filter where; 50 < i <= 100
    collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock);

    // Sorting
    myDoc = collection.find(exists("i")).sort(descending("i")).first();
    System.out.println(myDoc.toJson());

    // Projection
    myDoc = collection.find().projection(excludeId()).first();
    System.out.println(myDoc.toJson());

    // Aggregation
    collection
            .aggregate(
                    asList(match(gt("i", 0)), project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}"))))
            .forEach(printBlock);

    myDoc = collection.aggregate(singletonList(group(null, sum("total", "$i")))).first();
    System.out.println(myDoc.toJson());

    // Update One
    collection.updateOne(eq("i", 10), set("i", 110));

    // Update Many
    UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("i", 100));
    System.out.println(updateResult.getModifiedCount());

    // Delete One
    collection.deleteOne(eq("i", 110));

    // Delete Many
    DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
    System.out.println(deleteResult.getDeletedCount());

    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));
    //collection.find().forEach(printBlock);

    // Clean up
    database.drop();

    // release resources
    mongoClient.close();
}

From source file:firesystem.model.FireSensor.java

/**
 * Saves output every x ms based on the constant refresh rate. Saves in mongodb and uploads to server on the given server brain url.
 *///www  . j  av  a  2 s.c o m
@Override
public void run() {
    while (true) {
        try {
            if (enabled == true) {

                //                    System.out.println(BRAIN_URL_STRING);
                //Create mongodb connection
                MongoClient mdb = new MongoClient(DatabaseConnectionPopup.getsHostName());

                DB db = mdb.getDB(DatabaseConnectionPopup.getsDbname());

                //Get relevant connections
                users = db.getCollection("users");
                temperatureCollection = db.getCollection(DatabaseConnectionPopup.getCollectionName());

                //Find my document in the users collection
                DBObject ME = findDocumentById(jsonId, users);

                //If document doesn't exist, add it to the users collection
                if (ME == null) {
                    ME = new BasicDBObject("_id", new ObjectId(jsonId));
                    users.insert(ME);
                }

                temperature = (int) (Math.random() * 100);
                humidity = (int) (Math.random() * 100);
                String mobile = "";
                String email = "";

                if (ME.containsField("mobile")) {
                    mobile = (String) ME.get("mobile");
                }
                if (ME.containsField("email")) {
                    email = (String) ME.get("email");
                }

                //Write temperature to mongodb
                temperatureCollection
                        .insert(new BasicDBObject("temperature", temperature).append("humidity", humidity));

                //Send temperature to server
                String temperatureJson = "{\"name\":\"sensor-" + number + "\",\"temperature\":" + temperature
                        + ",\"humidity\":" + humidity + ",\"mobile\":\"" + mobile + "\",\"email\":\"" + email
                        + "\"}";

                URL url = new URL(BRAIN_URL_STRING + "?temperature=" + temperatureJson + "&sensorId=" + number);

                url.openStream();
                //Hvis temperaturen er over 90 s send email og sms.
                if (temperature > 90) {
                    //Send sms
                    String message = "Room%20for%20sensor%20" + number + "%20is%20on%20fire!";
                    if (ME.containsField("mobile")) {
                        url = new URL(SMS_API_STRING + "?sMobileNumber=" + mobile + "&sMessage=" + message);

                        url.openStream();
                    }

                    //Send email
                    if (ME.containsField("email")) {
                        String subject = "FIRE";
                        url = new URL(EMAIL_API_STRING + "?email=" + email + "&subject=" + subject + "&message="
                                + message);

                        url.openStream();
                    }

                }

                mdb.close();
            }

            Thread.sleep(REFRESH_RATE);
        } catch (InterruptedException ex) {
            //
        } catch (IOException ex) {
            //
        } catch (Exception e) {
            enabled = false;
        }

    }
}

From source file:fr.utbm.repository.MongoDBDao.java

public void subscribeClientToCourseSession(Client cl) {

    MongoClient mongoClient = null;

    try {/*w  w w .  java 2  s .c o  m*/
        mongoClient = new MongoClient("localhost", 27017);

        MongoDatabase db;
        db = mongoClient.getDatabase("SCHOOL");

        MongoCollection<Document> collection = db.getCollection("CLIENTS");

        Document doc = new Document();
        doc.put("lastName", cl.getLastName());
        doc.put("firstName", cl.getFirstName());
        doc.put("address", cl.getAddress());
        doc.put("phone", cl.getPhone());
        doc.put("email", cl.getEmail());
        doc.put("courseSessionId", cl.getCourseSessionId().getId());

        collection.insertOne(doc);

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

From source file:fucksocks.utils.MongoDBUtil.java

License:Apache License

public <T> T doJob(MongoDBCallback<T> callback) {
    MongoClient client = null;
    T t = null;/*from  www. j  ava  2 s  .  co  m*/
    try {
        client = new MongoClient(host, port);
        MongoDatabase database = client.getDatabase(databaseName);
        MongoCollection<Document> collection = database.getCollection(collectionName);
        t = callback.process(collection);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return t;
}

From source file:geriapp.dao.ReadingDAO.java

public static void storeReading(Reading reading) {

    MongoClient mongo = new MongoClient("54.254.204.169", 27017);

    MongoDatabase db = mongo.getDatabase("GERI");
    MongoCollection newColl;/*from  w w w.  j a v a  2s . c o  m*/

    if (reading instanceof MedboxReading) {
        newColl = db.getCollection("Medbox");
        Document medboxReading = new Document("gw_id", ((MedboxReading) reading).getGw_id());
        medboxReading.append("server_timestamp", ((MedboxReading) reading).getServer_timestamp());
        medboxReading.append("sequence", ((MedboxReading) reading).getSequence());
        medboxReading.append("gw_timestamp", ((MedboxReading) reading).getGw_timestamp());
        medboxReading.append("sensor_id", ((MedboxReading) reading).getSensor_id());
        medboxReading.append("reed_val", ((MedboxReading) reading).getReed_val());
        newColl.insertOne(medboxReading);
        //TODO: append reading attributes
    } else if (reading instanceof DoorReading) {
        newColl = db.getCollection("Door");
        Document doorReading = new Document("gw_id", ((DoorReading) reading).getGw_id());
        doorReading.append("server_timestamp", ((DoorReading) reading).getServer_timestamp());
        doorReading.append("sequence", ((DoorReading) reading).getSequence());
        doorReading.append("gw_timestamp", ((DoorReading) reading).getGw_timestamp());
        doorReading.append("sensor_id", ((DoorReading) reading).getSensor_id());
        doorReading.append("reed_val", ((DoorReading) reading).getReed_val());
        newColl.insertOne(doorReading);
    }

    mongo.close();
}

From source file:geriapp.dao.ReadingDAO.java

public static Reading getLatestReading(String type) {//Change later to ID instead of type
    MongoClient mongo = new MongoClient("54.254.204.169", 27017);

    MongoDatabase db = mongo.getDatabase("GERI");

    MongoCollection<Document> newColl;

    Gson gson = new Gson();

    if (type.equals("medbox")) {
        newColl = db.getCollection("Medbox");
        Document latestEntry = newColl.find().iterator().next();
        String json = latestEntry.toJson();
        Reading reading = gson.fromJson(json, MedboxReading.class);
        mongo.close();
        return reading;
    } else if (type.equals("door")) {

    }//from w  w  w .j  a  va 2 s . c o m
    return null; //throw Exception??
}

From source file:geriapp.dao.ReadingDAO.java

public static Reading getReadingsBetween(String type, Timestamp startTime, Timestamp endTime) {
    MongoClient mongo = new MongoClient("54.254.204.169", 27017);

    MongoDatabase db = mongo.getDatabase("GERI");

    MongoCollection<Document> newColl;

    Gson gson = new Gson();

    if (type.equals("medbox")) {
        newColl = db.getCollection("Medbox");
        Document latestEntry = newColl.find().iterator().next();
        String json = latestEntry.toJson();
        MedboxReading reading = gson.fromJson(json, MedboxReading.class);
        String thisTimestamp = reading.getGw_timestamp();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parsedTimestamp = null;
        try {//from w w w . java 2  s  . c  o m
            parsedTimestamp = df.parse(thisTimestamp);
        } catch (ParseException e) {
            return null;
        }
        Timestamp gwTimestamp = new Timestamp(parsedTimestamp.getTime());
        mongo.close();
        if (gwTimestamp.after(startTime) && gwTimestamp.before(endTime)) {
            return reading;
        }
    } else if (type.equals("door")) {
        newColl = db.getCollection("Door");
        Document latestEntry = newColl.find().iterator().next();
        String json = latestEntry.toJson();
        DoorReading reading = gson.fromJson(json, DoorReading.class);
        String thisTimestamp = reading.getGw_timestamp();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parsedTimestamp = null;
        try {
            parsedTimestamp = df.parse(thisTimestamp);
        } catch (ParseException e) {
            return null;
        }
        Timestamp gwTimestamp = new Timestamp(parsedTimestamp.getTime());
        mongo.close();
        if (gwTimestamp.after(startTime) && gwTimestamp.before(endTime)) {
            return reading;
        }
    }
    return null; //throw Exception??
}

From source file:geriapp.dao.ReadingDAO.java

public static int getPastReadingsCountBetween(String type, Timestamp startTime, Timestamp endTime) {
    MongoClient mongo = new MongoClient("54.254.204.169", 27017);

    MongoDatabase db = mongo.getDatabase("GERI");
    int size = 0;
    MongoCollection<Document> newColl;

    Gson gson = new Gson();

    if (type.equals("medbox")) {
        newColl = db.getCollection("Medbox");
        MongoCursor<Document> iterator = newColl.find().iterator();
        Document latestEntry = null;
        boolean run = true;
        ArrayList<MedboxReading> results = new ArrayList<MedboxReading>();
        while (run) {
            latestEntry = iterator.next();
            if (latestEntry == null) {
                run = false;// w w w .j  a v  a2  s  .  c o m
                size = 121;
                break;
            }
            String json = latestEntry.toJson();
            MedboxReading reading = gson.fromJson(json, MedboxReading.class);
            String thisTimestamp = reading.getGw_timestamp();

            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parsedTimestamp = null;
            try {
                parsedTimestamp = df.parse(thisTimestamp);
                //System.out.println(""+parsedTimestamp);
            } catch (ParseException e) {
                e.printStackTrace();
                run = false;
            }
            Timestamp gwTimestamp = new Timestamp(parsedTimestamp.getTime());
            //if (gwTimestamp.after(startTime)) {
            if (gwTimestamp.after(startTime) && gwTimestamp.before(endTime)) {
                results.add(reading);
            }
            if (!iterator.hasNext()) {
                run = false;
            }
        }
        /*
        while (iterator.hasNext()) {
        latestEntry = iterator.next();
        String json = latestEntry.toJson();
        MedboxReading reading = gson.fromJson(json, MedboxReading.class);
        results.add(reading);
        }
        */
        mongo.close();
        size = results.size();
        return size;
    } else if (type.equals("door")) {
        newColl = db.getCollection("Door");
        MongoCursor<Document> iterator = newColl.find().iterator();
        Document latestEntry = null;
        boolean run = true;
        ArrayList<DoorReading> results = new ArrayList<DoorReading>();
        while (run) {
            latestEntry = iterator.next();
            if (latestEntry == null) {
                run = false;
                size = 121;
                break;
            }
            String json = latestEntry.toJson();
            DoorReading reading = gson.fromJson(json, DoorReading.class);
            String thisTimestamp = reading.getGw_timestamp();

            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parsedTimestamp = null;
            try {
                parsedTimestamp = df.parse(thisTimestamp);
                //System.out.println(""+parsedTimestamp);
            } catch (ParseException e) {
                e.printStackTrace();
                run = false;
            }
            Timestamp gwTimestamp = new Timestamp(parsedTimestamp.getTime());
            //if (gwTimestamp.after(startTime)) {
            if (gwTimestamp.after(startTime) && gwTimestamp.before(endTime)) {
                results.add(reading);
            }
            if (!iterator.hasNext()) {
                run = false;
            }
        }
        /*
        while (iterator.hasNext()) {
        latestEntry = iterator.next();
        String json = latestEntry.toJson();
        MedboxReading reading = gson.fromJson(json, MedboxReading.class);
        results.add(reading);
        }
        */
        mongo.close();
        size = results.size();
        return size;
    }
    return size; //throw Exception??
}