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:com.ca.apm.mongo.test.MongoReplicaSetForTestFactory.java

License:Open Source 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 www.  j a  v  a2 s  .  co  m
    // 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");
        }
        MongodStarter starter = MongodStarter.getDefaultInstance();
        MongodExecutable mongodExe = starter.prepare(mongoConfig);
        MongodProcess process = mongodExe.start();
        mongodProcessList.add(process);
    }
    Thread.sleep(1000);
    MongoClientOptions mo = MongoClientOptions.builder().autoConnectRetry(true).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:com.callidusrobotics.droptables.configuration.MongoFactory.java

License:Open Source License

private MongoClient buildClient(Environment env, String username, String password) throws UnknownHostException {
    final MongoClient mongoClient;
    if (StringUtils.isBlank(username)) {
        mongoClient = new MongoClient(new ServerAddress(host, port));
    } else {// w w w.ja v  a2s  .  c  o  m
        char[] passwordChars = password == null ? new char[0] : password.toCharArray();
        mongoClient = new MongoClient(new ServerAddress(host, port),
                Arrays.asList(MongoCredential.createCredential(username, dbName, passwordChars)));
    }

    env.lifecycle().manage(new Managed() {
        @Override
        public void start() throws Exception {
        }

        @Override
        public void stop() throws Exception {
            mongoClient.close();
        }
    });

    return mongoClient;
}

From source file:com.daprota.m2.realm.MongoDBRealm.java

License:Apache License

/**
 * Close the specified database connection.
 *
 * @param dbConn The connection to be closed
 *///  ww  w  . ja  va  2  s  .c  om
protected void close(DbConnection dbConn) {

    // Do nothing if the database connection is already closed
    if (dbConn == null)
        return;

    // Close this database connection, and log any errors
    MongoClient mongoClient = dbConn.getMongoClient();
    mongoClient.close();
    containerLog.warn("MongoDBRealm.close"); // Just log it here

}

From source file:com.dilmus.dilshad.scabi.ms.MetaServer.java

License:Open Source License

private static int createDatabasesIfAbsent(String dbHost, String dbPort) throws DScabiException {

    MongoClient mongo = new MongoClient(dbHost, Integer.parseInt(dbPort));
    MongoDatabase mongodb = mongo.getDatabase("MetaDB");
    MongoDatabase mongodb2 = mongo.getDatabase("AppTableDB");
    MongoDatabase mongodb3 = mongo.getDatabase("JavaFileDB");
    MongoDatabase mongodb4 = mongo.getDatabase("FileDB");
    log.debug("mongodb.getName() : {}", mongodb.getName());
    log.debug("mongodb2.getName() : {}", mongodb2.getName());
    log.debug("mongodb3.getName() : {}", mongodb3.getName());
    log.debug("mongodb4.getName() : {}", mongodb4.getName());

    mongo.close();
    return 0;//from w  ww  . j  av  a2s.c om
}

From source file:com.edgytech.umongo.UMongo.java

License:Apache License

void disconnect(MongoNode node) {
    mongos.remove(node);// w w w. j  av a  2s. c  o  m

    node.removeNode();
    MongoClient mongo = ((MongoNode) node).getMongoClient();
    mongo.close();

    if (mongos.size() > 0) {
        MongoNode other = mongos.get(0);
        getTree().expandNode(other);
        getTree().selectNode(other);
    } else {
        displayElement(null);
    }

}

From source file:com.ejbmongoembeddedtomcat.listener.MongoDBContextListener.java

@Override
public void contextDestroyed(ServletContextEvent sce) {
    MongoClient mongo = (MongoClient) sce.getServletContext().getAttribute("MONGO_CLIENT");
    mongo.close();
    System.out.println("MongoClient closed successfully");
}

From source file:com.epam.dlab.mongo.MongoServiceFactory.java

License:Apache License

public MongoService build(Environment environment) {
    MongoClient client = new MongoClient(new ServerAddress(host, port), Collections
            .singletonList(MongoCredential.createCredential(username, database, password.toCharArray())));
    environment.lifecycle().manage(new Managed() {
        @Override// w  ww .  j a va  2 s . c om
        public void start() {
        }

        @Override
        public void stop() {
            client.close();
        }
    });
    return new MongoService(client, database);
}

From source file:com.gatf.executor.dataprovider.MongoDBTestDataSource.java

License:Apache License

public void destroy() {
    for (Resource res : pool) {
        MongoClient mongoClient = (MongoClient) res.object;
        mongoClient.close();
    }// www  . ja  va  2  s .com
    logger.info("Releasing connections....");
}

From source file:com.gatf.executor.dataprovider.MongoDBTestDataSource.java

License:Apache License

public List<Map<String, String>> provide(GatfTestDataProvider provider, AcceptanceTestContext context) {

    List<Map<String, String>> result = new ArrayList<Map<String, String>>();

    Assert.assertNotNull("provider cannot be null", provider);
    Assert.assertTrue("provider cannot be null", provider.getArgs() != null && provider.getArgs().length > 0);
    Assert.assertNotNull("mongodb-collection cannot be empty", provider.getArgs()[0]);
    Assert.assertNotNull("queryString cannot be empty", provider.getQueryStr());
    Assert.assertNotNull("variableNames cannot be empty", provider.getSourceProperties());
    Assert.assertNotNull("propertyNames cannot be empty", provider.getProviderProperties());

    String dbName = args[2].trim();
    String collName = provider.getArgs()[0].trim();
    String queryString = provider.getQueryStr().trim();
    String variableNames = provider.getProviderProperties();
    String propertyNames = provider.getSourceProperties();

    Assert.assertNotNull("mongodb-collection cannot be empty", collName.isEmpty());
    Assert.assertFalse("queryString cannot be empty", queryString.isEmpty());

    List<String> variableNamesArr = new ArrayList<String>();
    for (String varName : variableNames.split(",")) {
        if (!varName.trim().isEmpty()) {
            variableNamesArr.add(varName);
        }//from www  .  j a va2  s  .  c o  m
    }
    Assert.assertTrue("need to define at-least a single variable name",
            !variableNames.isEmpty() && variableNames.split(",").length > 0 && variableNamesArr.size() > 0);

    List<String> propertyNamesArr = new ArrayList<String>();
    for (String varName : propertyNames.split(",")) {
        if (!varName.trim().isEmpty()) {
            propertyNamesArr.add(varName);
        }
    }
    Assert.assertTrue("need to define at-least a single property name",
            !propertyNames.isEmpty() && propertyNames.split(",").length > 0 && propertyNamesArr.size() > 0);

    Assert.assertTrue("property name and variable name sizes don't match",
            propertyNamesArr.size() == variableNamesArr.size());

    StringBuilder build = new StringBuilder();
    build.append("Provider configuration [\n");
    build.append(String.format("dataSource name is %s\n", getDataSourceName()));
    build.append(String.format("mongodb-collection is %s\n", collName));
    build.append(String.format("queryString is %s\n", queryString));
    build.append(String.format("propertyNames is %s\n", propertyNames));
    build.append(String.format("variableNames is %s]", variableNames));
    logger.info(build.toString());

    Resource res = null;
    try {

        res = getResource();
        MongoClient mongoClient = (MongoClient) res.object;

        DB db = null;
        try {
            db = mongoClient.getDB(dbName);

            DBCollection coll = db.getCollection(collName);
            Assert.assertNotNull(String.format("Mongodb collection %s not found", collName), coll);

            DBObject queryObject = null;
            try {
                queryObject = (DBObject) JSON.parse(queryString);
            } catch (Exception e) {
                Assert.assertNotNull("queryString passed is invalid");
            }

            DBCursor cursor = null;
            try {
                cursor = coll.find(queryObject);
                while (cursor.hasNext()) {
                    DBObject object = cursor.next();
                    Map<String, String> row = new HashMap<String, String>();
                    for (int i = 0; i < variableNamesArr.size(); i++) {
                        Assert.assertTrue(
                                String.format("Could not find %s field in the result document returned",
                                        propertyNamesArr.get(i)),
                                object.containsField(propertyNamesArr.get(i)));
                        row.put(variableNamesArr.get(i), object.get(propertyNamesArr.get(i)).toString());
                    }
                    result.add(row);
                }
            } catch (Exception e) {
                throw new AssertionError(e);
            } finally {
                if (cursor != null)
                    cursor.close();
            }
        } catch (Exception e) {
            throw new AssertionError(
                    String.format("Fetching Test Data failed while executing query %s with the error %s",
                            queryString, ExceptionUtils.getStackTrace(e)));
        } finally {
            if (mongoClient != null)
                mongoClient.close();
        }
    } catch (Exception e) {
        throw new AssertionError(
                String.format("Fetching Test Data failed while executing query %s with the error %s",
                        queryString, ExceptionUtils.getStackTrace(e)));
    } finally {
        if (res != null)
            releaseToPool(res);
    }
    return result;
}

From source file:com.groupon.jenkins.mongo.MongoRepository.java

License:Open Source License

protected void save(DBObject doc) {
    MongoClient client = getClient();
    try {//from  w w  w  . ja  v  a  2s.  c om
        getCollection(client).insert(doc);
    } finally {
        client.close();
    }
}