Example usage for com.mongodb BasicDBObject BasicDBObject

List of usage examples for com.mongodb BasicDBObject BasicDBObject

Introduction

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

Prototype

public BasicDBObject() 

Source Link

Document

Creates an empty object.

Usage

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 {//from  w ww .ja  v a  2s.  c  om
        // 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   ww w  . ja  v a  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:GSSAPICredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException, InterruptedException {
    // Set this property to avoid the default behavior where the program prompts on the command line for username/password
    //        Security.setProperty("auth.login.defaultCallbackHandler", "DefaultSecurityCallbackHandler");

    String server = args[0];/*w  w w  .j av  a2 s . com*/
    String user = args[1];
    String databaseName = args[2];

    System.out.println("javax.security.auth.useSubjectCredsOnly: "
            + System.getProperty("javax.security.auth.useSubjectCredsOnly"));
    System.out.println("java.security.krb5.realm: " + System.getProperty("java.security.krb5.realm"));
    System.out.println("java.security.krb5.kdc: " + System.getProperty("java.security.krb5.kdc"));
    System.out.println(
            "auth.login.defaultCallbackHandler: " + Security.getProperty("auth.login.defaultCallbackHandler"));
    System.out.println("login.configuration.provider: " + Security.getProperty("login.configuration.provider"));
    System.out.println(
            "java.security.auth.login.config: " + Security.getProperty("java.security.auth.login.config"));
    System.out.println("login.config.url.1: " + Security.getProperty("login.config.url.1"));
    System.out.println("login.config.url.2: " + Security.getProperty("login.config.url.2"));
    System.out.println("login.config.url.3: " + Security.getProperty("login.config.url.3"));

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

    System.out.println();

    MongoClient mongoClient = new MongoClient(new ServerAddress(server),
            Arrays.asList(MongoCredential.createGSSAPICredential(user)),
            new MongoClientOptions.Builder().socketKeepAlive(true).socketTimeout(30000).build());
    DB testDB = mongoClient.getDB(databaseName);

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

From source file:Credits.java

String SetCredits(String name, int credits) {

    DBCollection coll = db.getCollection("User");
    BasicDBObject newDocument = new BasicDBObject().append("$inc",
            new BasicDBObject().append("Credits", credits));
    coll.update(new BasicDBObject().append("Username", name), newDocument);

    DBObject db = coll.findOne(new BasicDBObject().append("Username", name));
    String s = db.toString();//from ww w  .jav  a  2  s.com
    String[] a = s.split(",");
    try {

        String b = a[a.length - 1];
        String[] c = b.split(":");
        System.out.println(c[1]);
        return c[1];
    } catch (Exception e) {
        return "0";
    }

}

From source file:PanBorrar.java

private void EliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EliminarActionPerformed
    // TODO add your handling code here:
    String name = nombreT.getText();
    String apPat = apPaternoT.getText();
    String apMat = apMaternoT.getText();

    if (!name.equals("") || !apPat.equals("") || !apMat.equals("")) {

        tabla.remove(new BasicDBObject().append("Nombre", name).append("ApPaterno", apPat).append("ApMaterno",
                apMat));//  w  w w  . ja  v  a  2s .c  om

        javax.swing.JOptionPane.showMessageDialog(this, "Se ha Eliminado exitosamente el nuevo alumno");
        PanBorrar newFrame = new PanBorrar();
        newFrame.setVisible(true);
        this.dispose();

    } else {
        javax.swing.JOptionPane.showMessageDialog(this, "No se han comletado los campos");
    }
}

From source file:CramMd5CredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException, InterruptedException {
    String server = args[0];//from ww  w . j  a v a 2 s. c  o m
    String user = args[1];
    String pwd = args[2];
    String db = args[3];
    MongoClient mongo = new MongoClient(
            new MongoClientAuthority(new ServerAddress(server),
                    new MongoClientCredentials(user, pwd.toCharArray(),
                            MongoClientCredentials.CRAM_MD5_MECHANISM, db)),
            new MongoClientOptions.Builder().socketKeepAlive(true).socketTimeout(30000).build());
    DB testDB = mongo.getDB(db);
    System.out.println("Find     one: " + testDB.getCollection("test").findOne());
    System.out.println("Count: " + testDB.getCollection("test").count());
    WriteResult writeResult = testDB.getCollection("test").insert(new BasicDBObject());
    System.out.println("Write result: " + writeResult);

    System.out.println();

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

}

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;/*from   w  ww  .  j a va 2s. 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());
        }

    }
}

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 /*from   w ww .j av a 2  s. com*/
    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:PlainCredentialsExample.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    String server = args[0];/*from  ww w . jav  a2s  . c  om*/
    String user = args[1];
    String password = args[2];
    String source = args[3];

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

    System.out.println();

    MongoClient mongoClient = new MongoClient(new ServerAddress(server),
            Arrays.asList(MongoCredential.createPlainCredential(user, source, password.toCharArray())),
            new MongoClientOptions.Builder().build());
    DB testDB = mongoClient.getDB("test");

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

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

From source file:Entry_OR_Exit.java

private void Entry_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Entry_buttonActionPerformed
    // TODO add your handling code here:
    /*/*from   www  .j av  a 2 s.com*/
    setVisible(false);
    new Vehicle_type_check().setVisible(true);
    */
    try {
        MongoClient mc = new MongoClient("localhost", 27017);
        DB db = mc.getDB("parking_system");
        DBCollection collection = db.getCollection("vehicle_count");

        if (radio_vehicle_check == -99)
            JOptionPane.showMessageDialog(null, "Please Chhose Vehicle Type");
        else {
            if (radio_vehicle_check == 2) {
                int count_bike;
                BasicDBObject query = new BasicDBObject();
                BasicDBObject field = new BasicDBObject();
                field.put("wheeler_2", 1);
                DBCursor cursor = collection.find(query, field);

                BasicDBObject obj = (BasicDBObject) cursor.next();
                count_bike = obj.getInt("wheeler_2");
                System.out.println(count_bike);

                if (count_bike < 50) {
                    /*BasicDBObject searchUpdate = new BasicDBObject();
                    searchUpdate.append("wheeler_2", count_bike);
                            
                    BasicDBObject UpdateObject = new BasicDBObject();
                    UpdateObject.append("$set", new BasicDBObject("wheeler_2", count_bike + 1));
                            
                    collection.update(searchUpdate, UpdateObject);
                    */
                    setVisible(false);
                    new Veehicle_entry(radio_vehicle_check).setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(null, "No Available Space For Parking 2 Wheelers");
                }
            }

            else if (radio_vehicle_check == 4) {
                int count_car;

                BasicDBObject query = new BasicDBObject();
                BasicDBObject field = new BasicDBObject();
                field.put("wheeler_4", 1);
                DBCursor cursor = collection.find(query, field);

                BasicDBObject obj = (BasicDBObject) cursor.next();
                count_car = obj.getInt("wheeler_4");
                System.out.println(count_car);

                if (count_car < 50) {
                    /*
                    BasicDBObject searchUpdate = new BasicDBObject();
                    searchUpdate.append("wheeler_4", count_car);
                            
                    BasicDBObject UpdateObject = new BasicDBObject();
                    UpdateObject.append("$set", new BasicDBObject("wheeler_4",count_car+1));
                            
                    collection.update(searchUpdate, UpdateObject);
                    */
                    setVisible(false);
                    new Veehicle_entry(radio_vehicle_check).setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(null, "No Available Space For Parking 2 Wheelers");
                }
            } else {
                int count_other;

                BasicDBObject query = new BasicDBObject();
                BasicDBObject field = new BasicDBObject();
                field.put("other", 1);
                DBCursor cursor = collection.find(query, field);

                BasicDBObject obj = (BasicDBObject) cursor.next();
                count_other = obj.getInt("other");
                System.out.println(count_other);

                if (count_other < 50) {
                    /*
                    BasicDBObject searchUpdate = new BasicDBObject();
                    searchUpdate.append("other", count_other);
                            
                    BasicDBObject UpdateObject = new BasicDBObject();
                    UpdateObject.append("$set", new BasicDBObject("other", count_other + 1));
                            
                    collection.update(searchUpdate, UpdateObject);
                            
                    */
                    setVisible(false);
                    new Veehicle_entry(radio_vehicle_check).setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(null, "No Available Space For Parking Trucks");
                }
            }
        }
    } catch (Exception e) {

    }
}