Saturday, July 13, 2013

Remot Sort : How to override SortParameters in Ext-Js Grid Panel?

When you sort using the gird, typically clicking on the column header, the dataIndex of the column will be passed as the sort properties, but not always the server will understand the grid name. for example, lets take below example.

Below is the Snap shot of the Activity Model
Ext.define('Activity', {
    extend: 'Ext.data.Model',
    uses: [ActivityType, ActivityStatus]
    fields: [
        {name: 'activityTypeId', type: 'int'},
        {name: 'activityStatusTypeId', type: 'int'},
        {name: 'accountId', type: 'int'},
        {name: 'dueDate', type: 'date', dateFormat: 'm/d/Y'},
    ],
});


The Relevant Java Model for the Activity
public class Activity {
  @ManyToOne(Fetch = FetchType.EAGAR)
  @JoinColumn(name = "activity_type_id")
  private ActivityType activityType;

  @NotNull
  @ManyToOne(Fetch = FetchType.EAGAR)
  @JoinColumn(name = "activity_status_type_id")
  private ActivityStatusType activityStatusType;

  @ManyToOne(Fetch = FetchType.EAGAR)
  @JoinColumn(name = "account_id")
  private Account account;

  @DateTimeFormat(pattern = "MM/dd/yyyy")
  private Date dueDate;
 
}

If you look at the variable names in Java Bean and Ext Model, you can see the difference. So when you are passing the sort parameters to your service call through, it needs to know the exact column name for example, Lets take activityStatusTypeId. If you click on the Column for Sort based on the activityStatsTypeId, the grid will pass on the dataIndex name as the property to the server. If you look at the FireBug console for the parameters, you see like this.

sort [{"property":"activityStatusTypeId", "direction":"DESC"}]

When you pass activityStatusTypeId to the service, really my server doesn't understand what activityStatusTypeId to the activity table. So we need to pass the extact column name as the sort property to make my service understand. To override the default parameters, we need to override getSortParam() in the colum config.

Ext.define('ActivitiesGridPanel', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.activitiesGridPanel,
    initComponent: function() {
       var me = this;
       Ext.applyIf(me, {
         columns:[
           { xtype: 'gridcolum',
             dataIndex: 'activityStatusTypeId',
             text: 'Status',
             getSortParam: function() {
                 return 'activity_status_type_id';
             }
           },
           { xtype: 'datecolumn',
             dataIndex: 'activityStatusTypeId',
             text: 'Due Date'
           },
           { xtype: 'gridcolum',
             dataIndex: 'activityTypeId',
             text: 'Type'
           },
         ]
       }    
    }    
});

After overriding the sortParameter for the column using getSortParam() function, if you click on the column in the gird, instead of passing the dataIndex name, it will sent out the overridden string as the sort parameter. You see the parameter in FirBug

sort [{"property":"activity_status_type_id", "direction":"DESC"}]

Happy Programming ...!!!

Thursday, June 20, 2013

JPA-Hibernate - Inheritance - Mapped Superclass

Most of the time, when we are developing an application we will use the concept called Inheritance, there will be a chance, where we need to abstract out the common properties to a separate class and extend it in our current class. Lets see how we are going to achieve this in hibernate or jpa.

Below is the initial entity (class), before we apply our inheritance, This entity(class) has three columns (properties), let say property id and name will be used
considerably throughout my application, in many entity (class), so lets abstract out the id and name from the Expense (entity) to new class name Base.

@Entity
@Table(name="Expense")
public class Expense 
{
 
 @Id
 @Column(name="ID")
 @GeneratedValue
 private int id;
 
 @NotBlank(message = "Name should not be empty")
 @Column(name="NAME")
 private String name; 

  
 @NotBlank(message = "Amount should not be empty")
 @Column(name="Amount")
 private double amount;
}
Here i have abstracted out id and name from the Expense entity and moved it to a separate class name Base,
and have the Expense entity extends Base, and i have annotated the Base class with @MappedSuperclass, note, the Base class is not an entity.

A class designated as a mapped superclass has no separate table defined for it. Its mapping information
is applied to the entities that inherit from it. An entity may inherit from a superclass that provides persistent entity state and mapping information, but which is not itself an entity. Mapping information can be overridden in such subclasses by using the AttributeOverride and AssociationOverride annotations

@MappedSuperclass
public class Base 
{
 
    @Id
    @Column(name="ID")
    @GeneratedValue
    private int id;
 
    @NotBlank(message = "Name should not be empty")
    @Column(name="NAME")
    private String name;
}


@Entity
@Table(name="Expense")
public class Expense extends Base
{

    @NotBlank(message = "Amount should not be empty")
    @Column(name="Amount")
    private double amount;
}

Happy Programming ...!!!

Wednesday, June 5, 2013

How to create Form Panel and add it to Window in Ext Js

FormPanel provides a standard container for forms. It is essentially a standard Ext.panel.Panel which automatically creates a BasicForm for managing any Ext.form.field.Field objects that are added as descendants of the panel.Creating a form starts with instantiating an object of FormPanel. Like any Ext component, the constructor accepts the configuration of the component you are creating. Now, let’s get our hands dirty with the code.

Below is the basic FormPanel, which just has only the FormPanel, it doesn't contain any Form Fields
var mf = new Ext.FormPanel( {  
 //frame: true,
 title: 'Add Medicine',
 cls: 'my-form-class',
 width: 350,
 height: 350
});

When you add the above code to your window, it will just show a blank panel inside the window like below screen shot

Lets how to add the Panel to the Window. To add the Panel, we need to create Window first. Below is the source code to create an Window and add the Panel to it. Here we have created an Window using new Ext.Window. If you look at the source you can see an attribute called items, which will holds the list of components to be added in the window, here we have added the FormPanel mf to the window. You can add any number of components to the Window. win.show() at the end is to render the window, which makes it visible in the browser.

var win = new Ext.Window(
{
    id:'myWindow',
    title:'Med Panel',
    width:900,
    height:500,
   //layout:'fit',
    items:[mf]
});
win.show();


Now lets how we can add the Form fields to the Form Panel. We can create components using the keyword "new" and the component we need to instantiate, the way above where we have created teh Window and FormPanel, or we can create them through configuration objects using the property "xtype". So for adding a TextField, we have to use "Ext.form.TextField" or using xtype:'textfield'. Lets see how we can add textfields using both mechanism to the Form Panel.

var desc = new Ext.form.TextField({
     name: 'description',
     fieldLabel: 'Description'
     
    });


var mf = new Ext.FormPanel( {  
 //frame: true,
 title: 'Add Medicine',
 cls: 'my-form-class',
 width: 350,
 height: 350,
 items: [
          {
  xtype: 'textfield',
  fieldLabel: 'Medicine Name',
  name: 'name',
  allowBlank : false
   },
          {
         xtype: 'textfield',
         fieldLabel: 'Company',
         name: 'companyName',
         allowBlank : false
          },
   desc
 ]
});

var win = new Ext.Window(
{
    id:'myWindow',
    title:'Med Panel',
    width:900,
    height:500,
   //layout:'fit',
    items:[mf]
});
win.show();

If you look at the above code, we have just added an new property called items to the FormPanel, compared to previous code at the top. Where we have defined two defined textfield using the xtype, and added on textfiled. That's it, you have created the FormPanel and added it to the Window, if you run the above code, you can see the Textfields shown up in the FormPanel, below is the screen shot, how it will look in the browser.



Happy Programming ...!!!

Tuesday, May 28, 2013

First step into Scala Framework

I have been recently moved to a new project, which is using Scala Framework. It seems to be an new word to me first, when i heard about the framework which we are going to use. So i have started digging into deep, to understand the real usage of the framework. So here's my record so I don't forget in future what i have learnt and how i did it.

Scala is a Functional/Object-Oriented and scripting language that exectues on Java Virtual Machine (JVM) and is becoming popular now, especially with the JAVA developers. It cleans up what are often considered to have been poor design decisions in Java (e.g. type erasure, checked exceptions, the non-unified type system) and adds a number of other features designed to allow cleaner, more concise and more expressive code to be written.

You can download Scala from here. If you have downloaded the .msi file, just double click it, it will do everything for you, if you have downloaded the zip file, extract it and put it in a location, and set the environment variable SCALA_HOME point to the bin directory of the scala folder. Once you did the above, just go to the command prompt, and type scala, you will enter into the scala prompt as below.



Once you are in scala prompt just type 8 * 5, your screen should be like this, once you typed just press enter

scala> 8 * 5

it will return res0: Int = 40

res0 is result index 0, Int is the type of output, 40 is the result. Suppose if you want to use the output for further processing, you have to just say

scala> res0 * 2

It will return res1: Int = 80

res1 is result index 1, Int is the type of output, 80 is the result.

Nice one right, seems to that it limits the number of lines we need to code to get the result :)

In the coming weeks, you can see some more examples on Scala, as and then, when i learn new things on this.

Happy programming ...!!!


Friday, May 24, 2013

Spring MVC Form Validation with Annotation using Spring Bean Validation Framework

This tutorial walks you through the step by step instructions in order to support and apply validation example in Spring MVC, using Spring Bean Validation Framework, which is part of the Spring Modules project.

So here's my record so I don't forget in future how I did it.

Make sure that you have downloaded the spring-modules-validation-0.8.jar have it in your classpath.

Spring Modules validation provides a bunch of generic validation out of the box for all the tedious, standard stuff - length validation, mandatory fields, valid e-mail addresses etc (details here). And you can plug this straight into your application by using annotations. How? Easy.

Below is the configuration, you have to do in your servlet xml file, where you are defining your validator.





Below is my simple Entity Model class, which deals with product. Since the Name and Description of the Product is a must while presisting the data, i have added an validation constraint through annotation, here you can see i have added @NotBlank for name and description variables, and also the message to be shown to the users when they left it blank.

public class Product{
 
    @Id
    @Column(name="ID")
    @GeneratedValue
 private int id;
 
 @NotBlank(message = "Name should not be empty")
 @Column(name="NAME")
 private String name;
 
 @NotBlank(message = "Description should not be empty")
 @Column(name="DESCRIPTION")
 private String description;
 
 public int getId() {
  return id;
 }
....

Now the Spring Controller
The Bean Validation Framework includes its own Validator implementation, called BeanValidator, we are injecting this into the controller, and it was autowired through the xml configuration which we did in the top.

On submitting the form, we will be routed to the addExpense method, where will call the validate() method by passing in the form bean (expense) and the BindingResult. If there any errors, we will just return the form view name which will show the error message.

@Controller
public class ExpenseController 
{
 @Autowired
 private ExpenseService expenseService;
 @Autowired
 private ExpenseTypeService expenseTypeService; 
 @Autowired
    private Validator validator;
    
    public void setValidator(Validator validator) {
        this.validator = validator;
    }
 
 @RequestMapping("/expenselist")
 public String expenselist(Map map, @ModelAttribute("ExpenseName") String expenseName)
 {
  List expenseTypeList = expenseTypeService.fetchAll();
  
  map.put("expense", new Expense()); 
  map.put("expenseTypeList", expenseTypeList);
  map.put("expenseList", expenseService.fetchAll()); 
  map.put("expenseName", expenseName);
  return "expenselist";
 }
 
 @RequestMapping(value="/addexpense", method=RequestMethod.POST)
 public String addExpense(@ModelAttribute("expense") 
   Expense expense, BindingResult result, RedirectAttributes redirectAttrs)
 {
  validator.validate(expense, result);
  if (result.hasErrors()) { return "expenselist"; }
  
  //System.out.println(expense.getExpenseTypeId());
  System.out.println(expense.getName());
  expenseService.add(expense);
  redirectAttrs.addFlashAttribute("ExpenseName", expense.getName());
  return "redirect:/expenselist.html";
 }
}

Suppose if you are not Injecting the Validator, you can just initilize the valiator as shown below in the controller, rest are same as above
public class ExpenseController 
{
 @Autowired
 private ExpenseService expenseService;
 @Autowired
 private ExpenseTypeService expenseTypeService;

        private BeanValidator beanValidator = new BeanValidator(new AnnotationBeanValidationConfigurationLoader());

}

Below is the screen shot, with the error message shown, when the form is submitted.



The tag form:errors will help us to show the error message to the users

Expense :


Amount :


ExpenseType :


Date Incurred :


Description :





Happy programming.

Saturday, May 11, 2013

Spring MVC - FlashAttributes

One of the common problem in a web based application, involving form submission is mutilple form submission, re-entering submitting the form on browser refresh, pop-up alert asking for re-submission of the form, if we press the back button. To overcome the above problem, we will be doing a redirect after a form submission instead of the forward. Doing a redirect causes the browser to do a new GET request and load the page, and provides a solution to the above mentioned problem, but comes with one serious problem, where we will be missing the vital data of request parameters and attributes.

To overcome this problem, Spring MVC comes with FlasAttributes. Flash attributes provide a way for one request to store attributes intended for use in another. This is most commonly needed when redirecting — for example, the Post/Redirect/Get pattern. Flash attributes are saved temporarily before the redirect (typically in the session) to be made available to the request after the redirect and removed immediately.

Spring MVC has two main abstractions in support of flash attributes. FlashMap is used to hold flash attributes while FlashMapManager is used to store, retrieve, and manage FlashMap instances.

Flash attribute support is always "on" and does not need to enabled explicitly although if not used, it never causes HTTP session creation. On each request there is an "input" FlashMap with attributes passed from a previous request (if any) and an "output" FlashMap with attributes to save for a subsequent request. Both FlashMap instances are accessible from anywhere in Spring MVC through static methods in RequestContextUtils.

Here in the below sample code, we are adding the expense details to the DB and redirecting back to the form, with the message saying the following expense have been added to the list.




Flash attributes added via RedirectAttributes are automatically propagated to the "output" FlashMap. Here we have added RedirectAttributes redirectAttrs to your Spring controller’s method addExpense. The addFlashAttribute method automatically add the given parameter to the output flash map and pass it to the subsequent requests.

Before your handler method will be called, Spring Framework will populate the Model with the available Flash Attributes – at this point value passed from addExpense will become a model attribute for the expenselist method, and the same can be added to the map, to return it to the presentation layer, to get it displayed. Here the from the redirect,it comes to the expenselist method, where it will reach as a ModelAttribute and the same have been defined in the method signature with the respective type.

@RequestMapping("/expenselist")
public String expenselist(Map map, @ModelAttribute("ExpenseName") String expenseName)
{
 List expenseTypeList = expenseTypeService.fetchAll();
 
 map.put("expense", new Expense()); 
 map.put("expenseTypeList", expenseTypeList);
 map.put("expenseList", expenseService.fetchAll()); 
 map.put("expenseName", expenseName);
 return "expenselist";
}

@RequestMapping(value="/addexpense", method=RequestMethod.POST)
public String addExpense(@ModelAttribute("expense") 
  Expense expense, BindingResult result, RedirectAttributes redirectAttrs)
{
 //System.out.println(expense.getExpenseTypeId());
 //System.out.println(expense.getName());
 expenseService.add(expense);
 redirectAttrs.addFlashAttribute("ExpenseName", expense.getName());
 return "redirect:/expenselist.html";
}

Happy Programming...!!!

Saturday, May 4, 2013

Integrate ExtJs DataGrid with Spring MVC

Sencha ExtJs is one of the rapidly growing standard for business-grade web application development, which have been used widely as presentation layer. Lets see, how we can intergrate the ExtJs with Spring MVC.

You can download ExtJs from here - Download Extjs

In this example, we are going to populate the list of medicine name available in ExtJS DataGrid.

Below is the Medicine Business clas, Simple POJO. For this example forget about the dealers in the class.
public class Medicine extends BaseObject 
{ 
 private String company;
 private String code;
 private String description; 
 private Set dealers;

        //Relevant Setters and Getters

}

Since the JSON is the most popular way of providing input to ExtJs DataGrid, we are going define the DataStore first, which reads the data from the server through the HttpProxy call, and we use the JsonReader to read a server response that is sent back in JSON format

var store = new Ext.data.Store({
  proxy: new Ext.data.HttpProxy({
   url: '/getmedicine.htm'
  }),
  reader: new Ext.data.JsonReader({
   root:'medicineJson'
  },
  [{name: 'id'}, 
   {name: 'name'}, 
   {name: 'description'},
   {name: 'company'}
  ])
 }); 

And our controller, which return the relevant Medicine data in JSON Format. To return the output from the controller in JSON format, we will be using the classes net.sf api's. Make sure that you have the below jars files in your classpath

json-lib-2.4-jdk15.jar
json-lib-ext-spring-1.0.2.jar
ezmorph-0.8.1.jar

public class DataServiceController implements Controller
{
 private MedicineDao medicineDao;
 
 
 public MedicineDao getMedicineDao() {
  return medicineDao;
 }

 public void setMedicineDao(MedicineDao medicineDao) {
  this.medicineDao = medicineDao;
 }

 public ModelAndView handleRequest(HttpServletRequest request,
   HttpServletResponse response) throws Exception 
 {
  List medicineList = this.getMedicineDao().getAll();
  
  JsonConfig config = new JsonConfig();
  config.setExcludes(new String[] {"dealers" });
  config.setIgnoreDefaultExcludes(false);
  config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
  
  //JSONObject obj = JSONObject.fromObject(medicineList, config);
  JSONArray obj = JSONArray.fromObject(medicineList, config);
  
  ModelMap modelMap = new ModelMap();
  //modelMap.addAttribute("medicineList" , obj);  
  //return new ModelAndView("jsonView", modelMap);
  modelMap.addAttribute("medicineJson", obj);
  //modelMap.addAttribute("medicineList" , medicineList);
  return new ModelAndView("jsonView", modelMap);
 }

}

Below is the entire content of medicinelist.js file defined in jsp, which includes the definition of the DataGrid.

Ext.onReady(function(){ 

 var store = new Ext.data.Store({
  proxy: new Ext.data.HttpProxy({
   url: '/getmedicine.htm'
  }),
  reader: new Ext.data.JsonReader({
   root:'medicineJson'
  },
  [{name: 'id'}, 
   {name: 'name'}, 
   {name: 'description'},
   {name: 'company'}
  ])
 }); 

 // row expander
  
    
    var gridBooks = new Ext.grid.GridPanel({
        store: store,
        width: 500,
        height: 500,        
        title: 'Medicine List',
        renderTo: 'medlist',
        cm: new Ext.grid.ColumnModel({
            defaults: {
                sortable: true
            },
            columns: [               
                {header: "Id", dataIndex: 'id'},
                {header: "Medicine Name", dataIndex: 'name'},
                {header: "Description", dataIndex: 'description'},
                {header: "Company" , dataIndex: 'company', renderer:renderCompany}
            ]
        }),       
        listeners: {
      rowClick: function(grid, rowI, event) {
       //alert("You Clicked Row " + rowI);
       //alert("Medicine Name" + grid.getStore().getAt(rowI).get('name'));
      }
     }
    });

    store.load();
});

Make sure that you have relevant extjs .js and .css file in your relevant, which can be downloaded from You can download ExtJs from here - Download Extjs










Happy programming ...!!!