Example usage for com.mongodb DBCursor hasNext

List of usage examples for com.mongodb DBCursor hasNext

Introduction

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

Prototype

@Override
public boolean hasNext() 

Source Link

Document

Checks if there is another object available.

Usage

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);//  ww  w  . j a v  a2 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:emp_detail_table.java

public void display_table() {
    try {//from   w ww  .  j  av a2  s  .c o m
        MongoClient mc = new MongoClient("localhost", 27017);
        DB db = mc.getDB("parking_system");
        DBCollection collection = db.getCollection("employee_info");

        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();

        DBCursor cursor = collection.find();

        jTable1.setShowGrid(true);
        while (cursor.hasNext()) {

            DBObject temp = cursor.next();
            model.addRow(new Object[] { temp.get("name"), temp.get("_id"), temp.get("password"),
                    temp.get("mobileno") });
        }

        //            else if(input.equalsIgnoreCase("")==true)
        //                JOptionPane.showMessageDialog(rootPane, "Error:: Enter a product name");
        //            else
        //              JOptionPane.showMessageDialog(rootPane, "Product not found");  
        //    
    } catch (UnknownHostException e) {
        e.getMessage();

    }
}

From source file:loc.java

public void loc() {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB dbBusiness = mongoClient.getDB("business");
    DBCollection collBusiness = dbBusiness.getCollection("business");
    List<DBObject> categoryIdList = new ArrayList<DBObject>();
    DBCursor cursorForBusiness = collBusiness.find();
    while (cursorForBusiness.hasNext()) {
        categoryIdList.add(cursorForBusiness.next());
    }//from w  w  w.jav  a 2 s  . co  m
    for (DBObject s : categoryIdList) {
        System.out.println(s.get("business_id").toString());
        System.out.println(s.get("longitude").toString());
        System.out.println(s.get("latitude").toString());

        BasicDBObject newDocument = new BasicDBObject();
        BasicDBList addFields = new BasicDBList();
        addFields.add(s.get("longitude").toString());
        addFields.add(s.get("latitude").toString());
        newDocument.append("$set", new BasicDBObject().append("loc", addFields));

        BasicDBObject searchQuery = new BasicDBObject().append("business_id", s.get("business_id").toString());

        collBusiness.update(searchQuery, newDocument);
    }

}

From source file:Ventana.java

public void consultar() {
    DBCursor cursor = coleccion.find();

    jFrame1.setVisible(true);/*  w  w  w.  ja va2s .c  o m*/
    jFrame1.setBounds(463, 0, 850, 650);

    jTextArea1.setText(" ");
    while (cursor.hasNext()) {
        jTextArea1.setText(jTextArea1.getText() + cursor.next() + "\n");

    }

}

From source file:PanBorrar.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    // TODO add your handling code here:
    int num = 1;//from www . j a  v  a2  s .co m
    DBCursor cursor = tabla.find();
    DefaultListModel model = new DefaultListModel();

    while (cursor.hasNext()) {
        BSONObject obj = cursor.next();

        // Obtener variables del JSON
        try {

            String name = (String) obj.get("Nombre");
            String ap = (String) obj.get("ApPaterno");
            String am = (String) obj.get("ApMaterno");
            String fechaNac = (String) obj.get("FechaNac");
            int edad = (int) obj.get("Edad");
            String sex = (String) obj.get("Sexo");
            String mat = (String) obj.get("Matricula");
            int semestre = (int) obj.get("Semestre");
            String carrera = (String) obj.get("Carrera");

            // Imprimir todo
            /*Mostrar.setText(Mostrar.getText() + "\n" + name +  " " + ap + " " + am + " " 
                + fechaNac + " " + edad + " " + sex + " " + mat + " " + semestre + 
                " " + carrera);*/

            model.addElement(num + "  " + name + " " + ap + " " + am + " " + fechaNac + " " + edad + " " + sex
                    + " " + mat + " " + semestre + " " + carrera);
            num++;

        } catch (Exception ex) {
            System.out.println("objeto no completo");
        }
        Lista.setModel(model);
    }
}

From source file:NewJFrame.java

@Override
public void actionPerformed(ActionEvent ae) {
    // TODO Auto-generated method stub
    add(jLabel5);//from w  w  w  .  ja  v a 2 s  .  c o m
    String user = jTextField1.getText().toString();
    @SuppressWarnings("deprecation")
    String pass = jPassword1.getText().toString();
    jLabel5.setText("");

    if (ae.getSource() == jButton1) {
        if ((String) jComboBox1.getSelectedItem() == "Admin") {
            if (user.equals("admin") && pass.equals("admin123")) {
                this.setVisible(false);
                new Admin().setVisible(true);
            } else {
                jLabel5.setFont(new java.awt.Font("SansSerif", 3, 14)); // NOI18N
                jLabel5.setForeground(new java.awt.Color(25, 25, 112));
                jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
                jLabel5.setText("Login Not Successful ");
                jTextField1.setText("");
                jPassword1.setText("");
                jLabel5.setBounds(120, 245, 170, 50);
            }
        } else if ((String) jComboBox1.getSelectedItem() == "Trainer") {
            try {
                MongoClient mongo = new MongoClient("localhost", 27017);
                DB db = mongo.getDB("Gym");
                DBCollection Gym_Collection = db.getCollection("trainer");
                BasicDBObject fields = new BasicDBObject("Username", user).append("Password", pass);
                String s;
                DBCursor cursor1 = Gym_Collection.find(fields);
                if (cursor1.hasNext()) {
                    cursor1.next();
                    s = cursor1.curr().get("First_Name").toString();
                    new Receptionist(s);
                    this.setVisible(false);
                    new Receptionist().setVisible(true);
                } else {
                    jLabel5.setFont(new java.awt.Font("SansSerif", 3, 14)); // NOI18N
                    jLabel5.setForeground(new java.awt.Color(25, 25, 112));
                    jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
                    jLabel5.setText("Login Not Successful ");
                    jTextField1.setText("");
                    jPassword1.setText("");
                    jLabel5.setBounds(120, 245, 170, 50);
                }
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
}

From source file:RestrictedService.java

License:Open Source License

/**
 * @param textToAnalize/*from  w w  w .  j a va  2  s  .co m*/
 * @param collectionName
 * @return
 * @throws Exception
 */
public static HttpEntity callANEW(String textToAnalize, String collectionName) throws Exception {
    String[] wordsInText = (textToAnalize + " ").split(" ");
    String wordAndValues[][] = new String[wordsInText.length][5]; //initialize the wordAndValues
    int position = 0; //Aux variable to see the position of each word inside the document
    String polarityAndValue[] = new String[2];

    DBCollection coll = db.getCollection(collectionName);
    Double positive = 0.0;
    Double negative = 0.0;
    for (int i = 0; i < wordsInText.length; i++) { //For each word
        wordAndValues[i][0] = wordsInText[i]; //We save the word
        wordAndValues[i][1] = Integer.toString(position); //add its initial 
        position += (wordsInText[i].length() - 1);
        wordAndValues[i][2] = Integer.toString(position);//and final position
        position += 2; //This is where the next word starts
        //We check if this word has a positive or negative annotation and set its value and polarity.
        BasicDBObject query = new BasicDBObject("Word", wordsInText[i].toLowerCase());
        DBCursor cursor = coll.find(query);
        Double value = 5.0;
        try {
            while (cursor.hasNext()) {
                value = (Double) cursor.next().get("ValMn");
            }
        } finally {
            cursor.close();
        }
        if (value > 5) {
            wordAndValues[i][3] = "1.0";
            wordAndValues[i][4] = "Positive";
            positive++;
        } else if (value < 5) {
            wordAndValues[i][3] = "-1.0";
            wordAndValues[i][4] = "Negative";
            negative++;
        } else {
            wordAndValues[i][3] = "0.0";
            wordAndValues[i][4] = "Neutral";
        }
        polarityAndValue[0] = Double.toString(0);
        if ((positive + negative) != 0) {
            polarityAndValue[0] = Double.toString((positive - negative) / (positive + negative));
        }
        if (new Double(polarityAndValue[0]) > 0) {
            polarityAndValue[1] = "Positive";
        } else if (new Double(polarityAndValue[0]) < 0) {
            polarityAndValue[1] = "Negative";
        } else {
            polarityAndValue[1] = "Neutral";
        }
    }

    return callMarl(textToAnalize, wordAndValues, polarityAndValue);
}

From source file:gMIRC_server.java

public static void cleaner() {
    try {//from   w ww. jav  a 2  s  . c o  m
        boolean hard_clean = false;
        MongoClient mongoClient = new MongoClient();
        DB db = mongoClient.getDB("mirc");
        DBCollection coll = db.getCollection("activeUser");

        DBCursor cursor = coll.find();
        try {
            Date now = new Date();
            long timestamp_now = now.getTime();
            long treshold = timestamp_now - (1000 * 60 * 5); //5 minutes
            while (cursor.hasNext()) {
                hard_clean = true;
                BasicDBObject temp = (BasicDBObject) cursor.next();
                Date time_temp = (Date) temp.get("timestamp");
                long timestamp_temp = time_temp.getTime();
                if (timestamp_temp < treshold) {
                    String target = temp.getString("username");
                    gMIRC_handler.SoftDelete(target);
                }
            }
            HardClean();
        } finally {
            cursor.close();
        }

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

From source file:gMIRC_server.java

public static void HardClean() {
    try {//ww w.  j  a  v  a 2 s  . c  om
        MongoClient mongoClient = new MongoClient();
        DB db = mongoClient.getDB("mirc");
        DBCollection coll[] = new DBCollection[4];
        coll[0] = db.getCollection("channelCollection");
        coll[1] = db.getCollection("inbox");
        coll[2] = db.getCollection("activeUser");
        coll[3] = db.getCollection("passiveUser");

        DBCursor cursor = coll[3].find();

        try {
            while (cursor.hasNext()) {
                BasicDBObject temp = (BasicDBObject) cursor.next();
                String username = temp.getString("username");
                BasicDBObject query = new BasicDBObject("username", username);
                System.out.println("cleaning " + username);
                for (int i = 0; i < 4; i++) {
                    DBCursor cursor2 = coll[i].find(query);

                    try {
                        while (cursor2.hasNext()) {
                            DBObject temp2 = cursor2.next();
                            coll[i].remove(temp2);
                        }
                    } finally {
                        cursor2.close();
                    }
                }
            }
        } finally {
            cursor.close();
        }

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

From source file:Proj.java

public static void main(String[] args) {
    System.out.println("Enter your choice do you want to work with 1.postgre 2.Redis 3.Mongodb");
    InputStreamReader input = new InputStreamReader(System.in);
    BufferedReader data = new BufferedReader(input);
    String choice = null;/* w  w  w. j a va 2 s .  c o m*/
    try {
        choice = data.readLine();
    } catch (Exception Eex) {
        System.out.println(Eex.getMessage());
    }

    // loading data from the CSV file 

    CsvReader Details = null;

    try {
        Details = new CsvReader("folder\\dataset.csv");
    } catch (FileNotFoundException EB) {
        System.out.println(EB.getMessage());
    }
    int ColumnCount = 3;
    int RowCount = 100;
    int k = 0;

    try {
        Details = new CsvReader("folder\\dataset.csv");
    } catch (FileNotFoundException E) {
        System.out.println(E.getMessage());
    }

    String[][] Dataarray = new String[RowCount][ColumnCount];
    try {
        while (Details.readRecord()) {
            String v;
            String[] x;
            v = Details.getRawRecord();
            x = v.split(",");
            for (int j = 0; j < ColumnCount; j++) {
                String value = null;
                int z = j;
                value = x[z];
                try {
                    Dataarray[k][j] = value;
                } catch (Exception E) {
                    System.out.println(E.getMessage());
                }
                // System.out.println(Dataarray[iloop][j]);
            }
            k = k + 1;
        }
    } catch (IOException Em) {
        System.out.println(Em.getMessage());
    }

    Details.close();

    // connection to Database 
    switch (choice) {
    // postgre code goes here 
    case "1":

        Connection Conn = null;
        Statement Stmt = null;
        URI dbUri = null;
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader out = new BufferedReader(in);
        try {
            Class.forName("org.postgresql.Driver");
        } catch (Exception E1) {
            System.out.println(E1.getMessage());
        }
        String username = "ejepndckpvzvrj";
        String password = "uBq0RRYh47bRt_vxrZZDC14ois";
        String dbUrl = "postgres://ejepndckpvzvrj:uBq0RRYh47bRt_vxrZZDC14ois@ec2-54-83-53-120.compute-1.amazonaws.com:5432/d1b2vsoh5fhl6n";

        // now update data in the postgress Database 

        for (int i = 0; i < RowCount; i++) {
            try {

                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = "insert into Details (first_name,last_name,county) values (' "
                        + Dataarray[i][0] + " ',' " + Dataarray[i][1] + " ',' " + Dataarray[i][2] + " ')";
                Stmt.executeUpdate(Connection_String);

            } catch (SQLException E4) {
                System.out.println(E4.getMessage());
            }
        }

        // Quering with the Database 

        System.out.println("1. Display Data ");
        System.out.println("2. Select data based on Other attributes e.g Name");
        System.out.println("Enter your Choice ");
        try {
            choice = out.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        switch (choice) {
        case "1":
            try {
                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = " Select * from Details;";
                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    System.out.println("First name " + objRS.getInt("First_name"));
                    System.out.println("Last name " + objRS.getString("Last_name"));
                    System.out.println("COunty " + objRS.getString("County"));

                }

            } catch (Exception E2) {
                System.out.println(E2.getMessage());
            }

            break;

        case "2":
            String Name = null;
            System.out.println("Enter First Name to find the record");
            InputStreamReader obj = new InputStreamReader(System.in);
            BufferedReader bur = new BufferedReader(obj);

            try {
                Name = (bur.readLine()).toString();
            } catch (IOException E) {
                System.out.println(E.getMessage());
            }
            try {
                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = " Select * from Details Distinct where Name=" + "'" + Name + "'"
                        + ";";

                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    System.out.println("First name: " + objRS.getInt("First_name"));
                    System.out.println("Last name " + objRS.getString("Last_name"));
                    System.out.println("County " + objRS.getString("County"));
                }

            } catch (Exception E2) {
                System.out.println(E2.getMessage());
            }
            break;
        }
        try {
            Conn.close();
        } catch (SQLException E6) {
            System.out.println(E6.getMessage());
        }
        break;

    // Redis code goes here 

    case "2":
        int Length = 0;
        String ID = null;
        Length = 100;

        // Connection to Redis 
        Jedis jedis = new Jedis("pub-redis-15228.us-east-1-2.1.ec2.garantiadata.com", 15228);
        jedis.auth("redis-cse-axt3229-2-7825704");
        System.out.println("Connected to Redis");

        // Storing values in the database 

        System.out.println("Storing values in the Database  ");

        for (int i = 0; i < Length; i++) {

            int j = i + 1;
            jedis.hset("DEtail:" + j, "First_name", Dataarray[i][0]);
            jedis.hset("Detail:" + j, "Last_name ", Dataarray[i][1]);
            jedis.hset("Detail:" + j, "Count", Dataarray[i][2]);

        }

        System.out.println("Search by First Name");

        InputStreamReader inob = new InputStreamReader(System.in);
        BufferedReader buob = new BufferedReader(inob);

        String ID2 = null;
        try {
            ID2 = buob.readLine();
        } catch (IOException E3) {
            System.out.println(E3.getMessage());
        }
        for (int i = 0; i < 100; i++) {
            Map<String, String> properties3 = jedis.hgetAll("Deatails:" + i);
            for (Map.Entry<String, String> entry : properties3.entrySet()) {
                String value = entry.getValue();
                if (entry.getValue().equals(ID2)) {
                    System.out.println(jedis.hget("Detials:" + i, "First_name"));
                }

            }
        }

        //for (Map.Entry<String, String> entry : properties1.entrySet())
        //{
        //System.out.println(entry.getKey() + "---" + entry.getValue());
        // }

        // mongo db code goes here 

    case "3":
        MongoClient mongo = new MongoClient(
                new MongoClientURI("mongodb://ank:123@ds055574.mongolab.com:55574/heroku_h7mxqs7l"));
        DB db;
        db = mongo.getDB("heroku_h7mxqs7l");
        // storing values in the database 
        for (int i = 0; i < 100; i++) {
            BasicDBObject document = new BasicDBObject();
            document.put("_id", i + 1);
            document.put("First_name", Dataarray[i][0]);
            document.put("Last_name", Dataarray[i][1]);
            document.put("County", Dataarray[i][2]);
            db.getCollection("DetailsRaw").insert(document);

        }
        System.out.println("Search by Name");

        InputStreamReader inobj = new InputStreamReader(System.in);
        BufferedReader objname = new BufferedReader(inobj);
        String Name = null;
        try {
            Name = objname.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        BasicDBObject inQuery1 = new BasicDBObject();
        inQuery1.put("first Name", Name);
        DBCursor cursor1 = db.getCollection("DetailsRaw").find(inQuery1);
        while (cursor1.hasNext()) {
            // System.out.println(cursor.next());
            System.out.println(cursor1.next());
        }

    }
}