List of usage examples for com.mongodb MongoClient MongoClient
public MongoClient(final MongoClientURI uri, final MongoDriverInformation mongoDriverInformation)
From source file:UnitTest3.java
License:Open Source License
public static void testgridfs3() throws FileNotFoundException, IOException { long time1;//w w w.j a va 2 s.c om long time2; long time3; long time4; int n = 0; // "/home/anees/workspace/testdata/in/App3.class" String fileName = "makezip4.rar"; MongoClient mongo = new MongoClient("localhost", 27017); //DB db = mongo.getDB("JFileDB"); MongoDatabase db = mongo.getDatabase("JFileDB"); GridFSBucket gridFSBucket = GridFSBuckets.create(db); // Get the input stream time1 = System.currentTimeMillis(); InputStream streamToUploadFrom = new FileInputStream("/home/anees/workspace/testdata/in/" + fileName); // Create some custom options GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024 * 1024) .metadata(new Document("type", "class")); byte data[] = new byte[64 * 1024 * 1024]; GridFSUploadStream uploadStream = gridFSBucket.openUploadStream(fileName, options); while ((n = streamToUploadFrom.read(data)) > 0) { uploadStream.write(data, 0, n); } uploadStream.close(); time2 = System.currentTimeMillis(); time3 = System.currentTimeMillis(); Date date = new Date(); FileOutputStream streamToDownloadTo = new FileOutputStream( "/home/anees/workspace/testdata/out/" + fileName + "_" + date.toString()); GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(-1); GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStreamByName(fileName, downloadOptions); long fileLength = downloadStream.getGridFSFile().getLength(); byte[] bytesToWriteTo = new byte[64 * 1024 * 1024]; while ((n = downloadStream.read(bytesToWriteTo)) > 0) { streamToDownloadTo.write(bytesToWriteTo, 0, n); } downloadStream.close(); time4 = System.currentTimeMillis(); System.out.println("The fileId of the uploaded file is: " + uploadStream.getFileId().toHexString()); System.out.println("Upload time taken : time2 - time1 : " + (time2 - time1)); System.out.println("Download time taken : time4 - time3 : " + (time4 - time3)); streamToDownloadTo.close(); streamToUploadFrom.close(); mongo.close(); }
From source file:UnitTest3.java
License:Open Source License
public static void testgridfs4() throws FileNotFoundException, IOException { MongoClient mongo = new MongoClient("localhost", 27017); //DB db = mongo.getDB("JFileDB"); MongoDatabase db = mongo.getDatabase("JFileDB"); GridFSBucket gridFSBucket = GridFSBuckets.create(db); // Get the input stream InputStream streamToUploadFrom = new ByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8)); // Create some custom options GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024) .metadata(new Document("type", "file")); ObjectId fileId = gridFSBucket.uploadFromStream("test", streamToUploadFrom, options); streamToUploadFrom.close();/*ww w .j a va2s . co m*/ System.out.println("The fileId of the uploaded file is: " + fileId.toHexString()); // Get some data to write byte[] data = "some data to upload into GridFS".getBytes(StandardCharsets.UTF_8); GridFSUploadStream uploadStream = gridFSBucket.openUploadStream("sample_data"); uploadStream.write(data); uploadStream.close(); System.out.println("The fileId of the uploaded file is: " + uploadStream.getFileId().toHexString()); /* gridFSBucket.find().forEach(new Block<GridFSFile>() { public void apply(final GridFSFile gridFSFile) { System.out.println(gridFSFile.getFilename()); } }); */ /* gridFSBucket.find(eq("metadata.contentType", "image/png")).forEach( new Block<GridFSFile>() { public void apply(final GridFSFile gridFSFile) { System.out.println(gridFSFile.getFilename()); } }); */ FileOutputStream streamToDownloadTo = new FileOutputStream("/tmp/test.txt"); gridFSBucket.downloadToStream(fileId, streamToDownloadTo); streamToDownloadTo.close(); streamToDownloadTo = new FileOutputStream("/tmp/test.txt"); GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(0); gridFSBucket.downloadToStreamByName("test", streamToDownloadTo, downloadOptions); streamToDownloadTo.close(); GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId); int fileLength = (int) downloadStream.getGridFSFile().getLength(); byte[] bytesToWriteTo = new byte[fileLength]; downloadStream.read(bytesToWriteTo); downloadStream.close(); System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8)); downloadStream = gridFSBucket.openDownloadStreamByName("sample_data"); fileLength = (int) downloadStream.getGridFSFile().getLength(); bytesToWriteTo = new byte[fileLength]; downloadStream.read(bytesToWriteTo); downloadStream.close(); System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8)); gridFSBucket.rename(fileId, "test2"); gridFSBucket.delete(fileId); mongo.close(); }
From source file:HW4.java
/** * Creates new form dbGui//from ww w .ja va 2 s . c om */ public HW4() throws SQLException { initComponents(); label = true; finalCat = new ArrayList<>(); fromCheckin = ""; fromCheckinHour = ""; toCheckin = ""; toCheckinHour = ""; operationCheckin = ""; valueCheckin = ""; operationStar = ""; operationVote = ""; valueStar = ""; valueVote = ""; fromReview = ""; toReview = ""; memberSince = ""; operReviewCount = ""; operNoOfFriends = ""; operAvgStar = ""; valueReviewCount = ""; valueNoOfFriends = ""; valueAvgStar = ""; andOrAttribute = ""; Address = ""; proximity = ""; searchFor = ""; latitude = 0.0; longitude = 0.0; operNoOfVotes = ""; valueNoOfVotes = ""; // checkinList = new ArrayList<CheckinDetail>(); mongoClient = new MongoClient("localhost", 27017); memberSinceDateBox.setEnabled(false); reviewCountComboBox.setEnabled(false); reviewCountValueTextField.setEnabled(false); numberOfFriendsComboBox.setEnabled(false); numberOfFriendsValueTextField.setEnabled(false); avgStarComboBox.setEnabled(false); avgStarValueTextField.setEnabled(false); andOrComboBox.setEnabled(false); model = (DefaultListModel) jList1.getModel(); checkinValueTextField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { text(); } @Override public void removeUpdate(DocumentEvent e) { text(); } @Override public void changedUpdate(DocumentEvent e) { text(); } public void text() { valueCheckin = checkinValueTextField.getText(); //System.out.println(valueCheckin); } }); starsValueTextField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { text(); } @Override public void removeUpdate(DocumentEvent e) { text(); } @Override public void changedUpdate(DocumentEvent e) { text(); } public void text() { valueStar = starsValueTextField.getText(); //System.out.println(valueStar); } }); votesValueTextField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { text(); } @Override public void removeUpdate(DocumentEvent e) { text(); } @Override public void changedUpdate(DocumentEvent e) { text(); } public void text() { valueVote = votesValueTextField.getText(); //System.out.println(valueVote); } }); reviewCountValueTextField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { text(); } @Override public void removeUpdate(DocumentEvent e) { text(); } @Override public void changedUpdate(DocumentEvent e) { text(); } public void text() { valueReviewCount = reviewCountValueTextField.getText(); //System.out.println(valueCheckin); } }); numberOfFriendsValueTextField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { text(); } @Override public void removeUpdate(DocumentEvent e) { text(); } @Override public void changedUpdate(DocumentEvent e) { text(); } public void text() { valueNoOfFriends = numberOfFriendsValueTextField.getText(); //System.out.println(valueCheckin); } }); avgStarValueTextField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { text(); } @Override public void removeUpdate(DocumentEvent e) { text(); } @Override public void changedUpdate(DocumentEvent e) { text(); } public void text() { valueAvgStar = avgStarValueTextField.getText(); //System.out.println(valueCheckin); } }); noOfVotesValueTextField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { text(); } @Override public void removeUpdate(DocumentEvent e) { text(); } @Override public void changedUpdate(DocumentEvent e) { text(); } public void text() { valueNoOfVotes = noOfVotesValueTextField.getText(); System.out.println(valueNoOfVotes); } }); //fromReview = ((JTextField) fromReviewDate.getDateEditor().getUiComponent()).getText(); //System.out.println(fromReview); resultTable.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent evt) { int row = resultTable.rowAtPoint(evt.getPoint()); int col = resultTable.columnAtPoint(evt.getPoint()); DB dbReview = mongoClient.getDB("review"); DBCollection collReview = dbReview.getCollection("review"); JTable im = new JTable(); DefaultTableModel reviewModel = new DefaultTableModel(0, 0); im.setModel(reviewModel); String header[] = new String[] { "Name", "Review" }; reviewModel.setColumnIdentifiers(header); //im.setRowHeight(50); if (!memberSince.isEmpty() || !operReviewCount.isEmpty() || !operNoOfFriends.isEmpty() || !operAvgStar.isEmpty() || !valueReviewCount.isEmpty() || !valueNoOfFriends.isEmpty() || !valueAvgStar.isEmpty() || !andOrAttribute.isEmpty()) { if (row >= 0 && col == 0) { String tableValue = resultTable.getValueAt(row, col).toString(); String name = resultTable.getValueAt(row, col + 1).toString(); BasicDBObject whereQuery = new BasicDBObject(); whereQuery.put("user_id", tableValue); DBCursor cursor = collReview.find(whereQuery); while (cursor.hasNext()) { Object[] rowReview = new Object[2]; rowReview[0] = name; rowReview[1] = cursor.next().get("text").toString(); reviewModel.addRow(rowReview); } mydialog = new JDialog(); mydialog.setSize(new Dimension(1000, 1000)); mydialog.setTitle("Reviews By User"); mydialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // prevent user from doing something else mydialog.add(im); mydialog.setVisible(true); mydialog.setResizable(true); // JOptionPane.showConfirmDialog(null, // getPanel(tableValue)); } } else { if (row >= 0 && col == 0) { String tableValue = resultTable.getValueAt(row, col).toString(); //String name= resultTable.getValueAt(row, col+1).toString(); BasicDBObject whereQuery = new BasicDBObject(); whereQuery.put("business_id", tableValue); DBCursor cursor = collReview.find(whereQuery); while (cursor.hasNext()) { Object[] rowReview = new Object[1]; //rowReview[0] =name; rowReview[0] = cursor.next().get("text").toString(); reviewModel.addRow(rowReview); } mydialog = new JDialog(); mydialog.setSize(new Dimension(1000, 1000)); mydialog.setTitle("Reviews By User"); mydialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // prevent user from doing something else mydialog.add(im); mydialog.setVisible(true); mydialog.setResizable(true); // JOptionPane.showConfirmDialog(null, // getPanel(tableValue)); } } } }); }
From source file:ImportCSVtoMongo.java
public void run() { String csvFile = ""; BufferedReader br = null;/*from w w w .j a v a 2 s . com*/ String line = ""; String csvSplitBy = "##"; Scanner io = new Scanner(System.in); int i = 1; try { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("doep"); // System.out.println("Enter the csv file path"); csvFile = io.next(); System.out.println("Enter the collection name you want to create"); String coll_name = io.next(); db.createCollection(coll_name, null); DBCollection coll = db.getCollection(coll_name); System.out.println("Connected to Collection"); BasicDBObject doc = new BasicDBObject(); br = new BufferedReader(new FileReader(csvFile)); int q_no = 1; while ((line = br.readLine()) != null) { //use comma seperated values String[] question = line.split(csvSplitBy); System.out.println(i++); System.out.println("Question:" + question[1]); System.out.println("Option1:" + question[2]); System.out.println("Option2:" + question[3]); System.out.println("Option3:" + question[4]); System.out.println("Option4:" + question[5]); System.out.println("ANSWER: " + question[6]); System.out.println(); doc.put("qid", coll_name + q_no); doc.put("quest", question[1]); doc.put("op1", question[2]); doc.put("op2", question[3]); doc.put("op3", question[4]); doc.put("op4", question[5]); doc.put("ans", question[6]); doc.put("image", "none"); coll.insert(doc); q_no++; doc.clear(); } } catch (UnknownHostException ex) { Logger.getLogger(ImportCSVtoMongo.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException e) { } catch (IOException e) { } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:Session_details.java
public Session_details() { initComponents();// ww w. j a va2 s .c o m try { String str = "stats", str2; MongoClient mc = new MongoClient("localhost", 27017); DB db = mc.getDB("parking_system"); DBCollection collection = db.getCollection("statistics"); BasicDBObject query = new BasicDBObject(); BasicDBObject field = new BasicDBObject(); field.put("_id", str); DBCursor cursor = collection.find(field); while (cursor.hasNext()) { DBObject obj = (DBObject) cursor.next(); str2 = obj.get("_id").toString(); if (str2.equals(str)) { wheeler2_cnt_field.setText(obj.get("2wheeler_count").toString()); wheeler2_income_field.setText(obj.get("2wheeler_income").toString()); wheeler4_cnt_field.setText(obj.get("4wheeler_count").toString()); wheeler4_income_field.setText(obj.get("4wheeler_income").toString()); other_cnt_field.setText(obj.get("other_count").toString()); other_income_field.setText(obj.get("other_income").toString()); time_field.setText(obj.get("time").toString()); break; } } } catch (Exception e) { System.err.println(e); } }
From source file:Session_details.java
public void updateSession(String s1)//, String s2) { try {//w w w . j a v a 2s . com int count; MongoClient mc = new MongoClient("localhost", 27017); DB db = mc.getDB("parking_system"); DBCollection collection2 = db.getCollection("statistics"); BasicDBObject query = new BasicDBObject(); BasicDBObject field = new BasicDBObject(); field.put(s1, 1); DBCursor cursor = collection2.find(query, field); BasicDBObject obj = (BasicDBObject) cursor.next(); count = obj.getInt(s1); System.out.println(count); BasicDBObject searchUpdate = new BasicDBObject(); searchUpdate.append(s1, count); BasicDBObject UpdateObject = new BasicDBObject(); UpdateObject.append("$set", new BasicDBObject(s1, 0)); collection2.update(searchUpdate, UpdateObject); } catch (Exception e) { } }
From source file:Session_details.java
private void clear_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clear_buttonActionPerformed // TODO add your handling code here: updateSession("2wheeler_count");//, "2wheeler_count" ); updateSession("2wheeler_income");// , "2wheeler_income"); updateSession("4wheeler_count");// , "4wheeler_count"); updateSession("4wheeler_income");// , "4wheeler_income"); updateSession("other_count");//, "other_count"); updateSession("other_income");//, "other_income"); Calendar cal = Calendar.getInstance(); SimpleDateFormat dt = new SimpleDateFormat("HH:mm:ss"); time_str = cal.getTime().toString(); try {/* www .ja v a 2s . com*/ String s; MongoClient mc = new MongoClient("localhost", 27017); DB db = mc.getDB("parking_system"); DBCollection collection2 = db.getCollection("statistics"); BasicDBObject query = new BasicDBObject(); BasicDBObject field = new BasicDBObject(); field.put("time", 1); DBCursor cursor = collection2.find(query, field); BasicDBObject obj = (BasicDBObject) cursor.next(); s = obj.getString("time"); System.out.println(s); BasicDBObject searchUpdate = new BasicDBObject(); searchUpdate.append("time", s); BasicDBObject UpdateObject = new BasicDBObject(); UpdateObject.append("$set", new BasicDBObject("time", time_str)); collection2.update(searchUpdate, UpdateObject); } catch (Exception e) { } JOptionPane.showMessageDialog(null, "Session Details Cleared!"); setVisible(false); new Admin_rights().setVisible(true); }
From source file:admin_update_Emp.java
public admin_update_Emp(String userid_new2) { initComponents();//from ww w. ja v a 2 s .co m //userid_new = admin_change.userid; userid_new = userid_new2; try { MongoClient mc = new MongoClient("localhost", 27017); DB db = mc.getDB("parking_system"); DBCollection collection = db.getCollection("employee_info"); BasicDBObject query = new BasicDBObject(); BasicDBObject field = new BasicDBObject(); field.put("_id", userid_new); DBCursor cursor = collection.find(field); while (cursor.hasNext()) { DBObject obj = (DBObject) cursor.next(); userid_db = obj.get("_id").toString(); System.out.println(userid_db); if (userid_db.equals(userid_new)) { old_name_field.setText(obj.get("name").toString()); old_lname_field.setText(obj.get("lname").toString()); old_mobno_field.setText(obj.get("mobileno").toString()); old_userid_field.setText(obj.get("_id").toString()); old_password_field.setText(obj.get("password").toString()); System.out.println("In if"); break; } } } catch (Exception e) { } }
From source file:admin_update_Emp.java
private void submit_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submit_buttonActionPerformed // TODO add your handling code here: try {/*from ww w.j a va 2 s .co m*/ MongoClient mc = new MongoClient("localhost", 27017); DB db = mc.getDB("parking_system"); DBCollection collection = db.getCollection("employee_info"); BasicDBObject query = new BasicDBObject(); BasicDBObject field = new BasicDBObject(); field.put("_id", userid_new); DBCursor cursor = collection.find(query, field); while (cursor.hasNext()) { DBObject obj = (DBObject) cursor.next(); userid_db = obj.get("_id").toString(); System.out.println(userid_db); if (userid_new.equals(userid_db)) { System.out.println("IN THIS WALA IF"); /* old_name_field.setText(obj.get("name").toString()); old_lname_field.setText(obj.get("lname").toString()); System.out.println("name "+obj.get("name").toString()); System.out.println("name "+obj.get("name").toString()); old_mobno_field.setText(obj.get("mobileno").toString()); old_userid_field.setText(userid_new); old_password_field.setText(obj.get("password").toString()); System.out.println("Done IN IF"); BasicDBObject query = new BasicDBObject(); BasicDBObject field = new BasicDBObject(); field.put("wheeler_2", 1); DBCursor cursor = collection1.find(query, field); */ String newname, newmobno, newuserid, newpassword, newlname; newname = new_name_field.getText(); newlname = new_lname_field.getText(); newmobno = new_mobno_field.getText(); newpassword = new_password_field.getText(); BasicDBObject searchUpdate = new BasicDBObject(); searchUpdate.append("_id", userid_new);/*. append("name",old_name_field.getText()). append("lname", old_lname_field.getText()). append("mobileno", old_mobno_field.getText()). append("password", old_password_field.getText()); */ BasicDBObject UpdateObject = new BasicDBObject(); UpdateObject.append("$set", new BasicDBObject("name", newname)); collection.update(searchUpdate, UpdateObject); UpdateObject.append("$set", new BasicDBObject("lname", newlname)); collection.update(searchUpdate, UpdateObject); UpdateObject.append("$set", new BasicDBObject("mobileno", newmobno)); collection.update(searchUpdate, UpdateObject); UpdateObject.append("$set", new BasicDBObject("password", newpassword)); collection.update(searchUpdate, UpdateObject); JOptionPane.showMessageDialog(null, "Entry Updated..!"); setVisible(false); new Admin_rights().setVisible(true); break; } } System.out.println("Done OUT IF"); } catch (Exception e) { System.err.println(e); } }
From source file:home.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . j a v a2s . 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"); PrintWriter out = response.getWriter(); response.setContentType("text/html"); String username = request.getParameter("username"); String tweet = request.getParameter("tweet"); try { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("test"); System.out.println("Connection established"); DBCollection User = db.getCollection("User"); DBCollection Tweet = db.getCollection("Tweet"); DBCursor cursor = Tweet.find(); int count = 0; if (cursor.size() < 1) { count = 1; } else { count = cursor.size() + 1; } BasicDBObject document = new BasicDBObject(); document.put("tweet_id", count); document.put("username", username); document.put("tweet_text", tweet); document.put("date", new Date()); Tweet.insert(document); ArrayList<Integer> tweet_id = new ArrayList(); tweet_id.add(count); DBObject searchObject = new BasicDBObject(); searchObject.put("username", username); DBObject modifiedObject = new BasicDBObject(); modifiedObject.put("$push", new BasicDBObject().append("tweet_id", count)); User.update(searchObject, modifiedObject); out.println(tweet); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } }