usermanager.Main3.java Source code

Java tutorial

Introduction

Here is the source code for usermanager.Main3.java

Source

/*
 * 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.WriteResult;

/**
 *
 * @author PDK
 */
public class Main3 extends javax.swing.JFrame {

    /**
     * Creates new form Main
     */
    public Main3() {
        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();
        txtId = new javax.swing.JTextField();
        txtFirstName = new javax.swing.JTextField();
        txtLastName = new javax.swing.JTextField();
        btnAddUser = new javax.swing.JButton();
        btnUpdateUser = new javax.swing.JButton();
        btnFindUser = new javax.swing.JButton();
        btnUpsertUser = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lblId.setText("ID");

        lblFirstName.setText("First Name");

        lblLastName.setText("Last Name");

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

        btnUpsertUser.setText("Upsert User");
        btnUpsertUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpsertUserActionPerformed(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(lblLastName).addComponent(lblFirstName))
                                .addGap(69, 69, 69)
                                .addGroup(layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(txtFirstName, javax.swing.GroupLayout.DEFAULT_SIZE, 96,
                                                Short.MAX_VALUE)
                                        .addComponent(txtLastName).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)
                                        .addComponent(btnUpsertUser).addComponent(btnUpdateUser))))
                        .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(67, 67, 67)
                        .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(btnUpsertUser))
                        .addContainerGap(13, 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:      
        // Get connection to the Collection
        DB userDB = DBManager.getDatabase();
        DBCollection col = userDB.getCollection("user");
        // Insert the Document
        BasicDBObject doc = new BasicDBObject();
        doc.put("_id", Integer.parseInt(txtId.getText()));
        doc.put("firstName", txtFirstName.getText());
        doc.put("lastName", txtLastName.getText());
        WriteResult result = col.insert(doc);
    }//GEN-LAST:event_btnAddUserActionPerformed

    private void btnUpdateUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateUserActionPerformed
        // Get connection to the Collection
        DB userDB = DBManager.getDatabase();
        DBCollection col = userDB.getCollection("user");
        // Search
        BasicDBObject query = new BasicDBObject();
        query.put("_id", Integer.parseInt(txtId.getText()));
        // Update values
        BasicDBObject doc = new BasicDBObject();
        doc.put("firstName", txtFirstName.getText());
        doc.put("lastName", txtLastName.getText());
        // Update object only with the relevant fields using $set
        BasicDBObject updateObj = new BasicDBObject();
        updateObj.put("$set", doc);
        WriteResult result = col.update(query, updateObj);
    }//GEN-LAST:event_btnUpdateUserActionPerformed

    private void btnFindUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFindUserActionPerformed
        // 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()) {
            // Find by field and show in the form
            txtFirstName.setText(cursor.next().get("firstName").toString());
            txtLastName.setText(cursor.curr().get("lastName").toString());
        }
    }//GEN-LAST:event_btnFindUserActionPerformed

    private void btnUpsertUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpsertUserActionPerformed
        // Get connection to the Collection
        DB userDB = DBManager.getDatabase();
        DBCollection col = userDB.getCollection("user");
        // Search
        BasicDBObject query = new BasicDBObject();
        query.put("_id", Integer.parseInt(txtId.getText()));
        // Update values
        BasicDBObject doc = new BasicDBObject();
        doc.put("firstName", txtFirstName.getText());
        doc.put("lastName", txtLastName.getText());
        // Update object only with the relevant fields using $set
        BasicDBObject updateObj = new BasicDBObject();
        updateObj.put("$set", doc);

        // Only difference is last two parameters
        /*Parameters:
        q - the selection criteria for the update
        o - the modifications to apply
        upsert - when true, inserts a document if no document matches the update query criteria
        multi - when true, updates all documents in the collection that 
           match the update query criteria, otherwise only updates one
        */
        WriteResult result = col.update(query, updateObj, true, false);
    }//GEN-LAST:event_btnUpsertUserActionPerformed

    /**
     * @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(Main3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main3().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddUser;
    private javax.swing.JButton btnFindUser;
    private javax.swing.JButton btnUpdateUser;
    private javax.swing.JButton btnUpsertUser;
    private javax.swing.JLabel lblFirstName;
    private javax.swing.JLabel lblId;
    private javax.swing.JLabel lblLastName;
    private javax.swing.JTextField txtFirstName;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtLastName;
    // End of variables declaration//GEN-END:variables
}