Monday, October 13, 2014

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

NoSql

1)
Advance stuff can be taken from tutorial point
http://www.tutorialspoint.com/mongodb/
u can learn abt relationshiops (embedded docs and references)

(but it is using console )

2)
more details about mongo crud operations etc
http://docs.mongodb.org/manual/reference/method/db.collection.find/

foreing keys
using generated object ids (1:n)
{
   "name": "Tom Benzamin",
   age:23
   "dep_ids": ObjectId("543b968daac4771b60848b8a")
   
}
(m:n)
{
   "_id":ObjectId("52ffc33cd85242f436000001"),
   "contact": "987654321",
   "dob": "01-01-1991",
   "name": "Tom Benzamin",
   "address_ids": [
      ObjectId("52ffc4a5d85242602e000000"),
      ObjectId("52ffc4a5d85242602e000001")
   ]
}
or just use _id field to reference..
need to separately retrieve and display

3)
 Using mongoVUE
install mongoVUE
      1 start d server

  • Extract MongoDB zip file and move its contents to a location of your choice (eg: c:\mongodb).
  • install mongoVUE (next next etc)
  • create folder called "data" parallel to bin folder inside mongodb folder
  • mongod.exe --dbpath "C:\mondogb\data"  This will show waiting for connections message on the console output which indicates that the mongod.exe process is running successfully.
     2 start monogoVUE (graphical interface)
            create connection...   server:localhost port:27017  ..give any name

Friday, October 10, 2014

NoSql console

NOSQL
This is a very brief summary with links to refer further



  1. http://www.youtube.com/watch?v=2ajlfURobd8


  • A you tube video explaining how to use mongo db (which is using NoSql) for basic operations using console

      1. first go inside bin n start server "mongod" in a command prompt
      2. In another command prompt go inside bin, type mongo
                             (automatically connects to test db)
                               use db_mydb
                                 //creating records and inserting to employee table
                                    emp1=(name :"mal" )
                                     db.employee.save(emp1);

                                        //directly inserting
                                          db.employee.insert((name : "Malsha"));

                                                 //view
                                                 db.employee.find();
                                                  //counting records
                                                    db.employee.count();

                                                           //updating
                                                           //adding new,deleting existing field of a record
                                                      using $set n $unset

                                                                / /deleting
                                                                   using remove