Pages

Wednesday, 29 April 2015

Gson with Ajax calls



Convert Class obj to JSON format:
Gson gson = new Gson();
strServiceResp = gson.toJson(classObj);
                                                                          
Convert JSON String to Class Object:
               Gson gson = new Gson();
ClassName classObj = (ClassName) gson.fromJson(jsonString, ClassName.class);

ClassVO.java
ClassVO{
 public String firstUser;
 public String lastUser;
}
Ajax:
var ClassVO = {
                "firstUser" : 'wilbert',
                "latsUser" : 'singh'
  };
 
   $.ajax({
         url:"webservice url",
                                type : "POST",
                                dataType : "json",
                                cache:false,
                                data :{jsonStr:JSON.stringify(ClassVO)},
                                               success: function(result){
                                              
                                               }
                                });

Data Representation:
data:{
                              Id : 101,
                              Name:'wilbert',
                              flag:'N'
                              },
                                                                                                                       
               @POST
               @Path("testName")
               @Produces("application/json")
               ClassVO methodName(String jsonStr);
              
              
              
              
                                                                                                                       
data : {
               'jsonStr' : JSON.stringify(javascript array name)
},
                                                                          
                                                                          
               @POST
    @Path("webservice name")
               @Consumes("application/json")
               @Produces("application/json")
               ClassVO methodName(String jsonStr);
              
              
              
               $.ajax( {
                                                                          
                              url: "wsurl",
                              type : 'POST',
                              dataType : "json",
                              contentType:"application/x-www-form-urlencoded; charset=UTF-8",
                              cache:false,
                              data:{jsonStr:JSON.stringify({"test":javascriptname})},
                              success: function(response) {
                                            
                              },
 });         
              

Tuesday, 18 February 2014

JavaScript Hashtable

USAGE:

1) Create a new Map

    var tempMap = new Hashtable();

2) Put values
   
    tempMap.put(key,values);
3) get Values
    tempMap.get(key);
4) Iterate Values

     Keys = tempMap.keys();   
      for(i=0;i<Keys.length;i++) {
            var selectedKey = Keys[i];
            var value = tempMap.get(selectedKey);
      }
5) Checking condition

     if (tempMap.containsKey(region)) {
         //
     }


HashTable.js
---------------------------------------------------------------------------------------------------------------------------------------
/*
   Created by: Michael Synovic;


   on: 01/12/2003

   This is a Javascript implementation of the Java Hashtable object.

Copyright (C) 2003  Michael Synovic

This library is free software; you can redistribute it and/or

modify it under the terms of the GNU Lesser General Public

License as published by the Free Software Foundation; either

version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,

but WITHOUT ANY WARRANTY; without even the implied warranty of

MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU

Lesser General Public License for more details.

   Contructor(s):

    Hashtable()

             Creates a new, empty hashtable

   Method(s):

    void clear()

             Clears this hashtable so that it contains no keys.

    boolean containsKey(String key)

             Tests if the specified object is a key in this hashtable.

    boolean containsValue(Object value)

             Returns true if this Hashtable maps one or more keys to this value.

    Object get(String key)

             Returns the value to which the specified key is mapped in this hashtable.

    boolean isEmpty()

             Tests if this hashtable maps no keys to values.

    Array keys()

             Returns an array of the keys in this hashtable.

    void put(String key, Object value)

             Maps the specified key to the specified value in this hashtable. A NullPointerException is thrown is the key or value is null.

    Object remove(String key)

             Removes the key (and its corresponding value) from this hashtable. Returns the value of the key that was removed

    int size()

             Returns the number of keys in this hashtable.

    String toString()

             Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters ", " (comma and space).

    Array values()

             Returns a array view of the values contained in this Hashtable.

    Array entrySet()

             Returns a reference to the internal object that stores the data. The object is backed by the Hashtable, so changes to the Hashtable are reflected in the object, and vice-versa.

*/

function Hashtable(){

   this.hashtable = new Object();

}


Hashtable.prototype.clear = function(){

   this.hashtable = new Object();

}             

Hashtable.prototype.containsKey = function(key){

   var exists = false;

   for (var i in this.hashtable) {

       if (i == key && this.hashtable[i] != null) {

           exists = true;

           break;

       }   

   }

   return exists;

}

Hashtable.prototype.containsValue = function(value){

   var contains = false;

   if (value != null) {

       for (var i in this.hashtable) {

           if (this.hashtable[i] == value) {

               contains = true;

               break;

           }

       }

   }       

   return contains;

}

Hashtable.prototype.get = function(key){

   return this.hashtable[key];

}

Hashtable.prototype.isEmpty = function(){

   return (parseInt(this.size()) == 0) ? true : false;

}

Hashtable.prototype.keys = function(){

   var keys = new Array();

   for (var i in this.hashtable) {

       if (this.hashtable[i] != null)

           keys.push(i);

   }

   return keys;

}

Hashtable.prototype.put = function(key, value){

   if (key == null || value == null) {

       throw "NullPointerException {" + key + "},{" + value + "}";

   }else{

       this.hashtable[key] = value;

   }

}

Hashtable.prototype.remove = function(key){

   var rtn = this.hashtable[key];

   this.hashtable[key] = null;

   return rtn;

}   

Hashtable.prototype.size = function(){

   var size = 0;

   for (var i in this.hashtable) {

       if (this.hashtable[i] != null)

           size ++;

   }

   return size;

}

Hashtable.prototype.toString = function(){

   var result = "";

   for (var i in this.hashtable)

   {   

       if (this.hashtable[i] != null)

           result += "{" + i + "},{" + this.hashtable[i] + "}\n"; 

   }

   return result;

}                                 

Hashtable.prototype.values = function(){

   var values = new Array();

   for (var i in this.hashtable) {

       if (this.hashtable[i] != null)

           values.push(this.hashtable[i]);

   }

   return values;

}                                 

Hashtable.prototype.entrySet = function(){

   return this.hashtable;

}

--------------------------------------------------------------------------------

Thursday, 25 July 2013

AJAX:Ajax call with JSON/XML Object

Ajax call with XML Object : 


jquery.ajax (or) $.ajax({
type: "GET",//POST
url:"../../Servlet?name=testServlet",
dataType: "xml",
cache:false,
contentType: "application/xml; charset=utf-8",
error: function(x, y, z) {

},
      success: function(xmlContent) {
 var $xmlCon = $(xmlContent);
          $xmlCon.find('address').each(function(i, src)
 {

        branch = $(src).find('branch').text();
         });
                $xmlCon.find('room').each(function(j, category)
             {
             if($(category).find("gender").text() == 'Male'){
             strArray.push(
              {
             book:parseFloat($(category).find('book').text()),
               cal:$(category).find('cal').text()

              }
             );
            }
             });


}, complete : function() {
  },
error : function(request, error) {

}
});

Ajax call with JSON Object :


var TestVO = {
 "name" : nameVal,
  "address" : addr
  };

var myDataArray = new Array();

 $.ajax({
                  url:"../../Servlet?name=testServlet",
                  type : "POST",
                  dataType : "json",
                  cache:false,
                  data :{jsonStr:JSON.stringify(TestVO)},
                  success: function(result){

var myData = result.resVO.dataList;
myDataArray = myData;
var len = myDataArray.length;
for (var i=0;i<len;i++){
var rool = myDataArray[i].rool;
}
}

Thursday, 20 December 2012

JAVA:Property File Reader Example

-------------------------------------------------------------------------------------------------------------
Java Code:
-------------------------------------------------------------------------------------------------------------
import java.util.HashMap;
import java.util.Map;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;


public class PropertyReader {
   
    public static final String MESSAGE_FILE = "com.wil.util.Messages";
    public static final String DB_PRECEDURE_FILE = "com.wil.util.DBProcedures";

    private static PropertyReader propReader = new PropertyReader();
   
    private Map<String,PropertyResourceBundle> bundles = new HashMap<String,PropertyResourceBundle>();
   
   
    private PropertyReader(){
       
    }
   
    public static PropertyReader getInstance(){
        return propReader;
    }
   
   
    public String getMessage(String bundleName, String messagekey){
        PropertyResourceBundle propertyResBd = bundles.get(bundleName);
        if(propertyResBd == null){
            propertyResBd = (PropertyResourceBundle) ResourceBundle.getBundle(bundleName);
            bundles.put(bundleName, propertyResBd);
        }
       
        return propertyResBd.getString(messagekey);
    }
}

-------------------------------------------------------------------------------------------------------------
Use :
-------------------------------------------------------------------------------------------------------------
    PropertyReader messagesReader = PropertyReader.getInstance();
    String errMessage = messagesReader.getMessage(PropertyReader.MESSAGE_FILE,"name_cannot_empty");
    String dbMessage = messagesReader.getMessage(PropertyReader.DB_PRECEDURE_FILE,"name_cannot_empty");

-------------------------------------------------------------------------------------------------------------
Place properties files into "com.wilbert.util" package :
-------------------------------------------------------------------------------------------------------------
Messages.properties

    name_cannot_empty=Name cannot be empty

DBProcedures.properties

    #SchemaName
    SchemaName=TESTDB

Wednesday, 22 August 2012

JAVA:Sorting Java Double

public  String[] selectionSortDouble(String[] data){ 
        try{
            int lenD = data.length; 
            int jj = 0; 
            String tmp = ""; 
            for(int i=0;i<lenD;i++){ 
                jj = i; 
                for(int k = i;k<lenD;k++){ 
                    if(Double.parseDouble(data[jj].split("\\|")[0])>Double.parseDouble(data[k].split("\\|")[0])){ 
                        jj = k; 
                    } 
                } 
                tmp = data[i]; 
                data[i] = data[jj]; 
                data[jj] = tmp; 
            } 
 
        }catch(Exception e){
            e.printStackTrace();
        }
        return data;
    }

JAVA:Convert String Date into Date Object

/****************************************************************
    * Desc : It convert the given String to Date object based on the given format.
    * @return java.util.Date
 ***************************************************************/
    public static java.util.Date stringToDate(String userDate, String format)
    {
        if (userDate != null)
        {
            DateFormat df = new SimpleDateFormat(format);   
            try {
                java.util.Date date = df.parse(userDate);
                return date;
            }
            catch (ParseException pe) {
                pe.printStackTrace();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

Thursday, 24 May 2012

JAVASCRIPT:Hashtable in Javascript

function Hashtable(){

   this.hashtable = new Object();

}

/* privileged functions */

Hashtable.prototype.clear = function(){

   this.hashtable = new Object();

}             

Hashtable.prototype.containsKey = function(key){

   var exists = false;

   for (var i in this.hashtable) {

       if (i == key && this.hashtable[i] != null) {

           exists = true;

           break;

       }   

   }

   return exists;

}

Hashtable.prototype.containsValue = function(value){

   var contains = false;

   if (value != null) {

       for (var i in this.hashtable) {

           if (this.hashtable[i] == value) {

               contains = true;

               break;

           }

       }

   }       

   return contains;

}

Hashtable.prototype.get = function(key){

   return this.hashtable[key];

}

Hashtable.prototype.isEmpty = function(){

   return (parseInt(this.size()) == 0) ? true : false;

}

Hashtable.prototype.keys = function(){

   var keys = new Array();

   for (var i in this.hashtable) {

       if (this.hashtable[i] != null)

           keys.push(i);

   }

   return keys;

}

Hashtable.prototype.put = function(key, value){

   if (key == null || value == null) {

       throw "NullPointerException {" + key + "},{" + value + "}";

   }else{

       this.hashtable[key] = value;

   }

}

Hashtable.prototype.remove = function(key){

   var rtn = this.hashtable[key];

   this.hashtable[key] = null;

   return rtn;

}   

Hashtable.prototype.size = function(){

   var size = 0;

   for (var i in this.hashtable) {

       if (this.hashtable[i] != null)

           size ++;

   }

   return size;

}

Hashtable.prototype.toString = function(){

   var result = "";

   for (var i in this.hashtable)

   {   

       if (this.hashtable[i] != null)

           result += "{" + i + "},{" + this.hashtable[i] + "}\n"; 

   }

   return result;

}                                 

Hashtable.prototype.values = function(){

   var values = new Array();

   for (var i in this.hashtable) {

       if (this.hashtable[i] != null)

           values.push(this.hashtable[i]);

   }

   return values;

}                                 

Hashtable.prototype.entrySet = function(){

   return this.hashtable;

}

Friday, 30 March 2012

JAVASCRIPT-GET Parameter values from the URL

Method:
 
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(
      window.location.href.indexOf('?') + 1).split('&');
    for ( var i = 0; i < hashes.length; i++) {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  }

 Usage:

  var emp_Id = getUrlVars()['empId'];

URL:


http://localhost:8080/sample/wilbert?empId=102

Friday, 10 February 2012

WEBSERVICES-Read JSON object from webservices url

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import com.ge.energy.pgs.myfleet.tpo.service.UpsFiltersService;
import com.ge.energy.pgs.myfleet.tpo.util.UPSDTO;
import com.ge.energy.pgs.myfleet.tpo.util.PropertyFileReader;
public class ReadJSONFromWebservice {

        try{
        URL url = new URL("http://localhost:8080/WebServices/empData");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        String jsonString = null;
        String output = null;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            jsonString = output;
            System.out.println(output);
        }
        try {
            JSONObject ups = new JSONObject(jsonString).getJSONObject("empNames");
           
            //String abc = (String)js.get("menuBeanObj");
            JSONArray  nameList     =  ups.getJSONArray("frameTypesList");
            System.out.println("nameList***********"+nameList);
       
        } catch (JSONException e) {
            // TODO Auto-generated catch block
           
            e.printStackTrace();
        }
       
       
        }catch(Exception ex){
           
        }
        return upsDTO;
    }

}

Required : json.jar

Wednesday, 18 January 2012

JAVA-Recursion Method-List All file name in sub directories

import java.io.File;
public class Recursion {
 public static void main(String[] args) {
  Recursion lstFiles = new Recursion();
  lstFiles.listFilesInAllDirectory(new File("C:\\"));
 }
 public void listFilesInAllDirectory(File dirName) {
    File[] lstfiles = dirName.listFiles();
    if (lstfiles != null) {
      for (File f : lstfiles) {
        if (f.isDirectory()) {
         listFilesInAllDirectory(f);
        } else {     
          System.out.println("File Path :: "+f.getAbsolutePath());
        }
      }
    }
  }
}

Tuesday, 17 January 2012

JAVA-How to Compare Document Object?

import java.util.Comparator;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DocumentComparator implements Comparator {


     private String criteria="standardname";
     private int srtOrder=1;
   
    public int compare(Object arg0, Object arg1) {
        if(arg0 instanceof DocumentInfo.FileInfo && arg1 instanceof DocumentInfo.FileInfo ){
            DocumentInfo.FileInfo doc0=(DocumentInfo.FileInfo)arg0;
            DocumentInfo.FileInfo doc1=(DocumentInfo.FileInfo)arg1;
           
            if(criteria.equals("description")){
                
             return this.getSrtOrder()*(doc0.busDescription.compareTo(doc1.busDescription));   
            }
            if(criteria.equals("filename")){
               
                return this.getSrtOrder()*(doc0.fileName.compareTo(doc1.fileName));   
            }
       
            if(criteria.equals("format")){
               
                return this.getSrtOrder()*(doc0.format.compareTo(doc1.format));   
            }
           
            if(criteria.equals("size")){
                  return this.getSrtOrder()*(new Integer(doc0.fileSize).compareTo(new Integer(doc1.fileSize)));   
            }
            if(criteria.equals("date")){
                Date date0=this.getDateObject(doc0.revisedDate);
                Date date1=this.getDateObject(doc1.revisedDate);
                return this.getSrtOrder()*(date0.compareTo(date1));   
                }
        }
        return 0;
    }


    public String getCriteria() {
        return criteria;
    }

    public void setCriteria(String string) {
        criteria = string;
    }

        private Date getDateObject(String string){
        SimpleDateFormat dateFormat=new SimpleDateFormat("MM/dd/yyyy");
        try{
            return(dateFormat.parse(string));
   
        }catch(Exception e){
            e.printStackTrace();
            return null;   
        }

    }

    public int getSrtOrder() {
        return srtOrder;
    }
    public void setSrtOrder(int i) {
        srtOrder = i;
    }

}

Wednesday, 4 January 2012

J2EE-How to get result set column count (), record count (), iterate data (), insert () and delete () record?


Class Name : DataSetUtil.java

package com.brigitz.util;

/* imports details */

import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Vector;

/**
 * This class is to initialize and retrive the datas of ResultSet.
 * This class stores the datas of ResultSet in a vector.so it can be
 * Serialised.
 */

public class DataSetUtil implements Serializable,Comparator {
     private static final long serialVersionUID = -270320030019L;

     private Vector colNames=new Vector();
     private Vector rowValues =new Vector();
     private int    curPos;
     /*this is a test */
     private String name;
     private boolean ignoreCase;
     private String  dateFormat;
     private int currentCol;
     private Vector groupval=new Vector();
     private boolean sort;
     private int[] sortedCol;

     public static final String VARCHAR = "VARCHAR";
     public static final String INTEGER = "INTEGER";
     public static final String DOUBLE = "DOUBLE";
     public static final String DATETIME = "DATETIME";
     public static final String LONG = "LONG";


     /**
     * Constructs an empty DataSet instance
     */
     public DataSetUtil(){
     }
     /**
      * Constructs a DataSet instance and initialize the ResultSet.
      * @param rs - The ResultSet value to be initialized.
      */
     public DataSetUtil(ResultSet rs){
          Vector row;
          int colcount;
          ResultSetMetaData rsmd;
          try{
               String[] coltype=getColumnTypes(rs);
               rsmd=rs.getMetaData();
               colcount=rsmd.getColumnCount();
               for(int i=1;i<=colcount;i++){
                    colNames.add(new DataColumn(rsmd.getColumnName(i)));
               }
               while(rs.next()){
                    row=new Vector();
                    for(int i=0;i<colcount;i++){
                        if(coltype[i].equalsIgnoreCase(VARCHAR)){
                              String str = rs.getString(i+1);
                              if(str==null)
                                   str="";
                              row.add(str.trim());
                         }
                         else if(coltype[i].equalsIgnoreCase(INTEGER)){
                              row.add(new Integer(rs.getInt(i+1)));
                         }
                         else if(coltype[i].equalsIgnoreCase(DOUBLE)){
                              row.add(new Double(rs.getDouble(i+1)));
                         }
                         else if(coltype[i].equalsIgnoreCase(LONG)){
                              row.add(new Long(rs.getLong(i+1)));
                         }
                         else if(coltype[i].equalsIgnoreCase(DATETIME)){
                              row.add(rs.getTimestamp(i+1));
                         }
                    }
                    rowValues.add(row);
                }
         }
         catch(Exception e){
               e.printStackTrace(System.out);
         }
         sort=false;
     }
     /**
      * Constructs a DataSet instance with values for columnnames and row values.
      * @param colnames - The string array of Column Names.
      * @param values - The Object array of Rowvalues.
      */
     public DataSetUtil(String[] colnames,Object[][] values){
          int tmp_i,tmp_j;
          Vector  tmpvec_row;
          for(tmp_i=0;tmp_i<colnames.length;tmp_i++){
               colNames.add(new DataColumn(colnames[tmp_i]));
          }
          for(tmp_i=0;tmp_i<values.length;tmp_i++){
               tmpvec_row=new Vector();
               for(tmp_j=0;tmp_j<values[0].length;tmp_j++){
                    tmpvec_row.add(values[tmp_i][tmp_j]);
               }
               rowValues.add(tmpvec_row);
          }
          sort=false;
     }
     /**
      * Constructs a DataSet instance with a ResultSet and column Types.
      * @param rs - The ResultSet value to be initialized.
      * @param coltype - The string array of column Types.
      * AS OF NOW THIS CONSTRUCTOR IS NOT USED
      */

      /**
       * Returns a string array of ColumnTypes.
       * @param rs - The ResultSet value for which columntype is required.
       */
     public String[] getColumnTypes(ResultSet rs) throws SQLException {
          ResultSetMetaData rsmd=rs.getMetaData();
          String[] columnTypes=new String[rsmd.getColumnCount()];
          for(int i=0;i<rsmd.getColumnCount();i++){
               columnTypes[i]=getColumnClass(i,rsmd);
          }
          return columnTypes;
     }

     /*
      *  Returns a String representation of the column type of specified column.
      *  @param column - The ColumnNo for which the columntype is required.
      *  @param rsmd - The datas in ResultSetMetaData form.
      */
     public static String getColumnClass(int column,ResultSetMetaData rsmd){
          int type = 0;
          int precision = 0;
          int scale=0;
          try {
               type = rsmd.getColumnType(column+1);
               precision = rsmd.getPrecision(column+1);
               scale=rsmd.getScale(column+1);
              
          }
          catch (SQLException e) {
               return "";
          }
          switch(type) {
               case Types.CHAR:
               case Types.VARCHAR:
               case Types.LONGVARCHAR:
                   return "VARCHAR";

               case Types.BIT:
                   return "BOOLEAN";

               case Types.TINYINT:
               case Types.SMALLINT:
               case Types.INTEGER:
               case Types.NUMERIC:
                   return (precision<6 ? "INTEGER" : "LONG");

               case Types.BIGINT:
                   return "LONG";

               case Types.DECIMAL:
                                    if(precision <7)
                                                if(scale==0)
                                                            return "INTEGER";
                                                else
                                                            return "DOUBLE";
                                    else
                                                if(scale==0)
                                                            return "LONG";
                                                else
                                                            return "DOUBLE";
              
               case Types.FLOAT:
               case Types.DOUBLE:
                   return "DOUBLE";

               case Types.DATE:
               case Types.TIME:
               case Types.TIMESTAMP:
                   return "DATETIME";

               default:
                   return "";
          }
     }
     /**
      * This method sets the value for name.
      * @param name - The String to be set for name.
      */
     public void setName(String name){
          this.name=name;
     }
     /**
      * Returns the value of name.
      */
     public String getName(){
          return this.name;
     }
     /**
      * Returns the value of Number of Columns.
      */
     public int getColumnCount(){
          return this.colNames.size();
     }
     /**
      * Returns the Number of records in the dataset.
      */
     public int getRecordCount(){
          return rowValues.size();
     }
     /**
      * Returns the columnNames in the dataset.
      */
     public String[] getColumnNames(){
          String colnames[]=new String[colNames.size()];
          int tmp_i;
          for(tmp_i=0;tmp_i<colNames.size();tmp_i++){
               colnames[tmp_i]=((DataColumn)colNames.elementAt(tmp_i)).getColumnName();
          }
          return colnames;
     }
     /**
      * Returns true if columnNames is null
      */
     public boolean isNull(){
          return (colNames.size()==0);
     }
     /**
      * Returns the Vector containing records of the specified column in the dataset.
      */
     public  Vector getColumn(int col){
          Vector column=new Vector();
          int tmp_i;
          try{
               for(tmp_i=0;tmp_i<rowValues.size();tmp_i++){
                    column.add(((Vector)rowValues.elementAt(tmp_i)).elementAt(col));
               }
               return column;
          }
          catch(ArrayIndexOutOfBoundsException e){
               return column;
          }
     }
     /**
      * Returns the Vector containing records of the specified ColumnName in the dataset.
      */
     public Vector getColumn(String col){
          return getColumn(colNames.indexOf(new DataColumn(col)));
/*
          int tmp_i;

          for(tmp_i=0;tmp_i<colNames.size();tmp_i++){

               if(((String)colNames.elementAt(tmp_i)).equalsIgnoreCase(col))
                    break;
          }
          return getColumn(tmp_i);
*/
     }
     /**
      * Returns the Vector containing records of the specified Row in the dataset.
      */
     public Object[] getRow(int row) throws com.brigitz.exception.DataNotFoundException {
          Object[] rowvalues=new Object[colNames.size()];
          int tmp_i;
          try{
               ((Vector)rowValues.elementAt(row)).copyInto(rowvalues);
               return rowvalues;
          }
          catch(ArrayIndexOutOfBoundsException e){
               throw new com.brigitz.exception.DataNotFoundException("Specified Row not Found");
          }
     }
     /**
      * Returns the Object array containing records of the specified ColumnName and rowNo in the dataset.
      */
     public Object[] getRow(int row,String[]colname) throws com.brigitz.exception.DataNotFoundException{
          Object[] rowvalues=new Object[colname.length];
          for(int index=0;index<colname.length;index++){
               int colindex = colNames.indexOf(new DataColumn(colname[index]));
               if(colindex<0)
                    continue;
               try{
                    rowvalues[index] = ((Vector)rowValues.elementAt(row)).elementAt(colindex);
               }
               catch(ArrayIndexOutOfBoundsException exp){
                    rowvalues[index] = null;
               }
          }
          return rowvalues;
     }
     /**
      * Returns the object containing datas of the specified ColumnNo and RowNo in the dataset.
      */
     public Object getValue(int row,int col) throws com.brigitz.exception.DataNotFoundException{
          try{
               return ((Vector)rowValues.elementAt(row)).elementAt(col);
          }
          catch(ArrayIndexOutOfBoundsException e){
               throw new com.brigitz.exception.DataNotFoundException("Specified Data Not Found");
          }
     }
     /**
      * Returns the Object containing records of the specified ColumnName and rowNo in the dataset.
      */
     public Object getValue(int row,String col) throws com.brigitz.exception.DataNotFoundException{
          int tmp_i;
          try{
               tmp_i=getColumnIndex(col);
               return getValue(row,tmp_i);
          }
          catch(ArrayIndexOutOfBoundsException e){
               throw new com.brigitz.exception.DataNotFoundException("Specified Data Not Found");
          }
          catch(com.brigitz.exception.DataNotFoundException e1){
               throw e1;
          }
     }
     /**
      * Returns the columnIndex  of the specified ColumnName in the dataset.
      */
     public int getColumnIndex(String colname) throws com.brigitz.exception.DataNotFoundException{
          return colNames.indexOf(new DataColumn(colname));
     }

     /**
      * Returns the RowNo in which the specified ColumnName and value occurs first in the dataset.
      */
     public int findFirst(String colname,Object value){
          int rowval,tmp_i,colno;
          rowval=-1;
          try{
               colno=getColumnIndex(colname);
               rowval=find(0,colno,value,1);
          }
          catch(com.brigitz.exception.DataNotFoundException e){
               return rowval;
          }
          return rowval;
     }
     /**
      * Returns the RowNo in which the specified ColumnNo and value occurs first in the dataset.
      */
     public int findFirst(int col,Object value){
          return find(0,col,value,1);
     }
     /**
      * Returns the RowNo in which the specified ColumnNo and value occurs after rowstart in the dataset.
      */
     public int findNext(int rowstart,String col,Object value){
          int rowval=-1,colno;
          try{
               colno=getColumnIndex(col);
               rowval=find(rowstart,colno,value,1);
          }
          catch(com.brigitz.exception.DataNotFoundException e){
               return rowval;
          }
          return rowval;
     }
     /**
      * Returns the RowNo in which the specified ColumnNo and value occurs after rowstart in the dataset.
      */
     public int findNext(int rowstart,int col,Object value){
          return find(rowstart,col,value,1);
     }
     /**
      * Returns the RowNo in which the specified ColumnName and value occurs before rowstart in the dataset.
      */
     public int findPrevious(int rowstart,String colname,Object value){
          int rowval=-1,col;
          try{
               col=getColumnIndex(colname);
               rowval=find(rowstart,col,value,-1);
          }
          catch(com.brigitz.exception.DataNotFoundException e){
               return rowval;
          }
          return rowval;
     }
     /**
      * Returns the RowNo in which the specified ColumnNo and value occurs before rowstart in the dataset.
      */
     public int findPrevious(int rowstart,int col,Object value){
          return find(rowstart,col,value,-1);
     }

     /**
      * Returns the RowNo in which the specified ColumnNo,direction and value occurs after rowstart in the dataset.
      */
     private int find(int rowstart,int col,Object value,int direction){
          int rowval,tmp_i;
          rowval=-1;
          try{
               for(tmp_i=rowstart;tmp_i<rowValues.size() && tmp_i>-1;tmp_i+=direction){
                     if((((Vector)rowValues.elementAt(tmp_i)).elementAt(col)).equals(value)) {
                         return tmp_i;
                     }
               }
          }
          catch(ArrayIndexOutOfBoundsException e){
               rowval=-1;
          }
          return rowval;
     }
     /**
      * Returns the vector containing data of the specified
      * columnName which is sorted in ascending order.
      */
     public Vector sortColumn(String columnName) throws com.brigitz.exception.DataNotFoundException{
          int col=getColumnIndex(columnName);
          return sortColumn(col);
     }

     /**
      * Returns the vector containing data of the specified
      * columnNo which is sorted in ascending order.
      */
     public Vector sortColumn(int column){
          for(int i=0;i<rowValues.size();i++)
          {
               for(int j=i+1;j<rowValues.size();j++)
               {
                    if(!(stringOf(((Vector)rowValues.elementAt(i)).elementAt(column)).compareTo(stringOf(((Vector)rowValues.elementAt(j)).elementAt(column)))<0))
                    {
                          Vector tempv=new Vector();
                          tempv=(Vector)rowValues.elementAt(i);
                          rowValues.setElementAt(rowValues.elementAt(j),i);
                          rowValues.setElementAt(tempv,j);
                    }
               }
          }
                return rowValues;
     }

     /**
      * Returns the String value of specified Object.
      */
     public String stringOf(Object obj){
          String curValue="";
          if (obj instanceof String)
               curValue=(String)obj;

          if (obj instanceof Integer)
               curValue=((Integer)obj).toString();

          if (obj instanceof Double)
               curValue=((Double)obj).toString();

          if (obj instanceof java.sql.Timestamp || obj instanceof java.util.Date)
               curValue=getDate(obj);
          return curValue;
     }

     /**
      * This method sorts DataSet of the specified Columnnames
      * @param cols  The array of columns.
      */
     public void sort(String cols[]){
          int col[]=new int[cols.length];
          try{
               for(int i=0;i<col.length;i++){
                    col[i]=getColumnIndex(cols[i]);
               }
          }
          catch(Exception e){
          }
          sort(col);
     }
     /**
      * This method sorts DataSet of the specified ColumnNos
      * @param cols  The array of columns.
      */
     public void sort(int col[]){
          Object val[];
          val=rowValues.toArray();
          Vector groupval=new Vector();
          currentCol=col[0];
          Arrays.sort(val,0,val.length,this);
          for(int i=1;i<col.length;i++){
               groupval=startGroup(val);
               currentCol=col[i];
               for(int j=0;j<groupval.size();j++){
                 Group g1;
                 g1=(Group)groupval.elementAt(j);
                    Arrays.sort(val,g1.startIndex,g1.endIndex+1,this);
               }
          }
          Vector vtemp=new Vector();
          for (int i=0;i<val.length;i++)
          vtemp.add(val[i]);
          rowValues=vtemp;
          sortedCol=col;
          sort=true;
     }
     /**
      * Returns the int value value after comparing two objects.
      */
     public int compare (Object o1,Object o2){
          Vector v1,v2;
          v1=(Vector)o1;
          v2=(Vector)o2;

          Object val1=v1.elementAt(currentCol);
          Object val2=v2.elementAt(currentCol);
          if (val1 instanceof String){
               String s1=((String)val1).toUpperCase();
               String s2=((String)val2).toUpperCase();
               return s1.compareTo(s2);
          }
          else if (val1 instanceof java.util.Date || val1 instanceof java.sql.Timestamp){
               String s1=getDate(val1);
               String s2=getDate(val2);
               return s1.compareTo(s2);
          }
          else if (val1 instanceof Integer){
               String s1,s2;
               Integer t1,t2;
               t1=(Integer)val1;
               t2=(Integer)val2;
               return t1.compareTo(t2);
          }
          else{
               String s1,s2;
               Double t1,t2;
               t1=(Double)val1;
               t2=(Double)val2;
               return t1.compareTo(t2);
          }
     }

     /**
      * allways returns false
      */
     public boolean equals(Object o){
          return false;
     }
     /**
     *  Returns a Vector which is sorted in ascending order of specified objects.
     */
     private Vector startGroup(Object[] val){
          int startIndex,endIndex;
          String preValue,curValue;
          Object obj;
          preValue=curValue="";
          startIndex=endIndex=0;
          for(int i=0;i<val.length;i++){
               obj=((Vector)val[i]).elementAt(currentCol);
               if (obj instanceof String)
                    curValue=(String)obj;
               if (obj instanceof Integer)
                    curValue=((Integer)obj).toString();
               if (obj instanceof Double)
                    curValue=((Double)obj).toString();
               if (obj instanceof java.sql.Timestamp || obj instanceof java.util.Date)
                    curValue=getDate(obj);
               if (i==0){
                    startIndex=i;
                    endIndex=i;
                    preValue=curValue;
               }
               else {

                    if (!curValue.equalsIgnoreCase(preValue)) {
                         groupval.add(new Group(startIndex,endIndex));
                         startIndex=i;
                         preValue=curValue;
                         endIndex=i;

                         if (i == val.length-1){
                         preValue=curValue;
                         endIndex=i;
                         groupval.add(new Group(startIndex,endIndex));

                         }


                    }
                    else {
                         endIndex=i;
                         preValue=curValue;
                         if (i == val.length-1){
                              preValue=curValue;
                              endIndex=i;
                              groupval.add(new Group(startIndex,endIndex));
                         }

                    }
               }
          }
          return groupval;
     }
     /**
      * Inner class to initialize startingindex and end index of a group.
      */
     private class Group {

          public int startIndex;
          public int endIndex;

          public Group(){
          }
          public Group(int s,int e){
               startIndex=s;
               endIndex=e;
          }

          public String toString(){
               return "startIndex= "+startIndex + " endIndex ="+endIndex;
          }
     }
     /**
      * Returns the String value of Date formats.
      */
     private String getDate(Object val1){
          SimpleDateFormat df=new SimpleDateFormat("dd-mm-yyyy");
          java.util.Date d1;
          java.sql.Timestamp  d;
          String s1;
          if (val1 instanceof java.util.Date){
               d1=(java.util.Date)val1;
               s1=df.format(d1);
          }
          else{
               d=(java.sql.Timestamp)val1;
               s1=df.format(d);
          }
          return s1;
      }
     /**
      * Returns the size of the groupval vector.
      */
     public int getGroupCount(){
          return groupval.size();
     }
     /**
      * Returns the starting index of the group.
      */
     public int getGroupStartIndex(int groupindex){
          return ((Group)groupval.elementAt(groupindex)).startIndex;
     }
     /**
      * Returns the end index of the group.
      */
     public int getGroupEndIndex(int groupindex){
          return ((Group)groupval.elementAt(groupindex)).endIndex;
     }
     /**
      * Returns the value set to sort.
      */
     public boolean isSorted(){
          return sort;
     }
     /**
      * This method inserts a record in the dataset.
      * @param data  The Object array of datas.
      */
     public void insertData(Object[] data) throws com.brigitz.exception.DataNotFoundException{
          Vector insert = new Vector();
          if (!(data.length==colNames.size()))
               throw new com.brigitz.exception.DataNotFoundException("Insufficient Data Found");
          try{
               for(int index=0;index<data.length;index++){
                    insert.addElement(data[index]);
               }
          }
          catch(Exception exp){
               throw new com.brigitz.exception.DataNotFoundException("Empty data Cannot be inserted");
          }
          rowValues.add(insert);
     }
     /**
      * This method deletes a particular row from the dataset.
      * @param row The RowNo.
      */
     public void deleteData(int row){
          rowValues.removeElementAt(row);
     }

    /**
     * Returns the DataSet which was initialized.
     */
     public DataSetUtil duplicate(){
              DataSetUtil ds = new DataSetUtil();
          ds.colNames = new Vector(colNames);
          ds.rowValues = new Vector(rowValues);
          return ds;
     }



     protected class Null implements Serializable{
          protected Null(){
          }
     }
     protected class DataColumn implements Serializable{
          private String columnName = "";
          public DataColumn(String columnName){
               if(columnName==null)
                    throw new IllegalArgumentException("Invalid Parameter ColumnName ");
               this.columnName = columnName;              
          }
          public String getColumnName(){
               return this.columnName;
          }
          public boolean equals(Object obj){
               if(!(obj instanceof DataColumn))
                    return false;
               DataColumn column = (DataColumn)obj;                   
               return (column.getColumnName().equalsIgnoreCase(columnName));
          }
          public String toString(){
               return "eti.ndt.DataSet$DataColumn " + columnName;
          }
     }
};

How to Use:
ResultSet rs = stmt.executeQuery(query);
DataSetUtil  ds=new DataSetUtil(rs);
System.out.println(“Total Record Count”+ds.getRecordCount());