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:org.eclipse.emf.cdo.server.internal.mongodb.MongoDBStoreFactory.java

License:Open Source License

protected void dropDatabase(MongoURI mongoURI, String dbName) {
    Mongo mongo = null;

    try {//  w  ww . j a v  a 2  s  .c  o m
        mongo = new Mongo(mongoURI);
        DB db = mongo.getDB(dbName);
        db.dropDatabase();
    } catch (Exception ex) {
        throw WrappedException.wrap(ex);
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}

From source file:org.eclipse.emf.cdo.tests.mongodb.MongoDBConfig.java

License:Open Source License

protected void dropDatabase(MongoURI mongoURI, String repoName) {
    Mongo mongo = null;

    try {/*from w w w . j a  va 2  s.c o  m*/
        mongo = new Mongo(mongoURI);
        DB db = mongo.getDB(repoName);
        if (!db.getCollectionNames().isEmpty()) {
            db.dropDatabase();
        }
    } catch (Exception ex) {
        throw WrappedException.wrap(ex);
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}

From source file:org.elasticsearch.river.mongodb.RiverMongoDBTestAbstract.java

License:Apache License

private void initMongoInstances(ExecutableType type) throws Exception {
    logger.debug("*** initMongoInstances(" + type + ") ***");
    CommandResult cr;//from   w ww  .  j av a2  s .c om
    Settings rsSettings = settings.getByPrefix(type.configKey + '.');
    int[] ports;
    if (rsSettings.getAsBoolean("useDynamicPorts", false)) {
        ports = new int[] { Network.getFreeServerPort(), Network.getFreeServerPort(),
                Network.getFreeServerPort() };
    } else {
        int start = 37017 + 10 * type.ordinal();
        ports = new int[] { start, start + 1, start + 2 };
    }
    String replicaSetName = "es-test-" + type.configKey;
    // Create 3 mongod processes
    Starter<IMongodConfig, MongodExecutable, MongodProcess> starter = type.newStarter();
    ImmutableList.Builder<MongoReplicaSet.Member> builder = ImmutableList.builder();
    for (int i = 1; i <= 3; ++i) {
        Storage storage = new Storage("target/" + replicaSetName + '/' + i, replicaSetName, 20);
        MongoReplicaSet.Member member = new MongoReplicaSet.Member();
        member.config = new MongodConfigBuilder()
                .version(Versions.withFeatures(new GenericVersion(rsSettings.get("version"))))
                .net(new de.flapdoodle.embed.mongo.config.Net(ports[i - 1], Network.localhostIsIPv6()))
                .replication(storage).build();
        logger.trace("replSetName in config: {}", member.config.replication().getReplSetName());
        member.executable = starter.prepare(member.config);
        member.process = member.executable.start();
        member.address = new ServerAddress(Network.getLocalHost().getHostName(), member.config.net().getPort());
        logger.debug("Server #" + i + ": {}", member.address);
        builder.add(member);
    }
    ImmutableList<MongoReplicaSet.Member> members = builder.build();
    Thread.sleep(2000);
    MongoClientOptions mco = MongoClientOptions.builder().autoConnectRetry(true).connectTimeout(15000)
            .socketTimeout(60000).build();
    Mongo mongo = new MongoClient(new ServerAddress(Network.getLocalHost().getHostName(), ports[0]), mco);
    DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME);

    cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1));
    logger.debug("isMaster: " + cr);

    // Initialize replica set
    cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate",
            (DBObject) JSON.parse("{'_id': '" + replicaSetName + "', 'members': [" + "{'_id': 0, 'host': '"
                    + members.get(0).address.getHost() + ':' + members.get(0).address.getPort() + "'}, "
                    + "{'_id': 1, 'host': '" + members.get(1).address.getHost() + ':'
                    + members.get(1).address.getPort() + "'}, " + "{'_id': 2, 'host': '"
                    + members.get(2).address.getHost() + ':' + members.get(2).address.getPort()
                    + "', 'arbiterOnly' : true}]} }")));
    logger.debug("replSetInitiate result: " + cr);

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

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

    mongo.close();
    mongo = null;

    // Initialize a new client using all instances.
    List<ServerAddress> mongoServers = new ArrayList<ServerAddress>();
    for (MongoReplicaSet.Member member : members) {
        mongoServers.add(member.address);
    }
    mongo = new MongoClient(mongoServers, mco);
    Assert.assertNotNull(mongo);
    mongo.setReadPreference(ReadPreference.secondaryPreferred());
    mongo.setWriteConcern(WriteConcern.REPLICAS_SAFE);
    replicaSets.put(type, new MongoReplicaSet(type, rsSettings.get("version"), mongo, mongoAdminDB, members));
}

From source file:org.geotools.data.mongodb.MongoDataStore.java

License:LGPL

/**
 * Get list of valid layers for this mongo DB; those containing at least one valid, non-null
 * GeoJSON geometry// w  w  w.j  a  v a  2s . co m
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private void getLayers() {
    Mongo mongo = null;
    try {
        // Get the list of collections from Mongo...
        mongo = new Mongo(config.getHost(), config.getPort());
        DB db = mongo.getDB(config.getDB()); // TODO add authentication
        Set<String> colls = db.getCollectionNames();
        for (String s : colls) {
            DBCollection dbc = db.getCollection(s);
            log.info("getLayers; collection=" + dbc);
            // find distinct non-null geometry to determine if valid layer
            // TODO branch point for separate geometry-specific layers per collection
            List geoList = dbc.distinct("geometry.type");
            // distinct returns single BSON List, may barf if results large, > max doc. size
            // trap exception on props distinct and assume it's valid since there's obviously
            // something there (http://www.mongodb.org/display/DOCS/Aggregation)
            List propList = null;
            try {
                propList = dbc.distinct("properties");
            } catch (IllegalArgumentException ex) {
                propList = new BasicBSONList();
                propList.add("ex nihilo");
            } catch (MongoException ex) {
                propList = new BasicBSONList();
                propList.add("ex nihilo");
            }
            // check that layer has valid geometry and some properties defined
            if (geoList != null && propList != null && propList.size() > 0) {
                boolean hasValidGeo = false;
                for (GeometryType type : GeometryType.values()) {
                    if (geoList.contains(type.toString())) {
                        hasValidGeo = true;
                        break;
                    }
                }
                if (hasValidGeo) {
                    layers.add(new MongoLayer(dbc, config));
                }
            }
        }
    } catch (Throwable t) {
        log.severe("getLayers error; " + t.getLocalizedMessage());
    }
    if (mongo != null) {
        mongo.close();
    }
}

From source file:org.geotools.data.mongodb.MongoResultSet.java

License:LGPL

/**
 * Build features for given layer; convert mongo collection records to equivalent geoTools
 * SimpleFeatureBuilder// w  w w .  j a  v a2s  . c  om
 * 
 * @param query mongoDB query (empty to find all)
 */
private void buildFeatures(BasicDBObject query) {
    if (layer == null) {
        log.warning("buildFeatures called, but layer is null");
        return;
    }
    Mongo mongo = null;
    try {
        if (layer.getGeometryType() == null) {
            return;
        }
        mongo = new Mongo(layer.getConfig().getHost(), layer.getConfig().getPort());
        DB db = mongo.getDB(layer.getConfig().getDB());
        DBCollection coll = db.getCollection(layer.getName());
        DBCursor cur = coll.find(query);
        minX = 180;
        maxX = -180;
        minY = 90;
        maxY = -90;
        SimpleFeatureBuilder fb = new SimpleFeatureBuilder(layer.getSchema());
        // use SimpleFeatureBuilder.set(name, value) rather than add(value) since
        // attributes not in guaranteed order
        log.finer("cur.count()=" + cur.count());

        while (cur.hasNext()) {
            DBObject dbo = cur.next();
            if (dbo == null) {
                continue;
            }

            // get mongo id and ensure valid
            if (dbo.get("_id") instanceof ObjectId) {
                ObjectId oid = (ObjectId) dbo.get("_id");
                fb.set("_id", oid.toString());
            } else if (dbo.get("_id") instanceof String) {
                fb.set("_id", dbo.get("_id"));
            } else {
                throw new MongoPluginException("_id is invalid type: " + dbo.get("_id").getClass());
            }

            // ensure geometry defined
            DBObject geo = (DBObject) dbo.get("geometry");
            if (geo == null || geo.get("type") == null
                    || (geo.get("coordinates") == null && geo.get("geometries") == null)) {
                continue;
            }

            // GeometryType of current record
            GeometryType recordGeoType = GeometryType.valueOf((String) geo.get("type"));
            // skip record if its geo type does not match layer geo type
            if (!layer.getGeometryType().equals(recordGeoType)) {
                continue;
            }

            // create Geometry for given type
            Geometry recordGeometry = createGeometry(recordGeoType, geo);
            if (recordGeometry != null) {
                fb.set("geometry", recordGeometry);
                // set non-geometry properties for feature (GeoJSON.properties)
                DBObject props = (DBObject) dbo.get("properties");
                setProperties(fb, "properties", props);
                features.add(fb.buildFeature(null));
                bounds = new ReferencedEnvelope(minX, maxX, minY, maxY, layer.getCRS());
            } else {
                fb.reset();
            }
        }
    } catch (Throwable t) {
        log.severe("Error building layer " + layer.getName() + "; " + t.getLocalizedMessage());
    }
    if (mongo != null) {
        mongo.close();
    }
}

From source file:org.helios.dashkuj.core.Dashkuj.java

License:Open Source License

/**
 * Synchronizes the api keys from mongoDB to redis for cases when redis loses them
 * @param redisHost The redis host/*  www.  j av  a  2  s .  c o  m*/
 * @param redisPort The redis port
 * @param mongoHost The mongodb host
 * @param mongoPort The mongodb port
 * FIXME:  Need to support credentials
 */
public void synchRedisApiKeys(String redisHost, int redisPort, String mongoHost, int mongoPort) {
    Mongo mongo = null;
    DBCursor cursor = null;
    Jedis jedis = null;
    try {
        mongo = new Mongo(mongoHost, mongoPort);
        jedis = new Jedis(redisHost, redisPort);
        log.info("Synchronizing APIKeys between mongo [{}:{}] and redis [{}:{}]", mongoHost, mongoPort,
                redisHost, redisPort);
        Map<String, String> apiKeys = jedis.hgetAll("apiKeys");
        DB db = mongo.getDB("dashku_development");
        DBCollection dbColl = db.getCollection("users");
        cursor = dbColl.find();
        while (cursor.hasNext()) {
            DBObject dbo = cursor.next();
            String apiKey = dbo.get("apiKey").toString();
            String id = dbo.get("_id").toString();
            String user = dbo.get("username").toString();
            log.debug("Inspecting user [" + user + "]");
            if (!apiKeys.containsKey(apiKey)) {
                jedis.hmset("apiKeys", Collections.singletonMap(apiKey, id));
                log.info("Added missing redis entry [" + apiKey + "] for user [" + user + "]");
            }
        }
        log.info("Redis Synch Complete");
    } catch (Exception ex) {
        log.error("Redis Synch Failed", ex);
        throw new RuntimeException("Redis Synch Failed", ex);
    } finally {
        if (cursor != null)
            try {
                cursor.close();
            } catch (Exception e) {
            }
        if (mongo != null)
            try {
                mongo.close();
            } catch (Exception e) {
            }
        if (jedis != null)
            try {
                jedis.disconnect();
            } catch (Exception e) {
            }
    }
}

From source file:org.helios.dashkuj.domain.Dashboard.java

License:Open Source License

public static void main(String[] args) {
    Jedis jedis = null;//from  w  w w . ja  v  a  2 s. com
    Mongo mongo = null;
    DBCursor cursor = null;
    Morphia morphia = null;
    Datastore mongoDs = null;
    try {
        jedis = new Jedis("dashku");
        Map<String, String> apiKeys = jedis.hgetAll("apiKeys");
        log(apiKeys);
        mongo = new Mongo("dashku");
        morphia = new Morphia();
        mongoDs = morphia.createDatastore(mongo, "dashku_development");
        DB db = mongo.getDB("dashku_development");
        DBCollection dbColl = db.getCollection("users");
        cursor = dbColl.find();
        while (cursor.hasNext()) {
            DBObject dbo = cursor.next();
            String apiKey = dbo.get("apiKey").toString();
            String id = dbo.get("_id").toString();
            String user = dbo.get("username").toString();
            log("Inspecting user [" + user + "]");
            if (!apiKeys.containsKey(apiKey)) {
                jedis.hmset("apiKeys", Collections.singletonMap(apiKey, id));
                log("Added missing redis entry [" + apiKey + "] for user [" + user + "]");
            }
        }
        cursor.close();

        //         CommandResult cr = db.command("serverStatus");
        //         Date date = cr.getDate("localTime");
        //         
        //         JsonElement je = new JsonParser().parse(cr.toString());
        //         String jsDate = je.getAsJsonObject().get("localTime").getAsJsonObject().getAsJsonPrimitive("$date").toString();
        //         //log(GsonFactory.getInstance().printer().toJson(je));
        //         log("Date:[" + date + "]");
        //         log("JS-Date:[" + jsDate + "]");
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    } finally {
        if (jedis != null)
            try {
                jedis.disconnect();
            } catch (Exception ex) {
            }
        if (cursor != null)
            try {
                cursor.close();
            } catch (Exception ex) {
            }
        if (mongo != null)
            try {
                mongo.close();
            } catch (Exception ex) {
            }
    }
}

From source file:org.ossmeter.platform.admin.FullMetricAnalysis.java

License:Open Source License

@Get("json")
public String represent() {
    Series<Header> responseHeaders = (Series<Header>) getResponse().getAttributes()
            .get("org.restlet.http.headers");
    if (responseHeaders == null) {
        responseHeaders = new Series(Header.class);
        getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
    }/*from  w w w  .  j  a v a2  s.  com*/
    responseHeaders.add(new Header("Access-Control-Allow-Origin", "*"));
    responseHeaders.add(new Header("Access-Control-Allow-Methods", "GET"));

    try {
        String metricId = (String) getRequest().getAttributes().get("metricId");

        Mongo mongo = Configuration.getInstance().getMongoConnection();

        DB db = mongo.getDB("ossmeter");
        DBCollection col = db.getCollection("metricAnalysis");

        BasicDBObject query = new BasicDBObject("metricId", metricId);

        BasicDBObject sort = new BasicDBObject("analysisDate", 1);

        DBCursor cursor = col.find(query).sort(sort);

        ObjectMapper mapper = new ObjectMapper();
        ArrayNode results = mapper.createArrayNode();

        while (cursor.hasNext()) {
            DBObject obj = cursor.next();

            if ("true".equals(getQueryValue("incDate"))) {
                ObjectNode on = mapper.createObjectNode();
                on.put("date", obj.get("analysisDate").toString());
                on.put("millis", (Double) obj.get("millisTaken"));
                results.add(on);
            } else {
                results.add((Double) obj.get("millisTaken"));
            }
        }

        mongo.close();

        return results.toString();

    } catch (UnknownHostException e1) {
        e1.printStackTrace();
    }

    return null;
}

From source file:org.ossmeter.platform.admin.LoggingInformation.java

License:Open Source License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Get("json")// w  ww .  j  a  v  a2  s . c  o  m
public String represent() {
    @SuppressWarnings("unchecked")
    Series<Header> responseHeaders = (Series<Header>) getResponse().getAttributes()
            .get("org.restlet.http.headers");
    if (responseHeaders == null) {
        responseHeaders = new Series(Header.class);
        getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
    }
    responseHeaders.add(new Header("Access-Control-Allow-Origin", "*"));
    responseHeaders.add(new Header("Access-Control-Allow-Methods", "GET"));

    try {
        Mongo mongo = new Mongo();

        DB db = mongo.getDB("logging");
        DBCollection col = db.getCollection("log");

        ObjectMapper mapper = new ObjectMapper();
        ArrayNode results = mapper.createArrayNode();

        DBCursor cursor = col.find();
        try {
            while (cursor.hasNext()) {
                DBObject p = cursor.next();
                p.removeField("_id");
                p.removeField("thread");
                p.removeField("host");
                p.removeField("class");
                results.add(mapper.readTree(p.toString()));
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            cursor.close();
        }

        mongo.close();

        return results.toString();

    } catch (UnknownHostException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    return null;
}

From source file:org.ossmeter.platform.admin.MetricListAnalysis.java

License:Open Source License

@Get("json")
public String represent() {
    Series<Header> responseHeaders = (Series<Header>) getResponse().getAttributes()
            .get("org.restlet.http.headers");
    if (responseHeaders == null) {
        responseHeaders = new Series(Header.class);
        getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
    }/*  ww  w . ja  v  a 2  s .c  o  m*/
    responseHeaders.add(new Header("Access-Control-Allow-Origin", "*"));
    responseHeaders.add(new Header("Access-Control-Allow-Methods", "GET"));

    try {
        Mongo mongo = Configuration.getInstance().getMongoConnection();

        DB db = mongo.getDB("ossmeter");
        DBCollection col = db.getCollection("metricAnalysis");

        ObjectMapper mapper = new ObjectMapper();
        ArrayNode results = mapper.createArrayNode();

        for (Object p : col.distinct("metricId")) {
            results.add(p.toString());
        }

        mongo.close();

        return results.toString();

    } catch (UnknownHostException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    return null;
}