Working with GXT(Ext GWT) Grid : Add Grouping Funtionality

Grouping is very helpful when you view a large set of data. It creates a more readable view for the user. GXT provides us with a very easy way of adding grouping functionality with a grid. Here i describe how to add grouping functionality with GXT grid.

Create a new project named GxtGridGrouping and add GXT library in the project. As like my previous blogs about GXT Grid i have used the same Employee model and TestData class for generating data. You will find the code of these classes here. Go to the onModuleLoad method of GxtGridGrouping class and remove all the auto generated code of this method.

First create an instance of GroupingStore, a specialized store implementation which extends the ListStore that provides for grouping models by one of the available fields.

GroupingStore<Employee> employeeList = new GroupingStore<Employee>();  
employeeList.add(TestData.getEmployees());  
employeeList.groupBy("department");   

The groupBy method takes a property of your model by which you want to group your grid. In the example i have grouped the grid by 'department' property. You can change it to 'designation' property and see how it works.

Now define a list of ColumnConfig and a ColumnModel by using this list as before.
List<Columnconfig> configs = new ArrayList<Columnconfig>();

ColumnConfig column = new ColumnConfig();  
column.setId("name");  
column.setHeader("Employee Name");  
column.setWidth(200);  
configs.add(column);

column = new ColumnConfig("department", "Department", 150);  
column.setAlignment(HorizontalAlignment.LEFT);  
configs.add(column);

column = new ColumnConfig("designation", "Designation", 150);   
column.setAlignment(HorizontalAlignment.LEFT);  
configs.add(column);

column = new ColumnConfig("salary", "Slary", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
final NumberFormat number = NumberFormat.getFormat("0.00");  
GridCellRenderer<Employee> checkSalary = new GridCellRenderer<Employee>() {  
public String render(Employee model, String property, ColumnData config, int rowIndex,  
int colIndex, ListStore<Employee> employeeList, Grid<Employee> grid) {  
double val = (Double) model.get(property);  
String style = val < 70000 ? "red" : "green";  
return "<span style='color:" + style + "'>" + number.format(val) + "</span>"; 
}  
};  
column.setRenderer(checkSalary);  
configs.add(column);

column = new ColumnConfig("joiningdate", "Joining Date", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
column.setDateTimeFormat(DateTimeFormat.getShortDateFormat());  
configs.add(column);

final ColumnModel cm = new ColumnModel(configs); 

Create an instance of GroupView which groups the data based on the GroupStore. Then set it as the view of the Grid.

GroupingView view = new GroupingView();  
view.setForceFit(true);  
view.setGroupRenderer(new GridGroupRenderer() {  
public String render(GroupColumnData data) {  
String f = cm.getColumnById(data.field).getHeader();  
String l = data.models.size() == 1 ? "Item" : "Items";  
return f + ": " + data.group + " (" + data.models.size() + " " + l + ")";  
}  
});  

Grid<Employee> grid = new Grid<Employee>(employeeList, cm);  
grid.setView(view);  
grid.setBorders(true);

Here setForceFit is set true to auto expand the columns to fit the grid width and setGroupRenderer is used to create a heading for the groups.

Finally add the grid to the content panel.

ContentPanel cp = new ContentPanel();  
cp.setBodyBorder(false);  
cp.setHeading("Employee List");  
cp.setButtonAlign(HorizontalAlignment.CENTER);  
cp.setLayout(new FitLayout());  
cp.setSize(700, 420); 
cp.add(grid);  
RootPanel.get().add(cp);



Run the application and see how readable the grid is now. To view the live demo of this tutorial Click here.
gxtGridGrouping

Working with GXT(Ext GWT) Grid : Add Local Pagination Functionality

In my previous blog i have described how to create a simple Grid of GXT.  I have a plan to write a series of blog about other useful functionalities which can be added to the Grid. Here i write down the way of adding local pagination functionality with the Grid.

Create a new project named GxtPagingExample and add GXT library in the project. To create a grid at first you need a base model class and have to generate data for that model. In this tutorial i have used the same Employee model and TestData class for generating data which i used in my previous blog. You will find the code of these classes there.

Now go to the onModuleLoad method of GxtPagingExample class. Remove all the auto generated code of this method. First create an instance of PagingModelMemoryProxy which is a specialized DataProxy that supports paging when the entire data set is in the memory.

PagingModelMemoryProxy proxy = new PagingModelMemoryProxy(TestData.getEmployees());
   PagingLoader loader = new BasePagingLoader(proxy);
   loader.setRemoteSort(true);
   ListStore<Employee> employeeList = new ListStore<Employee>(loader);  
BasePagingLoader is an implementation of the PagingLoader interface which loads data using the proxy.If remote sort is enable then it will allow you to sort between the whole data set otherwise the sorting will be done only between the viewable data set. Then create a ListStore of Employee type.




Now create a PagingToolBar widget then bind it with the loader. It takes the page size in the constructor.
final PagingToolBar toolBar = new PagingToolBar(5);
   toolBar.bind(loader);
   loader.load(0, 5);
The arguments of the load method of PagingLoader are the begin index and page size.

Create a list of ColumnConfig and define each column. Then create a grid and add the grid and the PagingToolBar in a panel.

List<Columnconfig> configs = new ArrayList<Columnconfig>();

ColumnConfig column = new ColumnConfig();  
column.setId("name");  
column.setHeader("Employee Name");  
column.setWidth(200);  
configs.add(column);

column = new ColumnConfig("department", "Department", 150);  
column.setAlignment(HorizontalAlignment.LEFT);  
configs.add(column);

column = new ColumnConfig("designation", "Designation", 150);  
column.setAlignment(HorizontalAlignment.LEFT);  
configs.add(column);

column = new ColumnConfig("salary", "Slary", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
final NumberFormat number = NumberFormat.getFormat("0.00");  
GridCellRenderer<Employee> checkSalary = new GridCellRenderer<Employee>() {  
public String render(Employee model, String property, ColumnData config, int rowIndex,  
int colIndex, ListStore<Employee> employeeList, Grid<Employee> grid) {  
double val = (Double) model.get(property);  
String style = val < 70000 ? "red" : "green";  
return "<span style='color:" + style + "'>" + number.format(val) + "</span>"; 
}  
};  
column.setRenderer(checkSalary);  
configs.add(column);

column = new ColumnConfig("joiningdate", "Joining Date", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
column.setDateTimeFormat(DateTimeFormat.getShortDateFormat());  
configs.add(column);

ColumnModel cm = new ColumnModel(configs);
Grid<Employee> grid = new Grid<Employee>(employeeList, cm); 
grid.setStyleAttribute("borderTop", "none"); 
grid.setAutoExpandColumn("name"); 
grid.setBorders(true); 
grid.setStripeRows(true);

ContentPanel cp = new ContentPanel();  
cp.setBodyBorder(false);  
cp.setHeading("Employee List");  
cp.setButtonAlign(HorizontalAlignment.CENTER);  
cp.setLayout(new FitLayout());  
cp.setSize(700, 300); 
cp.add(grid);  
cp.setBottomComponent(toolBar);
RootPanel.get().add(cp);

Explanation of the above code is written here.
That's all. Run the application and test the pagination functionality. To view the live demo of this tutorial Click here.

How to create a simple Grid using GXT(Ext GWT)

GXT provides us with many powerful UI tools. One of this is the Grid. You can select which column you want to see or which you want to discard from the Grid at run time. Can sort the Grid by any column in both ascending and descending order. More over with the GridCellRenderer you can customized the look and feel of a cell. This tutorial describes every steps of creating a simple Grid using GXT in detail.
First create a new project named GxtGridExample and add GXT library in the project.  To show a list of data in the Grid you have to prepare the data first. In this tutorial i am going to show you a list of employee. So i need a Employee class which extends the BaseModel class of the GXT. Here is the code for the Employee class.
package com.ratul.GxtGridExample.client.model;
import java.util.Date;
import com.extjs.gxt.ui.client.data.BaseModel;

public class Employee extends BaseModel {
private static final long serialVersionUID = 1L;

public Employee() {
}
public Employee(String name, String department, String designation,double salary, Date joiningdate) {
set("name", name);
set("department", department);
set("designation", designation);
set("salary", salary);
set("joiningdate", joiningdate);
}
public Date getJoiningdate() {
return (Date) get("joiningdate");
}
public String getName() {
return (String) get("name");
}
public String getDepartment() {
return (String) get("department");
}
public String getDesignation() {
return (String) get("designation");
}
public double getSalary() {
Double salary = (Double) get("salary");
return salary.doubleValue();
}
public String toString() {
return getName();
}
}


Employee has 5 properties and to set the value of a property the set method is used. First parameter of the method is the property name and second is the value of that property. The class has also the getter method for each property.
Now populate a list of Employee in the TestData class.
package com.ratul.GxtGridExample.client;

import java.util.ArrayList;
import java.util.List;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.ratul.GxtGridExample.client.model.Employee;

public class TestData {

public static List<Employee> getEmployees()
{
  List<Employee> employees = new ArrayList<Employee>();
DateTimeFormat f = DateTimeFormat.getFormat("yyyy-mm-dd");
  employees.add(new Employee("Hollie Voss","General Administration","Executive Dir  ector",150000,f.parse("2006-05-01")));
  employees.add(new Employee("Emerson Milton","Information Technology","CTO",12000  0,f.parse("2007-03-01")));
  employees.add(new Employee("Christina Blake","Information Technology","Project M  anager",90000,f.parse("2008-08-01")));
  employees.add(new Employee("Heriberto Rush","Information Technology","Senior S/W  Engineer",70000,f.parse("2009-02-07")));
  employees.add(new Employee("Candice Carson","Information Technology","S/W Engine  er",60000,f.parse("2007-11-01")));
  employees.add(new Employee("Chad Andrews","Information Technology","Senior S/W E  ngineer",70000,f.parse("2008-02-01")));
  employees.add(new Employee("Dirk Newman","Information Technology","S/W Engineer"  ,62000,f.parse("2009-03-01")));
  employees.add(new Employee("Bell Snedden","Information Technology","S/W Engineer  ",73000,f.parse("2007-07-07")));
  employees.add(new Employee("Benito Meeks","Marketing","General Manager",105000,f  .parse("2008-02-01")));
  employees.add(new Employee("Gail Horton","Marketing","Executive",55000,f.parse("  2009-05-01")));
  employees.add(new Employee("Claudio Engle","Marketing","Executive",58000,f.parse  ("2008-09-03")));
  employees.add(new Employee("Buster misjenou","Accounts","Executive",52000,f.pars  e("2008-02-07")));

return employees;
}
}

You data is prepared now to place in a GXT Grid.
Go to the onModuleLoad method of GxtGridExample class. Remove all the auto generated code of this method.
First create a list of ColumnConfig and configure each column.

List<Columnconfig> configs = new ArrayList<Columnconfig>();

ColumnConfig column = new ColumnConfig();  
column.setId("name");  
column.setHeader("Employee Name");  
column.setWidth(200);  
configs.add(column);

column = new ColumnConfig("department", "Department", 150);  
column.setAlignment(HorizontalAlignment.LEFT);  
configs.add(column);

column = new ColumnConfig("designation", "Designation", 150);  
column.setAlignment(HorizontalAlignment.LEFT);  
configs.add(column);

column = new ColumnConfig("salary", "Slary", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
final NumberFormat number = NumberFormat.getFormat("0.00");  
GridCellRenderer<Employee> checkSalary = new GridCellRenderer<Employee>() {  
public String render(Employee model, String property, ColumnData config, int rowIndex,  
int colIndex, ListStore<Employee> employeeList, Grid<Employee> grid) {  
double val = (Double) model.get(property);  
String style = val < 70000 ? "red" : "green";  
return "<span style='color:" + style + "'>" + number.format(val) + "</span>";   
}  
};  
column.setRenderer(checkSalary);  
configs.add(column);

column = new ColumnConfig("joiningdate", "Joining Date", 100);  
column.setAlignment(HorizontalAlignment.RIGHT);  
column.setDateTimeFormat(DateTimeFormat.getShortDateFormat());  
configs.add(column);

The setId method bind the column with a property of the model and the setHeader method set the column header. You can also set this property of the ColumnConfig by using the constructor.  For the salary column here i define a custom GridCellRenderer<Employee> and set it with the setRenderer method which set the color of the salary value either green or red by checking its value. The other methods are self explanatory.
Create a ListStore of Employee type and add the employee list created in the TestData class.


ListStore<Employee> employeeList = new ListStore<Employee>();  
employeeList.add(TestData.getEmployees());

Now create a ColumnModel with the column configurations defined above and a Grid of Type Employee.

ColumnModel cm = new ColumnModel(configs);
Grid<Employee> grid = new Grid<Employee>(employeeList, cm); 
grid.setStyleAttribute("borderTop", "none"); 
grid.setAutoExpandColumn("name"); 
grid.setBorders(true); 
grid.setStripeRows(true);

The setAutoExpandColumn is used to defined which column will be expanded automatically when you hide a column. Other methods are self identifying.
You are just one step away from running the code. Create a ContentPanel and add the Grid to the panel.
ContentPanel cp = new ContentPanel();  
cp.setBodyBorder(false);  
cp.setHeading("Employee List");  
cp.setButtonAlign(HorizontalAlignment.CENTER);  
cp.setLayout(new FitLayout());  
cp.setSize(700, 300); 
cp.add(grid);  
RootPanel.get().add(cp);



Run the application and check the magic of GXT Grid. To view the live demo of this tutorial Click here.
employeeList

Keep yourself updated with the latest GWT technologies (gwt , app engine and gxt)

It’s been long since i have worked with GWT. I have been very busy with my scheduled tasks and can not afford to spend time on investing the features of this outstanding web technology.  Today i have sit with it and found that everything is required to be updated. The SDK for GWT, Google App Engine and the Ext GWT Library (The world is running fast?huh). I have updated all these and  here i write down the procedure for eclipse 3.4.

Download GWT version 1.7 from here and Google App Engine SDK 1.2.2 from here. Unzip the folders then open the Window->Preference window of eclipse.

Expand the Google menu from the left tree menu.  Select the Web Toolkit menu and it will show you the previous version of GWT. Click on the Add Button and select the unzipped folder as the installation directory.  Now check the latest SDK so that it will be the default SDK for the newly created projects.

gwtupdate1

 

Now select the App Engine menu and follow the steps stated above to add the latest version of the SDK.

You are now ready to use the latest version of GWT and Google App Engine SDK.

To use the latest version of Ext GWT library download this from here and follow my previous blog about how to use it in your GWT project.

How to use Ext GWT(GXT) in Eclipse 3.4 to create a rich internet application

Ext GWT is a Java library for building rich internet applications with the Google Web Toolkit (GWT). If you have started working with GWT you will find the Ext GWT library very helpful for its high performance and customizable UI widgets. Here I describe you how to use this library in your GWT project.

First of all download Ext GWT 1.2.4 SDK, the latest stable version of this library and extract it.

Now Create a GWT project by following the steps I have described in my previous blog. Follow the steps to add gxt.jar to the project.

->Right click on project and select the properties menu..
->Select Java Build Path.
->Select Libraries tab.
->Click on Add External JARS and select gxt.jar. (You will find this jar file inside the folder where you have extracted the library previously. )



Now change the your_project_name.gwt.xml file. Add the following line in this file.

<inherits name='com.extjs.gxt.ui.GXT'/>





Here goes the tricky part. You will find a folder named resources in the extracted folder. This contains the css and images used in this library. Copy the css and images folder in the war folder of your application. Now add the following stylesheet to your host page.

<link rel="stylesheet" type="text/css" href="css/ext-all.css" />


And remember Ext GWT requires no doctype or the following doctype (quirksmode).

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


That's all. You are now ready to use the Ext GWT library to enhance your application.

Getting started with GWT : Create your first GWT application in Eclipse 3.4

To my mind GWT is going to take the lead among the web application development tools. So this is the high time to start learning about GWT. Here I describe you how to create your first GWT application in Eclipse 3.4 (Ganymede).

If you have not installed Google plugin and SDK for eclipse please go to this page and follow the instructions.

Create your project
Select File-> New-> Web Application project. Enter "FirstGwtApp" for your project name and "com.ratul.FirstGwtApp" for the package name.



Create GWT entry point

Now you have to create an Entry point class which is similar to the main method in Java.
Right click on the "com.ratul.FirstGwtApp.client" and select New-> Class. Enter "HelloWorld" as the name of the class.



This class must implement the interface "com.google.gwt.core.client.EntryPoint".
So click on the Add button and write "entrypoint" in the choose interface text field.
Select the matching item.



Here is the code of the HelloWorld class

package com.ratul.FirstGwtApp.client;

import com.google.gwt.core.client.EntryPoint;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.RootPanel;

public class HelloWorld implements EntryPoint {

@Override
public void onModuleLoad() {
Label label = new Label("Enter your name:");
final TextBox textBox = new TextBox();
Button button = new Button("Click Here");
button.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Window.alert("Hello "+ textBox.getText());
}
});

RootPanel.get().add(label);
RootPanel.get().add(textBox);
RootPanel.get().add(button);
}
}


Now change the FirstGwtApp.gwt.xml in package com.ratul.FirstGwtApp to set the HelloWorld class as the entry point class of your application.



Create a Start HTML page

In the war folder you will find a file, named FirstGwtApp.html. Between the body tag write the following code

<!-- OPTIONAL: include this if you want history support -->
<iframe src="javascript:''" id="__gwt_historyFrame" tabindex="-1" style="border: 0pt none ; position: absolute; width: 0pt; height: 0pt;"></iframe>

<h1>Welcome to my first GWT Application</h1>




Configure the web.xml

Go to war-> WEB-INF folder and there you will find a web.xml file. The Google Plug-in created this configuration file and placed a reference to a servlet.
Set the FirstGwtApp.html as the welcome file of your application.



You are only one step away from running your first GWT application.

Run GWT application

To run your application right-click the project and select Run As -> "Web application".

The result will be like this.



Enter your name in the text field and click on the button. Your name will be appeared in the alert window :).


Implementing Strategy pattern to support different fingerprint device login system

In our ERP project one of the features of Human resource module is managing daily attendance of the employee using biometric authentication. Our client wants to use NAC 3000 as a fingerprint verification device.

The task is simple. The software of that device writes data in an access database and in a log file whenever an employee place finger on it. We just have to pull the data from the access file or the log file after certain interval. The problem is that as our ERP is generalized and can be customizable for any type of organization so we have to think about other devices that serve the same purpose.

We analyze that all the devices vary in one point and that is the format of the log file or the database file. That is only the file parsing algorithm varies from device to device. This motivates me to use Strategy pattern here as the Strategy pattern defines a family o algorithms, encapsulate each one and makes them interchangeable.

Class diagram


Details
LogInDevice is an abstract class which has an instance fileParser as the interface type not a concrete class implementation type. The LogInDevice objects will set the variable polymorphically to reference the specific file parser.

The FileParser is an interface which has four mehthods. The NAC300Parser, NAC2500Parser implements this interface. When we need to integrate a new device we just have to create a new class that will implement this interface. The code of parsing the logfile will be written in the parseFile() method.

Implementation of the doParsing() method of LogInDevice class

  
public void doParsing()
{
this.fileParser.parseFile();
userId = this.fileParser.getUserId();
purpose = this.fileParser.getPurpose();
time = this.fileParser.getTime();
//Code block for saving the data to database goes here.
}


In this part of the code we don't care about what kind of file parser it is.

Are you thinking of setting the fileParser instance variable? Let’s take a look at the NAC3000 class


public class NAC3000 extends LogInDevice
{
public NAC3000()
{
this.fileParser = new NAC3000Parser();
}
}



The NAC3000 uses the NAC3000Parser to handle its file parsing. So when the doParsing() is called the responsibility for the parsing is delegated to the NAC3000Parser object and we got our desired data.

Change the FileParser dynamically

To change the parsing algorithm dynamically you just need a setter method in LogInDevice class


public void setFileParser(FileParser fileParser)
{
this.fileParser = fileParser;
}



We can call this method anytime we want to change the file parsing algorithm on the fly.

With this design we can integrate a new Fingerprint or any other authentication device very easily in our system and obviously without modifying the existing code.

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers