Example usage for com.mongodb DBCollection insert

List of usage examples for com.mongodb DBCollection insert

Introduction

In this page you can find the example usage for com.mongodb DBCollection insert.

Prototype

public WriteResult insert(final List<? extends DBObject> documents) 

Source Link

Document

Insert documents into a collection.

Usage

From source file:AppletECF.java

public String salvarCupomFiscal() {
    MongoClient mongo = null;/*from   w  ww. j a  v a  2 s.c om*/
    try {
        mongo = new MongoClient("192.168.252.10", 27017);
    } catch (Exception ex) {
    }

    try {
        if (mongo == null) { // se nao achou o mongo db no servidor salva local
            mongo = new MongoClient("localhost", 27017);
        }
    } catch (Exception ex) {
        return "Nao foi possivel conectar a base local! Verifique se o MongoDB esta instalado no seu computador. Erro: "
                + ex.getMessage();
    }

    DB db = mongo.getDB("cupons_db");
    DBCollection cupons = db.getCollection("cupons");

    cupomFiscal.put("itens", new ArrayList<BasicDBObject>());
    cupons.insert(cupomFiscal);
    return "";
}

From source file:AddRecord.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    int flag = 0;
    try {/*w w  w.jav a 2s.  c  o  m*/
        // TODO add your handling code here:
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        db = mongoClient.getDB("Classic_Hangman");
        System.out.println("Connected to database successfully!!");
        BasicDBObject d = new BasicDBObject();
        String movie = jTextField1.getText();
        //String genre = jTextField2.getText();
        String director = jTextField3.getText();
        for (int i = 0; i < director.length(); i++) {
            if (Character.isDigit(director.charAt(i))) {
                JOptionPane.showMessageDialog(this, "Invalid director entry!");
                flag = 1;
                break;
            }
        }
        if (movie.equals("") || genre.equals("")) {
            JOptionPane.showMessageDialog(this, "Empty Field!");
        } else {
            if (flag != 1) {
                DBCollection coll = db.getCollection("movies");
                DBCollection coll1 = db.getCollection("counter");
                System.out.println("Collection selected successfully");
                BasicDBObject query = new BasicDBObject();
                DBObject c = coll1.findOne();
                count = ((Number) c.get("count")).intValue();
                System.out.println("Count = " + count);
                //count = (int)c.get("count");
                BasicDBObject doc = new BasicDBObject("id", count + 1).append("name", movie)
                        .append("director", director).append("genre", genre);
                coll.insert(doc);
                System.out.println("Document inserted successfully");
                count++;
                /*DBCursor cursor = coll.find();
                int i=1;
                while (cursor.hasNext()) { 
                    System.out.println("Inserted Document: "+i); 
                    System.out.println(cursor.next()); 
                    i++;
                }*/
                //DBCollection coll1 = db.getCollection("counter");
                //System.out.println("Collection selected successfully");
                coll1.remove(new BasicDBObject());
                BasicDBObject doc1 = new BasicDBObject("count", count);
                coll1.insert(doc1);
                /*cursor = coll.find();
                BasicDBObject newDocument = new BasicDBObject();
                System.out.println(count);
                newDocument.put("count", count);
                BasicDBObject searchQuery = new BasicDBObject().append("count", count);
                coll.update(searchQuery, newDocument);*/
                jTextField1.setText("");
                //jTextField2.setText("");
                jTextField3.setText("");
                JOptionPane.showMessageDialog(this, "Record added!");
            }
        }
    } catch (UnknownHostException ex) {
        //Logger.getLogger(AdminLogin.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:add_user.java

/**
 * Processes requests for both HTTP <codeGET</code> and <code>POST</code>
 * methods./*from  w  w  w . j a  va 2 s.  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");
    try (PrintWriter out = response.getWriter()) {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Registeration</title>");
        out.println("</head>");
        out.println("<body>");

        response.sendRedirect("admin.jsp");
        out.println("</body>");
        out.println("</html>");
        String a, b, c, d, e, f, g, s;
        a = request.getParameter("name");
        b = request.getParameter("prof");
        c = request.getParameter("org");
        d = request.getParameter("user");
        e = request.getParameter("mob");
        f = request.getParameter("email");
        g = request.getParameter("password");

        //Get the session object
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("smartstorechallenge@gmail.com", "smarttcs");//change accordingly
            }
        });

        //compose message
        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress("smartstorechallenge@gmail.com"));//change accordingly
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(f));
            message.setSubject("Smart Store Registeration");
            /* message.setText("username");
             message.setText(f);
             message.setText("Password");
             message.setText(g);*/
            message.setText("You have been Successfully Registered\n" + "Username:" + f + "\n" + "Password:" + g
                    + "\n");

            //send message
            Transport.send(message);

            out.println("message sent successfully");

        } catch (MessagingException j) {
            out.println("Error");
        }
        int n, i = 0, j = 0, k = 0, l, m, p = 1, j1 = 0, p1 = 1, len2 = 0, len1, len, rem, rem1, quot, quot1,
                j2, p2, count, jj, pp, lt, jj1, jj2, jj3, pp1, pp2, pp3;
        String s1 = "", e1 = "0", o = "1", k1 = "", k2 = "", k3 = "", k4 = "", x1 = "", x2 = "", x3 = "",
                x4 = "", code = "", total, tot = "";
        String str = "", c1, b1, c2, key = "", c3, t1 = "", t2 = "", t3 = "", t4 = "", c4 = "", c5, c6,
                remaining = "";

        String res[] = new String[1000];
        String res1[] = new String[1000];
        String binar[] = new String[1000];
        String dna[] = new String[1000];
        String dna1[] = new String[1000];
        String dna2[] = new String[1000];
        String dna3[] = new String[1000];
        String res2[] = new String[1000];

        char ch, ch1;
        add_user h = new add_user();
        str = g;
        l = str.length();
        for (int cc = 0; cc < l - 1; cc++) {
            ch = str.charAt(cc);
            if (!Character.isUpperCase(ch)) {
                str = str.toUpperCase();
            }
        }
        //s=str.replace('T','U');
        System.out.println("pattern" + str);
        System.out.println("pattern length" + l);
        // DNA code generation
        for (i = 0; i <= l - 1; i++) {
            //System.out.println("i value"+i);
            //System.out.println("j value"+j);
            //System.out.println("p value"+p);
            if (k != -1) {
                res[i] = str.substring(j, p);
                System.out.println(res[i]);
            }
            j = j + 1;
            p = p + 1;
        }
        // binary code generation

        c1 = h.dna(res);
        System.out.println(c1);
        int l1 = c1.length();
        c1 = c1.replace('U', 'T');
        System.out.println(c1);
        for (int i1 = 0; i1 <= l1 - 1; i1++) {
            if (k != -1) {
                res1[i1] = c1.substring(j1, p1);
                //System.out.println("result"+res1[i1]);
            }
            j1 = j1 + 1;
            p1 = p1 + 1;
        }
        c2 = h.code(res1);
        System.out.println(c2);
        //parity bit generation
        len = c2.length();
        quot = len / 4;
        rem = (len) % (4);
        j2 = 0;
        p2 = quot;
        count = 0;
        System.out.println("Length of binary seq" + len + "REM" + rem);
        if (rem == 0) {
            for (int gg = 0; gg < 4; gg++) {
                binar[gg] = c2.substring(j2, p2);
                System.out.println("j2" + " " + j2);
                System.out.println("p2" + " " + p2);
                System.out.println("no parity" + " " + c2);
                System.out.println("no parity array" + " " + binar[gg]);
                j2 = p2;
                p2 = p2 + quot;
            }
        } else {
            for (int sh = 0; sh < len - 1; sh++) {
                ch = c2.charAt(sh);
                if (ch == '1') {
                    count = count + 1;
                }
            }
            int cn = (count) % (2);
            if (cn == 0) {
                for (int v = 0; v < rem; v++) {
                    c2 = c2 + e1;
                    //System.out.println("value"+v);
                    System.out.println("even" + " " + c2);
                }
                len1 = c2.length();
                len2 = len1 / 4;
                System.out.println("len1" + len1);
                rem1 = (len1) % (4);
                quot1 = len1 / 4;
                //System.out.println("quot"+quot1);
                p2 = quot1;
                //System.out.println("p2"+p2);
                for (int g1 = 0; g1 < 4; g1++) {
                    //System.out.println("c2"+c2);
                    binar[g1] = c2.substring(j2, p2);
                    //System.out.println("j2"+j2);
                    //System.out.println("p2"+p2);
                    System.out.println("even parity array" + " " + binar[g1]);
                    j2 = p2;
                    p2 = p2 + quot1;
                }
                //System.out.println("j2"+j2);
                //System.out.println("p2"+p2);
            } else {
                for (int w = 0; w < rem; w++) {
                    c2 = c2 + o;
                    System.out.println("odd" + " " + c2);
                }
                for (int g2 = 0; g2 < len - 1; g2++) {
                    binar[g2] = c2.substring(j2, p2);
                    System.out.println("odd parity array" + "  " + binar[g2]);
                }
            }

        }
        k1 = binar[0];
        k2 = binar[1];
        k3 = binar[2];
        k4 = binar[3];
        String bits = "";
        int binlen = k1.length();
        Random r = new Random();
        for (int r1 = 0; r1 < binlen; r1++) {
            int x = 0;
            if (r.nextBoolean()) {
                x = 1;
            }
            bits += x;
        }
        System.out.println("binlen" + binlen);
        key = bits;
        System.out.println("key" + " " + key);
        System.out.println("keylength" + key.length());

        System.out.println("k1" + k1);
        String temp1[] = k1.split("");
        String temp2[] = k2.split("");
        String temp3[] = k3.split("");
        String temp4[] = k4.split("");
        String temp5[] = key.split("");
        System.out.print("temp1");
        for (int sas = 0; sas <= key.length() - 1; sas++) {
            System.out.println("array" + sas);
            System.out.print(temp1[sas]);

        }
        /*System.out.print("temp2");
        for(int sas1=0;sas1<=key.length()-1;sas1++)
        {
           System.out.print(temp2[sas1]);
        }
        System.out.print("temp3");
        for(int sas2=0;sas2<=key.length()-1;sas2++)
        {
           System.out.print(temp3[sas2]);
        }
        System.out.print("temp4");
        for(int sas3=0;sas3<=key.length()-1;sas3++)
        {
           System.out.print(temp4[sas3]);
        }
        System.out.print("temp5");
        for(int sas4=0;sas4<=key.length()-1;sas4++)
        {
           System.out.print(temp5[sas4]);
        }*/

        for (int gg = 0; gg <= key.length() - 1; gg++) {
            System.out.println("gg" + gg);
            System.out.println("key length" + key.length());
            if ((temp1[gg]).equals((temp5[gg]))) {
                temp1[gg] = "0";
                System.out.print("tempaa" + temp1[gg]);
            } else {
                temp1[gg] = "1";
                System.out.print("tempaa" + temp1[gg]);
            }
        }
        for (int g1 = 0; g1 <= key.length() - 1; g1++) {
            //System.out.println("temp2"+temp2[g1]);
            //System.out.println("temp5b4"+temp5[g1]);
            if ((temp2[g1]).equals((temp5[g1]))) {
                temp2[g1] = "0";
                System.out.print("tempaa" + temp2[g1]);
            } else {
                temp2[g1] = "1";
                System.out.print("temp2xx" + temp2[g1]);
            }
        }
        for (int g2 = 0; g2 <= key.length() - 1; g2++) {
            if ((temp3[g2]).equals((temp5[g2]))) {
                temp3[g2] = "0";
            } else {
                temp3[g2] = "1";
            }
        }
        for (int g3 = 0; g3 <= key.length() - 1; g3++) {
            if ((temp4[g3]).equals((temp5[g3]))) {
                temp4[g3] = "0";
            } else {
                temp4[g3] = "1";
            }
        }
        System.out.println();
        System.out.print("After xor temp1");
        /*for(int sa=0;sa<=key.length()-1;sa++)
        {
           System.out.print(" "+temp1[sa]);
        }
        System.out.println();
        System.out.print("After xor temp2");
        /*for(int sa1=0;sa1<=key.length()-1;sa1++)
        {
           System.out.print(" "+temp2[sa1]);
        }*/
        /*System.out.println();
        System.out.print("After xor temp3");
        for(int sa2=0;sa2<=key.length()-1;sa2++)
        {
           System.out.print(" "+temp3[sa2]);
        }
        System.out.println();
        System.out.print(" After xor temp4");
        for(int sa3=0;sa3<=key.length()-1;sa3++)
        {
           System.out.print(" "+temp4[sa3]);
        }
        System.out.println();*/
        //rule 51
        for (int ba = 0; ba <= key.length() - 1; ba++) {
            //System.out.print("AFTER"+temp1[ba]);
            if ((temp1[ba]).equals("0")) {
                temp1[ba] = "1";

            } else {
                temp1[ba] = "0";
            }
            //System.out.print("RULE"+temp1[ba]);
        }
        for (int ba1 = 0; ba1 <= key.length() - 1; ba1++) {
            if ((temp2[ba1]).equals("0")) {
                temp2[ba1] = "1";
            } else {
                temp2[ba1] = "0";
            }
            //System.out.print("RULE"+temp2[ba1]);
        }
        for (int ba2 = 0; ba2 <= key.length() - 1; ba2++) {
            if ((temp3[ba2]).equals("0")) {
                temp3[ba2] = "1";
            } else {
                temp3[ba2] = "0";
            }
            //System.out.print("RULE"+temp3[ba2]);
        }
        for (int ba3 = 0; ba3 <= key.length() - 1; ba3++) {
            if ((temp4[ba3]).equals("0")) {
                temp4[ba3] = "1";
            } else {
                temp4[ba3] = "0";
            }
            //System.out.print("RULE"+temp4[ba3]);
        }

        //AFTer rule 51
        for (int kk = 0; kk <= key.length() - 1; kk++) {
            t1 = t1 + temp1[kk];
        }
        System.out.println("t1" + " " + t1);
        for (int kk1 = 0; kk1 <= key.length() - 1; kk1++) {
            t2 = t2 + temp2[kk1];
        }
        System.out.println("t2" + " " + t2);
        for (int kk2 = 0; kk2 <= key.length() - 1; kk2++) {
            t3 = t3 + temp3[kk2];
        }
        System.out.println("t3" + " " + t3);
        for (int kk3 = 0; kk3 <= key.length() - 1; kk3++) {
            t4 = t4 + temp4[kk3];
        }
        System.out.println("t4" + " " + t4);
        total = t1 + t2 + t3 + t4;
        lt = total.length();
        //System.out.println("Length"+lt);
        jj = 0;
        pp = 2;
        for (int gg = 0; gg < lt / 2; gg++) {
            dna[gg] = total.substring(jj, pp);
            //System.out.println("jj"+jj);
            //System.out.println("pp"+pp);
            //System.out.println(" split of binary array1"+dna[gg]);
            jj = pp;
            pp = pp + 2;
        }
        c3 = h.bin(dna);
        System.out.println("c3" + " " + c3);
        int leng = c3.length();
        //System.out.println("Length of C3"+leng);
        //code=code+c3+c4+c4+c5;
        //System.out.println("code"+total);
        for (int kk1 = 1; kk1 <= total.length(); kk1++) {
            tot = tot + dna[kk1];
        }

        jj1 = 0;
        pp1 = 3;
        int cl = c3.length();
        c4 = c3.replace("T", "U");
        //System.out.println("t to u"+c4);
        int q1 = cl / 3;
        int r1 = cl % 3;
        if (r1 == 0) {
            for (int gg1 = 0; gg1 < cl / 3; gg1++) {
                dna1[gg1] = c4.substring(jj1, pp1);
                //System.out.println("jj1"+jj1);
                //System.out.println("pp1"+pp1);
                //System.out.println(" split of dna array"+dna1[gg1]);
                jj1 = pp1;
                pp1 = pp1 + 3;

            }
        } else {
            for (int gg3 = 0; gg3 < cl / 3; gg3++) {
                dna1[gg3] = c4.substring(jj1, pp1);
                //System.out.println("jj1"+jj1);
                //System.out.println("pp1"+pp1);
                //System.out.println(" split of dna array"+dna1[gg3]);
                jj1 = pp1;
                pp1 = pp1 + 3;

            }
            for (int gg2 = 0; gg2 < r1; gg2++) {
                int lll = cl - 1;
                remaining = c4.substring(lll);
                System.out.println("c1-1" + lll);
                if (r1 > 1) {
                    lll = lll - 1;
                    //System.out.println("greater remainder"+lll);
                }
                //System.out.println("remaining"+remaining);
            }
        }

        c5 = h.dnacode(dna1);
        System.out.println("c4" + c4);
        c5 = c5 + remaining;
        System.out.println("Encrypted Data" + " " + c5);
        int c5len = c5.length();
        System.out.println("Length of  encrypted data" + " " + c5len);

        String dbURI = "mongodb://Bharath:Bharath@ds033097.mongolab.com:33097/smart";
        MongoClient mongoClient = new MongoClient(new MongoClientURI(dbURI));
        DB db = mongoClient.getDB("smart");
        DBCollection coll = db.getCollection("register");
        DBObject doc = new BasicDBObject().append("Name", a).append("Profession", b).append("Organisation", c)
                .append("User_type", d).append("Mobile_no", e).append("email_id", f).append("Password", c5)
                .append("Key", key);
        coll.insert(doc);
    }
}

From source file:Add_cust.java

@Override
/* Check The code below for insertion of values */
public void actionPerformed(ActionEvent ae) {
    // TODO Auto-generated method stub
    add(jLabel9);/* w  w  w  . j a va2  s  . c  o m*/
    String History = jComboBox3.getSelectedItem().toString();
    if (ae.getSource() == jButton1) {
        try {
            MongoClient mongo = new MongoClient("localhost", 27017);
            DB db = mongo.getDB("Gym");
            DBCollection Gym_Collection = db.getCollection("Customers");
            DBCollection Allot = db.getCollection("Batch"); //Declaration of collection for Batch
            DBCursor cursor = Allot.find();
            float Slots, Morning, Evening, Night;
            cursor.next();
            Slots = Float.parseFloat(cursor.curr().get("Slots").toString());
            Morning = Float.parseFloat(cursor.curr().get("Morning").toString());
            Evening = Float.parseFloat(cursor.curr().get("Evening").toString());
            Night = Float.parseFloat(cursor.curr().get("Night").toString());
            String first_name = jTextField1.getText();
            String last_name = jTextField2.getText();
            float weight = Float.parseFloat(jTextField6.getText().toString());
            float height = Float.parseFloat(jTextField5.getText().toString());
            String address = jTextArea1.getText();
            int age = Integer.parseInt(jComboBox1.getSelectedItem().toString());
            String Subs = jComboBox2.getSelectedItem().toString();

            String Batches = jComboBox5.getSelectedItem().toString();
            String phone_number = jTextField3.getText().toString();
            if (!isAlpha(first_name) || !isAlpha(last_name)) {
                JOptionPane.showMessageDialog(this, "Enter a valid name");
                jTextField1.setText("");
                jTextField2.setText("");
            } else if (weight > 150 || weight < 40) {
                JOptionPane.showMessageDialog(this, "Please add weight between 40 and 150");
                jTextField6.setText("");
            } else if (height > 250 || height < 50) {
                JOptionPane.showMessageDialog(this, "Please add height between 100 and 250");
                jTextField5.setText("");
            } else if (phone_number.length() < 8 || phone_number.length() > 11) {
                JOptionPane.showMessageDialog(this, "Enter a valid Phone no.");
                jTextField3.setText("");
            } else {
                int random_1, random_2, sub_sum = 0, days = 0;
                if (Subs.equals("1 Month")) {
                    sub_sum = 1000;
                    days = 30;
                } else if (Subs.equals("2 Months")) {
                    sub_sum = 1500;
                    days = 60;
                } else if (Subs.equals("3 Months")) {
                    sub_sum = 2250;
                    days = 90;
                } else if (Subs.equals("1 YEAR")) {
                    sub_sum = 6000;
                    days = 360;
                }
                int flag = 0, flag1 = 0, flag2 = 0, flag3 = 0;
                if (Batches.equals("Morning")) {
                    Morning += 1;
                    flag1 = 1;
                } else if (Batches.equals("Evening")) {
                    Evening += 1;
                    flag2 = 1;
                } else if (Batches.equals("Night")) {
                    Night += 1;
                    flag3 = 1;
                }
                if (Morning > Slots || Evening > Slots || Night > Slots) {
                    if (flag1 == 1) {
                        Morning -= 1;
                    } else if (flag2 == 1) {
                        Evening -= 1;
                    } else if (flag3 == 1) {
                        Night -= 1;
                    }
                    flag = 1;
                }
                if (flag == 1) {
                    float temp1, temp2;
                    if (flag1 == 1) {
                        temp1 = Slots - Evening;
                        temp2 = Slots - Night;
                        JOptionPane.showMessageDialog(this, "This time slot slot is full. Evening has " + temp1
                                + " Slots. Night has " + temp2 + " Slots.");
                    } else if (flag2 == 1) {
                        temp1 = Slots - Morning;
                        temp2 = Slots - Night;
                        JOptionPane.showMessageDialog(this, "This time slot slot is full. Morning has " + temp1
                                + " Slots. Night has " + temp2 + " Slots.");
                    } else {
                        temp1 = Slots - Morning;
                        temp2 = Slots - Evening;
                        JOptionPane.showMessageDialog(this, "This time slot slot is full. Morning has " + temp1
                                + " Slots. Evening has " + temp2 + " Slots.");
                    }
                } else {
                    do {
                        random_1 = (int) Math.floor(Math.random() * 360);
                        random_2 = (int) Math.floor(Math.random() * 360);
                    } while (random_1 >= random_2 || days <= random_2);
                    BasicDBObject doc = new BasicDBObject("First_Name", first_name.toLowerCase())
                            .append("Last_Name", last_name.toLowerCase()).append("Phone_Number", phone_number)
                            .append("Age", age).append("Height", height).append("History", History)
                            .append("Subscribe", days).append("Batch", Batches).append("Weight", weight)
                            .append("Attended", random_1).append("Total", random_2).append("Fees", sub_sum)
                            .append("Address", address);
                    Gym_Collection.insert(doc);
                    jTextField1.setText("");
                    jTextField2.setText("");
                    jTextField3.setText("");
                    jTextField5.setText("");
                    jTextField6.setText("");
                    jTextArea1.setText("");

                    BasicDBObject newDocument = new BasicDBObject();
                    newDocument.append("$set", new BasicDBObject().append("Morning", Morning)
                            .append("Evening", Evening).append("Night", Night));

                    BasicDBObject searchQuery = new BasicDBObject().append("Slots", Slots);

                    Allot.update(searchQuery, newDocument);

                    this.setVisible(false);
                    new work(History, first_name.toLowerCase(), last_name.toLowerCase());
                    this.setVisible(false);
                    new work().setVisible(true);
                }
            }
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NumberFormatException e) {// To validate for data types
            JOptionPane.showMessageDialog(this, "Please Check the Data types");
            jTextField1.setText("");
            jTextField2.setText("");
            jTextField3.setText("");
            jTextField5.setText("");
            jTextField6.setText("");
            jTextArea1.setText("");
        }
    }

    else if (ae.getSource() == jButton2) {
        this.setVisible(false);
        new Receptionist().setVisible(true);
    }
}

From source file:PersistMongo.java

public static void main(String[] args) {
    // conectando ao mongo, como esta sem parametros
    //se conecta ao mongo local por default 
    MongoClient mongoClient = new MongoClient("localhost", 27017);

    // Base de dados
    DB db = (DB) mongoClient.getDB("JavaDB");
    // Tabela /* ww  w . j  a  v  a 2  s  .c  o  m*/
    DBCollection collection = db.getCollection("colJava");
    // objeto para ser persistido
    BasicDBObject document1 = new BasicDBObject();
    document1.put("id", 1001);
    document1.put("msg", "Persistencia com mongoDB");

    // salvando o documento na base nosql
    collection.insert(document1);
    BasicDBObject document = new BasicDBObject();
    document = new BasicDBObject();
    document.put("id", 1002);
    document.put("msg", "Java + Mongo");

    // salvando o documento na base nosql
    collection.insert(document);
    // objeto que recebe os dados do banco
    DBCursor cursor = collection.find();
    // percorrendo o objeto e mostrando os dados
    while (cursor.hasNext()) {
        System.out.println("Document: " + cursor.next());

    }
    // Passando o documento que sera removido
    collection.remove(document);
    // Passando o documentoque sera atualizado e o documento que entrara em seu lugar 
    collection.update(document, document1);

}

From source file:Add_train.java

@Override
/* Check The code below for insertion of values */
public void actionPerformed(ActionEvent ae) {
    // TODO Auto-generated method stub
    add(jLabel9);//from   w ww  .  j av  a 2s. c  om
    jLabel9.setText("");
    if (ae.getSource() == jButton1) {
        try {
            MongoClient mongo = new MongoClient("localhost", 27017);
            DB db = mongo.getDB("Gym");
            DBCollection Allot = db.getCollection("Batch_Trainer");
            DBCursor cursor1 = Allot.find();
            DBCollection Gym_Collection = db.getCollection("trainer");
            String first_name = jTextField1.getText();
            String last_name = jTextField2.getText();
            String password = jPassword1.getText().toString();
            String dup = jPassword2.getText().toString();
            String username = jTextField5.getText().toString();
            String address = jTextArea1.getText();

            String Batches = jComboBox5.getSelectedItem().toString();
            float Slots, Morning, Evening, Night;
            cursor1.next();
            Slots = Float.parseFloat(cursor1.curr().get("Slots").toString());
            Morning = Float.parseFloat(cursor1.curr().get("Morning").toString());
            Evening = Float.parseFloat(cursor1.curr().get("Evening").toString());
            Night = Float.parseFloat(cursor1.curr().get("Night").toString());
            int age = Integer.parseInt(jComboBox1.getSelectedItem().toString());
            String phone_number = jTextField3.getText().toString();
            DBCursor cursor = Gym_Collection.find();
            int i = 0;
            while (cursor.hasNext()) {
                cursor.next();
                if (username.equals(cursor.curr().get("Username").toString())) {
                    i = 1;
                }
            }
            if (i == 1) {
                JOptionPane.showMessageDialog(this, "Username has been taken !!!");
                jTextField5.setText("");
            } else if (!isAlpha(first_name) || !isAlpha(last_name)) {
                JOptionPane.showMessageDialog(this, "Enter a valid name");
                jTextField1.setText("");
                jTextField2.setText("");
            } else if (phone_number.length() < 8 || phone_number.length() > 10) {
                JOptionPane.showMessageDialog(this, "Enter a valid Phone no.");
                jTextField3.setText("");
            } else if (!password.equals(dup)) {
                JOptionPane.showMessageDialog(this, "Passwords didn't match");
                jPassword1.setText("");
                jPassword2.setText("");
            } else {

                int flag = 0, flag1 = 0, flag2 = 0, flag3 = 0;
                if (Batches.equals("Morning")) {
                    Morning += 1;
                    flag1 = 1;
                } else if (Batches.equals("Evening")) {
                    Evening += 1;
                    flag2 = 1;
                } else if (Batches.equals("Night")) {
                    Night += 1;
                    flag3 = 1;
                }
                if (Morning > Slots || Evening > Slots || Night > Slots) {
                    if (flag1 == 1) {
                        Morning -= 1;
                    } else if (flag2 == 1) {
                        Evening -= 1;
                    } else if (flag3 == 1) {
                        Night -= 1;
                    }
                    flag = 1;
                }
                if (flag == 1) {
                    float temp1, temp2;
                    if (flag1 == 1) {
                        temp1 = Slots - Evening;
                        temp2 = Slots - Night;
                        JOptionPane.showMessageDialog(this, "This time slot slot is full. Evening has " + temp1
                                + " Slots. Night has " + temp2 + " Slots.");
                    } else if (flag2 == 1) {
                        temp1 = Slots - Morning;
                        temp2 = Slots - Night;
                        JOptionPane.showMessageDialog(this, "This time slot slot is full. Morning has " + temp1
                                + " Slots. Night has " + temp2 + " Slots.");
                    } else {
                        temp1 = Slots - Morning;
                        temp2 = Slots - Evening;
                        JOptionPane.showMessageDialog(this, "This time slot slot is full. Morning has " + temp1
                                + " Slots. Evening has " + temp2 + " Slots.");
                    }
                } else {

                    BasicDBObject doc = new BasicDBObject("First_Name", first_name.toLowerCase())
                            .append("Last_Name", last_name.toLowerCase()).append("Batch", Batches)
                            .append("Phone_Number", phone_number).append("Age", age)
                            .append("Username", username).append("Password", password)
                            .append("Address", address);
                    Gym_Collection.insert(doc);
                    jTextField1.setText("");
                    jTextField2.setText("");
                    jTextField3.setText("");
                    jTextField5.setText("");
                    jPassword1.setText("");
                    jPassword2.setText("");
                    jTextArea1.setText("");
                    jLabel9.setFont(new java.awt.Font("SansSerif", 3, 16)); // NOI18N
                    jLabel9.setForeground(new java.awt.Color(204, 255, 204));
                    jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
                    jLabel9.setText("Successfully Added");
                    jLabel9.setBounds(200, 10, 200, 40);

                    BasicDBObject newDocument = new BasicDBObject();
                    newDocument.append("$set", new BasicDBObject().append("Morning", Morning)
                            .append("Evening", Evening).append("Night", Night));

                    BasicDBObject searchQuery = new BasicDBObject().append("Slots", Slots);

                    Allot.update(searchQuery, newDocument);

                    setVisible(true);
                }
            }
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "Please Check the Data types");
            jTextField1.setText("");
            jTextField2.setText("");
            jTextField3.setText("");
            jTextField5.setText("");
            jPassword1.setText("");
            jPassword2.setText("");
            jTextArea1.setText("");
        }
    }

    else if (ae.getSource() == jButton2) {
        this.setVisible(false);
        new Admin().setVisible(true);
    }
}

From source file:admin_Add_newEmp.java

private void Add_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Add_buttonActionPerformed
    // TODO add your handling code here:

    try {/*from  w  ww  .  j ava  2  s. c  o m*/

        MongoClient mc = new MongoClient("localhost", 27017);
        DB db = mc.getDB("parking_system");
        DBCollection collection = db.getCollection("employee_info");

        name = name_field.getText();
        lname = lname_field.getText();
        mobno = mobno_field.getText().toCharArray();

        //userid = userid_field.getText();
        //password = password_field.getText();
        //mobno = Integer.parseInt(mobno_field.getText());
        //mobno = mobno_field.getText();
        String mobnoStr = new String(mobno);

        BasicDBObject doc = new BasicDBObject("_id", userid).append("name", name).append("lname", lname)
                .append("password", password).append("mobileno", mobnoStr);

        collection.insert(doc);

        JOptionPane.showMessageDialog(null, "Added!");

        setVisible(false);
        new Admin_rights().setVisible(true);

    } catch (Exception e) {

    }
}

From source file:RegisterUI.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    String username = Usernamefield.getText();
    char[] pw1 = Passwordfield.getPassword();
    String pw1s = new String(pw1);
    char[] pw2 = Repeat.getPassword();
    String pw2s = new String(pw2);

    if (usernames.contains(username)) {
        JOptionPane.showMessageDialog(null, "Username already exists!", "Failed", JOptionPane.ERROR_MESSAGE);
    }/*from   w  ww . j a  v a2s . c o m*/

    else if (!pw1s.equals(pw2s)) {
        JOptionPane.showMessageDialog(null, "Passwords do not match!", "Failed", JOptionPane.ERROR_MESSAGE);
    }

    else {
        DBCollection col = db.getCollection("Users");
        BasicDBObject doc = new BasicDBObject("Info",
                new BasicDBObject("Username", username).append("Password", pw1s))
                        .append("Beginner", new BasicDBObject("Total", 0).append("Correct", 0))
                        .append("Easy", new BasicDBObject("Total", 0).append("Correct", 0))
                        .append("Medium", new BasicDBObject("Total", 0).append("Correct", 0))
                        .append("Hard", new BasicDBObject("Total", 0).append("Correct", 0)).append("Last",
                                new BasicDBObject("Question", "").append("Answer", "").append("Correct", ""));
        col.insert(doc);

        JOptionPane.showMessageDialog(null, "Registration Successful!", "Success!",
                JOptionPane.INFORMATION_MESSAGE);
        WindowEvent winClosingEvent = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
        Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
    }

}

From source file:bom.BOM.java

/**
 * @param args the command line arguments
 *//*from  w  ww . j  a va2  s .c o m*/
public static void main(String[] args) {
    // TODO code application logic here
    try {

        MongoClient mongoClient = new MongoClient("localhost", 5000);
        // Now connect to your databases
        //mongod --port 5000 --dbpath D:\mongodbdata\ (please mention above created path)
        //mongo --port 5000
        DB db = mongoClient.getDB("bomdb");
        System.out.println("Connect to database successfully");

        //DBCollection col1 = db.createCollection("Parts",p1);
        DBCollection col2 = db.getCollection("BOM");
        System.out.println("Collection created successfully");

        List<BillOfMaterial> list;
        LocalDataSource ds = new LocalDataSource();
        list = ds.LoadBom(1000);
        // To connect to mongodb server

        for (BillOfMaterial Element : list) {
            for (Parts ElementPart : Element.partList) {
                for (Operation ElementOp : ElementPart.optList) {
                    BasicDBObject doc = new BasicDBObject("BOM_Name", Element.getBOM_Name())
                            .append("Level", Element.getLevel()).append("Stock", Element.getStock()).

                            append("Parts", new BasicDBObject("Part_ID", ElementPart.getPart_ID())
                                    .append("Part_Name", ElementPart.getPart_Name())
                                    .append("Diameter", ElementPart.getDiamter())
                                    .append("Dept", ElementPart.getDept()).append("Area", ElementPart.getArea())
                                    .append("Quantity", ElementPart.getQuantity()).

                                    append("Material",
                                            new BasicDBObject("Material_ID", ElementPart.getMaterial_ID())
                                                    .append("Material_Name", ElementPart.getMaterial_Name()).

                                                    append("Operation", new BasicDBObject("Operation_ID",
                                                            ElementOp.getOperation_ID())
                                                                    .append("Operation_Name",
                                                                            ElementOp.getOperation_Name())
                                                                    .append("Equipment_Name",
                                                                            ElementOp.getEquipment_Name())
                                                                    .append("No_of_Staff",
                                                                            ElementOp.getNo_of_Staff())
                                                                    .append("Operation_Time", ElementOp
                                                                            .getOperation_Time()
                                                                            .get(Calendar.MINUTE)
                                                                            * ElementOp.getOperation_Time()
                                                                                    .get(Calendar.SECOND))
                                                                    .append("Assembly_Time", ElementOp
                                                                            .getAssembly_Time()
                                                                            .get(Calendar.MINUTE)
                                                                            * ElementOp.getAssembly_Time()
                                                                                    .get(Calendar.SECOND))
                                                                    .append("Set_Up_Time", ElementOp
                                                                            .getSet_Up_Time()
                                                                            .get(Calendar.MINUTE)
                                                                            * ElementOp.getSet_Up_Time()
                                                                                    .get(Calendar.SECOND))
                                                                    .

                                                                    append("Contractor", new BasicDBObject(
                                                                            "Contractor_ID",
                                                                            ElementOp.getContractor_ID())
                                                                                    .append("Contractor_Name",
                                                                                            ElementOp
                                                                                                    .getContractor_Name())))));

                    col2.insert(doc);
                }
            }
        }

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

}

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

License:Open Source License

private DBCollection getTitle(final String mstName, final String mstEncoding, final int indexTag,
        final int returnTag) throws UnknownHostException, BrumaException {
    assert mstName != null;
    assert indexTag > 0;
    assert returnTag > 0;

    final DBCollection coll = db.getCollection(COL_NAME);
    coll.ensureIndex(new BasicDBObject(INDEX_TAG, 1));

    final Master mst = MasterFactory.getInstance(mstName).setEncoding(mstEncoding).open();
    for (Record rec : mst) {
        if (rec.isActive()) {
            final int mfn = rec.getMfn();
            final List<Field> lst1 = rec.getFieldList(indexTag);
            if (!lst1.isEmpty()) {
                final List<Field> lst2 = rec.getFieldList(returnTag);
                if (!lst2.isEmpty()) {
                    final BasicDBList dblist1 = new BasicDBList();
                    for (Field fld1 : lst1) {
                        final String str = removeAccents(fld1.getContent()).toUpperCase();
                        dblist1.add(str);
                    }/*from   w  w w  .ja v a 2  s .c  o m*/
                    final BasicDBList dblist2 = new BasicDBList();
                    for (Field fld2 : lst2) {
                        dblist2.add(fld2.getContent());
                    }
                    coll.insert(new BasicDBObject(INDEX_TAG, dblist1).append(RETURN_TAG, dblist2).append("mfn",
                            mfn));
                }
            }
        }
    }
    mst.close();

    return coll;
}