Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package usermanager; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoException; import com.mongodb.WriteResult; import static com.sun.xml.internal.fastinfoset.alphabet.BuiltInRestrictedAlphabets.table; import java.net.UnknownHostException; /** * * @author PDK */ public class Main2 extends javax.swing.JFrame { /** * Creates new form Main */ public Main2() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { lblId = new javax.swing.JLabel(); lblFirstName = new javax.swing.JLabel(); lblLastName = new javax.swing.JLabel(); lblEmail = new javax.swing.JLabel(); txtId = new javax.swing.JTextField(); txtFirstName = new javax.swing.JTextField(); txtLastName = new javax.swing.JTextField(); txtEmail = new javax.swing.JTextField(); btnAddUser = new javax.swing.JButton(); btnUpdateUser = new javax.swing.JButton(); btnFindUser = new javax.swing.JButton(); btnDeleteUser = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); lblId.setText("ID"); lblFirstName.setText("First Name"); lblLastName.setText("Last Name"); lblEmail.setText("Email"); btnAddUser.setText("Add User"); btnAddUser.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAddUserActionPerformed(evt); } }); btnUpdateUser.setText("Update User"); btnUpdateUser.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnUpdateUserActionPerformed(evt); } }); btnFindUser.setText("Find User"); btnFindUser.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnFindUserActionPerformed(evt); } }); btnDeleteUser.setText("Delete User"); btnDeleteUser.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDeleteUserActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(47, 47, 47).addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(lblId) .addComponent(lblEmail).addComponent(lblLastName).addComponent(lblFirstName)) .addGap(69, 69, 69).addGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtFirstName).addComponent(txtLastName) .addComponent(txtEmail, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE) .addComponent(txtId))) .addGroup(layout.createSequentialGroup().addGap(107, 107, 107) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnAddUser).addComponent(btnFindUser)) .addGap(28, 28, 28).addGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(btnUpdateUser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnDeleteUser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap(95, Short.MAX_VALUE))); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(72, 72, 72) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblId).addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblFirstName).addComponent(txtFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lblLastName).addComponent(txtLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblEmail).addComponent(txtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnAddUser).addComponent(btnUpdateUser)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnFindUser).addComponent(btnDeleteUser)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); pack(); }// </editor-fold>//GEN-END:initComponents private void btnAddUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddUserActionPerformed // TODO add your handling code here: // Create user object User newUser = new User(); newUser.setId(Integer.parseInt(txtId.getText())); newUser.setFirstName(txtFirstName.getText()); newUser.setLastName(txtLastName.getText()); newUser.setEmail(txtEmail.getText()); // Get connection to the Collection DB userDB = DBManager.getDatabase(); DBCollection col = userDB.getCollection("user"); // Insert the Document BasicDBObject doc = new BasicDBObject(); doc.put("_id", newUser.getId()); doc.put("firstName", newUser.getFirstName()); doc.put("lastName", newUser.getLastName()); doc.put("email", newUser.getEmail()); WriteResult result = col.insert(doc); System.out.println("Inserted..."); }//GEN-LAST:event_btnAddUserActionPerformed private void btnUpdateUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateUserActionPerformed // TODO add your handling code here: // Create user object User newUser = new User(); newUser.setId(Integer.parseInt(txtId.getText())); newUser.setFirstName(txtFirstName.getText()); newUser.setLastName(txtLastName.getText()); newUser.setEmail(txtEmail.getText()); // Get connection to the Collection DB userDB = DBManager.getDatabase(); DBCollection col = userDB.getCollection("user"); // Search BasicDBObject query = new BasicDBObject(); query.put("_id", newUser.getId()); // Update values BasicDBObject doc = new BasicDBObject(); doc.put("firstName", newUser.getFirstName()); doc.put("lastName", newUser.getLastName()); doc.put("email", newUser.getEmail()); /* // Method A // This will update all values, including all fields and values WriteResult result = col.update(query, doc); */ //Method B // Update object only with the relevant fields using $set BasicDBObject updateObj = new BasicDBObject(); updateObj.put("$set", doc); WriteResult result = col.update(query, updateObj); System.out.println("Updated..."); }//GEN-LAST:event_btnUpdateUserActionPerformed private void btnFindUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFindUserActionPerformed // TODO add your handling code here: // Get connection to the Collection DB userDB = DBManager.getDatabase(); DBCollection col = userDB.getCollection("user"); // Search BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("_id", Integer.parseInt(txtId.getText())); DBCursor cursor = col.find(searchQuery); while (cursor.hasNext()) { // Access next object cursor.next(); // Get the whole document printed in the console, if needed System.out.println(cursor.curr()); // Find by field and set to user object User newUser = new User(); newUser.setId(Integer.parseInt(cursor.curr().get("_id").toString())); newUser.setFirstName(cursor.curr().get("firstName").toString()); newUser.setLastName(cursor.curr().get("lastName").toString()); newUser.setEmail(cursor.curr().get("email").toString()); // Show in the form txtId.setText(String.valueOf(newUser.getId())); txtFirstName.setText(newUser.getFirstName()); txtLastName.setText(newUser.getLastName()); txtEmail.setText(newUser.getEmail()); } }//GEN-LAST:event_btnFindUserActionPerformed private void btnDeleteUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteUserActionPerformed // TODO add your handling code here: // Get connection to the Collection DB userDB = DBManager.getDatabase(); DBCollection col = userDB.getCollection("user"); try { BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("_id", Integer.parseInt(txtId.getText())); col.remove(searchQuery); System.out.println("Deleted..."); } catch (MongoException e) { e.printStackTrace(); } // Empty the form txtId.setText(""); txtFirstName.setText(""); txtLastName.setText(""); txtEmail.setText(""); }//GEN-LAST:event_btnDeleteUserActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Main2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Main2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Main2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Main2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Main2().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAddUser; private javax.swing.JButton btnDeleteUser; private javax.swing.JButton btnFindUser; private javax.swing.JButton btnUpdateUser; private javax.swing.JLabel lblEmail; private javax.swing.JLabel lblFirstName; private javax.swing.JLabel lblId; private javax.swing.JLabel lblLastName; private javax.swing.JTextField txtEmail; private javax.swing.JTextField txtFirstName; private javax.swing.JTextField txtId; private javax.swing.JTextField txtLastName; // End of variables declaration//GEN-END:variables }