No SQL mongoDB


1)create new folder
C:\MongoDB\data
C:\MongoDB\log

2)create Mongo.config file
dbpath=C:\MongoDB\data
logpath=C:\MongoDB\log\mongodb.log
diaglog=3

goto cmd: C:\MongoDB\mongodb-win32-x86_64-2008plus-2.6.4\bin
execute to start server :mongod.exe --config="C:\MongoDB\Mongo.config"


Task 2 – Create new database and collection for storing user data
1.     Connect to MongoDB server using MongoVUE.
2.     Create new database by right clicking on the server node and selecting “Add Database”. Name the new database as “usermanager”.
3.     Add new collection to usermanager database by right clicking on the database node and selecting “Add Collection”. Name the new collection as “user”.
Task 3 – Create client application
1.     Open Eclipse and create a new java project.
a.     Select File > New > Project.
b.     Expand ‘Java’ node and select ‘Java Project’. Click ‘Next’.
c.      Name the project as ‘UserManager’ and click ‘Finish’.
2.     Add MongoDB Java driver to the classpath.
a.     Right click project node and select ‘Properties’.
b.     Select ‘Java Build Path’ and go to ‘Libraries’ tab.
c.      Click on ‘Add External JARs’ button and browse for the jar file.
d.     Click ‘OK’ to close the window.
3.     Add ‘DBManager’ singleton class for managing database connections
a.     Right click src node > New > Class.
b.     Name the new class as DBManager.
c.      Click ‘Finish’.

d.     Add the following code to the new class:

1. Create DBManager class

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.MongoClient;


public class DBManager {

    private static DB database;
   
    public static DB getDatabase(){
        if(database==null){
            MongoClient mongo;
            try {
                mongo = new MongoClient("localhost",27017);
                database = mongo.getDB("usermanager");
            } catch (UnknownHostException e) {
            e.printStackTrace();
            }
        }
        return database;
       
    }
}


2. User POJO class


public class User {
    private int id;
    private String firtNmae;
    private String lastName;
    private String email;
          
  /*  public User() {
        super();
    }
    public User(int id) {
        super();
        this.id = id;
    }*/

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirtNmae() {
        return firtNmae;
    }
    public void setFirtNmae(String firtNmae) {
        this.firtNmae = firtNmae;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
   
   
}
Main Method

Imports
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;

3. Add user codes
Bold methods implementation are mentioned below
Add user Button Click
JButton btnAddUser = new JButton("Add User");
        btnAddUser.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                User newUser = new User();
                newUser.setId(Integer.parseInt(txtid.getText()));
              
                newUser.setFirtNmae(txtname.getText());
              
                newUser.setLastName(txtlastname.getText());

                newUser.setEmail(txtemail.getText());
              
                DBObject doc =createDBObject(newUser);
              
                DB userDB = DBManager.getDatabase();
                DBCollection col = userDB.getCollection("user");
                WriteResult result = col.insert(doc);
                }
        });
4.Update user button click

JButton btnUpdateUser = new JButton("Update User");
        btnUpdateUser.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               
                //updating values
                User newUser = new User();
                newUser.setFirtNmae(txtname.getText());
                newUser.setLastName(txtlastname.getText());
                newUser.setEmail(txtemail.getText());
                DBObject doc =createUpdateDBObject(newUser);
               
                //Key for update values
                User newUser2 = new User();
                newUser2.setId(Integer.parseInt(txtid.getText()));
                DBObject key = createIdDBObject(newUser2);
               
                               
                DB userDB = DBManager.getDatabase();
                DBCollection col = userDB.getCollection("user");
                WriteResult result = col.update(key, doc);
               
            }
        });


5.Delete User button click

JButton btnRemoveUser = new JButton("Remove User");
        btnRemoveUser.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
               
                User newUser = new User();
                newUser.setId(Integer.parseInt(txtid.getText()));
               
                DBObject doc =createIdDBObject(newUser);
               
                DB userDB = DBManager.getDatabase();
                DBCollection col = userDB.getCollection("user");
                WriteResult result = col.remove(doc);
            }
        });

Bold methods
private static DBObject createDBObject(User user){
        BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();
        docBuilder.append("_id", user.getId());
        docBuilder.append("firstName", user.getFirtNmae());
        docBuilder.append("lastName", user.getLastName());
        docBuilder.append("email", user.getEmail());
        return docBuilder.get();
    }
   
    private static DBObject createUpdateDBObject(User user){
        BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();
        docBuilder.append("firstName", user.getFirtNmae());
        docBuilder.append("lastName", user.getLastName());
        docBuilder.append("email", user.getEmail());
        return docBuilder.get();
    }
   
   
    private static DBObject createIdDBObject(User user){
        BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();
        docBuilder.append("_id", user.getId());
        return docBuilder.get();
    }

View All/Search method

public static void viewAll( ){
          try{      
             DB userDB = DBManager.getDatabase();
             DBCollection coll = userDB.getCollection("user");
             DBCursor cursor = coll.find();
             int i=1;
             while (cursor.hasNext()) {
                System.out.println("Inserted Document: "+i);
                System.out.println(cursor.next());
                i++;
             }
          }catch(Exception e){
             System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          }
       }

---------------------------------------------------------------------------------------------------------------------
EmployeeManager.java

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;

import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class EmployeeManager extends JFrame {

private JPanel contentPane;
private JTextField txt_id;
private JTextField txt_fname;
private JTextField txt_lname;
private JTextField txt_email;
private JTextField txt_username;
private JPasswordField txt_password;

private boolean employeAvailable = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
EmployeeManager frame = new EmployeeManager();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

private static DBObject createDBObject(Employee emp) {
BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();
docBuilder.append("_id", emp.getId());
docBuilder.append("firstName", emp.getFirtName());
docBuilder.append("lastName", emp.getLastName());
docBuilder.append("email", emp.getEmail());
docBuilder.append("username", emp.getUsername());
docBuilder.append("pwd", emp.getPwd());
return docBuilder.get();
}

/**
* Create the frame.
*/
public EmployeeManager() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 448, 451);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(0, 0, 434, 412);
contentPane.add(tabbedPane);

JPanel panel = new JPanel();
tabbedPane.addTab("Add Employee", null, panel, null);
panel.setLayout(null);

JLabel lblNewLabel = new JLabel("ID");
lblNewLabel.setBounds(10, 22, 46, 14);
panel.add(lblNewLabel);

JLabel lblNewLabel_1 = new JLabel("First Name");
lblNewLabel_1.setBounds(10, 79, 62, 14);
panel.add(lblNewLabel_1);

JLabel lblNewLabel_2 = new JLabel("Last Name");
lblNewLabel_2.setBounds(10, 133, 75, 14);
panel.add(lblNewLabel_2);

JLabel lblNewLabel_3 = new JLabel("Email");
lblNewLabel_3.setBounds(10, 187, 46, 14);
panel.add(lblNewLabel_3);

JLabel lblUserName = new JLabel("User Name");
lblUserName.setBounds(10, 239, 62, 14);
panel.add(lblUserName);

JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(10, 299, 62, 14);
panel.add(lblPassword);

txt_id = new JTextField();
txt_id.setBounds(153, 19, 136, 20);
panel.add(txt_id);
txt_id.setColumns(10);

txt_fname = new JTextField();
txt_fname.setBounds(153, 76, 136, 20);
panel.add(txt_fname);
txt_fname.setColumns(10);

txt_lname = new JTextField();
txt_lname.setBounds(153, 130, 136, 20);
panel.add(txt_lname);
txt_lname.setColumns(10);

txt_email = new JTextField();
txt_email.setBounds(153, 184, 136, 20);
panel.add(txt_email);
txt_email.setColumns(10);

txt_username = new JTextField();
txt_username.setBounds(153, 236, 136, 20);
panel.add(txt_username);
txt_username.setColumns(10);

txt_password = new JPasswordField();
txt_password.setBounds(153, 296, 136, 20);
panel.add(txt_password);

JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String id = txt_id.getText();
String fname = txt_fname.getText();
String lname = txt_lname.getText();
String email = txt_email.getText();
String username = txt_username.getText();
String pwd = txt_password.getPassword().toString();
String emailreg = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$";
if (!(id.isEmpty())
&& !(fname.isEmpty())
&& !(lname.isEmpty() && !(username.isEmpty()) && !(pwd
.isEmpty())) && !(email.isEmpty())) {

if (email.matches(emailreg)) {
if (pwd.length() >= 3) {
Employee newUser = new Employee();
newUser.setId(Integer.parseInt(id));
newUser.setFirtName(fname);
newUser.setLastName(lname);
newUser.setEmail(email);
newUser.setUsername(username);
newUser.setPwd(pwd);

Employee SearchUser = new Employee();
SearchUser.setId(Integer.parseInt(id));
DBObject objSearch = BasicDBObjectBuilder.start()
.append("_id", SearchUser.getId()).get();
DB userDB1 = DBManager.getDatabase();
DBCollection col1 = userDB1.getCollection("Employee");
DBCursor search = col1.find(objSearch);
if (search.hasNext()) {
employeAvailable = true;
JOptionPane.showMessageDialog(null,
"Entered Employee ID Available",
"Registered Message",
JOptionPane.INFORMATION_MESSAGE);
} else {
DBObject doc = createDBObject(newUser);
DB userDB = DBManager.getDatabase();
DBCollection col = userDB.getCollection("Employee");
WriteResult result = col.insert(doc);
JOptionPane.showMessageDialog(null,
"Sucessfully Registered",
"Registered Message",
JOptionPane.INFORMATION_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null,
"Not a Valid Fname", "Name warning",
JOptionPane.ERROR_MESSAGE);
}

} else {
JOptionPane.showMessageDialog(null,
"Not a Valid Email", "Email warning",
JOptionPane.ERROR_MESSAGE);
}

} else {
JOptionPane.showMessageDialog(null, "Please Fill Details");
}
}
});
btnRegister.setBounds(300, 350, 89, 23);
panel.add(btnRegister);
}
}