Pages

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