Example usage for com.mongodb Mongo Mongo

List of usage examples for com.mongodb Mongo Mongo

Introduction

In this page you can find the example usage for com.mongodb Mongo Mongo.

Prototype

Mongo(final MongoClientURI mongoURI, @Nullable final MongoDriverInformation mongoDriverInformation) 

Source Link

Usage

From source file:org.fracturedatlas.athena.apa.impl.MongoApaAdapter.java

License:Open Source License

public MongoApaAdapter(String host, Integer port, String dbName, String fieldsCollectionName)
        throws UnknownHostException {
    this.fieldsCollectionName = fieldsCollectionName;
    Mongo m = new Mongo(host, port);
    db = m.getDB(dbName);/*from w w  w  .  j a  v a  2 s .c o  m*/
    fields = db.getCollection(fieldsCollectionName);

    initializeIndex();
}

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//from   www  .  j  a va2 s  . c  o 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//ww w. jav a2 s.  co  m
 * 
 * @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.greenmongoquery.db.service.impl.MongoServiceImpl.java

License:Open Source License

@Override
public Mongo getConnection(String host, int port, String username, String password)
        throws UnknownHostException {
    logger.info("connect to " + host + port);
    Mongo mongo = null;//from   w ww  . j  a  v  a2s  .c  o m

    mongo = new Mongo(host, port);
    DB admin = mongo.getDB("admin");
    if (username != null && username.length() > 0) {
        try {
            admin.authenticateCommand(username, password.toCharArray());
        } catch (Exception e) {
            logger.log(Level.SEVERE, "", e);
        }
    }

    return mongo;
}

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/*from w  ww .  j  a v 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.ingini.monogo.testbed.MongoManager.java

License:Apache License

private MongoManager(int port) {

    logger.debug("Starting Mongo-TestBed coordinator ...");
    try {/*  w w w.j  a  va 2s. c  o  m*/

        MongodStarter runtime = MongodStarter.getDefaultInstance();
        mongodExe = runtime.prepare(new MongodConfig(Version.V2_2_0, port, Network.localhostIsIPv6()));
        mongod = mongodExe.start();

        mongo = new Mongo(DEFAULT_HOST, DEFAULT_PORT);
        logger.debug("Mongo TestBed process {} created.", MONGODB_TESTBED_INSTANCE);
        mongoDB = mongo.getDB(MONOGO_TESTBED_DB);
        logger.debug("Mongo TestBed database {} created.", MONOGO_TESTBED_DB);
    } catch (UnknownHostException e) {
        logger.error("Unable to start mongo due to an exception!", e);
    } catch (IOException e) {
        logger.error("Unable to start mongo due to an exception!", e);
    }
}

From source file:org.ingini.monogo.testbed.MongoManager.java

License:Apache License

/**
 * Use this constructor if you want to run mongoDB via system command
 *
 * @param command//from  w w  w.  j a  va2  s  .  c om
 * @param dbpath  directory for datafiles
 */
private MongoManager(final String command, final String dbpath) {
    try {

        externalMongoThread = executorService.submit(new Runnable() { //TODO externalize into a separate class
            @Override
            public void run() {
                try {
                    ProcessBuilder processBuilder = new ProcessBuilder(command, "--port",
                            String.valueOf(DEFAULT_PORT), "--dbpath", dbpath);
                    processBuilder.directory(new File("target"));
                    processBuilder.redirectErrorStream(true);
                    process = processBuilder.start();

                    BufferedReader bufferedInputStream = new BufferedReader(
                            new InputStreamReader(process.getInputStream()));

                    String line;
                    while ((line = bufferedInputStream.readLine()) != null && !Thread.interrupted()) {
                        System.out.println("Mongo DB: " + line);
                    }

                } catch (IOException e) {
                    logger.error("Could not start external mongo process due to an exception!", e);
                }
            }
        });

        mongo = new Mongo(DEFAULT_HOST, DEFAULT_PORT);
        logger.debug("Mongo TestBed process {} created.", MONGODB_TESTBED_INSTANCE);
        mongoDB = mongo.getDB(MONOGO_TESTBED_DB);
        logger.debug("Mongo TestBed database {} created.", MONOGO_TESTBED_DB);
    } catch (IOException e) {
        logger.error("Could not start external mongo process due to an exception!", e);
    }
}

From source file:org.iternine.jeppetto.testsupport.db.MongoDatabase.java

License:Apache License

@Override
public void close() {
    if (mongoDbName == null) {
        return;//w  w w.j  ava  2  s .  c o m
    }

    try {
        Mongo mongo = new Mongo("127.0.0.1", mongoDbPort);
        DB db = mongo.getDB(mongoDbName);

        db.resetError();
        db.dropDatabase();

        DBObject err = db.getLastError();
        if (err != null && err.get("err") != null) {
            logger.error("Could not drop database {}: {}", mongoDbName, err);
        }

        mongo.dropDatabase(mongoDbName);

        if (mongo.getDatabaseNames().contains(mongoDbName)) {
            logger.error("Database {} will not go away!", mongoDbName);
        }
    } catch (UnknownHostException e) {
        // weird
    } catch (MongoException e) {
        logger.warn("Could not drop database {}: {}", mongoDbName, e.getMessage());
    }
}

From source file:org.javaee7.extra.mongo.PersonSessionBean.java

License:Open Source License

@PostConstruct
private void initDB() {
    try {/*from ww w .j  av  a 2  s. co  m*/
        // Start embedded Mongo
        MongodStarter runtime = MongodStarter.getDefaultInstance();
        mongodExe = runtime.prepare(new MongodConfigBuilder().version(Version.Main.PRODUCTION)
                .net(new Net(MONGO_PORT, Network.localhostIsIPv6())).build());
        mongod = mongodExe.start();

        // Get an instance of Mongo
        Mongo m = new Mongo("localhost", MONGO_PORT);
        DB db = m.getDB("personDB");
        personCollection = db.getCollection("persons");
        if (personCollection == null) {
            personCollection = db.createCollection("persons", null);
        }
    } catch (MongoException | IOException ex) {
        Logger.getLogger(PersonSessionBean.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.lisapark.octopus.util.json.JsonUtils.java

License:Open Source License

/**
 * Returns mongo collection using supplied properties. 
 * @param properties/*  www .ja va 2 s  .  c  o m*/
 * @return
 * @throws UnknownHostException 
 */
public DBCollection mongoCollection(Properties properties) throws UnknownHostException {
    DBCollection collection = null;

    Mongo mongoDb;

    String host = properties.getProperty(HOST);
    Integer port = getInteger(properties, PORT);
    String dbName = properties.getProperty(MONGO_DB_NAME);
    String collectionName = properties.getProperty(MONGO_COLLECTION);

    mongoDb = new Mongo(host, port);
    DB db = mongoDb.getDB(dbName);
    collection = db.getCollection(collectionName);

    return collection;
}