Example usage for com.mongodb Mongo close

List of usage examples for com.mongodb Mongo close

Introduction

In this page you can find the example usage for com.mongodb Mongo 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.hangum.tadpole.mongodb.core.test.MongoTestReferenceCollection.java

License:Open Source License

/**
 * @param args//  w  ww . jav a2s .  c o m
 */
public static void main(String[] args) throws Exception {

    ConAndAuthentication testMongoCls = new ConAndAuthentication();
    Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, ConAndAuthentication.port);
    DB db = mongo.getDB("test");

    DBObject colInformation = (DBObject) JSON.parse("{capped:true, size:100000}");
    DBCollection ref1Coll = db.getCollection(REF_1);
    if (ref1Coll != null)
        ref1Coll.drop();
    ref1Coll = db.createCollection(REF_1, colInformation);

    DBObject dbObjRef1 = (DBObject) JSON.parse("{ 'name' : 'cho'}");//"{'names': {'First': 'Gonza', 'Last': 'Vieira'}}");
    WriteResult wr = ref1Coll.insert(dbObjRef1);

    DBObject retDBObj = ref1Coll.findOne();
    createRef1Collection(db, retDBObj.get("_id"));

    mongo.close();
}

From source file:com.hangum.tadpole.mongodb.core.test.MongoTestReIndex.java

License:Open Source License

/**
 * @param args// w  ww .ja  va  2s.co  m
 */
public static void main(String[] args) throws Exception {
    ConAndAuthentication testMongoCls = new ConAndAuthentication();
    Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, ConAndAuthentication.port);
    DB db = mongo.getDB("test");

    DBObject queryObj = new BasicDBObject("reIndex", "store");
    CommandResult cr = db.command(queryObj);

    System.out.println("[ok]" + cr.ok());
    if (!cr.ok())
        System.out.println("[Exception ]" + cr.getException().toString());
    System.out.println("[toString]" + cr.toString());
    System.out.println("[size]" + cr.size());

    mongo.close();
}

From source file:com.hangum.tadpole.mongodb.core.test.MongoTestRunCommand.java

License:Open Source License

/**
 * @param args//  w  w w .j  a v a2s  .c  om
 */
public static void main(String[] args) throws Exception {
    ConAndAuthentication testMongoCls = new ConAndAuthentication();
    Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, 27017);//ConAndAuthentication.port);
    DB db = mongo.getDB("test");

    DBCollection dbColl = db.getCollection("user");

    DBObject cmdObj = (DBObject) JSON.parse("{language  : 'en_us'}, {seq: true, email:true}, {seq, -1}");
    DBCursor dbCur = dbColl.find(cmdObj);
    for (DBObject obj : dbCur.toArray()) {
        System.out.println(obj);
    }

    //      CommandResult cr = db.command(cmdObj);//new BasicDBObject("create", "hyunjong"));
    //      System.out.println( cr.toString() );      

    mongo.close();
}

From source file:com.hangum.tadpole.mongodb.core.test.MongoTestServerSideJavascript.java

License:Open Source License

/**
 * @param args/*from ww w  . ja va2 s.c  o  m*/
 */
public static void main(String[] args) throws Exception {

    ConAndAuthentication testMongoCls = new ConAndAuthentication();
    Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, ConAndAuthentication.port);
    DB db = mongo.getDB("test");

    createServerSideJavaScript(db);
    updateServerSideJavaScript(db, "addNumbers", "update java script");
    findAllServerSideJavaScript(db);

    Object[] arryArgs = { 25, 34 };
    evalServerSideJavaScript(db, "addNumbers2", arryArgs);

    mongo.close();

    try {
        Thread.sleep(1);
    } catch (Exception e) {
    }
}

From source file:com.hangum.tadpole.mongodb.core.test.MongoTestServerStatus.java

License:Open Source License

/**
 * @param args/*ww  w.  j a  v a2  s. c  o m*/
 */
public static void main(String[] args) throws Exception {
    ConAndAuthentication testMongoCls = new ConAndAuthentication();
    Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, ConAndAuthentication.port);
    DB db = mongo.getDB("test");

    DBObject queryObj = new BasicDBObject("serverStatus", 0);
    CommandResult cr = db.command(queryObj);

    String strHost = cr.getString("host");
    String version = cr.getString("version");
    String process = cr.getString("process");
    String pid = cr.getString("pid");
    String uptime = cr.getString("uptime");
    String uptimeMillis = cr.getString("uptimeMillis");
    String uptimeEstimate = cr.getString("uptimeEstimate");
    String localTime = cr.getString("localTime");

    System.out.println("[strHost]\t " + strHost);
    System.out.println("[version]\t " + version);

    System.out.println("[process]\t " + process);
    System.out.println("[pid]\t " + pid);
    System.out.println("[uptime]\t " + uptime);
    System.out.println("[uptimeMillis]\t " + uptimeMillis);
    System.out.println("[uptimeEstimate]\t " + uptimeEstimate);
    System.out.println("[localTime]\t " + localTime);

    System.out.println("[ok]" + cr.ok());
    if (!cr.ok())
        System.out.println("[Exception ]" + cr.getException().toString());
    System.out.println("[toString]" + cr.toString());
    System.out.println("[size]" + cr.size());

    mongo.close();
}

From source file:com.hangum.tadpole.mongodb.core.test.MongoTestUpdateCollection.java

License:Open Source License

/**
 * @param args//from   ww  w.j a  v  a2s . co m
 */
public static void main(String[] args) throws Exception {

    ConAndAuthentication testMongoCls = new ConAndAuthentication();
    Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, ConAndAuthentication.port);
    DB db = mongo.getDB("test");
    DBCollection collAddress = db.getCollection("test555");

    BasicDBObject findObj = new BasicDBObject().append("n", 2);
    DBCursor cur = collAddress.find(findObj);
    DBObject dbObj = cur.next();
    System.out.println(dbObj);
    System.out.println("================================================================================");

    if (dbObj != null) {
        BasicDBObject newDocument3 = new BasicDBObject().append("$set",
                new BasicDBObject().append("allPlans.0.cursor", "t2est"));
        //  allPlans.0.cursor
        WriteResult wr = collAddress.update(dbObj, newDocument3);
    }
    //
    //      System.out.println(wr.toString());
    //      
    mongo.close();
}

From source file:com.ikanow.infinit.e.utility.MongoEntityFeatureTxfer.java

License:Apache License

@SuppressWarnings("unused")
private void doUnitTestCode(String sMongoDbHost, String sMongoDbPort, String sElasticHost, String sElasticPort,
        BasicDBObject query, int nLimit) {
    Mongo mongoDB = null;
    ElasticSearchManager elasticManager = null;

    try {// ww w.ja  va  2s  .  c  om
        // Initialize the DB:

        mongoDB = new Mongo(sMongoDbHost, Integer.parseInt(sMongoDbPort));
        DBCollection gazDB = mongoDB.getDB("feature").getCollection("entity");

        // Initialize the ES (create the index if it doesn't already):

        // 1. Set-up the entity feature index 

        String indexName = "entity_index";

        //TEST: delete the index:
        //         elasticManager = ElasticSearchManager.getIndex(indexName, sElasticHost + ":" + sElasticPort);
        //         elasticManager.deleteMe();

        //TEST: create the index
        //         String sMapping = new Gson().toJson(new GazateerPojo.Mapping(), GazateerPojo.Mapping.class);
        //         Builder localSettings = ImmutableSettings.settingsBuilder();
        //         localSettings.put("number_of_shards", 1).put("number_of_replicas", 0);          q
        //         elasticManager = ElasticSearchManager.createIndex
        //                        (indexName, false, 
        //                              sElasticHost + ":" + sElasticPort, 
        //                              sMapping, localSettings);

        //TEST: delete the index:
        //         elasticManager.deleteMe();

        //TEST: get the index:
        //         elasticManager = ElasticSearchManager.getIndex(indexName, sElasticHost + ":" + sElasticPort);

        // Now query the DB:

        DBCursor dbc = null;
        if (nLimit > 0) {
            dbc = gazDB.find(query).limit(nLimit);
        } else { // Everything!
            dbc = gazDB.find(query);
        }

        Type listType = new TypeToken<ArrayList<EntityFeaturePojo>>() {
        }.getType();
        List<EntityFeaturePojo> entities = new Gson().fromJson(dbc.toArray().toString(), listType);

        //Debug:
        List<String> entIds = new LinkedList<String>();

        // Loop over array and invoke the cleansing function for each one

        for (EntityFeaturePojo ent : entities) {

            if (null != ent.getAlias()) { // (some corrupt gazateer entry)

                //Debug:
                //System.out.println("entity=" + ent.getGazateerIndex());
                //System.out.println("aliases=" + Arrays.toString(ent.getAlias().toArray()));

                // Insert into the elasticsearch index

                //Debug:
                //System.out.println(new Gson().toJson(ent, GazateerPojo.class));

                // Handle groups (system group is: "4c927585d591d31d7b37097a")
                if (null == ent.getCommunityId()) {
                    ent.setCommunityId(new ObjectId("4c927585d591d31d7b37097a"));
                }

                //TEST: index documemt
                //               ent.synchronizeWithIndex();
                //               boolean b = elasticManager.addDocument(ent, ent.getGazateerIndex(), true);

                //TEST: remove document
                //b = elasticManager.removeDocument(ent.getGazateerIndex());

                //TEST: (part of get, bulk add/delete)
                entIds.add(ent.getIndex());

                // Debug:
                //               if (!b) {
                //                  System.out.println("Didn't add " + ent.getGazateerIndex());                  
                //               }               
            }

        } // End loop over entities

        //TEST: bulk delete
        //elasticManager.bulkAddDocuments(entities, "index", null);
        //elasticManager.bulkDeleteDocuments(entIds);

        //TEST: get document
        //         elasticManager.getRawClient().admin().indices().refresh(Requests.refreshRequest(indexName)).actionGet();
        //         for (String id: entIds) {
        //            Map<String, GetField> results = elasticManager.getDocument(id,"doccount", "disambiguated_name");
        //            System.out.println(id + ": " + results.get("doccount").values().get(0) + " , " + results.get("disambiguated_name").values().get(0));
        //         }

        //TEST: search
        //         elasticManager.getRawClient().admin().indices().refresh(Requests.refreshRequest(indexName)).actionGet();
        //         SearchRequestBuilder searchOptions = elasticManager.getSearchOptions();
        //         XContentQueryBuilder queryObj = QueryBuilders.matchAllQuery();
        //         searchOptions.addSort("doccount", SortOrder.DESC);
        //         searchOptions.addFields("doccount", "type");
        //         SearchResponse rsp = elasticManager.doQuery(queryObj, searchOptions);
        //         SearchHit[] docs = rsp.getHits().getHits();
        //         for (SearchHit hit: docs) {
        //            String id = hit.getId();
        //            Long doccount = (Long) hit.field("doccount").value();
        //            String type = (String) hit.field("type").value();
        //            System.out.println(id + ": " + doccount + ", " + type);
        //         }         

    } catch (NumberFormatException e) {
        e.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (MongoException e) {
        e.printStackTrace();
    } finally {

        if (null != mongoDB) {
            mongoDB.close();
        }
        if (null != elasticManager) {
            //NB not sure when exactly to call this - probably can just not bother?
            //elasticManager.getRawClient().close();
        }
    }
}

From source file:com.imaginea.mongodb.controllers.LogoutController.java

License:Apache License

/**
 * Listens to a logout reuest made by user to end his session from mViewer.
 *
 * @param dbInfo/*from  www . j  av a2  s .  com*/
 *            Mongo Db Configuration provided by user to connect to.
 * @return Logout status
 *
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public String doGet(@QueryParam("dbInfo") final String dbInfo) {
    String response = ErrorTemplate.execute(logger, new ResponseCallback() {
        public Object execute() throws Exception {
            // Not checking in logout if session has dbInfo or not
            Mongo m = LoginController.mongoConfigToInstanceMapping.get(dbInfo);
            if (m != null) {
                int noOfActiveUsers = LoginController.mongoConfigToUsersMapping.get(dbInfo);
                if (noOfActiveUsers == 0) {
                    m.close();
                    LoginController.mongoConfigToInstanceMapping.remove(dbInfo);
                } else {
                    LoginController.mongoConfigToUsersMapping.put(dbInfo, noOfActiveUsers - 1);
                }
            }
            String status = "User Logged Out";
            return status;
        }
    });
    return response;
}

From source file:com.imaginea.mongodb.requestdispatchers.UserLogout.java

License:Apache License

/**
 * Listens to a logout reuest made by user to end his session from mViewer.
 * /*from ww  w . jav  a2 s  . com*/
 * @param dbInfo
 *            Mongo Db Configuration provided by user to connect to.
 * @return Logout status
 * 
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public String doGet(@QueryParam("dbInfo") final String dbInfo) {
    String response = ErrorTemplate.execute(logger, new ResponseCallback() {
        public Object execute() throws Exception {
            // Not checking in logout if session has dbInfo or not
            Mongo m = UserLogin.mongoConfigToInstanceMapping.get(dbInfo);
            if (m != null) {
                int noOfActiveUsers = UserLogin.mongoConfigToUsersMapping.get(dbInfo);
                if (noOfActiveUsers == 0) {
                    m.close();
                    UserLogin.mongoConfigToInstanceMapping.remove(dbInfo);
                } else {
                    UserLogin.mongoConfigToUsersMapping.put(dbInfo, noOfActiveUsers - 1);
                }
            }
            String status = "User Logged Out";
            return status;
        }
    });
    return response;
}

From source file:com.liferay.mongodb.servlet.MongoServletContextListener.java

License:Open Source License

@Override
protected void doPortalDestroy() throws Exception {
    Mongo mongo = MongoDBUtil.getMongo();

    mongo.close();
}