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:de.dfki.mmf.examples.craft_task_example.MongoDBWorldDescription.java

License:Open Source License

public MongoDatabase clearDatabase(String dbName) {
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(dbName);
    MongoIterable<String> collectionNames = db.listCollectionNames();
    for (String name : collectionNames) {
        db.getCollection(name).drop();/*from  w ww . ja v  a 2 s  .  c o m*/
    }
    return db;
}

From source file:de.dfki.mmf.examples.messy_workingplace_example.MongoDBWorldDescription.java

License:Open Source License

public MongoDatabase createUserStudyDatabase() {
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("userstudydb");
    db.getCollection("Person").insertOne(new Document("worldObjectId", "Person1")
            .append("worldobjecttype", "Person").append("name", "Magdalena"));
    db.getCollection("Person")
            .insertOne(new Document("worldObjectId", "Person2").append("worldobjecttype", "Person"));
    db.getCollection("User").insertOne(new Document("worldObjectId", "User1").append("worldobjecttype", "User")
            .append("name", "Magdalena"));
    db.getCollection("User")
            .insertOne(new Document("worldObjectId", "User2").append("worldobjecttype", "User")
                    .append("position", new Document().append("xPosition", "0.8").append("yPosition", "0.0")
                            .append("zPosition", "0.13")));
    db.getCollection("Robot")
            .insertOne(new Document("worldObjectId", "Robot1")
                    .append("worldobjecttype", "Robot").append("position", new Document()
                            .append("xPosition", "0.0").append("yPosition", "0.0").append("zPosition", "0.0"))
                    .append("name", "Nao"));
    db.getCollection("Scissors")
            .insertOne(new Document("worldObjectId", "Scissors1").append("worldobjecttype", "Scissors")
                    .append("color", "black").append("size", "big")
                    .append("position", new Document().append("xPosition", "0.27").append("yPosition", "-0.85")
                            .append("zPosition", "-0.15")));
    db.getCollection("Scissors")
            .insertOne(new Document("worldObjectId", "Scissors2").append("worldobjecttype", "Scissors")
                    .append("color", "blue and red").append("size", "small")
                    .append("position", new Document().append("xPosition", "0.6").append("yPosition", "-0.55")
                            .append("zPosition", "-0.15")));
    db.getCollection("Pen")
            .insertOne(new Document("worldObjectId", "MarkerPen1").append("worldobjecttype", "MarkerPen")
                    .append("color", "pink").append("size", "big").append("label", "Rex Textmarker")
                    .append("position", new Document().append("xPosition", "0.68").append("yPosition", "-0.3")
                            .append("zPosition", "-0.12")));
    db.getCollection("Pen")
            .insertOne(new Document("worldObjectId", "MarkerPen2").append("worldobjecttype", "MarkerPen")
                    .append("color", "yellow").append("size", "big").append("label", "Stabilo")
                    .append("position", new Document().append("xPosition", "0.39").append("yPosition", "-0.32")
                            .append("zPosition", "-0.12")));
    db.getCollection("Pen")
            .insertOne(new Document("worldObjectId", "MarkerPen3").append("worldobjecttype", "MarkerPen")
                    .append("color", "pink").append("size", "small").append("label", "Stabilo")
                    .append("position", new Document().append("xPosition", "0.39").append("yPosition", "0.26")
                            .append("zPosition", "-0.22")));
    db.getCollection("Pen")
            .insertOne(new Document("worldObjectId", "MarkerPen4").append("worldobjecttype", "MarkerPen")
                    .append("color", "green").append("size", "small")
                    .append("position", new Document().append("xPosition", "0.5").append("yPosition", "-0.61")
                            .append("zPosition", "-0.15")));
    db.getCollection("Pen")
            .insertOne(new Document("worldObjectId", "MarkerPen5").append("worldobjecttype", "MarkerPen")
                    .append("color", "yellow").append("size", "big").append("label", "Pelikan"));
    db.getCollection("Pen").insertOne(new Document("worldObjectId", "MarkerPen6")
            .append("worldobjecttype", "MarkerPen").append("color", "orange").append("size", "big"));
    db.getCollection("Pen").insertOne(new Document("worldObjectId", "MarkerPen7")
            .append("worldobjecttype", "MarkerPen").append("color", "pink").append("size", "big"));
    db.getCollection("Pen")
            .insertOne(new Document("worldObjectId", "ColoredPencil1")
                    .append("worldobjecttype", "ColoredPencil").append("color", "purple")
                    .append("size", "small").append("position", new Document().append("xPosition", "0.36")
                            .append("yPosition", "-0.58").append("zPosition", "-0.20")));
    db.getCollection("Pen")
            .insertOne(new Document("worldObjectId", "ColoredPencil2")
                    .append("worldobjecttype", "ColoredPencil").append("color", "blue").append("size", "medium")
                    .append("position", new Document().append("xPosition", "0.53").append("yPosition", "-0.275")
                            .append("zPosition", "-0.12")));
    db.getCollection("Pen").insertOne(new Document("worldObjectId", "ColoredPencil3")
            .append("worldobjecttype", "ColoredPencil").append("color", "red").append("size", "small"));
    db.getCollection("Pen").insertOne(new Document("worldObjectId", "ColoredPencil4")
            .append("worldobjecttype", "ColoredPencil").append("color", "green").append("size", "medium"));
    db.getCollection("Pen").insertOne(new Document("worldObjectId", "ColoredPencil5")
            .append("worldobjecttype", "ColoredPencil").append("color", "orange").append("size", "big"));
    db.getCollection("Pen").insertOne(new Document("worldObjectId", "ColoredPencil6")
            .append("worldobjecttype", "ColoredPencil").append("color", "purple").append("size", "big"));
    db.getCollection("Pen")
            .insertOne(new Document("worldObjectId", "BallPen1").append("worldobjecttype", "BallPen")
                    .append("color", "blue").append("label", "Mathema")
                    .append("approximate Position", "on your left"));
    db.getCollection("Pen").insertOne(new Document("worldObjectId", "BallPen2")
            .append("worldobjecttype", "BallPen").append("color", "blue").append("label", "Mathema")
            .append("approximate Position", "on your far left").append("position", new Document()
                    .append("xPosition", "0.32").append("yPosition", "-0.45").append("zPosition", "-0.12")));
    db.getCollection("Pen")
            .insertOne(new Document("worldObjectId", "BallPen3").append("worldobjecttype", "BallPen")
                    .append("color", "yellow").append("label", "pizza")
                    .append("position", new Document().append("xPosition", "0.32").append("yPosition", "-0.38")
                            .append("zPosition", "-0.22")));
    db.getCollection("Pen").insertOne(new Document("worldObjectId", "BallPen4")
            .append("worldobjecttype", "BallPen").append("color", "yellow"));
    db.getCollection("Pen")
            .insertOne(new Document("worldObjectId", "BallPen5").append("worldobjecttype", "BallPen")
                    .append("color", "blue").append("approximate position", "on your far left"));
    db.getCollection("Pen").insertOne(new Document("worldObjectId", "BallPen6")
            .append("worldobjecttype", "BallPen").append("color", "white").append("label", "KTH"));
    db.getCollection("Pen").insertOne(new Document("worldObjectId", "BallPen7")
            .append("worldobjecttype", "BallPen").append("color", "red"));
    db.getCollection("Paper")
            .insertOne(new Document("worldObjectId", "Paper1").append("worldobjecttype", "Paper")
                    .append("position", new Document().append("xPosition", "0.63").append("yPosition", "0.15")
                            .append("zPosition", "-0.2")));
    db.getCollection("Plate")
            .insertOne(new Document("worldObjectId", "Plate1").append("worldobjecttype", "Plate")
                    .append("material", "paper").append("color", "orange").append("motif", "white dots")
                    .append("position", new Document().append("xPosition", "0.33").append("yPosition", "0.56")
                            .append("zPosition", "-0.15")));
    db.getCollection("Plate")
            .insertOne(new Document("worldObjectId", "Plate2").append("worldobjecttype", "Plate")
                    .append("material", "paper").append("color", "grey white").append("motif", "zig-zag line")
                    .append("position", new Document().append("xPosition", "0.27").append("yPosition", "-0.85")
                            .append("zPosition", "-0.15")));
    db.getCollection("Plate")
            .insertOne(new Document("worldObjectId", "Plate3").append("worldobjecttype", "Plate")
                    .append("material", "ceramic").append("color", "white")
                    .append("position", new Document().append("xPosition", "0.6").append("yPosition", "-0.87")
                            .append("zPosition", "-0.12")));
    db.getCollection("Cup").insertOne(new Document("worldObjectId", "Cup1").append("worldobjecttype", "Cup")
            .append("print", "TECS").append("color", "white").append("position", new Document()
                    .append("xPosition", "0.45").append("yPosition", "0.35").append("zPosition", "-0.15")));
    db.getCollection("Cup")
            .insertOne(new Document("worldObjectId", "Cup2").append("worldobjecttype", "Cup")
                    .append("color", "blue").append("position", new Document().append("xPosition", "0.14")
                            .append("yPosition", "0.48").append("zPosition", "-0.15")));

    return db;/* w  w w .  j  ava  2  s  .c o  m*/
}

From source file:de.dfki.mmf.input.worldmodel.WorldModelFactory.java

License:Open Source License

/**
 *
 * @param saliencyAnnotation/*w w w . j a  va2  s. c o  m*/
 * @param robotModel
 * @param databaseName
 * Retrieve object properties from a MongoDB database
 */
private void mongoDBModelRetrieval(JsonObject saliencyAnnotation, RobotModel robotModel, String databaseName) {
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoIterable<String> collectionNames = db.listCollectionNames();
    ArrayList<JsonObject> worldProperties = new ArrayList<>();
    for (String name : collectionNames) {
        FindIterable<Document> iterable = db.getCollection(name).find();
        iterable.forEach(new Block<Document>() {
            public void apply(final Document document) {
                JsonObject jsonObject = (new JsonParser()).parse(document.toJson()).getAsJsonObject();
                worldProperties.add(jsonObject);
            }
        });
    }
    postProcessWorldModel(worldProperties, saliencyAnnotation, robotModel);

}

From source file:de.felix_klauke.pegasus.server.database.Database.java

License:Apache License

public Database(MongoCredential credential, String database, String collection) {
    final MongoClient mongoClient = new MongoClient(new ServerAddress("5.1.82.58", 27017),
            Collections.singletonList(credential));
    this.database = mongoClient.getDatabase(database);
    this.collection = this.database.getCollection(collection);
}

From source file:dummydata.DummyData.java

private static Map GenerateNodeMacAddress() {
    MongoClient mongoClient = new MongoClient("129.217.152.20", 27017);
    MongoDatabase db = mongoClient.getDatabase("autophy-dev");
    MongoCollection<Document> collection = db.getCollection("macAddrs");
    FindIterable<Document> iterable = collection.find();
    Document document = iterable.first();
    document.remove("_id");
    Map<String, String> documentMap = (Map) document;
    return documentMap;
}

From source file:ELK.ELKController.java

License:Apache License

public ELKController(String mongoURIString) throws IOException {
    MongoCredential cred = MongoCredential.createCredential("admin", "cmpe283", "admin".toCharArray());
    final MongoClient mongoClient = new MongoClient(new ServerAddress("ds047107.mongolab.com:47107"),
            Arrays.asList(cred));
    final MongoDatabase blogDatabase = mongoClient.getDatabase("cmpe283");

    userDAO = new UserDAO(blogDatabase);
    sessionDAO = new SessionDAO(blogDatabase);

    // statsDAO= new StatsDAO(mongoClient.getDatabase("cmpe283project1"));
    //  AvailabiltyManager av =new AvailabiltyManager();
    //  av.start();

    //  Thread statsThread= new Thread(new statsCollector());
    // statsThread.start();

    cfg = createFreemarkerConfiguration();
    // this.si = null;
    // this.rootFolder = null;

    //  si = new ServiceInstance(new URL(SJSULAB.getVmwareHostURL()), SJSULAB.getVmwareLogin(), SJSULAB.getVmwarePassword(), true);
    //  rootFolder = si.getRootFolder();

    setPort(8082);//from w w  w . j a va 2  s . co  m
    initializeRoutes();
    VMsDBCollection = mongoClient.getDatabase("cmpe283").getCollection("virtual_machines");
    if (VMsDBCollection != null) {
        System.out.println("VMs DB Collection found");
    } else
        System.out.println("Sorry VMs DB Collection NOT found");

}

From source file:eu.seaclouds.platform.discoverer.core.Discoverer.java

License:Apache License

public Discoverer(MongoClient mongoClient, ArrayList<String> activeCrawlers) {
    this.initializeResources();

    MongoDatabase db = mongoClient.getDatabase(this.databaseName);
    MongoCollection<Document> coll = db.getCollection(this.collectionName);

    this.offeringManager = new OfferingManager(coll);
    this.offeringManager.initializeOfferings();

    this.activeCrawlers = activeCrawlers;
}

From source file:eu.vital.vitalcep.cep.CEP.java

public Boolean CEPStart(CEPType type, DolceSpecification dolceSpecification, String mqin, String mqout,
        String confFile, String sources, JSONObject credentials) throws FileNotFoundException, IOException {

    ConfigReader configReader = ConfigReader.getInstance();

    mongoURL = configReader.get(ConfigReader.MONGO_URL);
    mongoDB = configReader.get(ConfigReader.MONGO_DB);

    cp = new CepProcess(dolceSpecification.toString(), mqin, mqout, confFile);
    cp.startCEP();//from  w ww . j  av a 2 s.c o m
    this.PID = cp.PID;

    CepContainer.putCepProc(cp);

    this.type = type.toString();
    String T = type.toString();

    if (cp.PID > 0) {

        this.fileName = cp.fileName;
        MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL));
        MongoDatabase db = mongo.getDatabase(mongoDB);

        try {

            Document doc = new Document();

            doc.put("PID", PID);
            doc.put("mqin", mqin);
            doc.put("mqout", mqout);
            doc.put("dolceSpecification", dolceSpecification.toString());
            doc.put("dolcefile", cp.cepFolder + "/" + cp.fileName);
            doc.put("cepType", T);
            doc.put("clientId", fileName);
            //doc.put("sensorId", id);
            doc.put("fileName", fileName);
            doc.put("cepFolder", cp.cepFolder);

            Date NOW = new Date();

            switch (T) {
            case "DATA":
                doc.put("data", sources);
                break;
            case "QUERY":
                doc.put("querys", sources);
                break;

            case "CEPICO":
            case "ALERT":
                doc.put("lastRequest", getXSDDateTime(NOW));
                BasicDBList sourcesCEPICO = (BasicDBList) JSON.parse(sources);
                doc.put("requests", sourcesCEPICO);
                doc.put("lastRequest", getXSDDateTime(NOW));
                doc.put("username", credentials.getString("username"));
                doc.put("password", encrypt(credentials.getString("password")));
                break;

            case "CONTINUOUS":

                BasicDBList sourcesB = (BasicDBList) JSON.parse(sources);
                BasicDBList propertiesB = (BasicDBList) JSON.parse(dolceSpecification.getEvents().toString());
                doc.put("sources", sourcesB);
                doc.put("properties", propertiesB);
                doc.put("lastRequest", getXSDDateTime(NOW));
                doc.put("username", credentials.getString("username"));
                doc.put("password", encrypt(credentials.getString("password")));
                break;
            }

            doc.put("status", "OK");
            db.getCollection("cepinstances").insertOne(doc);
            ObjectId idO = (ObjectId) doc.get("_id");
            this.id = idO.toString();

            if (id != null && !(T == "DATA" || T == "QUERY")) {
                Boolean insertIntoCollectorList = insertIntoCollectorList(doc, idO);

                if (!insertIntoCollectorList) {
                    db.getCollection("cepinstances").updateOne(doc,
                            new Document("$set", new Document("status", "no collector available")));
                    throw new ServerErrorException(500);
                }

            }

        } catch (JSONException | GeneralSecurityException | UnsupportedEncodingException
                | ServerErrorException ex) {
            String a = "";
        } finally {
            if (db != null)
                db = null;
            if (mongo != null) {
                mongo.close();
                mongo = null;
            }
        }

    } else {
        this.fileName = "";
        return false;
    }
    return true;

}

From source file:eu.vital.vitalcep.collector.Collector.java

private void getCollectorList() {
    try {/*from ww w .  j  a  va  2s  .  co m*/
        MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL));

        final MongoDatabase db = mongo.getDatabase(mongoDB);

        BasicDBObject clause1 = new BasicDBObject("cepType", "CONTINUOUS").append("status", "OK");
        BasicDBObject clause2 = new BasicDBObject("cepType", "CEPICO");
        BasicDBObject clause3 = new BasicDBObject("cepType", "ALERT");
        BasicDBList or = new BasicDBList();
        or.add(clause1);
        or.add(clause2);
        or.add(clause3);
        BasicDBObject query = new BasicDBObject("$or", or);

        FindIterable<Document> coll;
        coll = db.getCollection("cepinstances").find(query);

        coll.forEach(new Block<Document>() {
            @Override
            public void apply(final Document document) {

                JSONObject oCollector = new JSONObject();

                oCollector.put("id", document.getObjectId("_id").toString());
                oCollector.put("mqin", document.getString("mqin"));
                oCollector.put("mqout", document.getString("mqout"));
                oCollector.put("cepType", document.getString("cepType"));

                if (document.getString("cepType").equals("CONTINUOUS")) {

                    final Document doc = new Document("sources", document.get("sources"));
                    final String jsonStringSources = doc.toJson();
                    JSONObject sources = new JSONObject(jsonStringSources);

                    final Document docproperties = new Document("properties", document.get("properties"));
                    final String jsonStringproperties = docproperties.toJson();
                    JSONObject sourcesproperties = new JSONObject(jsonStringproperties);

                    oCollector.put("sources", sources.getJSONArray("sources"));
                    oCollector.put("properties", sourcesproperties.getJSONArray("properties"));
                    oCollector.put("username", document.getString("username"));
                    oCollector.put("password", document.getString("password"));

                } else {

                    final Document doc = new Document("requests", document.get("requests"));
                    final String jsonStringRequests = doc.toJson();
                    JSONObject requestsObject = new JSONObject(jsonStringRequests);

                    oCollector.put("requests", requestsObject.getJSONArray("requests"));
                    oCollector.put("username", document.getString("username"));
                    oCollector.put("password", document.getString("password"));
                }
                oCollector.put("lastRequest", document.getString("lastRequest"));
                sensors.put(oCollector);

            }
        });

    } catch (Exception e) {
        String a = "a";
    } finally {
        if (db != null)
            db = null;
        if (mongo != null) {
            mongo.close();
            mongo = null;
        }
    }
}

From source file:eu.vital.vitalcep.publisher.MessageProcessor_publisher.java

@Override
public boolean processMsg(MqttMsg mqttMsg) {

    Encoder encoder = new Encoder();
    Date date = new Date();
    String xsdTime = getXSDDateTime(date);
    UUID uuid = UUID.randomUUID();
    String id = uuid.toString();//ww w .  ja v a2s  .co  m

    JSONObject observation = null;
    try {
        observation = encoder.dolceOutput2Jsonld(mqttMsg.msg, id, this.sensorId, xsdTime);
    } catch (ParseException ex) {
        java.util.logging.Logger.getLogger(MessageProcessor_publisher.class.getName())
                .log(java.util.logging.Level.SEVERE, null, ex);
    }

    Document doc = null;
    try {
        doc = encoder.dolceOutput2Document(mqttMsg.msg, id, this.sensorId, xsdTime);
    } catch (ParseException ex) {
        java.util.logging.Logger.getLogger(MessageProcessor_publisher.class.getName())
                .log(java.util.logging.Level.SEVERE, null, ex);
    }

    logger.debug("MQTTMessage received: " + mqttMsg.msg);

    MongoClient mongo = null;
    MongoDatabase db = null;
    try {
        mongo = new MongoClient(new MongoClientURI(this.mongoURL));
        db = mongo.getDatabase(this.mongoDB);
        db.getCollection(mongocollection).insertOne(doc);
    } catch (MongoException ex) {
        logger.error("observation not saved");
    } finally {
        if (db != null)
            db = null;
        if (mongo != null)
            mongo.close();
    }

    JSONArray body = new JSONArray();
    body.put(observation);

    DMSManager oDMS = new DMSManager(dms_URL, cookie);

    try {
        if (!oDMS.pushObservations(body.toString())) {
            logger.error("couldn't push to DMS");
            return false;
        } else {
            return true;
        }
    } catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException ex) {
        logger.error(ex);
    }

    return true;

}