Example usage for com.mongodb MongoClient MongoClient

List of usage examples for com.mongodb MongoClient MongoClient

Introduction

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

Prototype

public MongoClient(final MongoClientURI uri) 

Source Link

Document

Creates a Mongo described by a URI.

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:Publisher.java

public static void main(String[] args) throws UnknownHostException, InterruptedException {
    System.out.println("testing publisher");

    //System.out.println(tripUpdates.get(0).tripId + " - " + 
    //      tripUpdates.get(0).stopUpdates.get(0).stopSeq + ": " + 
    //   tripUpdates.get(0).stopUpdates.get(0).arrivalDelay);

    GtfsRealtimeHttpVehicleUpdateSource gtfs = new GtfsRealtimeHttpVehicleUpdateSource();
    GtfsRealtimeHttpTripUpdateSource tripgtfs = new GtfsRealtimeHttpTripUpdateSource();
    //GtfsRealtimeHttpAlertsUpdateSource alertgtfs = new GtfsRealtimeHttpAlertsUpdateSource();

    Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
    jedisClusterNodes.add(new HostAndPort("193.10.227.200", 7005));
    JedisCluster jc = new JedisCluster(jedisClusterNodes);
    System.out.println("Currently " + jc.getClusterNodes().size() + " nodes in cluster");
    Map<String, JedisPool> nodeMap = jc.getClusterNodes();
    List<JedisPool> nodePoolList = new ArrayList<JedisPool>(nodeMap.values());
    Collections.shuffle(nodePoolList);

    System.out.println("connect to mongo");
    ;/*from w  ww.  j av a  2s .  c  o  m*/
    MongoClient mongoClient = new MongoClient("192.168.93.73");
    DB db = mongoClient.getDB("mydb");
    System.out.println("connected!");
    DBCollection coll = db.getCollection("testCollection");

    /*String ID = "test";
          BasicDBObject doc = new BasicDBObject();
          doc.append("_id", ID).append("seq", "0");
          System.out.println("find");
          DBCursor cursor = coll.find();
          System.out.println("print");
           while(cursor.hasNext()) {
     System.out.println(cursor.next());
             }*/
    while (true) {
        List<TripUpdate> tripUpdates;
        List<AlertTest> alerts = null;
        TripUpdateTest tpt = new TripUpdateTest();
        if (args.length > 0 && args[0].equals("testArrivalDelay"))
            tripUpdates = tpt.testArrivalDelay("testTrip");
        else if (args.length > 0 && args[0].equals("testDepartureDelay"))
            tripUpdates = tpt.testDepartureDelay("testTrip");
        else if (args.length > 0 && args[0].equals("tesTripUpdate"))
            tripUpdates = tpt.testTripUpdate("testTrip");
        else if (args.length > 0 && args[0].equals("testDepArrDelay"))
            tripUpdates = tpt.testDepArrDelay("testTrip", "testTrip2");
        else if (args.length > 0 && args[0].equals("testRandomDelay"))
            tripUpdates = tpt.testRandomDelay("testTrip", "testTrip2");
        else if (args.length > 0 && args[0].equals("testFileDelay"))
            tripUpdates = tpt.testFileDelay("testTrip");
        else
            tripUpdates = tripgtfs.getTripUpdates();

        if (args.length > 0 && (args[0].equals("testAlert") || args.length > 1 && args[1].equals("testAlert")))
            alerts = tpt.testAlert("testRoute");

        //List<Alert> alerts = alertgtfs.getAlerts();
        List<VehiclePositionTest> positions = gtfs.getVehiclePositionUpdates();

        correctNullValues(positions);
        //printPositions(positions);

        if (args.length > 0 && args[0].equals("mongo")) {
            mongoInsertTest(db, positions);
            mongoQueryTest(db, positions);
            mongoInsertTest2(db, tripUpdates);
            mongoQueryTest2(db, tripUpdates);
        }

        //redisInsertTest(jc, positions);
        //redisQueryTest(jc, positions);
        //redisInsertTest2(jc, tripUpdates);
        //redisInsertTest3(jc, alerts);
        //redisQueryTest2(jc, tripUpdates);
        pubTest(nodePoolList, positions);
        pubTest2(nodePoolList, tripUpdates);
        if (alerts != null)
            pubTest3(nodePoolList, alerts);
        Thread.sleep(10000);
    }
}

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());

    /*//from  w  w  w  .  jav  a 2s .  c  o  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.j  av a 2 s .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;//ww  w . ja  v a2  s .co  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:act.installer.reachablesexplorer.FreemarkerRenderer.java

License:Open Source License

private void init(String dbHost, Integer dbPort, String dbName, String dnaCollection, String pathwayCollection)
        throws IOException {
    cfg = new Configuration(Configuration.VERSION_2_3_23);

    cfg.setClassLoaderForTemplateLoading(this.getClass().getClassLoader(),
            "/act/installer/reachablesexplorer/templates");
    cfg.setDefaultEncoding("UTF-8");

    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(true);//from  www  .j ava  2  s. c  o m

    reachableTemplate = cfg.getTemplate(reachableTemplateName);
    pathwayTemplate = cfg.getTemplate(pathwayTemplateName);

    // TODO: move this elsewhere.
    MongoClient client = new MongoClient(new ServerAddress(dbHost, dbPort));
    DB db = client.getDB(dbName);

    dnaDesignCollection = JacksonDBCollection.wrap(db.getCollection(dnaCollection), DNADesign.class,
            String.class);
    Cascade.setCollectionName(pathwayCollection);
}

From source file:act.installer.reachablesexplorer.Loader.java

License:Open Source License

/**
 * Constructor for Loader. Instantiates connexions to Mongo databases
 * and Virtuoso triple store (Pubchem synonyms only)
 * @param host The host for the target Reachables MongoDB
 * @param port The port for the target Reachables MongoDB
 * @param targetDB The database for the target Reachables MongoDB
 * @param targetCollection The collection for the target Reachables MongoDB
 * @param targetSequenceCollection The collection for the target SequenceData MongoDB
 * @param renderingCache A directory where rendered images should live
 *///from   w w w.ja  v  a2  s .co m
public Loader(String host, Integer port, String sourceDB, String targetDB, String targetCollection,
        String targetSequenceCollection, String renderingCache) {
    // when the caller does not intend to touch the sourceDB, it can pass null as a param and we
    // won't setup a "source" connection. Creating a connection with "dummy" params leads mongod
    // to create (!) those dummy collections, mucking up our database with empty dbs/collections
    if (sourceDB != null) {
        sourceDBconn = new MongoDB(host, port, sourceDB);
        wordCloudGenerator = new WordCloudGenerator(host, port, sourceDB, renderingCache);
    }
    pubchemSynonymsDriver = new PubchemMeshSynonyms();
    moleculeRenderer = new MoleculeRenderer(new File(renderingCache));

    MongoClient mongoClient;
    try {
        mongoClient = new MongoClient(new ServerAddress(host, port));
    } catch (UnknownHostException e) {
        LOGGER.error(
                "Connection to MongoClient failed. Please double check the target database's host and port.");
        throw new RuntimeException(e);
    }
    DB reachables = mongoClient.getDB(targetDB);

    // TODO: this unsafe initialization does not belong in the constructor.
    try {
        calculator = new PhysiochemicalPropertiesCalculator.Factory().build();
    } catch (PluginException e) {
        LOGGER.error("Unable to initialize physiochemical calculator: %s", e.getMessage());
        throw new RuntimeException(e);
    }

    if (targetCollection != null) {
        jacksonReachablesCollection = JacksonDBCollection.wrap(reachables.getCollection(targetCollection),
                Reachable.class, String.class);
        jacksonReachablesCollection.ensureIndex(new BasicDBObject(Reachable.INCHI_FIELD_NAME, "hashed"));
    }

    if (targetSequenceCollection != null) {
        jacksonSequenceCollection = JacksonDBCollection.wrap(reachables.getCollection(targetSequenceCollection),
                SequenceData.class, String.class);
        jacksonSequenceCollection.createIndex(new BasicDBObject(SequenceData.SEQUENCE_FIELD_NAME, "hashed"));
        jacksonSequenceCollection.createIndex(new BasicDBObject(SequenceData.ORGANISM_FIELD_NAME, 1));
    }
}

From source file:adc.data.viewer.dao.ConnectionBuilderMongo.java

License:Open Source License

@Override
public MongoClient getConnection() {

    try {//from ww w .j  a v  a 2s  .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:aic2013.extractor.TwitterExtractor.java

public static void main(String[] args) throws Exception {
    EntityManagerFactory emf = null;/*from   w  w  w .  j  av a  2  s . co m*/
    MongoClient mongoClient = null;
    Twitter twitter = null;
    Neo4jConnection neo4j = null;

    try {
        // Database configuration
        Properties prop = new Properties();
        prop.load(new FileInputStream("hibernate.properties"));
        // prop.load(TwitterExtractor.class.getClassLoader().getResourceAsStream("hibernate.properties"));

        emf = Persistence.createEntityManagerFactory("twitterdb", prop);
        final String mongoServer = "localhost";
        mongoClient = new MongoClient(mongoServer);
        twitter = TwitterFactory.getSingleton();

        //         final String neo4jJdbc = "jdbc:neo4j:ec2-54-217-131-208.eu-west-1.compute.amazonaws.com:7474";
        final String neo4jJdbc = "jdbc:neo4j://localhost:7474";
        neo4j = new Driver().connect(neo4jJdbc, new Properties());
        neo4j.setAutoCommit(true);//false);

        final TwitterDataAccess twitterDataAccess = new TwitterDataAccess(twitter);
        final MongoDataAccess mongoDataAccess = new MongoDataAccess(mongoClient);
        final Neo4jService neo4jService = new Neo4jService(neo4j);
        final EntityManager em = emf.createEntityManager();
        final UserDataAccess userDataAcces = new UserDataAccess(em);

        final TopicExtractionCoordinator extractionCoordinator = new TopicExtractionCoordinatorImpl();

        //         final ConcurrentLinkedQueue<E>
        final UserService userService = new UserService(em);
        final Processor<Status> mongoProcessor = new Processor<Status>() {

            @Override
            public void process(final Status status) {
                final TwitterUser user = new TwitterUser(status.getUser());
                userService.persist(user);
                neo4jService.transactional(new Neo4jUnitOfWork() {

                    @Override
                    public void process() throws SQLException {
                        neo4jService.createPersonIfAbsent(user);
                        // HashtagEntity[] topics =
                        // status.getHashtagEntities();
                        Status originalStatus = status;
                        if (status.isRetweet()) {
                            originalStatus = status.getRetweetedStatus();
                        }

                        extractionCoordinator.doExtraction(originalStatus, new TopicExtractionCallback() {

                            @Override
                            public void handleExtractionResult(Set<Topic> extractedTopics) {
                                /* TODO: comment out outputs */
                                //                              System.out.println(status.getText());
                                //                              for (Topic t : extractedTopics) {
                                //                                 System.out.println(t.getName());
                                //                              }
                                try {
                                    /* add hash tags to topics */
                                    for (HashtagEntity tag : status.getHashtagEntities()) {
                                        extractedTopics.add(new Topic(new String[] { tag.getText() }));
                                    }
                                    for (Topic topic : extractedTopics) {
                                        neo4jService.createTopicIfAbsent(topic);
                                        if (status.isRetweet()) {
                                            neo4jService.createRelationIfAbsent("RETWEETS", user, topic);
                                        } else {
                                            neo4jService.createRelationIfAbsent("TWEETS", user, topic);
                                        }
                                    }
                                } catch (SQLException e) {
                                    throw new RuntimeException(e);
                                }

                            }

                            @Override
                            public void handleExtractionError(ExtractionException e) {
                                throw new RuntimeException(e);
                            }
                        });
                    }
                });
            }
        };
        final Processor<TwitterUser> userProcessor = new Processor<TwitterUser>() {

            @Override
            public void process(final TwitterUser user) {
                try {
                    twitterDataAccess.forAllFollowers(user, new Processor<User>() {

                        @Override
                        public void process(User u) {
                            final TwitterUser follower = em.find(TwitterUser.class, u.getId());

                            if (follower != null) {
                                neo4jService.transactional(new Neo4jUnitOfWork() {

                                    @Override
                                    public void process() throws SQLException {
                                        neo4jService.createUniqueRelation("FOLLOWS", user, follower);
                                    }
                                });
                            }
                        }
                    });
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        };

        // invoke the processor for every entry in mongo
        mongoDataAccess.forAll(mongoProcessor);
        extractionCoordinator.awaitTermination(-1, TimeUnit.SECONDS);
        // invoke the processor for every entry in the rdbms
        //         userDataAcces.forAll(userProcessor);
    } finally {
        if (emf != null && emf.isOpen()) {
            emf.close();
        }
        if (mongoClient != null) {
            mongoClient.close();
        }
        if (twitter != null) {
            twitter.shutdown();
        }
        if (neo4j != null) {
            neo4j.close();
        }
    }
}

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);//from  ww w .  j a v a 2 s  .co m
    initializeRoutes();
}