Monday, October 13, 2014

my webservice with mysql just for reference

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Windows;


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]

public class Service : System.Web.Services.WebService
{
    MySqlConnection connection;
    MySqlDataAdapter adapter;
    MySqlDataReader reader;
    int circleRadius = 10;

    MySql.Data.MySqlClient.MySqlConnection conn;
    // string connectionString = "server=localhost;user id=Malsha;database=centraldbvol1;";
    string myConnectionString = "server=localhost;uid=Malsha;" +
    "pwd=sliit123;database=centraldbvol1;";

    public Service()
    {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

 [WebMethod]
    public int getShopIdBySquareId(int x, int y)
    {
     
        string a = "-100";
        int shopId = -1;
        try
        {
            conn = new MySqlConnection(myConnectionString);
            conn.Open();

            string query = "select Shop_Id from vertualmap_relatedshop a where a.Square_Id_X=" + x.ToString() + " and a.Square_Id_Y=" + y.ToString() + ";";
            MySqlCommand cmd = new MySqlCommand(query, conn);
            reader = cmd.ExecuteReader();

            while (reader.Read())
            {//**assume 1 square id belongs to only 1 shop**
                a = reader.GetInt32(0).ToString();
                shopId = int.Parse(a);
                //if (a.Equals("-100"))
                //    return -1;//if no result dnt come even inside

            }
            if (a.Equals("-100"))
                return -1;//no shop




        }
        catch (MySqlException ex)
        {
            return -2;//execption
        }


        return shopId;

    }
    [WebMethod]
    public List<int> getXYByAutoId(int autoId)
    {
        //workinggggggggggggggggggggggggggggggggggggggggggggggggg////////////////huraaaaaaaaaa
        string a = "-100";
        string b = "-100";
        List<int> xy = new List<int>();
        xy.Add(-100);
        xy.Add(-100);
       
        try
        {
            conn = new MySqlConnection(myConnectionString);
            conn.Open();

            string query = "select Square_Id_X,Square_Id_Y from vertualmap_relatedshop a where a.Auto_Id =" + autoId.ToString() + ";";
            MySqlCommand cmd = new MySqlCommand(query, conn);
            reader = cmd.ExecuteReader();

            while (reader.Read())
            {//**assume 1 square id belongs to only 1 shop**
                a = reader.GetInt32(0).ToString();
                b = reader.GetInt32(1).ToString();
                xy[0]= int.Parse(a);
                xy[1] = int.Parse(b);
                //if (a.Equals("-100"))
                //    return -1;//if no result dnt come even inside

            }
        }
        catch (MySqlException ex)
        {
            return xy;//execption
        }

        return xy;

    }
    [WebMethod]
    public List<int> getStoredResultByInput(int autoId, double anglePoint1X, double anglePoint1Y, double anglePoint2X, double anglePoint2Y,double radius)
    {
        //workingggggggggggggggggggggggggggggggggggggggggggggg
        string a = "-100";
        string b = "-100";
        List<int> xy = new List<int>();
        xy[0] = -100;
        xy[1] = -100;
        try
        {
            conn = new MySqlConnection(myConnectionString);
            conn.Open();

            string query = "select Shop_Id,X,Length  from ar_output a,ar_input b where a.Input_Id=b.Auto_Id AND Square_Id" + autoId.ToString() + "  AND X1=" + anglePoint1X.ToString() + "  AND Y1=" + anglePoint1Y.ToString() + "   AND X2=" + anglePoint2X.ToString() + " AND Y2=" + anglePoint2Y.ToString() + " AND Radius=" + radius.ToString() + ";";
            MySqlCommand cmd = new MySqlCommand(query, conn);
            reader = cmd.ExecuteReader();


            if (reader.Read())
            {



                while (reader.Read())
                {//**assume 1 square id belongs to only 1 shop**
                    a = reader.GetInt32(0).ToString();
                    b = reader.GetInt32(1).ToString();
                    xy[0] = int.Parse(a);
                    xy[1] = int.Parse(b);
                    //if (a.Equals("-100"))
                    //    return -1;//if no result dnt come even inside

                }

            }
            else {
           
           
           
            }

         
        }
        catch (MySqlException ex)
        {
            return xy;//execption
        }

        return xy;

    }

    /* A function to check whether point P(x, y) lies inside the triangle formed
 by A(x1, y1), B(x2, y2) and C(x3, y3) */
    [WebMethod]
    public bool isInsideTriangle(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y)
    {
        bool response = false;

        double A = calculateTriangleArea(x1, y1, x2, y2, x3, y3);

        /* Calculate Area of triangle PBC */
        double A1 = calculateTriangleArea(x, y, x2, y2, x3, y3);

        /* Calculate area of triangle PAC */
        double A2 = calculateTriangleArea(x1, y1, x, y, x3, y3);

        /* Calculate area of triangle PAB */
        double A3 = calculateTriangleArea(x1, y1, x2, y2, x, y);

        double small = 0.001;
        /* Check if sum of A1, A2 and A3 is same as A */
        if (((A1 + A2 + A3) - A) <= small)
            response = true;
        else
            response = false;

        return response;



        // return false;
    }



    /* A function to calculate area of triangle formed by (x1, y1),
       (x2, y2) and (x3, y3) */
    public double calculateTriangleArea(int x1, int y1, int x2, int y2, int x3, int y3)
    {
        return Math.Abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0);
    }

    public class Shop
    {
        public int shopId;
        public double x;
        public double length;
        public string comment;

        public Shop() {
        this.comment="Success";
        }

        public Shop(int id,double x,double length)
        {
            this.shopId = id;
            this.x = x;
            this.length = length;
           
        }
    }

    public class ShopInsideTriangle
    {
        public int shopId;
        public int noOfSquares;
        public List<Square> Squares;
        //double midPointX;
        //double midPointY;
        //double distance;
        public  Square midSquare;
        public double minDistance;
        public double minAngle;
        public double maxAngle;
       // public double relativeMinAngle;
        //public double relativeMaxAngle;

        public double angle;
        public double midAngle;//mx mn

        public ShopInsideTriangle(int shopId)
        {
            this.shopId = shopId;
            this.Squares = new List<Square>();
            this.noOfSquares = 0;


        }
        public void addSquare(Square square)
        {
            this.Squares.Add(square);
            this.noOfSquares++;

        }
        //-------------------------------------------------
        public void setMidSquare(double xo, double yo, double actualAngleTriLeft)
        {

            double midX = this.Squares.Sum(s => s.x);
            double midY = this.Squares.Sum(s => s.y);
            this.midSquare = new Square(midX, midY, xo, yo, actualAngleTriLeft);
        }
        public void setMinDistance()
        {
            this.minDistance= this.Squares.Max(s => s.distance);

        }
        public void setAngles(double xo, double yo, double actualAngleTriLeft)
        {
            this.maxAngle = this.Squares.Max(s => s.relativeAngle);
            this.minAngle = this.Squares.Min(s => s.relativeAngle);
            this.setAngle();

        }
        //------------------
        public void setAngle()
        {

            this.angle = this.maxAngle - this.minAngle;
        }
        public void setMinAngle(double m)
        {
            this.minAngle = m;
            setAngle();
       
        }
        public void setMaxAngle(double m)
        {
            this.maxAngle = m;
            setAngle();

        }
        //double finalX;
        //double finalLength;

        //public List<Album> Albums;
        // public string Name;
    }


    public class Square
    {
        public double x { get; set; }
        public double y { get; set; }
        public double distance;
        public double actualAngle;
        public double relativeAngle { get; set; }

        public Square(double x, double y)
        {
            this.x = x;
            this.y = y;
        }
        public Square(double x, double y, double xo, double yo, double actualAngleTriLeft)
        {
            this.x = x;
            this.y = y;
            this.calulateDistance(xo, yo);
            this.calculateAngles(xo, yo, actualAngleTriLeft);
        }
        public void calulateDistance(double x1, double y1)
        {
            this.distance = Math.Abs(Math.Sqrt(x1 * x1 + y1 * y1));
        }

        //public void getAngleInBetween(double x1, double y1)
        public void calculateAngles(double xo, double yo, double actualAngleTriLeft)
        {
            //const double Rad2Deg = 180.0 / Math.PI;
            ////const double Deg2Rad = Math.PI / 180.0;
            //return Math.Atan2(y1 - y2, x2 - x1) * Rad2Deg;
            double m = (yo - this.y) / (xo - this.x);
            double angleInRadians = Math.Atan(m);
            double angleInDegree = angleInRadians * (180 / Math.PI);
            if (angleInDegree < 0)
            {
                this.actualAngle = angleInDegree + 360;
            }
            else
            {
                this.actualAngle = angleInDegree;
            }
            //---------------------
            this.relativeAngle = actualAngleTriLeft - this.actualAngle;

        }


    }
    //------------------------
    [WebMethod]//workingggggggggg
    public double getActualAngle(double x1, double y1, double x2, double y2)
    {
        //const double Rad2Deg = 180.0 / Math.PI;
        ////const double Deg2Rad = Math.PI / 180.0;
        //return Math.Atan2(y1 - y2, x2 - x1) * Rad2Deg;
        double m = (y1 - y2) / (x1 - x2);
        double angleInRadians = Math.Atan(m);
        double angleInDegree = angleInRadians * (180 / Math.PI);
        if (angleInDegree < 0)
        {
            angleInDegree = angleInDegree + 360;
        }
     
        return angleInDegree;

    }
    [WebMethod]//workinggggggg
    public double calulateDistance(double x1, double y1)
    {
        return Math.Abs(Math.Sqrt(x1 * x1 + y1 * y1));
    }

    //============================================================================================




 




      [WebMethod]
    public double AngleTesting(double x1, double y1)
    {
        //const double Rad2Deg = 180.0 / Math.PI;
        double  angleInRadians = Math.Atan(x1/y1);
        double angleInDegree = angleInRadians * (180/Math.PI);
        //const double Deg2Rad = Math.PI / 180.0;
        return angleInDegree;

    }
   
    //-----------------------

     // [WebMethod]
      public double Hello(double x1, string y1)
      {
          //const double Rad2Deg = 180.0 / Math.PI;
        //  double angleInRadians = Math.Atan(x1 / y1);
         // double angleInDegree = angleInRadians * (180 / Math.PI);
          //const double Deg2Rad = Math.PI / 180.0;
         // return angleInDegree;
          return x1;
      }
      [WebMethod]
      public Shop Hello1(Shop shop)
      {
          //const double Rad2Deg = 180.0 / Math.PI;
          //  double angleInRadians = Math.Atan(x1 / y1);
          // double angleInDegree = angleInRadians * (180 / Math.PI);
          //const double Deg2Rad = Math.PI / 180.0;
          // return angleInDegree;
          return shop;
      }

Webservicessss1


  • adding service references..

RC on reference
add SERVICE reference
type url of web service
go
type name
then ok
============================
currency convertor- client.. webservice is else where-------------------------------------------
//---Form1.cs
//----ServiceReference1 is d name given for reference here
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Webservice1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            loading();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            String one = comboBox1.SelectedItem.ToString();
            String two = comboBox2.SelectedItem.ToString();
            int three = Int32.Parse(textBox3.Text);

            ServiceReference1.Currency cd = (ServiceReference1.Currency)Enum.Parse(typeof(ServiceReference1.Currency), one);
            ServiceReference1.Currency cd1 = (ServiceReference1.Currency)Enum.Parse(typeof(ServiceReference1.Currency), two);


            ServiceReference1.CurrencyConvertorSoapClient ws = new ServiceReference1.CurrencyConvertorSoapClient("CurrencyConvertorSoap");
            double ds = ws.ConversionRate(cd, cd1);
            double result = ds * three;

            label5.Text = result.ToString();


        }

        public void loading()
        {
            foreach (var item in Enum.GetValues(typeof(ServiceReference1.Currency)))
            {
                comboBox1.Items.Add(item);
                comboBox2.Items.Add(item);
            }
        }
    }
}

//--------------------------------------------------------------------
//program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Webservice1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

mongo with net beans not tested..

package com.mongodb.UserManager_mvn;

import java.net.UnknownHostException;
import java.util.Date;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;

public class TestMongo {

public static void main(String[] args) {
// TODO Auto-generated method stub
try {

/**** Connect to MongoDB ****/
// Since 2.10.0, uses MongoClient
MongoClient mongo = new MongoClient("localhost", 27017);

/**** Get database ****/
// if database doesn't exists, MongoDB will create it for you
DB db = mongo.getDB("testdb");

/**** Get collection / table from 'testdb' ****/
// if collection doesn't exists, MongoDB will create it for you
DBCollection table = db.getCollection("user");

/**** Insert ****/
// create a document to store key and value
BasicDBObject document = new BasicDBObject();
document.put("name", "mkyong");
document.put("age", 30);
document.put("createdDate", new Date());
table.insert(document);


System.out.println("Inserted : ");

/**** Find and display ****/
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "mkyong");

DBCursor cursor = table.find(searchQuery);

while (cursor.hasNext()) {
System.out.println(cursor.next());
}

/**** Update ****/
// search document where name="mkyong" and update it with new values
BasicDBObject query = new BasicDBObject();
query.put("name", "mkyong");

BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "mkyong-updated");

BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);

table.update(query, updateObj);

System.out.println("\n Updated : ");

/**** Find and display ****/
BasicDBObject searchQuery2
   = new BasicDBObject().append("name", "mkyong-updated");

DBCursor cursor2 = table.find(searchQuery2);

while (cursor2.hasNext()) {
System.out.println(cursor2.next());
}




/**** Find and Delete ****/

BasicDBObject searchQuery3 = new BasicDBObject();
searchQuery3.put("name", "mkyong-updated" );

table.remove(searchQuery3);

System.out.println("\n Deleted");
/**** Done ****/
System.out.println("Done");

   } catch (UnknownHostException e) {
e.printStackTrace();
   } catch (MongoException e) {
e.printStackTrace();
   }

 }

}

mongo with netbeans

//DBManager.java------------------------------
package usermanager;

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

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;
   }
}
//===========================================
//User.java pojo class
/*
 * 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;


public class User {
   private int id;
   private String firstName;
   private String lastName;
   private String email;

   /**
    * @return the id
    */
   public int getId() {
      return id;
   }

   /**
    * @param id the id to set
    */
   public void setId(int id) {
      this.id = id;
   }

   /**
    * @return the firstName
    */
   public String getFirstName() {
      return firstName;
   }

   /**
    * @param firstName the firstName to set
    */
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }

   /**
    * @return the lastName
    */
   public String getLastName() {
      return lastName;
   }

   /**
    * @param lastName the lastName to set
    */
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }

   /**
    * @return the email
    */
   public String getEmail() {
      return email;
   }

   /**
    * @param email the email to set
    */
   public void setEmail(String email) {
      this.email = email;
   }
}
//======================================
//Main2.java=== method 1
/*
 * 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;


//add delete update search.. everything works fine
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">                          
   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>                        

   private void btnAddUserActionPerformed(java.awt.event.ActionEvent evt) {                                           
      // 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...");
   }                                          

   private void btnUpdateUserActionPerformed(java.awt.event.ActionEvent evt) {                                              
      // 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...");
   }                                             

   private void btnFindUserActionPerformed(java.awt.event.ActionEvent evt) {                                            
      // 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());
      }      
   }                                           

   private void btnDeleteUserActionPerformed(java.awt.event.ActionEvent evt) {                                              
      // 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("");
   }                                             

   /**
    * @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                     
   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                   
}


///===================================================
//method 2 main3.java==not much imp
/*
 * 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;


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">                          
   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>                        

   private void btnAddUserActionPerformed(java.awt.event.ActionEvent evt) {                                           
      // 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);
   }                                          

   private void btnUpdateUserActionPerformed(java.awt.event.ActionEvent evt) {                                              
      // 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);
   }                                             

   private void btnFindUserActionPerformed(java.awt.event.ActionEvent evt) {                                            
      // 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());
      }
   }                                           

   private void btnUpsertUserActionPerformed(java.awt.event.ActionEvent evt) {                                              
      // 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);
   }                                             

   /**
    * @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                     
   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                   
}




Mongo with Eclipse

This is a simple program


In Eclipse create following 3 classes n add relevant mongo libraray
(in eclipse)
     RC on project -> properties-> java build path -> libraries tab -> add external JARs....
  (in net beans also same)  
     RC on project -> properties->libraries tab -> add JARs/Folder ......
make sure u start mongo server b4 executing java program



// DBManager.java
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");
//database = mongo.getDB("student");
//if db dnt exit it ll create one no prob
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return database;
}

}
//----------------------------------------------
//User.java.. pojo class

public class User {
private int id;
private String firstName;
private String lastName;
private String email;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
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
import java.awt.BorderLayout;
import java.awt.EventQueue;

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

import java.awt.FlowLayout;

import javax.swing.JLabel;
import javax.swing.JTextField;

import java.awt.GridLayout;

import javax.swing.BoxLayout;

import java.awt.CardLayout;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;

import com.mongodb.BasicDBObject;
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 java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;

public class Main extends JFrame {

private JPanel contentPane;
private JTextField txtId;
private JTextField txtFirstName;
private JTextField txtLastName;
private JTextField txtEmail;

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

/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));

JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(null);

JLabel lblId = new JLabel("ID");
lblId.setBounds(33, 11, 46, 14);
panel.add(lblId);

txtId = new JTextField();
txtId.setBounds(108, 8, 147, 20);
panel.add(txtId);
txtId.setColumns(10);

JLabel lblFirstName = new JLabel("First Name");
lblFirstName.setBounds(33, 53, 69, 14);
panel.add(lblFirstName);

txtFirstName = new JTextField();
txtFirstName.setBounds(108, 50, 147, 20);
panel.add(txtFirstName);
txtFirstName.setColumns(10);

JLabel lblLastName = new JLabel("Last Name");
lblLastName.setBounds(33, 96, 69, 14);
panel.add(lblLastName);

txtLastName = new JTextField();
txtLastName.setBounds(108, 93, 147, 20);
panel.add(txtLastName);
txtLastName.setColumns(10);

JLabel lblEmail = new JLabel("Email");
lblEmail.setBounds(33, 140, 46, 14);
panel.add(lblEmail);

txtEmail = new JTextField();
txtEmail.setBounds(106, 137, 149, 20);
panel.add(txtEmail);
txtEmail.setColumns(10);

//add-------------------------
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.setFirstName(txtFirstName.getText());
newUser.setLastName(txtLastName.getText());
newUser.setEmail(txtEmail.getText());

DBObject doc = createDBObject(newUser);// a row
DB userDB = DBManager.getDatabase();
DBCollection col = userDB.getCollection("user");// getting table
WriteResult result = col.insert(doc);// inserting row to d table
}

private DBObject createDBObject(User user) {
// TODO Auto-generated method stub
BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();

docBuilder.append("_id", user.getId());
docBuilder.append("firstName", user.getFirstName());
docBuilder.append("lastName", user.getLastName());
docBuilder.append("email", user.getEmail());
return docBuilder.get();
}
});
btnAddUser.setBounds(33, 179, 121, 23);
panel.add(btnAddUser);

//delete-------------------------
JButton btnDeleteUser = new JButton("Delete User");
btnDeleteUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
User newUser = new User();
newUser.setId(Integer.parseInt(txtId.getText()));
// DBObject doc = createDBObject(newUser);
DB userDB = DBManager.getDatabase();
DBCollection col = userDB.getCollection("user");// getting table
DBObject query = BasicDBObjectBuilder.start()
.append("_id", newUser.getId()).get();
col.remove(query);// deleting
}
});
btnDeleteUser.setBounds(176, 179, 128, 23);
panel.add(btnDeleteUser);

JButton btnUpdateUser = new JButton("Update User");
btnUpdateUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
User user = new User();
user.setId(Integer.parseInt(txtId.getText()));
// DBObject doc=createDBObject(user);
DB userDB = DBManager.getDatabase();
DBCollection col = userDB.getCollection("user");// getting table

DBObject query = BasicDBObjectBuilder.start()
.add("_id", user.getId()).get();
// DBCursor cursor = col.find(query);
// while(cursor.hasNext()){
// System.out.println(cursor.next());
// }
// user.setId(Integer.parseInt(txtId.getText()));
user.setFirstName(txtFirstName.getText());
user.setLastName(txtLastName.getText());
user.setEmail(txtEmail.getText());

DBObject doc = createDBObject(user);
WriteResult result = col.update(query, doc);// updating
}

private DBObject createDBObject(User user) {
BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();

docBuilder.append("_id", user.getId());
docBuilder.append("firstName", user.getFirstName());
docBuilder.append("lastName", user.getLastName());
docBuilder.append("email", user.getEmail());
return docBuilder.get();
}
});
btnUpdateUser.setBounds(178, 213, 128, 23);
panel.add(btnUpdateUser);

//search-------------------------
JButton btnSearchUser = new JButton("Search User");
btnSearchUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
User user = new User();
user.setId(Integer.parseInt(txtId.getText()));

//DBObject doc = createDBObject(user);//wasnt 
DB userDB = DBManager.getDatabase();
DBCollection col = userDB.getCollection("user");
// WriteResult result=col.insert(doc);
DBObject query = BasicDBObjectBuilder.start()
.add("_id", user.getId()).get();
DBCursor cursor = col.find(query);//search...like select
ArrayList List = (ArrayList) col.find(query).toArray();
// //ArrayList<String> items =
// (ArrayList)Arrays.asList(split("\\s*,\\s*"));

while (cursor.hasNext()) {

// System.out.println(cursor.next());
//java.util.List<User> students = new ArrayList<User>();//wasnt
DBObject theObj = cursor.next();//wasnt commented//if commented prob
//it s like incrementing
System.out.println(List);//printing list on console

// BasicDBList studentsList = (BasicDBList)
// theObj.get("user");
// System.out.println(studentsList);
for (int i = 0; i < List.size(); i++) {
BasicDBObject studentObj = (BasicDBObject) List.get(i);
String cc = studentObj.getString("firstName");
String cc1 = studentObj.getString("lastName");
String cc2 = studentObj.getString("email");
System.out.println(cc);//printing a item on console
txtFirstName.setText(cc);
txtLastName.setText(cc1);
txtEmail.setText(cc2);
}
}
}

private DBObject createDBObject(User user) {
BasicDBObjectBuilder docBuilder = BasicDBObjectBuilder.start();

docBuilder.append("_id", user.getId());
if (txtFirstName.getText() != "") {
docBuilder.append("firstName", user.getFirstName());
}
if (txtLastName.getText() != "") {
docBuilder.append("lastName", user.getLastName());
}
if (txtEmail.getText() != "") {
docBuilder.append("email", user.getEmail());
}
return docBuilder.get();

}
});
btnSearchUser.setBounds(33, 213, 121, 23);
panel.add(btnSearchUser);
}
}