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: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   w w w .  ja va 2 s .  c  o m
@SuppressWarnings("deprecation")
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 the "mydb" database
    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 handle to the "test" collection
    DBCollection collection = db.getCollection("test");

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

    collection.insert(doc);

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

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

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

    // now use a query to get 1 document out
    cursor = collection.find(new BasicDBObject("i", 71));

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

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

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

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

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

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

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

    // release resources
    mongoClient.close();
}

From source file:tourapi.TourAPI.java

private void MLUpdate(String from, String to) {
    // ?//from ww  w . j av a 2 s . c om
    //fromt->to 
    MongoClient mongoClient = getMongoClient();
    String result = null;
    try {
        DB db = mongoClient.getDB("my_database");
        DBCollection coll = db.getCollection("ML_Result");
        WriteConcern w = new WriteConcern(1, 0);
        mongoClient.setWriteConcern(w);

        DBObject doc = new BasicDBObject();
        // string?  select
        BasicDBObject query = new BasicDBObject();
        query.put("from", from);
        query.put("to", to);

        DBCursor cursor = coll.find(query);

        if (cursor.hasNext())// ?? 
        {
            DBObject mapObj = cursor.next();
            int num = ((Number) mapObj.get("num")).intValue();
            num++;
            BasicDBObject newDocument = new BasicDBObject();
            newDocument.append("$set", new BasicDBObject().append("num", num));
            BasicDBObject searchQuery = new BasicDBObject().append("from", from).append("to", to);
            coll.update(searchQuery, newDocument);
            cursor.close();
        } else {// ??  ? -> ?? insert
            doc.put("from", from);
            doc.put("to", to);
            doc.put("num", 1);
            coll.insert(doc);
            cursor.close();
        }
        System.out.println(coll.getCount());
        // close resources
        mongoClient.close();
    } catch (Exception e) {
        System.err.println("error evoke");
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:tourapi.TourAPI.java

private String convertTitleToId(String title, String url, int num) {
    String result = null;/*from  w ww.  j  ava 2 s  . c om*/
    try {

        // To connect to mongodb server
        MongoClient mongoClient = getMongoClient();
        DB db = mongoClient.getDB("my_database");
        DBCollection coll = db.getCollection("TB_titleID");
        System.out.println("? ");

        WriteConcern w = new WriteConcern(1, 0);
        mongoClient.setWriteConcern(w);
        // Now connect to your databases

        DBObject doc = new BasicDBObject();
        BasicDBObject query = new BasicDBObject("title", title);

        DBCursor cursor = coll.find(query);

        if (cursor.hasNext())// ?? 
        {
            result = cursor.next().get("ID").toString();
            cursor.close();
        } else {// ??  ? -> ?? insert
            int autoIncre = (int) coll.getCount();
            doc.put("ID", autoIncre);
            doc.put("title", title);
            System.out.println("URL : " + url);
            doc.put("url", url);
            doc.put("num", num);
            coll.insert(doc);
            cursor.close();
            result = autoIncre + "";
        }
        // close resources
        mongoClient.close();
    } catch (Exception e) {
        System.err.println("convertTitleToId error");
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    return result;
}

From source file:tourapi.TourAPI.java

/**
 * @param args the command line arguments
 *//*from  w w  w .  jav  a2s .  c om*/

private tour_Information findwithDB(String from) {

    tour_Information returntour = new tour_Information();
    String to = null;

    try {
        MongoClient mongoClient = getMongoClient();
        DB db = mongoClient.getDB("my_database");
        DBCollection coll = db.getCollection("ML_Result");
        WriteConcern w = new WriteConcern(1, 0);
        mongoClient.setWriteConcern(w);

        // string?  select
        BasicDBObject query = new BasicDBObject();
        query.put("from", from);

        DBCursor cursor = coll.find(query);
        cursor.sort(new BasicDBObject("num", -1));

        int num = -1;
        System.out.println("from 0: " + from);
        if (cursor.hasNext())// ??  
        {
            DBObject mapObj = cursor.next();
            String temp = mapObj.get("to").toString();
            num = Integer.parseInt(temp);
            //num = ((Number) mapObj.get("to")).intValue();
            cursor.close();

        } else {
            //System.out.println("from2 : "+from);
            returntour.myURL = null;
        }
        System.out.println(coll.getCount());
        // close resources
        if (num != -1) {
            db = mongoClient.getDB("my_database");
            coll = db.getCollection("TB_titleID");
            w = new WriteConcern(1, 0);// ? ,   2000 // ? 2 ??  ? ?
            mongoClient.setWriteConcern(w);

            // string?  select
            query = new BasicDBObject();
            //
            query.put("ID", num);
            //query.put("to",to);
            cursor = coll.find(query);
            if (cursor.hasNext())// ?? 
            {
                System.out.println("num : " + num);
                DBObject mapObj = cursor.next();
                returntour.myURL = mapObj.get("url").toString();
                returntour.myLocation = Integer.parseInt(mapObj.get("num").toString());
                cursor.close();
            } else {
                returntour.myURL = null;
                returntour.myLocation = 0;
            }
        }
        mongoClient.close();
    } catch (Exception e) {
        System.err.println("findwithDB Exception");
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    return returntour;
}

From source file:uk.ac.ebi.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(HUMAN_TEST_DB_NAME, COW_TEST_DB_NAME, SHEEP_TEST_DB_NAME);
    for (String dbName : dbs) {
        DB db = mongoClient.getDB(dbName);
        db.dropDatabase();//from   ww  w  .  j a va 2 s  .  c om
    }
    mongoClient.close();
}

From source file:utils.ExternalResources.java

public static Map<String, Map<String, Integer>> initAPs(final String mongoHostname, final int port)
        throws FileNotFoundException, IOException {
    Map<String, Map<String, Integer>> aps = new HashMap<String, Map<String, Integer>>();

    MongoClient mongoClient = new MongoClient(mongoHostname, port);
    DBCollection collection = mongoClient.getDB("AR").getCollection("aps");

    // we need to merge namespace with name
    // {$project : { name : {$concat: ["$namespace", "-", "$name"]}, groups:1}}
    BasicDBList concatArgs = new BasicDBList();
    concatArgs.add("$namespace");
    concatArgs.add("-");
    concatArgs.add("$name");
    DBObject project = new BasicDBObject("$project",
            new BasicDBObject("name", new BasicDBObject("$concat", concatArgs)).append("groups", 1)
                    .append("poems", 1));

    AggregationOutput output = collection.aggregate(project);

    // For each AP
    for (DBObject dbo : output.results()) {
        Map<String, Integer> sfGroup = new HashMap<String, Integer>();
        aps.put((String) dbo.get("name"), sfGroup);

        BasicDBList l = (BasicDBList) dbo.get("groups");

        int groupID = 0;
        // For each group
        for (Object o : l) {
            BasicDBList dbl = (BasicDBList) o;

            // For each service flavour
            for (Object sf : dbl) {
                sfGroup.put((String) sf, groupID);
            }/*from ww w.j  a  v a  2  s  .c o  m*/

            groupID++;
        }
    }

    mongoClient.close();
    return aps;
}

From source file:utils.ExternalResources.java

public static Map<String, Map<String, DataBag>> getSFtoAvailabilityProfileNames(final String mongoHostname,
        final int port) throws UnknownHostException {
    Map<String, Map<String, DataBag>> poemMap = new HashMap<String, Map<String, DataBag>>(10);
    BagFactory mBagFactory = BagFactory.getInstance();
    TupleFactory mTupleFactory = TupleFactory.getInstance();

    MongoClient mongoClient = new MongoClient(mongoHostname, port);
    DBCollection collection = mongoClient.getDB("AR").getCollection("aps");

    // We need to implement this query to get the unique service flavors 
    // for each AP
    // {$project: { name : {$concat : ["$namespace", "-", "$name"]}, groups : 1, poems : 1 }}
    // { $unwind : "$poems" }, {$unwind : "$groups"}, {$unwind : "$groups"},
    // { $group : { _id : {poem : "$poems", sf : "$groups" }, aps : {$addToSet : "$name"}}},
    // { $group : { _id : {poem : "$_id.poem"}, sfs : {$addToSet: { sf : "$_id.sf", aps : "$aps" }}}}
    BasicDBList concatArgs = new BasicDBList();
    concatArgs.add("$namespace");
    concatArgs.add("-");
    concatArgs.add("$name");
    DBObject project = new BasicDBObject("$project",
            new BasicDBObject("name", new BasicDBObject("$concat", concatArgs)).append("groups", 1)
                    .append("poems", 1));
    DBObject unwindPoems = new BasicDBObject("$unwind", "$poems");
    DBObject unwindGroups = new BasicDBObject("$unwind", "$groups");
    DBObject group = new BasicDBObject("$group",
            new BasicDBObject("_id", new BasicDBObject("poem", "$poems").append("sf", "$groups")).append("aps",
                    new BasicDBObject("$addToSet", "$name")));
    DBObject group2 = new BasicDBObject("$group",
            new BasicDBObject("_id", new BasicDBObject("poem", "$_id.poem")).append("sfs",
                    new BasicDBObject("$addToSet", new BasicDBObject("sf", "$_id.sf").append("aps", "$aps"))));

    AggregationOutput output = collection.aggregate(project, unwindPoems, unwindGroups, unwindGroups, group,
            group2);/*from   w w  w .j a va  2s.  c  o m*/

    // For each poem profile
    for (DBObject dbo : output.results()) {
        BasicDBList l = (BasicDBList) dbo.get("sfs");
        String poemProfile = (String) ((DBObject) dbo.get("_id")).get("poem");

        Map<String, DataBag> sfMap = new HashMap<String, DataBag>(10);
        // For each service flavour
        for (Object o : l) {
            DBObject sfs = (DBObject) o;

            String serviceFlaver = (String) sfs.get("sf");
            BasicDBList apList = (BasicDBList) sfs.get("aps");

            DataBag apBag = mBagFactory.newDefaultBag();
            // For each AP
            for (Object ap : apList) {
                apBag.add(mTupleFactory.newTuple((String) ap));
            }

            sfMap.put(serviceFlaver, apBag);
        }

        poemMap.put(poemProfile, sfMap);
    }

    mongoClient.close();
    return poemMap;
}

From source file:utils.ExternalResources.java

public static Map<String, Map<String, Object>> getRecalculationRequests(final String mongoHostname,
        final int port, final int date, final int quantum) throws UnknownHostException, IOException {
    Map<String, Map<String, Object>> recalcMap = new HashMap<String, Map<String, Object>>(10);

    MongoClient mongoClient = new MongoClient(mongoHostname, port);
    DBCollection collection = mongoClient.getDB("AR").getCollection("recalculations");

    // We need to take all recalculatios that include the date we calculate.
    DBCursor cursor = collection.find(new BasicDBObject("$where", String.format(
            "'%s' <= this.et.split('T')[0].replace(/-/g,'') || '%s' >= this.st.split('T')[0].replace(/-/g,'')",
            date, date)));//  ww  w.java2  s.  co m

    for (DBObject dbo : cursor) {
        String ngi = (String) dbo.get("n");
        int size = ((BasicDBList) dbo.get("es")).size();
        String[] excludedSites = ((BasicDBList) dbo.get("es")).toArray(new String[size]);

        int startGroup = Utils.determineTimeGroup((String) dbo.get("st"), date, quantum);
        int endGroup = Utils.determineTimeGroup((String) dbo.get("et"), date, quantum);

        // data object is Entry<Integer, Integer>
        // exclude object is String[]
        Map<String, Object> hmap = new HashMap<String, Object>(5);
        hmap.put("data", new SimpleEntry<Integer, Integer>(startGroup, endGroup));
        hmap.put("exclude", excludedSites);
        recalcMap.put(ngi, hmap);
    }

    mongoClient.close();
    return recalcMap;
}

From source file:yelpmongodb.hw4.java

private void checkMainCategories() {
    ArrayList<String> list = getCategories(mainCategoriesPanel);
    ArrayList<String> attList = new ArrayList<>();
    removeComponents(attributesPanel, attributesScrollBar);
    MongoClient client = new MongoClient();
    DB db = client.getDB("db");
    DBCollection coll = db.getCollection("business");
    String attribute = "";

    if (list.size() > 0) {
        DBObject mainQuery = mainCategoriesQuery(list, 0);
        List curs = coll.distinct("attributes", mainQuery);

        for (int i = 0; i < curs.size(); i++) {
            BasicDBObject dbo = (BasicDBObject) curs.get(i);

            for (Entry<String, Object> entry : dbo.entrySet()) {
                if (entry.getValue() instanceof BasicDBObject) {
                    BasicDBObject nestedobj = (BasicDBObject) entry.getValue();
                    for (Entry<String, Object> nestedentry : nestedobj.entrySet()) {
                        attribute = entry.getKey() + ":" + nestedentry.getKey() + ":" + nestedentry.getValue();
                    }/*from   ww  w. jav a  2 s .  c  om*/
                } else {
                    attribute = entry.getKey() + ":" + entry.getValue();
                }
                if (!(attList.contains(attribute))) {
                    attList.add(attribute);
                }
            }
        }

        createAttributeCheckBox(attList);
        client.close();
    }
}

From source file:yelpmongodb.hw4.java

private void createReviewTable(String name, String city, String state, String rating) {
    String columnNames[] = new String[] { "Date", "Rating", "Review Text", "Username", "Useful Votes" };
    JFrame frame = new JFrame("Reviews");
    frame.setMinimumSize(new Dimension(1000, 600));
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(1, 0));
    JTable table = new JTable();
    DefaultTableModel model = (DefaultTableModel) table.getModel();
    model.setColumnIdentifiers(columnNames);
    JScrollPane scrollPane = new JScrollPane(table);

    String bid = getBusinessID(name, city, state, Double.parseDouble(rating));

    MongoClient client = new MongoClient();
    DB db = client.getDB("db");
    DBCollection coll = db.getCollection("review");
    String username = "";
    DBObject clause = new BasicDBObject("business_id", bid);
    DBCursor cursor = coll.find(clause);

    while (cursor.hasNext()) {
        DBObject dbo = cursor.next();/*www  . j  a va  2s . c o m*/
        String userid = dbo.get("user_id").toString();
        coll = db.getCollection("user");
        clause = new BasicDBObject("user_id", userid);
        DBCursor userCursor = coll.find(clause);
        username = userCursor.next().get("name").toString();
        DBObject voteList = (DBObject) dbo.get("votes");
        model.addRow(new Object[] { dbo.get("date"), dbo.get("stars"), dbo.get("text"), username,
                voteList.get("useful") });
    }

    client.close();
    panel.add(scrollPane);
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);

}