Example usage for com.mongodb MongoClient getDatabase

List of usage examples for com.mongodb MongoClient getDatabase

Introduction

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

Prototype

public MongoDatabase getDatabase(final String databaseName) 

Source Link

Usage

From source file:org.trade.core.persistence.local.mongo.MongoPersistence.java

License:Apache License

@Override
public byte[] loadBinaryData(String collectionName, String identifier) throws Exception {
    byte[] data = new byte[0];

    MongoClient client = new MongoClient(new MongoClientURI(this.mongoUrl));
    MongoDatabase db = client.getDatabase(this.dbName);

    Document doc = db.getCollection(collectionName).find(Filters.eq(IDENTIFIER_FIELD, identifier)).limit(1)
            .first();//w ww. j a  v a  2 s. c  o  m

    if (doc != null) {
        if (doc.containsKey(DATA_FIELD)) {
            data = ((Binary) doc.get(DATA_FIELD)).getData();
        } else {
            logger.info("Model object '{}' from model collection '{}' does not have any associated data at the "
                    + "moment.", identifier, collectionName);
        }
    } else {
        logger.info("The database does not know the specified model object '{}' from model collection '{}'",
                identifier, collectionName);
    }

    client.close();

    return data;
}

From source file:org.trade.core.persistence.local.mongo.MongoPersistence.java

License:Apache License

@Override
public void storeBinaryData(byte[] data, String collectionName, String identifier) throws Exception {
    MongoClient client = new MongoClient(new MongoClientURI(this.mongoUrl));
    MongoDatabase db = client.getDatabase(this.dbName);

    MongoCollection<Document> collection = db.getCollection(collectionName);
    Document doc = collection.find(Filters.eq(IDENTIFIER_FIELD, identifier)).limit(1).first();

    if (data == null) {
        // We assume that if the value is set to null, we should delete also the corresponding database entry
        if (doc != null) {
            collection.deleteOne(Filters.eq(IDENTIFIER_FIELD, identifier));
        }/*ww  w. j  av  a 2 s . c o m*/
    } else {
        // Check if the document already exists and update it
        if (doc != null) {
            collection.updateOne(Filters.eq(IDENTIFIER_FIELD, identifier),
                    Updates.combine(Updates.set(DATA_FIELD, data), Updates.currentDate("lastModified")));
        } else {
            Document document = new Document(IDENTIFIER_FIELD, identifier).append(DATA_FIELD, data)
                    .append("lastModified", new Date());
            collection.insertOne(document);
        }
    }

    client.close();
}

From source file:org.trade.core.persistence.local.mongo.MongoPersistence.java

License:Apache License

@Override
public void deleteBinaryData(String collectionName, String identifier) throws Exception {
    MongoClient client = new MongoClient(new MongoClientURI(this.mongoUrl));
    MongoDatabase db = client.getDatabase(this.dbName);

    Document doc = db.getCollection(collectionName).findOneAndDelete(Filters.eq(IDENTIFIER_FIELD, identifier));

    if (doc != null) {
        logger.info("Model object '{}' from model collection '{}' and its associated data successfully deleted "
                + "from DB.", identifier, collectionName);
    } else {/*ww  w  . jav  a 2 s. c o m*/
        logger.info("The database does not know the specified model object '{}' from model collection '{}'",
                identifier, collectionName);
    }

    client.close();
}

From source file:org.trade.server.IntegrationTestEnvironment.java

License:Apache License

public void destroyEnvironment() {
    // Cleanup the database
    MongoClient dataStoreClient = new MongoClient(new MongoClientURI(properties.getDataPersistenceDbUrl()));
    MongoDatabase dataStore = dataStoreClient.getDatabase(properties.getDataPersistenceDbName());
    dataStore.getCollection(ModelConstants.DATA_MODEL__DATA_COLLECTION).drop();
    dataStore.getCollection(ModelConstants.DATA_DEPENDENCY_GRAPH__DATA_COLLECTION).drop();
    dataStore.getCollection(ModelConstants.DATA_VALUE__DATA_COLLECTION).drop();

    dataStore.getCollection("dataElements").drop();
    dataStore.getCollection("dataObjects").drop();
    dataStore.getCollection("dataModels").drop();
    dataStore.getCollection("dataDependencyGraphs").drop();
    dataStore.getCollection("notifications").drop();
    dataStore.getCollection("dataValues").drop();
    dataStore.getCollection("dataElementInstances").drop();
    dataStore.getCollection("dataObjectInstances").drop();

    dataStoreClient.close();/*from  ww  w. jav a  2s .  c om*/

    // Stop the server
    try {
        server.stopHTTPServer();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.waziup.waziupmongoconsumer.MongoDBConsumer.java

/**
 * @param args the command line arguments
 *//*from   www  . j av a 2s  .c  om*/
public static void main(String[] args) {
    // TODO code application logic here
    MongoClient waziupMongo = new MongoClient();
    try {

        //Get broker properties
        InputStream brokerConfigfile = new FileInputStream(
                "./src/main/java/org/waziup/waziupmongoconsumer/smtpkafkaconsumer.properties");

        Properties brokerprops = new Properties();

        brokerprops.load(brokerConfigfile);

        KafkaConsumer consumer = new KafkaConsumer(brokerprops);

        consumer.subscribe(Arrays.asList("waziup"));

        MongoDatabase db = waziupMongo.getDatabase("waziup");

        while (true) {

            ConsumerRecords<String, String> records = consumer.poll(10);

            for (ConsumerRecord<String, String> record : records) {

                System.out.println("Temperature => " + record.value());

                db.getCollection("weather")
                        .insertOne(new Document().append("SensorID", "waziupOuaga").append("Location", "Ouaga")
                                .append("dataTime", record.value().substring(0, record.value().indexOf("=")))
                                .append("temperature",
                                        record.value().substring(record.value().indexOf("=") + 1,
                                                record.value().lastIndexOf("=")))
                                .append("humidity",
                                        record.value().substring(record.value().lastIndexOf("=") + 1)));

                System.out.println("Data inserted");

            }
        }

    } catch (IOException ex) {
        Logger.getLogger(MongoDBConsumer.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MongoException m) {
        Logger.getLogger(MongoDBConsumer.class.getName()).log(Level.SEVERE, null, m);
    }

}

From source file:Principal.ETL.ETLDAO.Mongo.java

public static void insertimage(Imagen img) {
    Document bson = null;/*w w  w . j  a v a 2  s .c  o m*/

    try {

        // To connect to mongodb server
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        bson = img.toBson();
        // Now connect to your databases
        MongoDatabase db = mongoClient.getDatabase("test");
        System.out.println("Connect to database successfully");

        MongoCollection coll = db.getCollection("imagenes");
        System.out.println("Collection mycol selected successfully");

        Document i = new Document().append("_id", bson.get("_id"));
        if (!coll.find(i).iterator().hasNext()) {
            coll.insertOne(bson);
        } else {
            coll.findOneAndReplace(i, bson);
        }

        //    FindIterable cursor = coll.find();
        //         MongoCursor x = cursor.iterator();      

    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }

}

From source file:pt.ua.cbd.cbd_project.database.MongoDatabaseConnector.java

public MongoDatabaseConnector() {
    try {/*w w w  . ja v a  2 s.  c o  m*/
        // To connect to mongodb server
        MongoClient mongoClient = new MongoClient();
        // Now connect to your databases
        this.db = mongoClient.getDatabase(this.dbName);
        logger.info("Connect to mongo database successfully");
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
}

From source file:rapture.mongodb.MongoDBFactory.java

License:Open Source License

private Mongo getMongoFromLocalConfig(String instanceName) {
    String mongoHost = MultiValueConfigLoader.getConfig("MONGODB-" + instanceName);
    log.info("Host is " + mongoHost);
    if (StringUtils.isBlank(mongoHost)) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                mongoMsgCatalog.getMessage("NoHost"));
    }/*from   w w  w .j  av  a2s  .c  o m*/
    MongoClientURI uri = new MongoClientURI(mongoHost);
    log.info("Username is " + uri.getUsername());
    log.info("Host is " + uri.getHosts().toString());
    log.info("DBName is " + uri.getDatabase());
    log.info("Collection is " + uri.getCollection());
    try {
        MongoClient mongo = new MongoClient(uri);
        mongoDBs.put(instanceName, mongo.getDB(uri.getDatabase()));
        mongoDatabases.put(instanceName, mongo.getDatabase(uri.getDatabase()));
        mongoInstances.put(instanceName, mongo);
        return mongo;
    } catch (MongoException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, new ExceptionToString(e));
    }
}

From source file:rapture.mongodb.MongoDBFactory.java

License:Open Source License

private Mongo getMongoFromSysConfig(String instanceName) {
    Map<String, ConnectionInfo> map = Kernel.getSys().getConnectionInfo(ContextFactory.getKernelUser(),
            ConnectionType.MONGODB.toString());
    if (!map.containsKey(instanceName)) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                mongoMsgCatalog.getMessage("NoInstance", instanceName));
    }//from  www .j ava2s  .  c  o  m
    ConnectionInfo info = map.get(instanceName);
    log.info("Connection info = " + info);
    try {
        MongoClient mongo = new MongoClient(new MongoClientURI(info.getUrl()));
        mongoDBs.put(instanceName, mongo.getDB(info.getDbName()));
        mongoDatabases.put(instanceName, mongo.getDatabase(info.getDbName()));
        mongoInstances.put(instanceName, mongo);
        return mongo;
    } catch (MongoException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, new ExceptionToString(e));
    }
}

From source file:result.analysis.Dbops.java

void CreateDb(String name) {

    try {/*from  w w  w. j  a  va  2s  .c  om*/

        // To connect to mongodb server
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // Now connect to your databases
        MongoDatabase db = mongoClient.getDatabase(name);//must be there where csvparser is invoked
        System.out.println("Connect to database successfully");
        MongoCollection<Document> collection = db.getCollection("test");
        Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1)
                .append("info", new Document("x", 203).append("y", 102));
        collection.insertOne(doc);

        System.out.println(collection.count());
        Document myDoc = collection.find().first();
        System.out.println(myDoc.toJson());

    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }

}