Example usage for com.mongodb MongoClientURI MongoClientURI

List of usage examples for com.mongodb MongoClientURI MongoClientURI

Introduction

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

Prototype

public MongoClientURI(final String uri) 

Source Link

Document

Creates a MongoURI from the given string.

Usage

From source file:SparkToMongo.java

License:Apache License

private static void dropDatabase(final String connectionString) {
    MongoClientURI uri = new MongoClientURI(connectionString);
    new MongoClient(uri).dropDatabase(uri.getDatabase());
}

From source file:JavaSimpleExample.java

License:MIT License

public static void main(String[] args) throws UnknownHostException {

    // Create seed data

    final BasicDBObject[] seedData = createSeedData();

    // Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname

    MongoClientURI uri = new MongoClientURI("mongodb://user:pass@host:port/db");
    MongoClient client = new MongoClient(uri);
    DB db = client.getDB(uri.getDatabase());

    /*/* ww  w. j a va2s  .co  m*/
     * First we'll add a few songs. Nothing is required to create the
     * songs collection; it is created automatically when we insert.
     */

    DBCollection songs = db.getCollection("songs");

    // Note that the insert method can take either an array or a document.

    songs.insert(seedData);

    /*
     * Then we need to give Boyz II Men credit for their contribution to
     * the hit "One Sweet Day".
     */

    BasicDBObject updateQuery = new BasicDBObject("song", "One Sweet Day");
    songs.update(updateQuery,
            new BasicDBObject("$set", new BasicDBObject("artist", "Mariah Carey ft. Boyz II Men")));

    /*
     * Finally we run a query which returns all the hits that spent 10 
     * or more weeks at number 1.
     */

    BasicDBObject findQuery = new BasicDBObject("weeksAtOne", new BasicDBObject("$gte", 10));
    BasicDBObject orderBy = new BasicDBObject("decade", 1);

    DBCursor docs = songs.find(findQuery).sort(orderBy);

    while (docs.hasNext()) {
        DBObject doc = docs.next();
        System.out.println("In the " + doc.get("decade") + ", " + doc.get("song") + " by " + doc.get("artist")
                + " topped the charts for " + doc.get("weeksAtOne") + " straight weeks.");
    }

    // Since this is an example, we'll clean up after ourselves.

    songs.drop();

    // Only close the connection when your app is terminating

    client.close();
}

From source file:add_user.java

/**
 * Processes requests for both HTTP <codeGET</code> and <code>POST</code>
 * methods./*from  w w  w.  jav a  2s.co 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: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  va2s .c  om
    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:adc.data.viewer.dao.ConnectionBuilderMongo.java

License:Open Source License

@Override
public MongoClient getConnection() {

    try {/*from w ww  .jav  a2 s . c o  m*/

        MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoURI));
        mongoClient.getAddress();
        return mongoClient;
    } catch (MongoException | IllegalArgumentException me) {
        System.out.println("Connection to MongoDB failed");
        //    BaseController.alertMongoDBConnectionError();
        return null;
    }
}

From source file:alxpez.blog.BlogController.java

License:Apache License

public BlogController(String mongoURIString) throws IOException {
    final MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoURIString));
    final MongoDatabase blogDatabase = mongoClient.getDatabase("blog");

    blogPostDAO = new BlogPostDAO(blogDatabase);
    userDAO = new UserDAO(blogDatabase);
    sessionDAO = new SessionDAO(blogDatabase);

    cfg = createFreemarkerConfiguration();
    setPort(8082);//  w  ww  .ja  v a2s  . c om
    initializeRoutes();
}

From source file:amazonwebcrawler.Mongo.java

private DBCollection queryDb(String[] args) {
    try {//from www  .j  a  va 2  s . c o m

        /**** Connect to MongoDB ****/
        // Since 2.10.0, uses MongoClient
        MongoClientURI uri = new MongoClientURI(
                "mongodb://heroku_73s67dx7:2d6hshk9a78f2dlfkachg486t7@ds011399.mlab.com:11399/heroku_73s67dx7");
        MongoClient mongo = new MongoClient(uri);

        /**** Get database ****/
        // if database doesn't exists, MongoDB will create it for you
        DB db = mongo.getDB("heroku_73s67dx7");

        /**** Get collection / table from 'testdb' ****/
        // if collection doesn't exists, MongoDB will create it for you
        DBCollection table = db.getCollection("products");
        return table;
    } catch (MongoException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:at.grahsl.kafka.connect.mongodb.end2end.MinimumViableIT.java

License:Apache License

@BeforeAll
public static void setup() throws IOException {
    CONTAINER_ENV.start();//from  w  ww. j a  va 2s  .  c  o  m
    MONGODB_CLIENT_URI = new MongoClientURI("mongodb://" + MONGODB + ":" + MONGODB_PORT + "/kafkaconnect");
    MONGO_CLIENT = new MongoClient(MONGODB_CLIENT_URI);
    MONGO_DATABASE = MONGO_CLIENT.getDatabase(MONGODB_CLIENT_URI.getDatabase());

    Properties props = new Properties();
    props.put("bootstrap.servers", KAFKA_BROKER + ":" + KAFKA_BROKER_PORT);
    props.put("key.serializer", "io.confluent.kafka.serializers.KafkaAvroSerializer");
    props.put("value.serializer", "io.confluent.kafka.serializers.KafkaAvroSerializer");
    props.put("schema.registry.url", "http://" + SCHEMA_REGISTRY + ":" + SCHEMA_REGISTRY_PORT);
    PRODUCER = new KafkaProducer<>(props);

    String config = new String(Files.readAllBytes(Paths.get(SINK_CONNECTOR_CONFIG)));

    deferExecutionToWaitForDataPropagation(Duration.ofMinutes(2),
            "wait some time so that all container processes become available");

    registerMongoDBSinkConnector(config);
}

From source file:at.rocworks.oa4j.logger.dbs.NoSQLMongoDB.java

private void initStorage(String url, String db) {
    JDebug.out.info("mongodb init storage...");
    MongoClientURI uri = new MongoClientURI(url);
    client = new MongoClient(uri);
    database = client.getDatabase(db);/*  w  w  w. j  a v a 2  s . c  om*/
    evcoll = database.getCollection("events");
}

From source file:be.nille.blog.web.BeanConfig.java

@Bean
public MongoDatabase database() {
    final String url = System.getenv("MONGO_URL");
    log.debug("MONGO URL:" + url);
    try {// w  w w. j  a  va 2s. c om
        MongoClient client = new MongoClient(new MongoClientURI(url));
        return client.getDatabase("openid-connect");
    } catch (RuntimeException ex) {
        log.error(ex.getMessage());
        throw new RuntimeException(String.format("Could not connect to Mongo Database with URL %s", url));
    }
}