Example usage for com.mongodb DBCursor size

List of usage examples for com.mongodb DBCursor size

Introduction

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

Prototype

public int size() 

Source Link

Document

Counts the number of objects matching the query this does take limit/skip into consideration

Usage

From source file:tweetList.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w w .  j a  va2  s. c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    String username = request.getParameter("username");

    try {
        MongoClient mongo = new MongoClient("localhost", 27017);
        DB db = mongo.getDB("test");
        System.out.println("Connection established");
        DBCollection User = db.getCollection("User");
        DBCollection Tweet = db.getCollection("Tweet");

        BasicDBObject query = new BasicDBObject("username", username);
        DBCursor curssc = User.find(query);
        // out.println(curssc.size());
        DBObject result = curssc.next();
        ArrayList<String> arr2 = new ArrayList();
        arr2 = (ArrayList<String>) result.get("tweet_id");

        ArrayList<String> e = new ArrayList();
        e = (ArrayList<String>) result.get("following_username");
        ArrayList<String> texts = new ArrayList();
        //out.println(e.size());
        //out.println(e.get(0));

        if (e.size() > 0 || arr2.size() > 0) {
            for (int i = e.size() - 1; i >= 0; i--) {
                BasicDBObject query2 = new BasicDBObject("username", e.get(i));
                DBCursor curssc2 = User.find(query2);
                if (curssc2.size() == 1) {
                    DBObject res = curssc2.next();
                    ArrayList<String> arr = new ArrayList();
                    arr = (ArrayList<String>) res.get("tweet_id");

                    texts.addAll(arr);

                }

            }
            texts.addAll(arr2);
            Collections.sort(texts);
            for (int j = texts.size() - 1; j >= 0; j--) {
                BasicDBObject query3 = new BasicDBObject("tweet_id", texts.get(j));
                DBCursor curssc3 = Tweet.find(query3);
                DBObject result1 = curssc3.next();
                response.getWriter().write(result1.get("username").toString());
                response.getWriter().write(":  ");
                response.getWriter().write(result1.get("tweet_text").toString());
                response.getWriter().write("\n");
            }

        } else {
            response.getWriter().write("No tweet");
        }

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

From source file:home.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww  w . j a  v a  2s  .c  o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    String username = request.getParameter("username");

    String tweet = request.getParameter("tweet");
    try {
        MongoClient mongo = new MongoClient("localhost", 27017);
        DB db = mongo.getDB("test");
        System.out.println("Connection established");
        DBCollection User = db.getCollection("User");
        DBCollection Tweet = db.getCollection("Tweet");

        DBCursor cursor = Tweet.find();
        int count = 0;
        if (cursor.size() < 1) {
            count = 1;
        } else {
            count = cursor.size() + 1;

        }
        BasicDBObject document = new BasicDBObject();
        document.put("tweet_id", count);
        document.put("username", username);
        document.put("tweet_text", tweet);
        document.put("date", new Date());
        Tweet.insert(document);

        ArrayList<Integer> tweet_id = new ArrayList();
        tweet_id.add(count);
        DBObject searchObject = new BasicDBObject();
        searchObject.put("username", username);

        DBObject modifiedObject = new BasicDBObject();
        modifiedObject.put("$push", new BasicDBObject().append("tweet_id", count));
        User.update(searchObject, modifiedObject);

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

From source file:mail.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    int success = 0;
    String id = request.getParameter("email");
    System.out.println(id);/* w w w.j av a 2 s  .c  o m*/
    //String id="anjaliverma25792@gmail.com";
    MongoClient mongo = new MongoClient();
    DB db = mongo.getDB("WebDB");
    DBCollection table = db.getCollection("User");
    Document d = new Document();
    d.put("Email", id);
    DBObject ob = new BasicDBObject(d);
    DBCursor cur = table.find(ob);
    System.out.println(cur.size());
    System.out.println("Above value");
    String user = null;
    if (cur.hasNext()) {
        success = 1;
        cur.next();
        DBObject temp = cur.curr();
        String pass = (String) temp.get("Password");

        HttpSession session = request.getSession();
        user = (String) temp.get("Name");

        final String username = "nature.lover.ritika@gmail.com";
        final String password = "ritika7vision";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session sess = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            Message message = new MimeMessage(sess);
            message.setFrom(new InternetAddress("papertree.official@gmail.com"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(id)); //retrive email id from forgot your password form.
            message.setSubject("PaperTree: Password Reset");
            message.setText("Dear, " + user + ". Your password is " + pass
                    + ". \n\n Directly LOGIN And START READING...");

            Transport.send(message);

            // Mongo DB connectivity LEFT 

            //                        response.sendRedirect("success.jsp");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

    }
    if (success == 1) {
        response.sendRedirect("success.jsp?success=yes");

    } else {
        response.sendRedirect("success.jsp?success=no");

    }
}

From source file:app.modules.SignIn.model.DAO_Login.java

/**
 * Compara el nombre de usuario con el de todos los clientes de la base de datos, cuando encuentra una coincidencia
 * compara la contrasea introducida con la de la base de datos, cuando ambos datos coinciden devuelve true y
 * rellena el perfil del usuario/*from   w ww.  j a  v a 2s  . c om*/
 * @return login True si se ha logrado iniciar sesin
 */
public static boolean SignInClient() {
    boolean login = false;
    DBCursor cursor = null;
    client c = new client();
    try {
        cursor = singleton_global.collection.find(new BasicDBObject().append("user", addusername.getText()));
        if (cursor.count() != 0) {
            for (int i = 0; i < cursor.size(); i++) {
                BasicDBObject document = (BasicDBObject) cursor.next();
                c = c.BBDD_to_client(document);
                fecha aux = new fecha();
                if (c.getPass().equals(addpass.getText())) {
                    new client_controller(new clientnew_view(), 2).Iniciar(2);
                    adddnic.setText(c.getDni());
                    caddname.setText(c.getName());
                    caddsurname.setText(c.getSubname());
                    caddmobile.setText(c.getMobile());
                    caddemail.setText(c.getEmail());
                    cadddatebirthday.setCalendar(aux.stringtocalendar(c.getDate_birthday()));
                    caddnameuser.setText(c.getUser());
                    caddpassword.setText(c.getPass());
                    caddavatar.setText(c.getAvatar());
                    cadd_status.setSelectedItem(c.getState());
                    caddreg.setCalendar(aux.stringtocalendar(c.getUp_date()));
                    caddshopping.setText(Float.toString(c.getShopping()));
                    caddpremium.setSelectedItem(c.getPremium());
                    caddtype.setText(c.getClient_type());
                    login = true;
                    if ("Premium".equals(c.getPremium())) {
                        cadddesc.setText("10%");
                    } else {
                        cadddesc.setText("0%");
                    }
                    caddyearsservice.setText(Integer.toString(
                            aux.restafechas(aux.stringtocalendar(c.getUp_date()), aux.fechasystem(), "years")));
                }
            }
        } else {
            System.out.println("NOT DATA");
        }
    } catch (Exception e) {
        if (cursor != null) {
            cursor.close();
        }
    }
    return login;
}

From source file:app.modules.users.client.model.DAO.DAO_client.java

/**
 * Comprueba que todos los datos sean correctos y los guarda sobre los antiguos
 * @return True si se ha modificado correctamente
*///from   ww  w . j  ava 2  s.  c o  m
public static boolean saveeditclient() {
    boolean val = false;
    if (pidedni() && pidenombre() && pideapellidos() && pidefechanacimiento() && pidetelefono() && pideemail()
            && pideusuario() && pidecontrasenya() && pidefecharegistro() && pidecompras() && pidetipo()) {
        if ("admin".equals(singleton_global.type)) {
            String dni = clientnew_view.adddnic.getText();
            String name = clientnew_view.caddname.getText();
            String surname = clientnew_view.caddsurname.getText();
            String mobile = clientnew_view.caddmobile.getText();
            String email = clientnew_view.caddemail.getText();
            fecha aux = new fecha();
            String datebirthday = aux.calendartostring(clientnew_view.cadddatebirthday.getCalendar(), 0);
            String nameuser = clientnew_view.caddnameuser.getText();
            String passwd = clientnew_view.caddpassword.getText();
            String avatar = clientnew_view.caddavatar.getText();
            String status = clientnew_view.cadd_status.getSelectedItem().toString();
            String update = aux.calendartostring(clientnew_view.caddreg.getCalendar(), 0);
            float shopping = Float.parseFloat(clientnew_view.caddshopping.getText());
            String premium = clientnew_view.caddpremium.getSelectedItem().toString();
            String type = clientnew_view.caddtype.getText();
            int inicio = (pagina.currentPageIndex - 1) * pagina.itemsPerPage;
            selectedcli = TABLA.getSelectedRow();
            int selected1 = inicio + selectedcli;
            BLL_client.UpdateClientMongo(singleton_client.client.getClient(selected1).getDni());
            singleton_client.client.getClient(selected1).setDni(dni);
            singleton_client.client.getClient(selected1).setName(name);
            singleton_client.client.getClient(selected1).setSubname(surname);
            singleton_client.client.getClient(selected1).setMobile(mobile);
            singleton_client.client.getClient(selected1).setEmail(email);
            singleton_client.client.getClient(selected1).setDate_birthday(datebirthday);
            singleton_client.client.getClient(selected1).setUser(nameuser);
            singleton_client.client.getClient(selected1).setPass(passwd);
            singleton_client.client.getClient(selected1).setAvatar(avatar);
            singleton_client.client.getClient(selected1).setState(status);
            singleton_client.client.getClient(selected1).setUp_date(update);
            singleton_client.client.getClient(selected1).setShopping(shopping);
            singleton_client.client.getClient(selected1).setPremium(premium);
            singleton_client.client.getClient(selected1).setClient_type(type);

            val = true;
        } else {
            client c = new client();
            DBCursor cursor = singleton_global.collection
                    .find(new BasicDBObject().append("dni", adddnic.getText()));
            for (int i = 0; i < cursor.size(); i++) {
                BasicDBObject document = (BasicDBObject) cursor.next();
                c = c.BBDD_to_client(document);
                if (c.getDni().equals(adddnic.getText())) {
                    c.setDni(clientnew_view.adddnic.getText());
                    c.setName(clientnew_view.caddname.getText());
                    c.setSubname(clientnew_view.caddsurname.getText());
                    c.setMobile(clientnew_view.caddmobile.getText());
                    c.setEmail(clientnew_view.caddemail.getText());
                    fecha aux = new fecha();
                    c.setDate_birthday(aux.calendartostring(clientnew_view.cadddatebirthday.getCalendar(), 0));
                    c.setUser(clientnew_view.caddnameuser.getText());
                    c.setPass(clientnew_view.caddpassword.getText());
                    c.setAvatar(clientnew_view.caddavatar.getText());
                    c.setState(clientnew_view.cadd_status.getSelectedItem().toString());
                    c.setUp_date(aux.calendartostring(clientnew_view.caddreg.getCalendar(), 0));
                    c.setShopping(Float.parseFloat(clientnew_view.caddshopping.getText()));
                    c.setPremium(clientnew_view.caddpremium.getSelectedItem().toString());
                    c.setClient_type(clientnew_view.caddtype.getText());
                    BLL_client.UpdateClientMongo(c.getDni());
                }
            }
            val = true;
        }
    }
    return val;
}

From source file:app.modules.users.client.model.DAO.DAO_Mongo.java

/**
 * Lee todos los clientes de la bbdd para mostrarlos en nuestra app
 *//*from ww w  . j  av a 2 s .  c  o  m*/
public static void read_client() {
    DBCursor cursor = null;
    client c = new client();
    try {
        cursor = singleton_global.collection.find();
        if (cursor.count() != 0) {
            for (int i = 0; i < cursor.size(); i++) {
                BasicDBObject document = (BasicDBObject) cursor.next();
                c = c.BBDD_to_client(document);
                client j = new client(c.getDni(), c.getName(), c.getSubname(), c.getMobile(), c.getEmail(),
                        c.getDate_birthday(), c.getUser(), c.getPass(), c.getAvatar(), c.getState(),
                        c.getUp_date(), c.getShopping(), c.getPremium(), c.getClient_type());
                singleton_client.client.AddClient(j);
            }
        } else {
            System.out.println("NOT DATA");
        }
    } catch (Exception e) {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:application.modules.client.model.DAO.daoC.java

public static void retrieve_admins() {
    //DBCollection dbCollection = db.getCollection(tableName);
    client c = new client();
    DBCursor cur = collection.find();
    for (int i = 0; i < cur.size(); i++) {
        BasicDBObject document = (BasicDBObject) cur.next();
        c = c.DB_to_client(document);//  w  w w .j ava2  s  . com
        client d = new client(c.getDni(), c.getName(), c.getSubname(), c.getPhone_number(), c.getEmail(),
                c.getUser(), c.getPass(), c.getAvatar(), c.getState(), c.getDate_birthday(),
                c.getDischarge_date(), c.getClient_type(), c.getShopping(), c.isPremium());
        singleton.clients.getClients().add(d);
    }
}

From source file:br.bireme.scl.TabulateField.java

License:Open Source License

public static void tabulate(final String host, final int port, final String user, final String password,
        final String database, final String collection, final String path) throws UnknownHostException {
    if (host == null) {
        throw new NullPointerException("host");
    }// w w w  .  ja  v a 2  s. com
    if (port <= 0) {
        throw new IllegalArgumentException("port <= 0");
    }
    if (collection == null) {
        throw new NullPointerException("collection");
    }
    if (path == null) {
        throw new NullPointerException("path");
    }
    final MongoClient mongoClient = new MongoClient(host, port);
    final DB db = mongoClient.getDB(database);
    if (user != null) {
        final boolean auth = db.authenticate(user, password.toCharArray());
        if (!auth) {
            throw new IllegalArgumentException("invalid user/password");
        }
    }
    final DBCollection coll = db.getCollection(collection);
    final DBCursor cursor = coll.find();
    final TreeMap<String, Integer> map1 = new TreeMap<String, Integer>();
    final TreeMap<Integer, String> map2 = new TreeMap<Integer, String>();
    final int ADD_VALUE = 99999999;
    final int size = cursor.size();

    while (cursor.hasNext()) {
        final BasicDBObject doc = (BasicDBObject) cursor.next();
        final String key = getValue(doc, path);

        if (key != null) {
            Integer val = map1.get(key);
            if (val == null) {
                val = 0;
            }
            val += 1;
            map1.put(key, val);
        }
    }
    cursor.close();
    for (Map.Entry<String, Integer> entry : map1.entrySet()) {
        map2.put(ADD_VALUE - entry.getValue(), entry.getKey());
    }

    System.out.println("Total # of docs: " + size + "\n");

    int idx = 0;
    for (Map.Entry<Integer, String> entry : map2.entrySet()) {
        final int val = ADD_VALUE - entry.getKey();
        final String percent = String.format("%.2f", ((float) val / size) * 100);
        System.out.println((++idx) + ") " + entry.getValue() + ": " + val + " (" + percent + "%)");
    }
}

From source file:br.bireme.scl.UndoUpdate.java

License:Open Source License

private static void undo(final String host, final int port, final String database, final String fromDate,
        final String docId) throws UnknownHostException, ParseException {
    assert host != null;
    assert port > 0;
    assert database != null;
    assert (fromDate != null || docId != null);

    final MongoClient client = new MongoClient(host, port);
    final DB db = client.getDB(database);
    final DBCollection from_coll = db.getCollection(HISTORY_COL);
    final DBCollection to_coll = db.getCollection(BROKEN_LINKS_COL);
    final String prefix = ELEM_LST_FIELD + ".0.";
    final BasicDBObject query;

    if (fromDate == null) {
        query = new BasicDBObject("_id", docId);
    } else {/*from   w w w  .j  a  v  a2s .  c om*/
        final SimpleDateFormat simple = new SimpleDateFormat(
                "yyyyMMdd" + (fromDate.contains(":") ? "-HH:mm:ss" : ""));
        final Date fDate = simple.parse(fromDate);
        query = new BasicDBObject(prefix + LAST_UPDATE_FIELD, new BasicDBObject("$gte", fDate));
    }
    final DBCursor cursor = from_coll.find(query);
    int total = 0;
    int reverted = 0;

    System.out.println("host=" + host);
    System.out.println("port=" + port);
    System.out.println("database=" + database);
    if (fromDate == null) {
        System.out.println("doc id=" + docId);
    } else {
        System.out.println("from date=" + fromDate);
    }
    System.out.println("found=" + cursor.size());

    while (cursor.hasNext()) {
        final BasicDBObject doc_from = (BasicDBObject) cursor.next();
        final BasicDBObject doc_to = new BasicDBObject(doc_from);
        final String id = doc_from.getString(ID_FIELD);
        final BasicDBList list = (BasicDBList) doc_from.get(ELEM_LST_FIELD);
        final BasicDBObject elem = (BasicDBObject) list.get(0);
        final Date date = elem.getDate(LAST_UPDATE_FIELD);

        doc_to.put(LAST_UPDATE_FIELD, date);
        doc_to.put(BROKEN_URL_FIELD, elem.getString(BROKEN_URL_FIELD));
        doc_to.put(MSG_FIELD, elem.getString(MSG_FIELD));
        doc_to.put(CENTER_FIELD, elem.get(CENTER_FIELD));
        doc_to.removeField(ELEM_LST_FIELD);

        final WriteResult wr = to_coll.save(doc_to, WriteConcern.ACKNOWLEDGED);
        if (wr.getCachedLastError().ok()) {
            final WriteResult wr2 = from_coll.remove(doc_from, WriteConcern.ACKNOWLEDGED);
            if (wr2.getCachedLastError().ok()) {
                reverted++;
                System.out.println("+++id=" + id + " date=" + date);
            } else {
                System.err.println("Document[" + id + "] delete error.");
            }
        } else {
            System.err.println("Document[" + id + "] update error.");
        }
        total++;
    }
    cursor.close();

    System.out.println("total/undo: " + total + "/" + reverted);
}

From source file:br.bireme.tmp.AddPrettyField.java

License:Open Source License

private static void add(final String mongo_host, final int mongo_port, final String mongo_db,
        final String mongo_col) throws UnknownHostException {
    assert mongo_host != null;
    assert mongo_port > 0;
    assert mongo_db != null;
    assert mongo_col != null;

    final MongoClient client = new MongoClient(mongo_host, mongo_port);
    final DB db = client.getDB(mongo_db);
    final DBCollection coll = db.getCollection(HISTORY_COL);
    final DBCursor cursor = coll.find();
    int total = 0;

    System.out.println("host=" + mongo_host);
    System.out.println("port=" + mongo_port);
    System.out.println("database=" + mongo_db);
    System.out.println("collection=" + mongo_col);
    System.out.println("num of documents=" + cursor.size());

    while (cursor.hasNext()) {
        final BasicDBObject doc1 = (BasicDBObject) cursor.next();
        final BasicDBList list = (BasicDBList) doc1.get(ELEM_LST_FIELD);

        for (Object obj : list) {
            final BasicDBObject doc2 = (BasicDBObject) obj;
            if (!doc2.containsField(PRETTY_BROKEN_URL_FIELD)) {
                final String burl = doc2.getString(BROKEN_URL_FIELD);
                try {
                    final String pburl = EncDecUrl.decodeUrl(burl);
                    doc2.append(PRETTY_BROKEN_URL_FIELD, pburl);

                    final WriteResult wr = coll.save(doc1, WriteConcern.ACKNOWLEDGED);
                    if (wr.getCachedLastError().ok()) {
                        total++;/*from w  ww . j  a v  a 2s  . co m*/
                    } else {
                        System.err.println("Document[" + doc1.getString("_id") + "] update error.");
                    }
                } catch (IOException ioe) {
                    System.err.println("Document[" + doc1.getString("_id") + "] bad encode conversion"
                            + " url=[" + burl + "]");
                }
            }
        }
    }
    cursor.close();
    System.out.println("num of added fields: " + total);
}