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:net.bunselmeyer.mongo.maven.plugin.MigrateMojo.java

License:Apache License

private void runMigrations(List<MigrationDetails> migrations) {
    if (migrations.isEmpty()) {
        return;/* w ww  .  j ava 2s .  co m*/
    }

    MigrationDetails migrationDetails = migrations.get(0);

    Mongo mongo;
    try {
        mongo = new Mongo(migrationDetails.host, Integer.parseInt(port));
    } catch (UnknownHostException e) {
        getLog().error("Failed to connect to " + migrationDetails.host + ":" + port);
        return;
    } catch (NumberFormatException e) {
        getLog().error("Invalid port: " + port);
        return;
    }

    mongo.setWriteConcern(WriteConcern.SAFE);

    DB db = mongo.getDB(migrationDetails.db);

    JacksonDBCollection<MigrationVersionDetails, ObjectId> migrationVersionCollection = createMigrationVersionCollection(
            db);

    getLog().info("Running migrations. Host: " + migrationDetails.host + ". DB: " + migrationDetails.db);

    sortMigrationDetails(migrations);

    Class<? extends Migration> lastMigration = null;
    try {
        for (MigrationDetails details : migrations) {
            lastMigration = details.migration;
            Migration m = details.migration.newInstance();

            MigrationVersionDetails versionDetails = new MigrationVersionDetails();
            versionDetails.setMigrationName(details.migration.getName());
            versionDetails.setVersion(details.version);

            if (migrationVersionCollection.getCount(versionDetails) == 0) {
                m.up(db);
                db.getLastError().throwOnError();
                getLog().info(
                        "    " + details.migration.getName() + ", v" + details.version + " migration complete");
                versionDetails.setRun(DateTime.now(DateTimeZone.UTC));
                migrationVersionCollection.insert(versionDetails);
            } else {
                getLog().info(
                        "    " + details.migration.getName() + ", v" + details.version + " was already run");
            }
        }
    } catch (Exception e) {
        String name = lastMigration != null ? lastMigration.getName() : "";
        getLog().info("    FAIL! " + name + " migration error", e);
    } finally {
        mongo.close();
    }
}

From source file:net.cit.tetrad.resource.ManagementResource.java

License:Open Source License

/**
 * mongos?  ?   ??  //  ww w  .  jav  a  2 s  . c  o m
 * @param request
 * @param response
 * @throws Exception
 */
@RequestMapping("/mongosResearch.do")
public void mongosResearch(HttpServletRequest request, HttpServletResponse response, CommonDto commDto)
        throws Exception {
    String authUser = Utility.isNull(commDto.getAuthUser());
    String authPasswd = Utility.isNull(commDto.getAuthPasswd());
    String tempIp = Utility.isNull(commDto.getIp());
    boolean loopbackCheck = commDto.isLoopbackCheck();

    boolean authCheck = false;
    Mongo mongo = null;
    List<Map<String, Object>> resultLst = new ArrayList<Map<String, Object>>();
    boolean auth = false;
    DB db;
    try {
        PersonJson result = new PersonJson();
        if (authUser != "" && authPasswd != "")
            authCheck = true;
        List<Object> readMongoShards = new ArrayList<Object>();
        List<Object> readMongos = new ArrayList<Object>();
        Object readConfigDb = null;
        mongo = new Mongo(commDto.getIp(), Integer.parseInt(commDto.getPort()));
        if (authCheck) {
            db = mongo.getDB("admin");
            auth = db.authenticate(authUser, authPasswd.toCharArray());
        }
        readMongos = mongoStatusToMonitor.readMongoShards(mongo, "mongos", "config");
        readMongoShards = mongoStatusToMonitor.readMongoShards(mongo, "shards", "config");

        readConfigDb = mongoStatusToMonitor.readMongoStatus(mongo, new Device(), "getCmdLineOpts")
                .get("parsed_configdb");
        mongo.close();

        //mongos
        int mongoIdNum = 0;
        for (Object mongosObj : readMongos) {
            mongoIdNum++;
            Map<String, Object> statusMap = (Map<String, Object>) mongosObj;
            String[] splitName = ((String) statusMap.get("_id")).split(":");

            boolean isExistCheck = false;
            if (isExistDeviceIpPort(splitName[0], splitName[1]) != null)
                isExistCheck = true;
            statusMap.put("isExistCheck", isExistCheck);
            statusMap.put("ipStr", splitName[0]);
            statusMap.put("portStr", splitName[1]);
            statusMap.put("groupNameStr", "mongos_grp");
            statusMap.put("uidStr", "mongos" + "_" + mongoIdNum + "_" + splitName[1]);
            statusMap.put("typeStr", "mongos");

            resultLst.add(statusMap);
        }

        // mongod
        for (Object shardObj : readMongoShards) {
            Map<String, Object> shardMap = (Map<String, Object>) shardObj;
            String[] host = ((String) shardMap.get("host")).split("/");
            String[] hostLst = host[1].split(",");
            String[] ipPortSplit = hostLst[0].split(":");

            if (ipPortSplit[0].equals("127.0.0.1") || ipPortSplit[0].equals("localhost")) {
                ipPortSplit[0] = tempIp;
            }

            mongo = new Mongo(ipPortSplit[0], Integer.parseInt(ipPortSplit[1]));
            if (authCheck) {
                db = mongo.getDB("admin");
                auth = db.authenticate(authUser, authPasswd.toCharArray());
            }
            Map<String, Object> readMongoStatus = mongoStatusToMonitor.readMongoStatus(mongo, new Device(),
                    "replSetGetStatus");
            mongoIdNum = 0;
            for (Object status : (List<Object>) readMongoStatus.get("members")) {
                mongoIdNum++;
                Map<String, Object> statusMap = (Map<String, Object>) status;

                String[] splitName = ((String) statusMap.get("name")).split(":");

                if (loopbackCheck == true
                        && (splitName[0].equals("127.0.0.1") || splitName[0].equals("localhost"))) {
                    splitName[0] = tempIp;
                }

                boolean isExistCheck = false;
                if (isExistDeviceIpPort(splitName[0], splitName[1]) != null)
                    isExistCheck = true;
                statusMap.put("isExistCheck", isExistCheck);
                statusMap.put("ipStr", splitName[0]);
                statusMap.put("portStr", splitName[1]);
                statusMap.put("groupNameStr", readMongoStatus.get("set"));
                statusMap.put("uidStr",
                        readMongoStatus.get("set") + "_" + mongoIdNum + "_" + statusMap.get("stateStr"));
                statusMap.put("typeStr", "mongod");

                resultLst.add(statusMap);
            }
            mongo.close();
        }

        //config
        mongoIdNum = 0;
        for (String configStr : ((String) readConfigDb).split(",")) {
            mongoIdNum++;
            Map<String, Object> statusMap = new HashMap<String, Object>();

            String[] splitName = configStr.split(":");

            if (loopbackCheck == true
                    && (splitName[0].equals("127.0.0.1") || splitName[0].equals("localhost"))) {
                splitName[0] = tempIp;
            }

            boolean isExistCheck = false;
            if (isExistDeviceIpPort(splitName[0], splitName[1]) != null)
                isExistCheck = true;
            statusMap.put("isExistCheck", isExistCheck);
            statusMap.put("ipStr", splitName[0]);
            statusMap.put("portStr", splitName[1]);
            statusMap.put("groupNameStr", "config_grp");
            statusMap.put("uidStr", "config" + "_" + mongoIdNum + "_" + splitName[1]);
            statusMap.put("typeStr", "config");

            resultLst.add(statusMap);
        }

        result.setAaData(resultLst);
        JSONObject jsonObject = JSONObject.fromObject(result);

        Writer writer = setResponse(response).getWriter();
        writer.write(jsonObject.toString());

        writer.flush();
    } catch (Exception e) {
        e.printStackTrace();
        mongo.close();
    }
    log.debug("end - mongosResearch()");
}

From source file:net.sf.okapi.lib.tmdb.mongodb.Repository.java

License:Open Source License

/**
 * Helper method to delete existing repository
 * @param repoName// w  ww  .ja  va2  s  .c om
 */
static public void delete(String repoName) {
    try {
        Mongo mDel = new Mongo();
        mDel.dropDatabase(repoName);
        mDel.close();
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    } catch (MongoException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.felix.useradmin.mongodb.MongoDB.java

License:Apache License

/**
 * Disconnects from the MongoDB.//  w  ww .  jav a  2  s.  c  o  m
 */
public void disconnect() {
    Mongo mongo = m_mongoRef.get();
    if (mongo != null) {
        try {
            mongo.close();
        } finally {
            m_mongoRef.compareAndSet(mongo, null);
        }
    }
}

From source file:org.apache.hadoop.contrib.mongoreduce.MongoInputFormat.java

License:Apache License

public static String[] hostsForShard(String shardName, boolean primaryOk)
        throws UnknownHostException, MongoException {

    ArrayList<String> hosts = new ArrayList<String>();

    String[] parts = shardName.split("/");
    if (parts.length == 1) { // no replicas
        hosts.add(shardName);/*from   w  w w .  j  a v a2s.  c o  m*/
    } else { // replicas

        // get first or only host listed
        String host = parts[1].split(",")[0];
        Mongo h = new Mongo(host);
        List<ServerAddress> addresses = h.getServerAddressList();
        h.close();
        h = null;

        // only one node in replica set ... - use it
        if (addresses.size() == 1) {
            ServerAddress addr = addresses.get(0);
            hosts.add(addr.getHost() + ":" + Integer.toString(addr.getPort()));
        }

        else {
            for (ServerAddress addr : addresses) {

                // use secondaries and primaries
                if (primaryOk) {
                    hosts.add(addr.getHost() + ":" + Integer.toString(addr.getPort()));
                }

                // only use secondaries
                else {
                    String haddr = addr.getHost() + ":" + Integer.toString(addr.getPort());
                    h = new Mongo(haddr);
                    if (!(Boolean) h.getDB(h.getDatabaseNames().get(0)).command(cmd).get("ismaster")) {
                        hosts.add(haddr);
                    }
                }
            }
        }
    }

    return hosts.toArray(new String[0]);
}

From source file:org.apache.jackrabbit.oak.upgrade.cli.container.MongoNodeStoreContainer.java

License:Apache License

private static boolean testMongoAvailability() {
    Mongo mongo = null;
    try {/*  w w  w.j a v  a2s.  c  om*/
        MongoClientURI uri = new MongoClientURI(MONGO_URI + "?connectTimeoutMS=3000");
        mongo = new MongoClient(uri);
        mongo.getDatabaseNames();
        return true;
    } catch (Exception e) {
        return false;
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}

From source file:org.ardverk.gibson.transport.MongoTransport.java

License:Apache License

private void destroy(Mongo mongo) {
    try {
        close();
    } finally {
        mongo.close();
    }
}

From source file:org.broad.igv.plugin.mongocollab.MongoCollabPlugin.java

License:Open Source License

static void closeMongo(String host, int port) {
    String key = createConnString(host, port);
    Mongo connection = connections.get(key);
    if (connection != null) {
        log.info("Closing connection to MongoDB host=" + host + " port=" + port);
        connection.close();
        connections.remove(key);//w  w  w  .j a  va  2 s  . co m
    }
}

From source file:org.eclipse.birt.data.oda.mongodb.impl.MongoDBDriver.java

License:Open Source License

public static void close() {
    synchronized (MongoDBDriver.class) {
        if (sm_mongoServerNodes == null)
            return;

        for (Mongo node : sm_mongoServerNodes.values()) {
            node.close();
        }/* w w w .  j  a va2s  . com*/
        sm_mongoServerNodes.clear();
        sm_mongoServerNodes = null;
    }
}

From source file:org.eclipse.birt.data.oda.mongodb.impl.MongoDBDriver.java

License:Open Source License

private static Mongo getMongoNodeInstance(ServerNodeKey serverNodeKey) throws OdaException {
    // first check if a cached node already exists and reuse
    Mongo mongoNode = getMongoServerNodes().get(serverNodeKey);
    if (mongoNode != null)
        return mongoNode;

    // now try get mongo node based on server host/port and supported options
    mongoNode = createMongoNode(serverNodeKey);
    Mongo existingNode = getMongoServerNodes().putIfAbsent(serverNodeKey, mongoNode); // cache the new mongo server node

    if (existingNode == null) // the new one got in
        return mongoNode;

    // there was a race, and the new node lost;
    // close the new node, and return the existing one
    mongoNode.close();
    return existingNode;
}