Tuesday, July 29, 2014

Excel Generator in Java using POI and Reflection

Excel Generator in JAVA using apache POI and Reflection


Code Snippet:


    @SuppressWarnings("unchecked")
    public HSSFWorkbook exportToCSV(Object srcDtos, String[] columnList,
            String[] valueIdList, String title
) {
       
        try {
           
            List<Object> dtoList = null;
            HSSFRow reportRow = null;
            int rowNum = 1;
            int colIndex = 0;
            String reportRowValue = "";
           
            if (srcDtos == null){
                return null;
            } else {
                dtoList = (ArrayList<Object>)srcDtos;
            }
           
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet(title);
                       
            /**
             * setting up the report header
             */
            HSSFRow reportHeader = sheet.createRow(0);

            for (String column : columnList) {
                reportHeader.createCell(colIndex++).setCellValue(column);
            }

            Method invokeMethod = null;
            Class<?> reqClass = null;
            // Loading methods parameters
            Class[] parameter = new Class[1];
            String getColumn = "";
            try { 
               
                for (Object srcClassObj : dtoList) {

                    /**
                     * creating the report row content
                     */
                    reportRow = sheet.createRow(rowNum++);
                    reportRowValue = "";
                    int rowColIndex = 0;
                   
                    Class dtoClzName =srcClassObj.getClass();
                   
                    reqClass = Class.forName(dtoClzName.getName());
               

                    for (String columnField : valueIdList) {
                         
                        getColumn = "get" + initCapString(columnField);

                        parameter[0] = String.class;

                        invokeMethod = reqClass.getMethod(getColumn);

                        Object tmpObj = invokeMethod.invoke(srcClassObj);

                        reportRowValue = (tmpObj == null ? "" : tmpObj
                                .toString());

                        reportRow.createCell(rowColIndex++).setCellValue(reportRowValue);

                    }

                }

            } catch (ClassNotFoundException e) {
                logger.error("Error during the CSV generation --->" +
                        e.getMessage());
            }
           
            return workbook;

        } catch (Exception e) {
            logger.error("Error during the CSV generation --->"
                    +   e.getMessage());
        }
        return null;
    }



    /**
     * method to init capitalize the given string(first letter as CAPITAL)
     * @param srcString
     * @return
     */
    public static String initCapString(String srcString) {
        String[] arr = srcString.split(" ");
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arr.length; i++) {
            sb.append(Character.toUpperCase(arr[i].charAt(0)))
                    .append(arr[i].substring(1)).append(" ");
        }
        return sb.toString().trim();
    }



public class VelsErrorMsgDTO implements Serializable {

    private Long errorMsgID;
    private String institutionID;
    private String errorMsgTitle;
    private String errorMsgDescription;
    private String lastUpdtTime;

    public Long getErrorMsgID() {
        return errorMsgID;
    }


    public void setErrorMsgID(Long errorMsgID) {
        this.errorMsgID = errorMsgID;
    }


    public String getInstitutionID() {
        return institutionID;
    }


    public void setInstitutionID(String institutionID) {
        this.institutionID = institutionID;
    }


    public String getErrorMsgTitle() {
        return errorMsgTitle;
    }


    public void setErrorMsgTitle(String errorMsgTitle) {
        this.errorMsgTitle = errorMsgTitle;
    }


    public String getErrorMsgDescription() {
        return errorMsgDescription;
    }


    public void setErrorMsgDescription(String errorMsgDescription) {
        this.errorMsgDescription = errorMsgDescription;
    }


    public String getLastUpdtTime() {
        return lastUpdtTime;
    }


    public void setLastUpdtTime(String lastUpdtTime) {
        this.lastUpdtTime = lastUpdtTime;
    }
   
}


Here the arguements

srcDtos      ------> actual  java DTO objects which carries your data
columnList  ------> Column header list
valueIdList  ------> java property names need to be invoked from DTO object(getter method of the
                                given  java field(example userName , address ..) would be  invoked to get the actual
                                value  that need to be displayed in excel file)
 title ---------------> Report title




    public static void main(String[] args) {
        List<VelsErrorMsgDTO > dtoList = new ArrayList<VelsErrorMsgDTO >();
        VelsErrorMsgDTO dto = new VelsErrorMsgDTO ();
        dto.setErrorMsgID(1L);
        dto.setErrorMsgTitle("Test errror");
        dto.setErrorMsgDescription("Test errror");
        dto.setInstitutionID("101");
        dtoList.add(dto);
       
        dto = new CIErrorMsgDTO();
        dto.setErrorMsgID(2L);
        dto.setErrorMsgTitle("Test errror");
        dto.setErrorMsgDescription("Test errror");
        dto.setInstitutionID("608");
        dtoList.add(dto);
       
        String[] columnList={ "Error Msg","Description","Institution"};
        String[] valueIdList={ "errorMsgTitle","errorMsgDescription","institutionID"};
        try {
          
            FileOutputStream fileOut = new FileOutputStream("C:\\temp\\TestXcel1.xls");
            workbook.write(fileOut);
            fileOut.close();

           
        }catch (Exception e){
            e.printStackTrace();
        }
       
    }



Tuesday, July 15, 2014

Create and configure the commons module in J2ee projects

How to create and configure the commons module in J2EE projects using maven

Step 1:  Create the commons project exampl: velsCommons with all the necessary util classes....

Step 2:  Include the velsCommonsproject as dependency in child projects pom.xml file as below.

         pom.xml
         ..

     <?xml version="1.0" encoding="UTF-8"?>

       <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org
           /2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
              http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

      


        <dependency>
            <groupId>org.vels.common</groupId>
            <artifactId>vels-commons</artifactId>
            <version>0.0.1</version>
            <type>jar</type>
            <scope>compile</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-annotations</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

.....
....

</project>

Step 3: Change your maven settings.xml(<USER_HOME>/.m2/settings.xml) to look for the referenced(commons module) jars in your local repository.

Location of the settings.xml file is C:/Users/<login name>/.m2 in windows...

<?xml version="1.0" encoding="utf-8"?>
<settings>
<localRepository>C:/Users/vselvaraj/.m2/repository/</localRepository>
...
....
...
...
</settings>



Note :  Incase if you are facing any class not found issue (class from commons module is not found) during the child module deployment. Make you have the WAS server publish settings as follows (server publish resources settings).


Choose the option " Run server with resources on Server".


While configuring the maven task  for the common module bamboo plan:

Use below goals for maven task in bamboo plan:   clean deploy






Wednesday, July 9, 2014

Simple REST Service using spring MVC

How to write a simple REST full service using spring MVC

Step 1:   

Create the following files in resources folder:

Web.xml
 

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>SampleRESTServlet</display-name>
    <description>Example Spring MVC App for SampleRESTServlet</description>
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>SampleRESTServlet</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.xml</param-value>
    </context-param>

    <!-- The definition of the Root Spring Container shared by all Servlets
        and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--
        HTTP Method Conversion to support HTML's lack of support for the HTTP verbs DELETE and PUT.
        If using spring's form tags designate the action as delete or put. If using standard forms or request arguments,
        create an hidden input or request param named _method with the value of DELETE or PUT.
   
    -->
    <filter>
        <filter-name>httpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>httpMethodFilter</filter-name>
        <servlet-name>SampleRESTServlet</servlet-name>
    </filter-mapping>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>SampleRESTServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext-web.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>SampleRESTServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file></welcome-file>
    </welcome-file-list>

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>


 

 
ApplicationContext.xml (which contains all your context services or hibernate settings)

Incase if you have used  hibernate features , include those files in applicationcontext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/util
                        http://www.springframework.org/schema/util/spring-util-3.1.xsd
                        http://www.springframework.org/schema/jee
                        http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd">
                       
   <!-- base package which has all the annotation classes to be scanned -->
    <context:component-scan base-package="org.vels.samples.rest" />

    <import resource="applicationContext-resources.xml" />
    <import resource="applicationContext-services.xml" />
    <import resource="applicationContext-hibernate.xml" />

</beans>

applicationContext-resources.xml :

Enabling the transaction manager for all your hibernate transactions and specifying the application datasource whic got created and configured  in your WAS server.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <tx:annotation-driven />
    <tx:jta-transaction-manager/>


    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
    <jdbc:embedded-database id="dataSource"/>
</beans>


applicationContext-hibernate.xml

 Specify all your hibernate settings/properties

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">
   
  
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="org.vels.samples.rest.domain"/>     
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
            </props>
        </property>
  </bean>

</beans>

applicationContext-services.xml


If you have some componets that would be used in your application , you can specify that.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd">


</beans>


Step 2:  

ApplicationContext-web.xml


This will enable the REST feature in spring MVC

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">

    <context:component-scan base-package="org.vels.samples.rest.web" />

    <mvc:annotation-driven />
   
</beans>

Step 3:

Write the controller class which would have all the REST functionalities.


package org.vels.samples.rest.web;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;

@Controller
public class OrderController {
    private static Log logger = LogFactory.getLog(OrderController.class);
    private ShoppingService shoppingService; // your service class which has all the buss logic to 
                                                                     invoke dao layer
   
    @Autowired
    public OrderController(ShoppingService shoppingService) { /// you can inject your service class
        this.shoppingService = shoppingService;
    }
   
    @RequestMapping("/orders")
    public @ResponseBody Map<String, ? extends Object> orders(){
        logger.debug("Loading all Orders");

        
         // you can write code to invoke the database vis sevice and dao layer

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orders", orders);

        return map;
    }



    @RequestMapping(value="/order/{id}", method=RequestMethod.GET)
    public String order(@PathVariable Long id, Model model) {



     
       // you can write code to invoke the database vis sevice and dao layer
      
        return "success";
    }



}


 Step 4:  Deploy into server by creating WAR/EAR.


Step 5 :
 Invoke the REST service  from your browser in following way to test the REST service

URL :

http://localhost:9080/rest-services/orders

output :

{"orders":[{"itemSize":0,"totalCost":0.0,"orderId":123,"description":"test
 order","createDate":1404849946247,"modifiedDate":1404849946247,"shoppingItems":[]}]}



Incase if you want full source code i can send it.....



Findout number of files in Zip

How to findout number of files in Zip files in java



    /**
     * returns number of files in zip
     * @param zin
     * @return
     */
    public int countNumberOfFileInZip(ZipInputStream zin) {
        int numFiles = 0;
        try {

            while (zin.getNextEntry() != null) {
                numFiles++;
            }
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {

                logger.error(" $$$$$$$$$$$$$  Error on zip file count processing :$$$$$$$$$$$ "+ e.getMessage());
            }
        } finally {
            if (zin != null) {
                try {
                    zin.closeEntry();
                    zin.close();
                } catch (Exception e) {
                    logger.error(" Error on zip file entry close : " + e.getMessage());
                }

            }
        }   

        return numFiles;
    }

Test :
              // where "writeToFile" is the byte array of zip file content
              // get the zip file content
              bis = new ByteArrayInputStream(writeToFile);

            // get the zipped file list entry           
            int zipFileCount = countNumberOfFileInZip(new ZipInputStream(new    
                                          ByteArrayInputStream(writeToFile)));



Findout the File Extension in java

How to findout the file extension in java



    public String getFileExtension(File file) {
        String fileName = file.getAbsolutePath()+ file.getName();
       
        String extn = FilenameUtils.getExtension(fileName);
        return extn;
    }




Data Filter feature in ExtJS 3.4 Grid panel based on input value(text field)

How to filter the ExtJS Grid data based on the input value ie value entered in textfield.


Step 1:
Write a keylistener function for the textfield which get trigged on keypress event.

                .........
               ..........
                 xtype: 'textfield',
                 fieldLabel: 'School Name',
                 name: 'schoolName',
                 id: 'schoolNameTxt',
                 enableKeyEvents: true,
                 listeners: {
                                  keyup: function (obj, e) {

                                                      var searchValue= obj.getValue();     //value entered by the user                               
                       
                                                      Ext.getCmp('schoolListGrid').getStore().clearFilter();     
                                                     // here 'schoolListGrid' is the id of the grid which data need to get
                                                           filtered.
                                                             
                                                          //filter( field, value, [anyMatch], [caseSensitive], [exactMatch] )
                                                     Ext.getCmp('schoolListGrid').getStore().filter("schoolName", 
                                                                         searchValue,true,false,false);
                                               // "schoolName"  is name of the field in grid , to filter the grid data 
                         
                                                     },
                                                    
                                                 blur: function(obj) {                                               
                                                           obj.setValue(""); // to reset the text field on lost focus
                                                         }

                                                }




Sample Working Code Example :


Grid to be filtered:

 var grid = new Ext.grid.GridPanel( {
                store : data,
                id:'schoolListGrid',
                  
                defaults: {
                    width: 100,
                     sortable: true
                 },
                columns : [{
                    id : 'schoolName',
                    header : 'School Name',
                    width : 200,
                        hidden:false,
                    sortable : true,
                    dataIndex : 'schoolName',
                    renderer: function(value, metaData, record) {                  
                            var schoolID = parseInt(record.data.schoolID);
                            var schoolName = record.data.schoolName;

                    }
    
                }, {
                    id : 'schoolID',
                    header : 'School ID',
                    width : 100,
                    hidden:false,
                    sortable : true,
                    dataIndex : 'schoolID',
                        renderer: function(value, metaData, record) {                  
                            var schoolID = parseInt(record.data.schoolID);
                            var schoolName = record.data.schoolName;

                            var returnText =value;                                 

                        //    var shFunc = "javascript:showSchoolDetails("+schoolID + ",'" +schoolName +"')";      
                        //    returnText =  '<a class="anchor_u_style"  href="' + shFunc +'" >' + value + '</a>';
                            return  returnText;                            
                         
                        }
                },{
                    id : 'schoolType',
                    header : 'Type',
                    width : 100,
                    sortable : true,
                    dataIndex : 'schoolType'
                }, {
                    id : 'state',
                    header : 'State/Province',
                    width : 150,
                    sortable : true,
                    dataIndex : 'state'
                },........

                stripeRows : true,
                    frame:false,
                autoExpandColumn : 'schoolName',
                height : 400,
                width:1100,
                columnLines: true,
                 sm:sm,
                     iconCls:'icon-grid',
                     enableColumnHide: false,
                // config options for stateful behavior
                stateful : false,
                stateId : 'grid'
            });

 Function to populate the search criteria panel

**
 * populate the search panel for searching the schools based on school name
 */
 function populateFilterData() {
    //Ext.get('fliter-form-panel').dom.innerHTML ="";
         var search_Panel = new Ext.FormPanel({
            id: 'fliter-form-panel',
            title:'Search Criteria',
            labelWidth: 100, // label settings here cascade unless overridden
            labelSeparator: '',
            frame: true,
            border:true,            
            width:1100,
            labelAlign: 'left',
            labelStyle: 'font-weight:bold;',                        

            renderTo:'filter_form_Panel',

               items: [{
                        layout: 'column',

                        items: [
                             {

                                  columnWidth: .25,
                                 layout: 'form',
                                 items:[{
                                          
                                             xtype: 'textfield',
                                            fieldLabel: 'School Name',
                                            name: 'schoolName',
                                            id: 'schoolNameTxt',
                                            enableKeyEvents: true,
                                            listeners: {
                                                 keyup: function (obj, e) {

                                                         var searchValue= obj.getValue();                                   
                        
                                                          Ext.getCmp('schoolListGrid').getStore().clearFilter();      
                                                            
                                                          //filter( field, value, [anyMatch], [caseSensitive], [exactMatch] )
                                                          Ext.getCmp('schoolListGrid').getStore().filter("schoolName", searchValue,true,false,false);
                        
                                                     },
                                                   
                                                 blur: function(obj) {                                              
                                                           obj.setValue("");
                                                         }

                                                }
                                              

                                 }]


                            },
                             {

                                  columnWidth: .25,
                                 layout: 'form',
                                 items:[{
                                          
                                             xtype: 'textfield',
                                            fieldLabel: 'School ID',
                                            name: 'schoolID',
                                            id: 'schoolIDTxt',
                                            enableKeyEvents: true,
                                            listeners: {
                                                 keyup: function (obj, e) {

                                                         var searchValue= obj.getValue();                                   
                        
                                                          Ext.getCmp('schoolListGrid').getStore().clearFilter();      
                                                            
                                                          //filter( field, value, [anyMatch], [caseSensitive], [exactMatch] )
                                                          Ext.getCmp('schoolListGrid').getStore().filter("schoolID",

  searchValue,true,false,false);
                        
                                                     },
                                                   
                                                 blur: function(obj) {                                              
                                                           obj.setValue("");
                                                         }

                                                }
                                              

                                 }]


                            },
                             {

                                  columnWidth: .25,
                                 layout: 'form',
                                 items:[{

                                         xtype: 'textfield',
                                        fieldLabel: 'School Type',
                                        name: 'schoolType',
                                        id: 'schoolTypeTxt',
                                        enableKeyEvents: true,
                                        listeners: {
                                             keyup:
                                                 function (obj, e)
                                                 {
                                                     var searchValue= obj.getValue();                                   
                    
                                                      Ext.getCmp('schoolListGrid').getStore().clearFilter();      
                                                        
                                                      //filter( field, value, [anyMatch], [caseSensitive], [exactMatch] )
                                                      Ext.getCmp('schoolListGrid').getStore().filter("schoolType",
                                                            searchValue,true,false,false);
                    
                                                 },
                                                   
                                                 blur: function(obj) {                                              
                                                           obj.setValue("");
                                                         }
                                            }
                                    }]
                            },
                            {
                                 columnWidth: .25,
                                 layout: 'form',
                                 items:[{
                                         xtype: 'textfield',
                                        fieldLabel: 'State/Province',
                                        name: 'state',
                                        id: 'schoolStateTxt',
                                        enableKeyEvents: true,
                                        listeners: {
                                             keyup:
                                                 function (obj, e)
                                                 {
                                                     var searchValue= obj.getValue();                                   
                    
                                                      Ext.getCmp('schoolListGrid').getStore().clearFilter();      
                                                        
                                                      //filter( field, value, [anyMatch], [caseSensitive], [exactMatch] )
                                                      Ext.getCmp('schoolListGrid').getStore().filter("state",  
                                                     searchValue,true,false,false);
                    
                                                 },
                                                   
                                                 blur: function(obj) {                                              
                                                           obj.setValue("");
                                                         }
                                            }
                                    }]
                            }
                        ]
                      }
                     ]

        });
 } 


Step 2 :