Example usage for com.mongodb MongoClient getDB

List of usage examples for com.mongodb MongoClient getDB

Introduction

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

Prototype

@Deprecated 
public DB getDB(final String dbName) 

Source Link

Document

Gets a database object.

Usage

From source file:example.X509CredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    String server = args[0];//  w  w  w . j ava2s. c o  m
    String user = "CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US";

    System.out.println("server: " + server);
    System.out.println("user: " + user);

    System.out.println();

    MongoClient mongoClient = new MongoClient(new ServerAddress(server),
            Arrays.asList(MongoCredential.createMongoX509Credential(user)),
            new MongoClientOptions.Builder().socketFactory(SSLSocketFactory.getDefault()).build());
    DB testDB = mongoClient.getDB("test");

    System.out.println("Count: " + testDB.getCollection("test").count());

    System.out.println("Insert result: " + testDB.getCollection("test").insert(new BasicDBObject()));

}

From source file:exifIndexer.MongoHandler.java

public DB connect() {

    MongoCredential credential = MongoCredential.createMongoCRCredential(user, bdname, password);
    MongoClient Client;
    try {/*from ww w  .  j av  a 2s . c o  m*/
        Client = new MongoClient(new ServerAddress(host, port), Arrays.asList(credential));
    } catch (UnknownHostException ex) {
        System.err.println("Error creating Mongo DB Client");
    }
    try {

        Client = new MongoClient(host, port);
        DB db = Client.getDB(bdname);

        //Elimino la bd por si hubiera datos

        mongoClient = Client;
        //db = deletedb(bdname);
        // mongoClient.getDB(bdname).dropDatabase();

        return db;

    } catch (UnknownHostException ex) {
        Logger.getLogger(MongoHandler.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:explorasi.GettingStarted.java

public static void main(String args[]) {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("pat_13512042");
    DBCollection coll = db.getCollection("users");

    BasicDBObject doc = new BasicDBObject("name", "joshua").append("kelas", "01").append("timestamp",
            new Date());
    coll.insert(doc);/*from   w ww.  j  a  va2 s  .  c o  m*/

    DBCursor cursor = coll.find(doc);

    while (cursor.hasNext()) {
        DBObject tmp = cursor.next();
        System.out.println(tmp.get("name"));
        System.out.println(tmp.get("kelas"));
        System.out.println(tmp.get("timestamp"));
        System.out.println(tmp.get("_id"));
    }

}

From source file:facebook.metrics.FacebookMetricsGroup.java

public static void main(String[] args) {

    try {//from   w w  w .  j ava  2 s .  c o m
        // Se crea el libro
        HSSFWorkbook libro = new HSSFWorkbook();

        // Se crea una hoja dentro del libro
        HSSFSheet hoja = libro.createSheet();

        // Se crea una fila dentro de la hoja
        HSSFRow fila = hoja.createRow(0);

        // Se crea una celda dentro de la fila
        HSSFCell celda = fila.createCell(1);

        // Se crea el contenido de la celda y se mete en ella.
        HSSFRichTextString texto = new HSSFRichTextString("Metricas de Grupo Cinepolitos");
        celda.setCellValue(texto);
        /************************************/
        /*Mongo DB Conection*/
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        DB db = mongoClient.getDB("JavaMongoFacebookGroup");

        DBCollection datos = db.getCollection("Datos");

        /********************/
        Facebook facebook = new FacebookFactory().getInstance();

        facebook.setOAuthAppId("603320016402931", "202694064e7a4e77f0c0042b1a16ebd4");

        System.out.println(facebook.getOAuthAppAccessToken().getToken());

        ResponseList<Post> feedX = facebook.getGroupFeed("17761155026", new Reading().limit(1135));

        List<ResponseList<Post>> X = new ArrayList<ResponseList<Post>>();

        do {

            X.add(feedX);
            Paging<Post> pag1 = feedX.getPaging();
            feedX = facebook.fetchNext(pag1);

        } while (feedX.getPaging() != null);

        fila = hoja.createRow(2);
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString("Id Post:"));
        celda = fila.createCell(2);
        celda.setCellValue(new HSSFRichTextString("Fecha del Post:"));
        celda = fila.createCell(3);
        celda.setCellValue(new HSSFRichTextString("Usuario que posteo:"));
        celda = fila.createCell(4);
        celda.setCellValue(new HSSFRichTextString("Post:"));
        celda = fila.createCell(5);
        celda.setCellValue(new HSSFRichTextString("# de Likes del Post:"));
        celda = fila.createCell(6);
        celda.setCellValue(new HSSFRichTextString("# de Comentarios del Post:"));
        celda = fila.createCell(7);
        celda.setCellValue(new HSSFRichTextString("Comentarios del Post:"));

        int filasX = 3;

        for (int j = 0; j < X.size(); j++) {

            ResponseList<Post> feed = X.get(j);
            System.out.println(feed.size());

            for (int i = 0; i < feed.size(); i++) {

                System.out.println("Feed:  " + i);

                BasicDBObject obj = new BasicDBObject();
                ResponseList<Like> likes = facebook.getPostLikes(feed.get(i).getId(),
                        new Reading().limit(1135));
                ResponseList<Comment> comments = facebook.getPostComments(feed.get(i).getId(),
                        new Reading().limit(1135));

                obj.append("idPost", feed.get(i).getId() + "");

                if (feed.get(i).getMessage() == null) {
                    obj.append("Post", "   ");
                    //System.out.println("Null");
                } else {
                    obj.append("Post", feed.get(i).getMessage());
                }

                obj.append("Likes", likes.size() + "");
                obj.append("Comments", comments.size() + "");

                datos.insert(obj);

                fila = hoja.createRow(filasX);
                celda = fila.createCell(1);
                celda.setCellValue(new HSSFRichTextString(feed.get(i).getId() + ""));
                celda = fila.createCell(2);
                celda.setCellValue(new HSSFRichTextString(feed.get(i).getCreatedTime() + ""));
                celda = fila.createCell(3);
                celda.setCellValue(new HSSFRichTextString(feed.get(i).getFrom().getName()));
                celda = fila.createCell(4);
                celda.setCellValue(new HSSFRichTextString(feed.get(i).getMessage()));
                celda = fila.createCell(5);
                celda.setCellValue(new HSSFRichTextString(likes.size() + ""));
                celda = fila.createCell(6);
                celda.setCellValue(new HSSFRichTextString(comments.size() + ""));

                filasX++;

                for (int y = 0; y < comments.size(); y++) {
                    fila = hoja.createRow(filasX);
                    celda = fila.createCell(7);
                    celda.setCellValue(new HSSFRichTextString(comments.get(y).getMessage() + ""));
                    filasX++;
                }

            }
            System.out.println();

        }

        FileOutputStream elFichero = new FileOutputStream("Metricas_Cinepolitos.xls");
        libro.write(elFichero);
        elFichero.close();

    } catch (Exception e) {
        System.err.println("Fatal Error:   " + e);
    }

}

From source file:facebook.metrics.FacebookMetricsPage.java

public static void main(String[] args) throws IOException {
    int varFeed = 0;
    int filasX = 0;
    HSSFRow fila = null;/*  w  ww.j  a va2  s  .  c om*/
    HSSFRow filam = null;
    HSSFCell celda = null;
    List<ResponseList<Post>> X = null;
    int j = 0;
    int i = 0;
    HSSFSheet hoja = null;
    Facebook facebook = null;
    HSSFWorkbook libro = null;
    try {
        // Se crea el libro
        libro = new HSSFWorkbook();

        hoja = libro.createSheet();

        fila = hoja.createRow(0);

        celda = fila.createCell(1);

        HSSFRichTextString texto = new HSSFRichTextString("Metricas de Infinitum");
        celda.setCellValue(texto);
        /************************************/
        /*Mongo DB Conection*/
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        DB db = mongoClient.getDB("JavaMongoFacebookGroup");

        DBCollection datos = db.getCollection("Datos");

        /********************/
        facebook = new FacebookFactory().getInstance();

        facebook.setOAuthAppId("603320016402931", "202694064e7a4e77f0c0042b1a16ebd4");

        System.out.println(facebook.getOAuthAppAccessToken().getToken());

        ResponseList<Post> feedX = facebook.getFeed("216786388331757", new Reading().limit(1000));

        X = new ArrayList<ResponseList<Post>>();
        int ui = 0;
        do {

            X.add(feedX);
            Paging<Post> pag1 = feedX.getPaging();
            feedX = facebook.fetchNext(pag1);
            System.out.println("" + ui);
            ui++;
        } while (feedX.getPaging() != null && ui < 25);

        fila = hoja.createRow(2);

        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString("Id Post:"));
        celda = fila.createCell(2);
        celda.setCellValue(new HSSFRichTextString("Fecha del Post:"));
        celda = fila.createCell(3);
        celda.setCellValue(new HSSFRichTextString("Usuario que posteo:"));
        celda = fila.createCell(4);
        celda.setCellValue(new HSSFRichTextString("Post:"));
        celda = fila.createCell(5);
        celda.setCellValue(new HSSFRichTextString("# de Likes del Post:"));
        celda = fila.createCell(6);
        celda.setCellValue(new HSSFRichTextString("# de Comentarios del Post:"));
        celda = fila.createCell(7);
        celda.setCellValue(new HSSFRichTextString("Comentarios del Post:"));
        celda = fila.createCell(8);
        celda.setCellValue(new HSSFRichTextString("Tipo de Post:"));

        filasX = 4;

        for (j = 0; j < X.size(); j++) {

            ResponseList<Post> feed = X.get(j);

            System.out.println(feed.size());

            for (i = 0; i < feed.size(); i++) {

                System.out.println("Feed:  " + i);

                BasicDBObject obj = new BasicDBObject();
                ResponseList<Like> likes = facebook.getPostLikes(feed.get(i).getId(),
                        new Reading().limit(1135));
                ResponseList<Comment> comments = facebook.getPostComments(feed.get(i).getId(),
                        new Reading().limit(1135));

                obj.append("idPost", feed.get(i).getId() + "");

                if (feed.get(i).getMessage() == null) {
                    obj.append("Post", "   ");
                    //System.out.println("Null");
                } else {
                    obj.append("Post", feed.get(i).getMessage());
                }

                obj.append("Likes", likes.size() + "");
                obj.append("Comments", comments.size() + "");

                datos.insert(obj);

                filam = hoja.createRow(filasX);
                celda = filam.createCell(1);
                celda.setCellValue(new HSSFRichTextString(feed.get(i).getId() + ""));
                celda = filam.createCell(2);
                celda.setCellValue(new HSSFRichTextString(feed.get(i).getCreatedTime() + ""));
                celda = filam.createCell(3);
                celda.setCellValue(new HSSFRichTextString(feed.get(i).getFrom().getName()));
                celda = filam.createCell(4);
                celda.setCellValue(new HSSFRichTextString(feed.get(i).getMessage()));
                celda = filam.createCell(5);
                celda.setCellValue(new HSSFRichTextString(likes.size() + ""));
                celda = filam.createCell(6);
                celda.setCellValue(new HSSFRichTextString(comments.size() + ""));
                celda = filam.createCell(8);
                celda.setCellValue(new HSSFRichTextString(feed.get(i).getType() + ""));

                filasX++;

                for (int y = 0; y < comments.size(); y++) {
                    filam = hoja.createRow(filasX);
                    celda = filam.createCell(7);
                    celda.setCellValue(new HSSFRichTextString(comments.get(y).getMessage() + ""));
                    filasX++;
                }

            }
        }

        FileOutputStream elFichero = new FileOutputStream("Metricas_Infinitum.xls");
        libro.write(elFichero);
        elFichero.close();

    } catch (Exception e) {

        System.err.println("Fatal Error:   " + e);
        FacebookMetricsPage s = new FacebookMetricsPage();

        s.porsi(i, j, filasX + 1, filam, celda, facebook, X, hoja, libro);

    }

}

From source file:facebook.metrics.FacebookMetricsPage2.java

public static void main(String[] args) throws IOException {
    int varFeed = 0;
    int filasX = 0;
    HSSFRow fila = null;//from   www. j av a  2s .  com
    HSSFCell celda = null;
    List<ResponseList<Post>> X = null;
    int j = 0;
    int i = 0;
    HSSFSheet hoja = null;
    Facebook facebook = null;
    HSSFWorkbook libro = null;
    try {
        // Se crea el libro
        libro = new HSSFWorkbook();

        // Se crea una hoja dentro del libro
        hoja = libro.createSheet();

        // Se crea una fila dentro de la hoja
        fila = hoja.createRow(0);

        // Se crea una celda dentro de la fila
        celda = fila.createCell(1);

        // Se crea el contenido de la celda y se mete en ella.
        HSSFRichTextString texto = new HSSFRichTextString("Metricas de Sony Futbol");
        celda.setCellValue(texto);
        /************************************/
        /*Mongo DB Conection*/
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        DB db = mongoClient.getDB("JavaMongoFacebookGroup");

        DBCollection datos = db.getCollection("Datos");

        /********************/
        facebook = new FacebookFactory().getInstance();

        facebook.setOAuthAppId("603320016402931", "202694064e7a4e77f0c0042b1a16ebd4");

        System.out.println(facebook.getOAuthAppAccessToken().getToken());

        ResponseList<Post> feedX = facebook.getFeed("120472297979101", new Reading().limit(1000));

        X = new ArrayList<ResponseList<Post>>();
        int ui = 0;
        do {

            X.add(feedX);
            Paging<Post> pag1 = feedX.getPaging();
            feedX = facebook.fetchNext(pag1);
            System.out.println("" + ui);
            ui++;
        } while (feedX.getPaging() != null && ui < 5);

        fila = hoja.createRow(2);
        celda = fila.createCell(1);
        celda.setCellValue(new HSSFRichTextString("Id Post:"));
        celda = fila.createCell(2);
        celda.setCellValue(new HSSFRichTextString("Fecha del Post:"));
        celda = fila.createCell(3);
        celda.setCellValue(new HSSFRichTextString("Usuario que posteo:"));
        celda = fila.createCell(4);
        celda.setCellValue(new HSSFRichTextString("Post:"));
        celda = fila.createCell(5);
        celda.setCellValue(new HSSFRichTextString("# de Likes del Post:"));
        celda = fila.createCell(6);
        celda.setCellValue(new HSSFRichTextString("# de Comentarios del Post:"));
        celda = fila.createCell(7);
        celda.setCellValue(new HSSFRichTextString("Comentarios del Post:"));
        celda = fila.createCell(8);
        celda.setCellValue(new HSSFRichTextString("Tipo de Post:"));

        filasX = 3;

        for (j = 0; j < X.size(); j++) {

            ResponseList<Post> feed = X.get(j);

            System.out.println(feed.size());

            for (i = 0; i < feed.size(); i++) {

                System.out.println("Feed:  " + i);

                BasicDBObject obj = new BasicDBObject();
                ResponseList<Like> likes = facebook.getPostLikes(feed.get(i).getId(),
                        new Reading().limit(1135));
                ResponseList<Comment> comments = facebook.getPostComments(feed.get(i).getId(),
                        new Reading().limit(1135));

                obj.append("idPost", feed.get(i).getId() + "");

                if (feed.get(i).getMessage() == null) {
                    obj.append("Post", "   ");
                    //System.out.println("Null");
                } else {
                    obj.append("Post", feed.get(i).getMessage());
                }

                obj.append("Likes", likes.size() + "");
                obj.append("Comments", comments.size() + "");

                datos.insert(obj);

                fila = hoja.createRow(filasX);
                celda = fila.createCell(1);
                celda.setCellValue(new HSSFRichTextString(feed.get(i).getId() + ""));
                celda = fila.createCell(2);
                celda.setCellValue(new HSSFRichTextString(feed.get(i).getCreatedTime() + ""));
                celda = fila.createCell(3);
                celda.setCellValue(new HSSFRichTextString(feed.get(i).getFrom().getName()));
                celda = fila.createCell(4);
                celda.setCellValue(new HSSFRichTextString(feed.get(i).getMessage()));
                celda = fila.createCell(5);
                celda.setCellValue(new HSSFRichTextString(likes.size() + ""));
                celda = fila.createCell(6);
                celda.setCellValue(new HSSFRichTextString(comments.size() + ""));
                celda = fila.createCell(8);
                celda.setCellValue(new HSSFRichTextString(feed.get(i).getType() + ""));

                filasX++;

                for (int y = 0; y < comments.size(); y++) {
                    fila = hoja.createRow(filasX);
                    celda = fila.createCell(7);
                    celda.setCellValue(new HSSFRichTextString(comments.get(y).getMessage() + ""));
                    filasX++;
                }

            }
        }

        FileOutputStream elFichero = new FileOutputStream("Metricas_SonyFutbol.xls");
        libro.write(elFichero);
        elFichero.close();

    } catch (Exception e) {

        System.err.println("Fatal Error:   " + e);
        FacebookMetricsPage s = new FacebookMetricsPage();

        s.porsi(i, j, filasX, fila, celda, facebook, X, hoja, libro);

    }

}

From source file:facebookwebcrawler.Mongo.java

private DBCollection queryDb(String[] args) {
    try {//from  ww w .  ja  va  2s  .c o  m

        /**** Connect to MongoDB ****/
        // Since 2.10.0, uses MongoClient
        MongoClient mongo = new MongoClient("localhost", 27017);

        /**** Get database ****/
        // if database doesn't exists, MongoDB will create it for you
        DB db = mongo.getDB("test");

        /**** Get collection / table from 'testdb' ****/
        // if collection doesn't exists, MongoDB will create it for you
        DBCollection table = db.getCollection("recommendations");
        return table;
    } catch (MongoException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:field_sum.Field_sum.java

/**
 * @param args the command line arguments
 * @throws java.net.UnknownHostException
 *///from  ww  w. j  ava 2s .  c  o m
public static void main(String[] args) throws UnknownHostException {

    MongoClient client = new MongoClient("localhost", 27017);
    DB myDB = client.getDB("m101");
    DBCollection collection = myDB.getCollection("Sample3");

    /**
     * random_number field generates random numbers 
    */
    Random random_numbers = new Random();

    collection.drop();

    DBObject query = QueryBuilder.start("x").greaterThan(10).lessThan(70).and("y").greaterThan(10).lessThan(70)
            .get();

    for (int i = 0; i < 100; i++) {
        collection.insert(new BasicDBObject("x", random_numbers.nextInt(100))
                .append("y", random_numbers.nextInt(100)).append("z", random_numbers.nextInt(200)));
    }

    DBCursor cursor = collection.find(query);
    int sum = 0;

    try {
        while (cursor.hasNext()) {
            DBObject dBObject = cursor.next();
            sum += (int) dBObject.get("x");
            System.out.println(dBObject.get("x"));
        }
    } finally {
        cursor.close();
    }
    System.out.println(sum);

}

From source file:firesystem.MainGui.java

public FireSensor[] getSensors(Stage primaryStage) {
    FireSensor[] sensors = new FireSensor[13];
    try {/*from ww  w .  j ava  2s.c  o  m*/

        MongoClient mongoClient = new MongoClient(DatabaseConnectionPopup.getsHostName());

        DB db = mongoClient.getDB(DatabaseConnectionPopup.getsDbname());

        DBCollection coll = db.getCollection("users");

        DBCursor cursor = coll.find();

        for (int i = 0; i < 13; i++) {
            DBObject thisUser;

            //Make sure the users exist
            if (cursor.hasNext()) {
                thisUser = cursor.next();
            } else {
                thisUser = new BasicDBObject();
                coll.insert(thisUser);
            }
            int j = i + 1;
            sensors[i] = new FireSensor(j, thisUser.get("_id").toString());
        }
    } catch (UnknownHostException e) {
        System.out.println(e.getMessage());
    } catch (Exception e) {
        new ExceptionPopup(
                "Der kunne ikke oprettes forbindelse til mongodb. Mongodb gav flgende fejlbesked: ",
                e.getMessage());
        System.exit(0);
    }

    return sensors;
}

From source file:firesystem.model.FireSensor.java

/**
 * Saves output every x ms based on the constant refresh rate. Saves in mongodb and uploads to server on the given server brain url.
 *///from  w ww . ja va2s  .  co  m
@Override
public void run() {
    while (true) {
        try {
            if (enabled == true) {

                //                    System.out.println(BRAIN_URL_STRING);
                //Create mongodb connection
                MongoClient mdb = new MongoClient(DatabaseConnectionPopup.getsHostName());

                DB db = mdb.getDB(DatabaseConnectionPopup.getsDbname());

                //Get relevant connections
                users = db.getCollection("users");
                temperatureCollection = db.getCollection(DatabaseConnectionPopup.getCollectionName());

                //Find my document in the users collection
                DBObject ME = findDocumentById(jsonId, users);

                //If document doesn't exist, add it to the users collection
                if (ME == null) {
                    ME = new BasicDBObject("_id", new ObjectId(jsonId));
                    users.insert(ME);
                }

                temperature = (int) (Math.random() * 100);
                humidity = (int) (Math.random() * 100);
                String mobile = "";
                String email = "";

                if (ME.containsField("mobile")) {
                    mobile = (String) ME.get("mobile");
                }
                if (ME.containsField("email")) {
                    email = (String) ME.get("email");
                }

                //Write temperature to mongodb
                temperatureCollection
                        .insert(new BasicDBObject("temperature", temperature).append("humidity", humidity));

                //Send temperature to server
                String temperatureJson = "{\"name\":\"sensor-" + number + "\",\"temperature\":" + temperature
                        + ",\"humidity\":" + humidity + ",\"mobile\":\"" + mobile + "\",\"email\":\"" + email
                        + "\"}";

                URL url = new URL(BRAIN_URL_STRING + "?temperature=" + temperatureJson + "&sensorId=" + number);

                url.openStream();
                //Hvis temperaturen er over 90 s send email og sms.
                if (temperature > 90) {
                    //Send sms
                    String message = "Room%20for%20sensor%20" + number + "%20is%20on%20fire!";
                    if (ME.containsField("mobile")) {
                        url = new URL(SMS_API_STRING + "?sMobileNumber=" + mobile + "&sMessage=" + message);

                        url.openStream();
                    }

                    //Send email
                    if (ME.containsField("email")) {
                        String subject = "FIRE";
                        url = new URL(EMAIL_API_STRING + "?email=" + email + "&subject=" + subject + "&message="
                                + message);

                        url.openStream();
                    }

                }

                mdb.close();
            }

            Thread.sleep(REFRESH_RATE);
        } catch (InterruptedException ex) {
            //
        } catch (IOException ex) {
            //
        } catch (Exception e) {
            enabled = false;
        }

    }
}