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:buysell.subads.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    try {//w w w.ja v a  2s .  c om
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("buysale");
        System.out.println("Connect to database successfully");
        DBCollection coll = db.getCollection("assetes");
        System.out.println("Collection created successfully");
        String name = jTextField1.getText().toString();
        String email = jTextField2.getText().toString();
        String phoneno = jTextField3.getText().toString();
        String price = jTextField4.getText().toString();
        String photourl = jTextField5.getText().toString();
        String type = jComboBox1.getSelectedItem().toString();
        DB dB = mongoClient.getDB("snehal");
        System.out.println("Connect to database successfully");
        DBCollection colle = dB.getCollection("user");
        System.out.println("Collection created successfully");
        String uname = jTextField6.getText().toString();
        String passwd = jPasswordField1.getText().toString();
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("name", uname);
        searchQuery.put("passwd", passwd);

        DBCursor cursor = colle.find(searchQuery);
        int i = 0;
        while (cursor.hasNext()) {
            i = 1;
            System.out.println(cursor.next());
        }
        if (i == 0) {
            JOptionPane.showMessageDialog(null, "user name or passwod is wrong");

        } else {
            if (jTextField2.getText().length() != 0 && jTextField3.getText().length() != 0
                    && jTextField4.getText().length() != 0 && jTextField1.getText().length() != 0
                    && jTextField5.getText().length() != 0) {

                BasicDBObject doc = new BasicDBObject("name", name).append("username", uname)
                        .append("passwd", passwd).append("email", email).append("phoneno", phoneno)
                        .append("price", price).append("type", type).append("photourl", photourl);

                coll.insert(doc);
                home h2 = new home();
                h2.setVisible(true);
                dispose();
                System.out.println("Document inserted successfully");
            } else {
                JOptionPane.showMessageDialog(null, "enter the every field");
            }
        }

    } catch (NumberFormatException e) {
        System.out.println();
    }
}

From source file:calliope.db.MongoConnection.java

License:Open Source License

/**
 * Connect to the database/*  w ww .  j ava2 s  . co m*/
 * @throws Exception 
 */
private void connect() throws Exception {
    if (db == null) {
        MongoClient mongoClient = new MongoClient(host, MONGO_PORT);
        db = mongoClient.getDB("calliope");
        //boolean auth = db.authenticate( user, password.toCharArray() );
        //if ( !auth )
        //    throw new AeseException( "MongoDB authentication failed");
    }
}

From source file:CapaDato.Conexion.java

public static void main(String[] Args) throws UnknownHostException {
    try {//from  www .j  av a  2 s  . c om
        // Para conectarse al servidor MongoDB
        MongoClient conexion = new MongoClient("localhost", 27017);
        // Ahora conectarse a bases de datos
        DB ejemplo = conexion.getDB("Ejemplo");
        System.out.println("Conectarse a la base de datos exitoso");
        DBCollection coleccion = ejemplo.getCollection("Alumno");
        //             Set<String> collectionNames = ejemplo.getCollectionNames();
        //            for (final String s : collectionNames) 
        //            {
        //            System.out.println(s);
        //            }
        //Para consultar otro mtodo
        Object objeto = new Object();
        objeto = "null,{nombre:1}";
        DBCursor cursor = coleccion.find();

        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }

        //DBObject doc = coleccion.findOne();

        //Para consultar
        //DBCursor cursor = coleccion.find ();
        //System.out.println(cursor);
        //            int i = 1;
        //          while (cursor.hasNext ()) 
        //          { 
        //             System.out.println ("insertado documento:" + i); 
        //             System.out.println (cursor.next ()); 
        //             i ++;
        //          }

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

}

From source file:cfel.test.InitAlbum.java

License:Open Source License

/**
 * @param args/*from ww w  .  j  a v a  2 s. c o m*/
 */
public static void main(String[] args) {
    try {
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        db = mongoClient.getDB("albumdb");
        fs = new GridFS(db);
        fs.remove((DBObject) null);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }
    System.out.println(IMAGE_DIR_PATH);
    addImages(IMAGE_DIR);
}

From source file:cl.wsconsulta.consulta.Consulta.java

@WebMethod(operationName = "consultar")
public String realizarConsulta(@WebParam(name = "consulta") BasicDBList privileges) throws IOException {
    DB database;/*from ww  w .  j  av a2 s .  co  m*/
    try (BufferedReader entrada = new BufferedReader(new FileReader("datos.ini"))) {
        database = null;
        try {
            dataBase = entrada.readLine();
            indiceInvertido = entrada.readLine();
            coleccionDocumentos = entrada.readLine();
            coleccionIndice = entrada.readLine();

            MongoClient mongoClient = new MongoClient();
            database = mongoClient.getDB(dataBase);

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

    DBCollection indiceInvertido = database.getCollection(coleccionIndice);
    DBCollection documento = database.getCollection(coleccionDocumentos);

    while (true) {

        BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
        String consulta = lector.readLine().toUpperCase();
        BasicDBObject query = new BasicDBObject("palabra", consulta);
        DBCursor cursor = indiceInvertido.find(query);
        if (cursor.count() == 0) {
            System.out.println("Busqueda sin resultados: " + consulta);
        } else {
            while (cursor.hasNext()) {
                privileges = (BasicDBList) cursor.next().get("documento");
                //DBObject obj = cursor.next();
                //Object value = obj.get("documento");
                //System.out.println(value);
            }
            System.out.println(privileges);
        }
    }

}

From source file:cl.wsconsulta.servlet.ConsultaServlet.java

public static String consultar(String consulta) throws FileNotFoundException, IOException {

    DB database;//from ww w .j a v  a 2s .  c om

    database = null;

    dataBase = "labsd";
    indiceInvertido = "prueba.xml";
    coleccionDocumentos = "documentos";
    coleccionIndice = "indiceInvertido";

    MongoClient mongoClient = new MongoClient();
    database = mongoClient.getDB(dataBase);

    DBCollection indiceInvertido = database.getCollection(coleccionIndice);
    DBCollection documento = database.getCollection(coleccionDocumentos);
    BasicDBList privileges = new BasicDBList();

    BasicDBObject query = new BasicDBObject("palabra", consulta);
    DBCursor cursor = indiceInvertido.find(query);
    if (cursor.count() == 0) {
        System.out.println("Busqueda sin resultados: " + consulta);
    } else {
        while (cursor.hasNext()) {

            privileges = (BasicDBList) cursor.next().get("documento");

            //DBObject obj = cursor.next();
            //Object value = obj.get("documento");
            //System.out.println(value);
        }
    }
    String lista = privileges.toString();
    return lista;

}

From source file:cn.edu.hfut.dmic.webcollector.example.DemoSelenium.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Executor executor = new Executor() {
        @Override/*w w  w  .  j a va  2 s. c  o m*/
        public void execute(CrawlDatum datum, CrawlDatums next) throws Exception {
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            // ?
            // DBCollection dbCollection = mongoClient.getDB("maoyan_crawler").getCollection("rankings_am"); 
            DB db = mongoClient.getDB("maoyan_crawler");
            // ?????
            Set<String> colls = db.getCollectionNames();
            for (String s : colls) {
                // Collection(?"")
                if (s.equals("attend_rate")) {
                    db.getCollection(s).drop();
                }
            }
            DBCollection dbCollection = db.getCollection("attend_rate");
            HtmlUnitDriver driver = new HtmlUnitDriver();
            driver.setJavascriptEnabled(false);
            driver.get(datum.getUrl());
            System.out.println(driver.getPageSource());
            WebElement click_view = driver.findElement(By.xpath("//div[@id='seatContent']//span[1]"));
            click_view.click();
            String gold_seat = driver.getWindowHandle();
            driver.switchTo().window(gold_seat);
            System.out.println(driver.getPageSource());
            WebElement city_name = driver.findElement(By.xpath("//*[@id='all-citys']/div[1]/ul/li[1]/a"));
            System.out.println(city_name.getText());
            WebElement element = driver.findElementByCssSelector("div#seat_table");
            List<WebElement> movie_name = element.findElements(By.className("c1 lineDot"));
            List<WebElement> boxoffice_rate = element.findElements(By.className("c2 red"));
            List<WebElement> visit_pershow = element.findElements(By.className("c3 gray"));
            WebElement cityarea = driver.findElementByCssSelector("span[class='today']");
            System.out.println(cityarea.getText());
            for (int i = 0; i < movie_name.size(); i++) {
                System.out.println(movie_name.get(i).getText());
                System.out.println(boxoffice_rate.get(i).getText());
                System.out.println(visit_pershow.get(i).getText());
                BasicDBObject dbObject = new BasicDBObject();
                dbObject.append("title", cityarea.getText()).append("movie_name", movie_name.get(i).getText())
                        .append("boxoffice_rate", boxoffice_rate.get(i).getText())
                        .append("visit_pershow", visit_pershow.get(i).getText());
                dbCollection.insert(dbObject);
            }
            mongoClient.close();
        }
    };

    //DBDBManager
    DBManager manager = new BerkeleyDBManager("crawl");
    //Crawler?DBManagerExecutor
    Crawler crawler = new Crawler(manager, executor);
    crawler.addSeed("http://pf.maoyan.com/attend/rate");
    crawler.start(1);
}

From source file:cn.edu.hfut.dmic.webcollector.example.FirefoxSelenium2.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Executor executor = new Executor() {
        @Override//from  ww w.  j  ava 2  s  .c  o  m
        public void execute(CrawlDatum datum, CrawlDatums next) throws Exception {
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            // ?
            // DBCollection dbCollection = mongoClient.getDB("maoyan_crawler").getCollection("rankings_am"); 
            DB db = mongoClient.getDB("maoyan_crawler");
            // ?????
            Set<String> colls = db.getCollectionNames();
            for (String s : colls) {
                // Collection(?"")
                if (s.equals("rankings_am")) {
                    db.getCollection(s).drop();
                }
            }
            DBCollection dbCollection = db.getCollection("attend_rate");
            ProfilesIni pi = new ProfilesIni();
            FirefoxProfile profile = pi.getProfile("default");
            WebClient webClient = new WebClient(BrowserVersion.FIREFOX_38);
            //             driver.setJavascriptEnabled(false);
            webClient.getOptions().setCssEnabled(true);
            HtmlPage page = webClient.getPage(datum.getUrl());
            //                System.out.println(driver.getPageSource());
            //                System.out.println(page.getByXPath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']/text()"));

            System.out.println(page.getByXPath("//span[@class='today']/em/text()"));
            System.out.println(page.getByXPath("//span[@class='today']/text()"));
            List<?> movie_name = page.getByXPath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']/text()");
            List<?> boxoffice_rate = page.getByXPath("//div[@id='seat_table']//ul//li[@class='c2 red']/text()");
            List<?> visit_pershow = page.getByXPath("//div[@id='seat_table']//ul//li[@class='c3 gray']/text()");
            for (int i = 0; i < movie_name.size(); i++) {
                System.out.println(movie_name.get(i));
                System.out.println(boxoffice_rate.get(i));
                System.out.println(visit_pershow.get(i));
            }
            //                   BasicDBObject dbObject = new BasicDBObject();
            //                  dbObject.append("title", title).append("rank", amList.get(0)).append("mov_cnname", cn_name).append("mov_enname", en_name).append("toweek_rev", amList.get(2)).append("total_rev", amList.get(3)).append("val_week", amList.get(4));
            //                   dbCollection.insert(dbObject);
            webClient.closeAllWindows();

        }
    };

    //DBDBManager
    DBManager manager = new BerkeleyDBManager("crawl");
    //Crawler?DBManagerExecutor
    Crawler crawler = new Crawler(manager, executor);
    crawler.addSeed("http://pf.maoyan.com/attend/rate");
    crawler.start(1);
}

From source file:cn.edu.hfut.dmic.webcollector.example.FirefoxSelenium3.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Executor executor = new Executor() {
        @Override/*ww w.  j a  v  a 2 s .c om*/
        public void execute(CrawlDatum datum, CrawlDatums next) throws Exception {
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            // ?
            // DBCollection dbCollection = mongoClient.getDB("maoyan_crawler").getCollection("rankings_am"); 
            DB db = mongoClient.getDB("maoyan_crawler");
            // ?????
            Set<String> colls = db.getCollectionNames();
            for (String s : colls) {
                // Collection(?"")
                if (s.equals("attend_rate")) {
                    db.getCollection(s).drop();
                }
            }
            DBCollection dbCollection = db.getCollection("attend_rate");
            ProfilesIni pi = new ProfilesIni();
            FirefoxProfile profile = pi.getProfile("default");
            WebDriver driver = new FirefoxDriver(profile);
            driver.manage().window().maximize();
            driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS);
            //                driver.setJavascriptEnabled(false);
            driver.get(datum.getUrl());
            //                System.out.println(driver.getPageSource());
            driver.findElement(By.xpath("//*[@id='seat_city']")).click();
            driver.switchTo().window(driver.getWindowHandle());

            int city_num = driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).size();
            for (int i = 0; i < city_num; i++) {
                System.out.println("A city chosen" + i);
                System.out.println(
                        driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i).getText());
                String city = driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i)
                        .getText();
                ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);",
                        driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i));
                ((JavascriptExecutor) driver).executeScript("window.scrollBy(0, -250)", "");
                Thread.sleep(1000);
                new Actions(driver)
                        .moveToElement(
                                driver.findElements(By.xpath("//div[@id='all-citys']/div/ul/li/a")).get(i))
                        .click().perform();
                driver.switchTo().window(driver.getWindowHandle());
                //                System.out.println(driver.findElement(By.xpath("//span[@class='today']/em")).getText());
                System.out.println(driver.findElement(By.xpath("//span[@class='today']")).getText());
                for (int j = 0; j < driver
                        .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']"))
                        .size(); j++) {
                    System.out.println(driver
                            .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']"))
                            .get(j).getText());
                    System.out.println(
                            driver.findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c2 red']"))
                                    .get(j).getText());
                    System.out.println(
                            driver.findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c3 gray']"))
                                    .get(j).getText());
                    BasicDBObject dbObject = new BasicDBObject();
                    dbObject.append("title", driver.findElement(By.xpath("//span[@class='today']")).getText())
                            .append("city", city)
                            .append("mov_cnname",
                                    driver.findElements(
                                            By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']"))
                                            .get(j).getText())
                            .append("boxoffice_rate", driver
                                    .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c2 red']"))
                                    .get(j).getText())
                            .append("visit_pershow", driver
                                    .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c3 gray']"))
                                    .get(j).getText());
                    dbCollection.insert(dbObject);
                }
                System.out.println("new city list to choose");
                new Actions(driver).moveToElement(driver.findElement(By.xpath("//*[@id='seat_city']"))).click()
                        .perform();
                driver.switchTo().window(driver.getWindowHandle());
                Thread.sleep(500);
            }
            driver.close();
            driver.quit();
            mongoClient.close();
        }
    };

    //DBDBManager
    DBManager manager = new BerkeleyDBManager("crawl");
    //Crawler?DBManagerExecutor
    Crawler crawler = new Crawler(manager, executor);
    crawler.addSeed("http://pf.maoyan.com/attend/rate");
    crawler.start(1);
}

From source file:cn.edu.hfut.dmic.webcollector.example.FirefoxSelenium4.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Executor executor = new Executor() {
        @Override// ww  w.ja v  a  2s . c  om
        public void execute(CrawlDatum datum, CrawlDatums next) throws Exception {
            MongoClient mongoClient = new MongoClient("localhost", 27017);
            // ?
            // DBCollection dbCollection = mongoClient.getDB("maoyan_crawler").getCollection("rankings_am"); 
            DB db = mongoClient.getDB("maoyan_crawler");
            // ?????
            Set<String> colls = db.getCollectionNames();
            for (String s : colls) {
                // Collection(?"")
                if (s.equals("rankings_am")) {
                    db.getCollection(s).drop();
                }
            }
            DBCollection dbCollection = db.getCollection("attend_rate");
            ProfilesIni pi = new ProfilesIni();
            FirefoxProfile profile = pi.getProfile("default");
            WebDriver driver = new FirefoxDriver(profile);
            driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS);
            //                driver.setJavascriptEnabled(false);
            driver.get(datum.getUrl());
            //                System.out.println(driver.getPageSource());
            List<WebElement> movie_name = driver
                    .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c1 lineDot']"));
            List<WebElement> boxoffice_rate = driver
                    .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c2 red']"));
            List<WebElement> visit_pershow = driver
                    .findElements(By.xpath("//div[@id='seat_table']//ul//li[@class='c3 gray']"));
            WebElement title = driver.findElement(By.xpath("//span[@class='today']/em"));
            WebElement title2 = driver.findElement(By.xpath("//span[@class='today']"));
            System.out.println(title.getText());
            System.out.println(title.getText());
            for (int i = 0; i < movie_name.size(); i++) {
                System.out.println(movie_name.get(i).getText());
                System.out.println(boxoffice_rate.get(i).getText());
                System.out.println(visit_pershow.get(i).getText());
                //                   BasicDBObject dbObject = new BasicDBObject();
                //                  dbObject.append("title", title).append("rank", amList.get(0)).append("mov_cnname", cn_name).append("mov_enname", en_name).append("toweek_rev", amList.get(2)).append("total_rev", amList.get(3)).append("val_week", amList.get(4));
                //                   dbCollection.insert(dbObject);
            }
            driver.quit();

        }
    };

    //DBDBManager
    DBManager manager = new BerkeleyDBManager("crawl");
    //Crawler?DBManagerExecutor
    Crawler crawler = new Crawler(manager, executor);
    crawler.addSeed("http://pf.maoyan.com/attend/rate");
    crawler.start(1);
}