Remember Old School OO Principle While Using RegularExpressionValidator

I'm sure all of you are frequently using RegularExpressionValidator in your project. But are sure you are not repeating same expression in multiple pages? Is your code impervious to Change? If you are a bit careful while writing code, you can avoid this. And your friend will be 'Inheritance'.

Suppose you are using a RegularExpressionValidator to validate phone number. You may possibly going to write following code block

<asp:RegularExpressionValidator ID="revPhoneNumber" Display="Dynamic" ErrorMessage="Valid phone no required." ControlToValidate="tbPhoneNumber" ValidationExpression="^\d{8,}$" runat="server">*</asp:RegularExpressionValidator>

If you need this Validator in more than one page, then writing the same code block in every page obviously produces code duplication. Moreover if your project manager asks you to allow '+' at the beginning of the phone number then you have to change the regular expression in all pages. That will be surely a painful task for you. You can make your life easy by following approach.

Create your own validator by inheriting RegularExpressionValidator. Assign a regular expression to the ValidationExpression property

namespace TestValidator.Validators
{
    public class PhoneNumberValidator : RegularExpressionValidator
    {
        public PhoneNumberValidator()
        {
            ValidationExpression = "^\\d{8,}$";
        }
    }
}

To use your own PhoneNumberValidator first add this in the Registry
<%@ Register Assembly="TestValidator(Project Name)" Namespace="TestValidator.Validators" TagPrefix="myvalidators" %>

Then use this in the following way

<myvalidators:PhoneNumberValidator ID="revPhoneNumber" Display="Dynamic" ErrorMessage="Valid phone no required." ControlToValidate="tbPhoneNumber" runat="server">*</myvalidators:PhoneNumberValidator>

Now it is a matter of seconds to accomplish what your project manager wants.

Working With GXT (Ext GWT) Grid : Add Filter Functionality

Yesterday I was looking for something new (new widgets, new functionality) in the latest GXT version (2.2.1) and found that, it is now providing grid filtering support. You can add MS Excel like filtering option in your application through this. I think it was the most demanded and expected feature from the GXT developers which can be highly utilized in Enterprise Reporting. I am going to describe how to add this functionality in GXT Grid.

Create a new project named GxtFilterGrid 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 GxtFilterGrid class and remove all the auto generated code of this method.

First create a list of ColumnConfig and a ColumnModel from this list.

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>() {
   @Override
   public Object render(Employee model, String property,
     com.extjs.gxt.ui.client.widget.grid.ColumnData config,
     int rowIndex, int colIndex, ListStore<Employee> store,
     Grid<Employee> grid) {
    double val = (Double) model.get(property);
    String style = val < 70000 ? "red" : "green";
    return ""
      + number.format(val) + "";

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

Now create different types of filters like Numeric, String, Date, etc. Constructor of these filter classes takes the column name to bind the specific filter with a specific column.

NumericFilter numericFilter = new NumericFilter("salary");
StringFilter nameFilter = new StringFilter("name");
StringFilter designationFilter = new StringFilter("designation");
DateFilter dateFilter = new DateFilter("joiningdate"); 

You can also add a ListStore as a filtering option with the help of ListFilter. For adding a list filter, create a ListStore of ModelData or your own BaseModel class and add this as the source of ListFilter.

ListStore<ModelData> departmentStore = new ListStore<ModelData>();
departmentStore.add(departement("General Administration"));
departmentStore.add(departement("Information Technology"));
departmentStore.add(departement("Marketing"));
departmentStore.add(departement("Accounts"));
 //department method is stated later
ListFilter listFilter = new ListFilter("department", departmentStore);
listFilter.setDisplayProperty("departmentname");

Display Property of the ListFilter will be the key name of your model data. Now create a GridFilters instance and add all the filters created above with this instance.

GridFilters filters = new GridFilters();
filters.setLocal(true);
filters.addFilter(numericFilter);
filters.addFilter(nameFilter);
filters.addFilter(designationFilter);
filters.addFilter(dateFilter);
filters.addFilter(listFilter);

Finally create a ListStore of Employee Model and, a Grid from this ListStore and ColumnModel. Add the GridFilters instance as the Plugin of the Grid.

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

Grid<Employee> grid = new Grid<Employee>(employeeList, cm);
grid.setStyleAttribute("borderTop", "none");
grid.setAutoExpandColumn("name");
grid.setBorders(true);
grid.setStripeRows(true);
grid.getView().setForceFit(true);
grid.setColumnLines(true);
grid.addPlugin(filters);

ContentPanel cp = new ContentPanel();  
cp.setBodyBorder(false);  
cp.setHeading("Employee List With Filtering Option");  
cp.setButtonAlign(HorizontalAlignment.CENTER);  
cp.setLayout(new FitLayout());  
cp.setSize(700, 300); 
cp.add(grid);  
RootPanel.get().add(cp);
Here is the code of department method which is used previously.
private ModelData departement(String departement) {
  ModelData model = new BaseModelData();
  model.set("departmentname", departement);
  return model;
}

That's all. Run the project and the output will be like this

Java Image Utility

Few days ago I did some image manipulation tasks like resizing, cropping, etc. java awt provides some useful functionality to do this type of tasks. Here I am going to share how I accomplish the tasks and finally and ImageUtility Class which you can use in your project.

Image Resizing
First read the image with the ImageIO which returns a BufferedImage. Then create another BufferedImage instance with the new width, height and image type.

BufferedImage originalImage = ImageIO.read(imageFile); 
BufferedImage scaledBI = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);

Now get the Graphics2D component of the new scaled image and draw it.

g.drawImage(originalImage, 0, 0, 100, 100, null);
g.dispose();

If you want to preserve the image quality, add following line of code before disposing the graphics component.

g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);

It's simple, is not it?

Image Croping

Read the image with ImageIO as stated previously and get the sub image of the original image.

BufferedImage originalImage = ImageIO.read(imageFile); 
originalImage .getSubimage(0,0, 100, 100);

First two parameter of the getSubimage method is the x,y coordinate, from where you want to begin cropping.


Get Byte Array of an Image

Sometimes you need this specially when you want to save an image in database in blob data type . We can get byte[] of an image with the help of ByteArrayOutputStream and ImageIO class.


BufferedImage originalImage = ImageIO.read(imageFile); 
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage , getImageExtension(), baos);
//getImageExtension method is stated later
baos.flush();
byte[] imageData = baos.toByteArray();
baos.close();

ImageUtility.java

All the above actions can be encapsulated into a simple ImageUtility class.

import java.awt.AlphaComposite;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import org.openide.util.Exceptions;

/**
 *
 * @author ratul
 */
public class ImageUtility
{
    private File imageFile;
    private BufferedImage image;
    public ImageUtility()
    {
    }

    public ImageUtility(File imageFile)
    {
        try
        {
            this.imageFile = imageFile;
            image = ImageIO.read(imageFile);
        }
        catch (IOException ex)
        {
            Exceptions.printStackTrace(ex);
        }
    }

    public ImageUtility(File imageFile, BufferedImage image)
    {
        this.imageFile = imageFile;
        this.image = image;
    }


    public File getImageFile()
    {
        return imageFile;
    }

    public void setImageFile(File imageFile)
    {
        this.imageFile = imageFile;
    }

    public BufferedImage getImage()
    {
        return image;
    }

    public void setImage(BufferedImage image)
    {
        this.image = image;
    }
    
    public String getImageExtension()
    {
        String fName = imageFile.getName();
        return fName.substring(fName.indexOf(".")+1, fName.length());
    }
    public BufferedImage getResizedCopy(int scaledWidth, int scaledHeight, boolean preserveAlpha)
    {
        return getResizedCopyOfImage(image, scaledWidth, scaledHeight, preserveAlpha);
    }
    
    public byte[] getByte()
    {
        return getByteOfImage(image);
    }
    public ImageIcon getImageIcon()
    {
        return new ImageIcon(image);
    }
    public BufferedImage getCropedImage(int x, int y, int width, int height)
    {
        return getCropedImageOfImage(image, x, y, width, height);
    }
    public BufferedImage getCropedImageFromCenter(Dimension panelDimension,int clipedWidth, int clipedHeight)
    {
        return getCropedImageOfImageFromCenter(image, panelDimension, clipedWidth, clipedHeight);
    }

    public BufferedImage getResizedCopyOfImage(BufferedImage originalImage,int scaledWidth, int scaledHeight, boolean preserveAlpha)
    {
        int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
        BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
        Graphics2D g = scaledBI.createGraphics();
        if (preserveAlpha)
        {
                g.setComposite(AlphaComposite.Src);
        }
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING,
        RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
        g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
        g.dispose();
        return scaledBI;
    }

    public byte[] getByteOfImage(BufferedImage sourceImage)
    {
        try
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(sourceImage, getImageExtension(), baos);
            baos.flush();
            byte[] imageData = baos.toByteArray();
            baos.close();
            return imageData;
        }
        catch (IOException ex)
        {
            Exceptions.printStackTrace(ex);
            return null;
        }
    }

    public ImageIcon getImageIconFromImage(BufferedImage sourceImage)
    {
        return new ImageIcon(sourceImage);
    }

    public BufferedImage  getCropedImageOfImage(BufferedImage sourceImage, int x, int y, int width, int height)
    {
        return sourceImage.getSubimage(x, y, width, height);
    }
    public BufferedImage getCropedImageOfImageFromCenter(BufferedImage sourceImage, Dimension panelDimension,int clipedWidth, int clipedHeight)
    {
        Rectangle clip = new Rectangle(clipedWidth, clipedHeight);
        clip.x = (panelDimension.width - clip.width) / 2;
        clip.y = (panelDimension.height - clip.height) / 2;
        int x0 = (panelDimension.width - sourceImage.getWidth()) / 2;
        int y0 = (panelDimension.height - sourceImage.getHeight()) / 2;
        int x = clip.x - x0;
        int y = clip.y - y0;
        return sourceImage.getSubimage(x, y, clip.width, clip.height);
    }
}

Entity Inheritance Using Abstract Entity

In my previous blog I shared my code re-factoring experience by using Mapped Superclass. Using Abstract Entity was another interesting experience. In our project there are some Entities like Customer, Vendor which have some common attributes like 'First Name', 'Last Name', etc. These attributes were defined  in both Customer and Vendor Class. This approach not only produced code duplication but also column duplication in underlying Datastore. JPA Abstract Entity feature inspires me to use a third Entity Class which is abstract to avoid this duplication.

Let's see how it works. Suppose you have two Entities Student and Teacher, and they have following attributes



Three attributes are common in this case and you can introduce a Person class which is abstract and has these common properties. Student and Teacher class will extend Person and only have their individual properties.

Your  Person, Student and Teacher Entity classes will be like this

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
@Table(name = "persons")
public abstract class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id_nr")
    protected Long idNr;
    @Column(name = "first_name")
    protected String firstName;
    @Column(name = "last_name")
    protected String lastName;
    
    public Person() {
    } 
    //getter setter of the properties ....


@Entity
@Table(name = "teachers")
public class Teacher extends Person {
    private static final long serialVersionUID = 1L;
    @Column(name = "designation")
    protected String designation;
    // constructor, getter setter of the property....


@Entity
@Table(name = "students")
public class Student extends Person {
    private static final long serialVersionUID = 1L;
    @Column(name = "role_number")
    protected String roleNumber;
    // constructor, getter setter of the property.... 

For above scenario three tables will be generated in the database, persons, students and teachers. Mapping strategy of @Inheritance annotation has a great impact in table generation process. As we have used InheritanceType.JOINED as the mapping strategy, three different tables are created. If we were using default mapping strategy which is InheritanceType.SINGLE_TABLE, only persons table will be created with all the attributes. In both cases Persistence provider will also create a discriminator column in the person table called DTYPE, which will store the name of the inherited entity used to create the person.

Now run the following code and see how data is stored in the database in this design.

        @PersistenceContext(unitName = "TaskBoard-ejbPU")
        EntityManager em;

        Teacher teacher = new Teacher();
        teacher.setFirstName("Sarwar");
        teacher.setLastName("Hossain");
        teacher.setDesignation("Associate Proffessor");
        teacher.setIdNr(null);
        em.persist(teacher);
        
        Student student = new Student();
        student.setFirstName("Shams");
        student.setLastName("Zawoad");
        student.setRoleNumber("001525");
        student.setIdNr(null);
        em.persist(student);
        em.flush();



If you try with InheritanceType.SINGLE_TABLE mapping strategy you will get the following output by running the same code

Attractive feature of abstract entities is that they can be queried just like concrete queries, which were not possible in Mapped Superclass. If an abstract entity is the target of a query, the query operates on all the concrete subclasses of the abstract entity.

Entity Inheritance Using Mapped Superclass

When I engaged myself into code re-factoring of our VELACORE project, I found that almost all Entities have four common properties createdBy, creationDate, modifiedBy and modificationDate.  I wanted to reduce this code duplication and found that JPA is providing Mapped Superclass for this type of requirement where state and mapping information are common to multiple Entity classes. It contains persistent state and mapping information, but is not Entitity. That is, it is not decorated with the @Entity annotation and is not mapped as an entity by JPA.

Mapped Superclasses do not have any corresponding tables in the underlying Datastore (that was also my requirement). Entities that inherit from the mapped Superclass define the table mappings. Mapped superclasses are specified by decorating the class with the javax.persistence.MappedSuperclass annotation.

Here is an example of using Mapped Superclass for entity inheritance

@MappedSuperclass
public class BaseEntity
{
    @Column(name = "created_by")
    private String createdBy;
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "creation_date")
    private Calendar creationDate;
    
   //getter setter of the properties ....
}

@Entity
public class Customer extends BaseEntity 
{
    @Column(name = "first_name")
    private String firstName;

    ...
}

@Entity
public class Invoice extends BaseEntity {
    @Column(name = "invoice_no")
    private String invoiceNo;

    ...
}


In the above code snippet BaseEntity is the MappedSuperclass which contains the mapping information of the common properties. Customer and Invoice are two Entities extending the BaseEntity. In this scenario only CUSTOMER and INVOICE tables will be created in the database not the BASEENTITY. "created_by" and "creation_date" columns will be present in both CUSTOMER and INVOICE tables.


Limitations of using Mapped Superclass :
-Mapped Superclasses are not queryable, and can’t be used in EntityManager or Query operations.
-Mapped Superclasses can’t be targets of entity relationships.

Protect Your Java Application by reCAPTCHA

4 months gone since I have post my last blog. Got a very encouraging feedback from my readers in this period but can't manage to write anything. Now feeling glad to start writing again. Hope java developers will find this tutorial useful to protect their application using reCaptcha, a widely used CAPTCHA system in the industry.

First go to the reCAPTCHA website and create your reCAPTCHA key by providing the domain name of your application. You will get two keys one is Private and another is Public. Public key will be used in the JavaScript code that is served to your users. Private key is required to communicate between your server and the reCAPTCHA server. Be sure to keep the Private key secret.

Now download the recaptcha4j library from here. And place the jar file in WEB-INF/lib/ directory. It will make your life easy to display the reCAPTCHA widget, send the user request to reCAPTCHA server and get response from there.

You are now ready to use reCAPTCHA in your application. First import the required classes in your JSP page.

<%@ page import="net.tanesha.recaptcha.ReCaptcha" %>
<%@ page import="net.tanesha.recaptcha.ReCaptchaFactory" %>
Now add the following code in the web page, where you want to put the reCAPTCHA box. Target of using reCAPTCHA is to protect form submission so place this between the form beginning and ending tags.
<%
ReCaptcha c = ReCaptchaFactory.newReCaptcha("your_public_key", "your_private_key", false);
          out.print(c.createRecaptchaHtml(null, null));
%>

First line of the code will create an instance of reCAPTCHA. Second line will generate and display a reCAPTCHA widget in your page.

Now come to the server side where you have to validate the submitted form with the reCAPTCHA server.


Here is a simple servlet which is used to do the validation job.
import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

public class GreetingServlet extends HttpServlet 
{
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {

        String challenge = req.getParameter("recaptcha_challenge_field");
        String response = req.getParameter("recaptcha_response_field");
        
        String remoteAddr = req.getRemoteAddr();

        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey("[write your privatekey here]");

        ReCaptchaResponse reCaptchaResponse =
                reCaptcha.checkAnswer(remoteAddr, challenge, response);

        if (reCaptchaResponse.isValid()) {
            //valid do something whatever you want to do
        } 
        else
        {
            //not valid do something like send error message to user
        }
    }
}

remoteAddr is the user's IP address which is passed to the reCAPTCHA servers. response contains the user's answer to the reCAPTCHA challenge.

You are done. Visit this link to get an example of how it works.
Reference link.

Working with DnD Framework of Ext GWT (GXT) : A Basic Example of Drag and Drop

DnD framework of Ext GWT is extremely powerful framework which supports drag and drop between two container, list view, grid, tree panel, tree grid and more over between heterogeneous components like list view to grid or grid to tree panel, etc. Here I am going to describe how you can drag a Html component and drop to a container.

Create a new project named BasicDnDExample and add GXT library in the project. Now go to the onModuleLoad method of BasicDnDExample class and remove all the auto generated code of this method.
First create a HorizontalPanel  and a LayoutContainer as the source container. Then add source components to the source container.

     HorizontalPanel hp = new HorizontalPanel();  
     hp.setSpacing(10);  
           
     final LayoutContainer sourceContainer = new LayoutContainer();  
     sourceContainer.setLayoutOnChange(true);  
     sourceContainer.setWidth(300);  
          
     List<Employee> employeeList = TestData.getEmployees();
     for(Employee employee : employeeList)
     {
        final Html html = new Html("<div style=\"font-size:11px; border: 1px solid #DDDDDD;float:left;margin:4px 0 4px  4px; padding:2px;width:220px;\">"+
          "<div style=\"color:#1C3C78;font-weight:bold;padding-bottom:5px;padding-top:2px;text-decoration:underline;\">"+employee.getName()+"</div>"+ 
          "<div style=\"color:green\">Department:"+employee.getDepartment()+"</div>"+ 
          "<div style=\"color:blue\">Designation:"+employee.getDesignation()+"</div>"+
          "<div style=\"color:black;padding-bottom:2px;\">Salary:"+employee.getSalary()+"</div>"+ 
          "</div>" ); 
        sourceContainer.add(html, new FlowData(3));  
                 
        DragSource source = new DragSource(html) {  
           @Override  
              protected void onDragStart(DNDEvent event) {  
                event.setData(html);  
                event.getStatus().update(El.fly(html.getElement()).cloneNode(true));  
             }  
        };  
                 
    }

Using the employee list I have created a Html component for each employee and add this to the source container. Then create DragSource with the component and set this as the Data of the DNDEvent.  You will find the code of Empoyee and TestData classes here.


Now create another LayoutContainer as the target container. Then create a DropTarget from the target container,  which identifies components that can receive data from a drag and drop operations. While the cursor is over a target, the target is responsible for determining if the drop is valid and showing any visual indicators for the drop.

           
    final LayoutContainer targetContainer = new LayoutContainer();  
    targetContainer.setLayoutOnChange(true);  
    targetContainer.setBorders(true);  
    targetContainer.setSize(300, 500); 

   DropTarget target = new DropTarget(targetContainer) {  
       @Override  
       protected void onDragDrop(DNDEvent event) {  
         super.onDragDrop(event);  
         Html html = event.getData();  
         targetContainer.add(html);  
       }  
  };  
  target.setOverStyle("drag-ok");

In the onDragDrop method you can define what you want to do after the element is dropped on the target. Here I have got the Html component from the DNDEvent and added the component in the target container.
Finally add the source and target container in the HorizontalPanel.

  hp.add(targetContainer);  
  hp.add(sourceContainer);  
  RootPanel.get().add(hp);

Output of this tutorial will be like this

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers