Working with Google Maps Javascript API V3

Google Maps Javascript API V3 is an awesome API provided by Google. Today I will give you a little flavor about this API. Later I will write about some advance features.

Here is a simple tool, created using this API. Click on the marker, the Latitude and Longitude position will be displayed in a window and also in the textbox. If you set a Latitude, Longitude point in the textbox and click on the button, that point will be shown in the map with a marker.

Latitude

Longitude


Now I'm going to show you, how you can make this tool..

First load the Google Maps Javascript API and the latest jQuery version . Then design the user interface.

 
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://zmodal.googlecode.com/files/jquery-1.6.1.min.js"></script>

<div style="float:left; width:200px; border:1px solid #CCCCCC;">
        Latitude <input type="text" id="tbLattitude"/><br/>
        Longitude <input type="text" id="tbLongitude"/><br/>
        <input type="button" name="btCal" value="Show in Map" onclick="return showInMap();" />
    </div>
    <div id="map_canvas" style="float:left;width: 400px; height: 400px; border: 2px solid #999;margin-left:10px;">
    </div>

The DIV element with id 'map_canvas' will be the container of the Map. This id will be required when you create the map object to display in this div.

Now come to the Javascript part..

Set the window onLoad callback method and in that method, call the LoadMap method with initial latitude,longitude.

 
google.maps.event.addDomListener(window, 'load', initializeMap);
function initializeMap() {
  LoadMap(23.70992, 90.40714);
}

In the LoadMap method first create a LatLng object using the lat, long parameter

 
function LoadMap(lat, longitude) {
var latlng = new google.maps.LatLng(lat, longitude);
Create a Map object using map options and the container ID
 
var myOptions = {
  zoom: 12,
  center: latlng, // previously created LatLng object
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

For the information window first create the content of the window then create a InfoWindow object using the content. This object will be later used in the onClick event of the Marker.

var contentString = '
' + 'Latitude : '+lat+'
Longitude : ' + longitude + '' '
'; var infowindow = new google.maps.InfoWindow({ content: contentString });

Now create the Marker object using the LatLng and Map object.

var marker = new google.maps.Marker({
  position: latlng,
  map: map,
  title: 'Location',
  draggable: true,
  animation: google.maps.Animation.DROP
});

Finally add an event listener for the Marker object. First open the InfoWindow object then call the method which set LatLng value to the textbox.

  google.maps.event.addListener(marker, 'click', function (event) {
    infowindow.open(map, marker);
    setLatLongToTextBox(event.latLng);
  });

}
Here is the setLatLongToTextBox and showInMap method
function setLatLongToTextBox(latlong) {
  var latstr = latlong + '';
  var value = latstr.slice(1, latstr.length - 1);
  var latlongs = value.split(",");
  $("#tbLattitude").attr("value", latlongs[0]);
  $("#tbLongitude").attr("value", latlongs[1]);
}

//this method is used as the onclick method of the button 
function showInMap() {
  var lat = $("#tbLattitude").attr("value");
  var longitude = $("#tbLongitude").attr("value");
  LoadMap(lat, longitude);
  return false;
}

Working with Google Chart Tools : Create a Geochart

Geochart can be a handy tool if you want to represent the demographic behavior of your service. In my recent project for Bangladesh Post Office I used this tool to represent the usage of their service in each Division of Bangladesh. Another big example is the Google Analytics where you can view the location based visitor information of your site. Here I am going to show you how you can use this in your project.

First load the Google's Javascript API
<script src="https://www.google.com/jsapi" type="text/javascript">  
</script> 

Now create a DIV element and give it an ID. This id will be required when you create the chart object to display in this div.

<div id="map">
    </div>

In your Javascript code first load the geomap package and set the onLoadCallback method name.

<script type="text/javascript">
 google.load('visualization', '1', { 'packages': ['geomap'] });
 google.setOnLoadCallback(drawGeoChart);

In the callback method first create a DataTable object add two columns. Just give a suitable name as per your requirement.

 function drawGeoChart() {
            var data = new google.visualization.DataTable();
            data.addRows(6);
            data.addColumn('string', 'Country');
            data.addColumn('number', 'Visit');

Now set some value to the DataTable. The first column can be an Address, country name, region name locations, or US metropolitan area codes. For country and region name follow this ISO-3166 code or text equivalent to the code. The second column will be the value of the area.

            data.setValue(0, 0, 'Germany');
            data.setValue(0, 1, 600);
            data.setValue(1, 0, 'United States');
            data.setValue(1, 1, 500);
            data.setValue(2, 0, 'Bangladesh');
            data.setValue(2, 1, 400);
            data.setValue(3, 0, 'Canada');
            data.setValue(3, 1, 200);
            data.setValue(4, 0, 'France');
            data.setValue(4, 1, 200);
            data.setValue(5, 0, 'RU');
            data.setValue(5, 1, 300);
Finally configure some property of the chart and draw it using the data previously set.
  var regionOptions = {};
  regionOptions['width'] = '400';
  regionOptions['height'] = '250';
  // Look the div id is used here to create the chart object 
  var regionChart = new  google.visualization.GeoMap(document.getElementById('map'));
  regionChart.draw(data, regionOptions);
        
}
</script>
And here is the outcome. On mouse over you can view the data of the area



You can load the chart data by a webservice call. For C# see my previous blog. Visit this link to know more about Geochart.

Working with Google Chart Tools in C# .NET : Create a Simple Pie Chart

If you want to load a chart asynchronously in C# . NET, Google Chart Tools will be the perfect choice for you. It is easy to use and enough flexible to customize. Suppose you want to show how many students in your class like Pizza, Burger, Hotdog, and Fried Chicken in a Pie chart. Here I will show you how to load the students' data from server side using WebService and show it in a chart asynchronously.

First create a new WebService file suppose GoogleChart.asmx . In this file create a Public Class named FoodLikingCount

    public class FoodLikingCount
    {
        public int PizzaCount { get; set; }
        public int BurgerCount { get; set; }
        public int HotdogCount { get; set; }
        public int FriedChickenCount { get; set; }
    }

After the class declaration add the following line

[System.Web.Script.Services.GenerateScriptType(typeof(FoodLikingCount))]

It will enable you to use the FoodLikingCount object in your Javascript code.

Create a new WebMethod in the WebService class named GetFoodLikingCountData

[WebMethod]
public FoodLikingCount GetFoodLikingCountData()
{
       FoodLikingCount countModel = new FoodLikingCount 
       {
           PizzaCount = 12,
           BurgerCount = 16,
           HotdogCount = 8,
           FriedChickenCount = 4,
       };
       // you can also load data from your database here

       return countModel ;
}

Now come to client side code. Create an aspx file named GoogleChartToolTest.aspx and add this line between head tag.

 <script src="https://www.google.com/jsapi" type="text/javascript">
 </script> 

Create a DIV element and give it an ID. This id will be required when you create the chart object to display in this div. Also add a ScriptManager to call your webservice method.

    <form id="form1" runat="server">
        <asp:ScriptManager ID="sm1" runat="server">
            <Services>
                 <asp:ServiceReference Path="~/[your_package]/GoogleChart.asmx" />
            </Services>
        </asp:ScriptManager>
    </form>
    <div id="pie_chart">
    </div>

Here is the Javascript code which you require to load data through the webservice call, create, and show chart in the div.

<script type="text/javascript">

//load the corechart package, the pie chart is in this package
google.load('visualization', '1', { packages: ['corechart'] });

//provide the method name which you want to call as onload callback
google.setOnLoadCallback(loadFoodLikingChart);

function loadFoodLikingChart()
{
       [your_package].GoogleChart.GetFoodLikingCountData(
            function (ws_rsp) {
              var foodLikingData= new google.visualization.DataTable();
              foodLikingData.addColumn('string', 'Food');
              foodLikingData.addColumn('number', 'Count');
              foodLikingData.addRows(4);
              
              foodLikingData.setValue(0, 0, "Pizza");
              foodLikingData.setValue(0, 1, ws_rsp.PizzaCount );
              foodLikingData.setValue(1, 0, "Burger");
              foodLikingData.setValue(1, 1, ws_rsp.BurgerCount );
              foodLikingData.setValue(2, 0, "Hotdog");
              foodLikingData.setValue(2, 1, ws_rsp.HotdogCount );
              foodLikingData.setValue(3, 0, "Fried Chicken");
              foodLikingData.setValue(3, 1, ws_rsp.FriedChickenCount );

              var options = {};
              options ['width'] = '400';
              options ['height'] = '250';
              options ['chartArea'] = { left: 20, top: 20, width: '95%', height: '90%' };

              // Look the div id is used here to create the chart object
              var chart = new google.visualization.PieChart(document.getElementById('pie_chart'));
              chart.draw(foodLikingData,options);
            },
            function (e) {
               alert("Error");
           }
      );
}
</script>

The result will be like this.

Visualize the DataTable as a two dimensional array. It will help you to understand the above code. Here is the Google Chart Gallery. You will get a lot of example there.

zModal, An Easy to Use jQuery Modal Plugin



There are lots of jQuery modal plugin available in the web. For my current project I need one which, I can easily customize. I realized creating a modal by myself is the best way for gaining maximum freedom.

It is very simple and easy to use and customizable. You can give it a try. Here I will describe how to use it.

First download all the required files from here and include in the page.

Create a DIV and give it an id and set the display property 'none'.

<div id="modalContent" style="width:400px; display:none;">
</div>
You can insert any content between the DIV tag.

Now place a button, the onclick event of which will show the modal
<input type="button" name="name2" value="Show Modal" 
onclick="$('#modalContent').showModal();" />
Here is an example. Click on the button and a modal will pop up.


<div id="modalContent" style="width:400px; height: 150px; display: none;">
<p style="padding-left:20px;">
modalContent:
Click the close button to hide the modal
You can also press ESCAPE button to hide the modal
</p>
</div>
<input type="button" name="name2" value="Show Modal" 
onclick="$('#modalContent').showModal();" />

There are some configurable options for the modal.
setModalButtonCss : Set True if you want to display all buttons contained in the modal in a zModal style.
hideDefaultClose : Set True if you want to hide the default close button.
opacity : You can control the opacity of the background with this parameter.
bgColor : You can change the background color with this parameter.

Here is an example with all the options are set.
<div id="modalContent2" style="width:400px; display:none;">
<p>
User Name:<br />
<input id="tbUname" type="text" name="uName">
</p>
<p>
Password:<br />
<input id="tbPass" type="text" name="pass">
</p>
<p>
<input type="button" name="login" value="Login" onclick="$('#modalContent2').hideModal()" />
</p>
</div>
<input type="button" name="name" value="Show Modal 1" 
onclick="$('#modalContent2').showModal({'setModalButtonCss': 'True', 
'hideDefaultClose' : 'True', 
'opacity' : '.2', 
'bgColor' : '#7FCFF9' });" />
Click on the button to view the example

If you want to hide your modal like the onclick event of the Login button write this code
$('#divID').hideModal();

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

Working with GXT Grid : Add Remote Pagination Functionality

As promised previously today I am going write about adding remote pagination functionality with GXT Grid which was one of most demanded one from my readers. In my previous blog I have described in detail how you can load data from a remote data store and show them in GXT Grid. In this writing the same Comments entity and CommentModel are used to represent data. You will find the code of these classes here.

At first in the implementation of your GWT RPC Service add a method to load all the comments from the data store.

public List<Commentmodel> getAllComment() 
{
   List<Commentmodel> commentList = new ArrayList<Commentmodel>();
   PersistenceManager pm = PMF.get().getPersistenceManager(); 
   try {
      String query = "select from " + Comments.class.getName()+" order by  postedDate desc"; 
      List<Comments> list = (List<Comments>) pm.newQuery(query).execute();
      if (!list.isEmpty()) {
         for (Comments c : list)
         {
            //convert from entity object to DTO
            commentList.add(CommentConverter.entityToModel(c));
         }
      }
   }catch (Exception ex) {}
   finally {
      pm.close();
   }
   return commentList;
}

Now add a method public PagingLoadResult<Commentmodel> getComments(PagingLoadConfig config) in your service which takes a PagingLoadConfig object to determine the limit and offset value of the request and returns the desired list for the paging loader. Here is the implementation of the method.
@Override
public PagingLoadResult<Commentmodel> getComments(PagingLoadConfig config) {

//comments is a private variable of the service implementation class
//private List<Commentmodel> comments;
comments = getAllComment();

//get all the comments from the data store
//and sort this list according to sorting info

if (config.getSortInfo().getSortField() != null) {
final String sortField = config.getSortInfo().getSortField();
if (sortField != null) {
Collections.sort(comments, config.getSortInfo().getSortDir().comparator(new Comparator<Commentmodel>() {
public int compare(CommentModel c1, CommentModel c2) {
if (sortField.equals("comments")) {
return c1.getComments().compareTo(c2.getComments());
} else if (sortField.equals("postedBy")) {
return c1.getPostedBy().compareTo(c2.getPostedBy());
} else if (sortField.equals("postedDate")) {
return c1.getStartingDate().compareTo(c2.getStartingDate());
}
return 0;
}
}));
}
}

//Create a sublist and add data to list according
//to the limit and offset value of the config

ArrayList<Commentmodel> sublist = new ArrayList<Commentmodel>();
int start = config.getOffset();
int limit = comments.size();
if (config.getLimit() > 0) {
limit = Math.min(start + config.getLimit(), limit);
}
for (int i = config.getOffset(); i < limit; i++) {         sublist.add(comments.get(i));       }       
return new BasePagingLoadResult<Commentmodel>
(sublist, config.getOffset(), comments.size());
}

Your server side coding is done. Let's come to client side coding and see how to use this service to add remote pagination functionality with GXT Grid.

First create a RpcProxy object, proxy to make RPC call using the load configuration. With the proxy object create a PagingLoader, loader which is required to load page enabled set of data and enable the remote sorting attribute of the loader.

RpcProxy<PagingLoadResult<CommentModel>> proxy = new RpcProxy<PagingLoadResult<CommentModel>>() {
@Override
public void load(Object loadConfig,
AsyncCallback<PagingLoadResult<CommentModel>> callback) {
Gxtexamplegalary.greetingService.getComments(
(PagingLoadConfig) loadConfig, callback);
}
};

// loader
final PagingLoader<PagingLoadResult<ModelData>> loader = new BasePagingLoader<PagingLoadResult<ModelData>>(
proxy);
loader.setRemoteSort(true);

Now use this loader to create a ListStore of CommentModel  and bind the loader with a PagingToolBar.

ListStore<CommentModel> commentList = new ListStore<CommentModel>(loader);

final PagingToolBar toolBar = new PagingToolBar(3);
toolBar.bind(loader);

Create a List of ColumnConfig  and a ColumnModel from the ColumnConfig list.

List<ColumnConfig> configs = new ArrayList<ColumnConfig>();
ColumnConfig column = new ColumnConfig();
column.setId("comments");
column.setHeader("Comments");
column.setWidth(200);
configs.add(column);

column = new ColumnConfig("postedBy", "Posted By", 150);
column.setAlignment(HorizontalAlignment.LEFT);
configs.add(column);

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

ColumnModel cm = new ColumnModel(configs);

Finally create a Grid with the commentList and the column model. Add a Listener with the Grid to handle the remote pagination functionality. In the handleEvent method of the Listener first create a PagingLoadConfig, config and set offset, limit, sort field and sort direction value of the config. Then load data by the loader with this configuration.
final Grid<CommentModel> grid = new Grid<CommentModel>(commentList, cm);
grid.setStateId("pagingGridExample");
grid.setStateful(true);
grid.addListener(Events.Attach, new Listener<GridEvent<CommentModel>>() {
public void handleEvent(GridEvent<CommentModel> be) {
PagingLoadConfig config = new BasePagingLoadConfig();
config.setOffset(0);
config.setLimit(3);

Map<String, Object> state = grid.getState();
if (state.containsKey("offset")) {
int offset = (Integer) state.get("offset");
int limit = (Integer) state.get("limit");
config.setOffset(offset);
config.setLimit(limit);
}
if (state.containsKey("sortField")) {
config.setSortField((String) state.get("sortField"));
config.setSortDir(SortDir.valueOf((String) state
.get("sortDir")));
}
loader.load(config);
}
});
grid.setLoadMask(true);
grid.setBorders(true);
grid.setAutoExpandColumn("comments");
grid.setStyleAttribute("borderTop", "none");
grid.setStripeRows(true);

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

That's all for today. Enjoy GWT and GXT :-)

Google App Engine, JDO and GXT(Ext GWT) Grid - Make All These Working Together

Previously I have written some blogs about GXT Grid  where the data resides in the client side. But as per the request of my readers I feel the necessity of writing some tutorials with remote data store. And for this purpose I have chosen Google App Engine data store as the back-end with JDO implementation.

It requires a configuration file in the final WAR named  jdoconfig.xml which resides in the directory war/WEB-INF/classes/META-INF/. Eclipse creates this file as src/META-INF/jdoconfig.xml. This file is automatically copied into war/WEB-INF/classes/META-INF/ when you build your project. This file should contain the following contains.

<?xml version="1.0" encoding="utf-8"?>
<jdoconfig xmlns="http://java.sun.com/xml/ns/jdo/jdoconfig"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:noNamespaceSchemaLocation="http://java.sun.com/xml/ns/jdo/jdoconfig">

   <persistence-manager-factory name="transactions-optional">
       <property name="javax.jdo.PersistenceManagerFactoryClass"
           value="org.datanucleus.store.appengine.jdo.DatastoreJDOPersistenceManagerFactory"/>
       <property name="javax.jdo.option.ConnectionURL" value="appengine"/>
       <property name="javax.jdo.option.NontransactionalRead" value="true"/>
       <property name="javax.jdo.option.NontransactionalWrite" value="true"/>
       <property name="javax.jdo.option.RetainValues" value="true"/>
       <property name="datanucleus.appengine.autoCreateDatastoreTxns" value="true"/>
   </persistence-manager-factory>
</jdoconfig>

Here I am going to describe the way of loading a comment list from the App Engine data store and making the list viewable in the GXT Grid. So At first I need a POJO class to store and retrieve comments from the App Engine data store using the JDO API. Here is my Comments class.

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Comments {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;

    @Persistent
    @Column(name="comments")
    private String comments;

    @Persistent
    @Column(name="posted_by")
    private String postedBy;
    
    @Persistent
    @Column(name="posted_date")
    private Date postedDate;

    public Comments(String comments, String postedBy, Date date) {
        this.comments = comments;
        this.postedDate = date;
        this.postedBy = postedBy;
   }

    public Long getId() {
        return id;
    }

 public String getComments() {
  return comments;
 }

 public void setComments(String comments) {
  this.comments = comments;
 }

 public Date getPostedDate() {
  return postedDate;
 }

 public void setPostedDate(Date postedDate) {
  this.postedDate = postedDate;
 }

 public void setId(Long id) {
  this.id = id;
 }

 public String getPostedBy() {
  return postedBy;
 }

 public void setPostedBy(String postedBy) {
  this.postedBy = postedBy;
 }
}

Now when you want to transfer data from server to client you need a DTO (Data Transfer Object). As I am going to show the comments in GXT Grid so my DTO has to inherit the properties of GXT's BaseModel. Here is the CommentModel class which will serve my purposes.

public class CommentModel extends BaseModel {

private static final long serialVersionUID = 1L;

public CommentModel(){}

public CommentModel(String comments, String postedBy, Date date) {
set("comments", comments);
set("postedDate", date);
set("postedBy",postedBy);
}

public String getComments() {
return (String) get("comments");
}

public String getPostedBy() {
return (String) get("postedBy");
}

public Date getStartingDate() {
return ((Date) get("postedDate"));
}
}

For any operation on data store you have to request the data store for the desired operation. Each request that uses the data store creates a new instance of the PersistenceManager class through the instance of  PersistenceManagerFactory class. As creating an instance of PersistenceManagerFactory class is a very costly process, I have used a Singleton class PMF for this purpose.

public final class PMF {
private static final PersistenceManagerFactory pmfInstance =
JDOHelper.getPersistenceManagerFactory("transactions-optional");

private PMF() {}

public static PersistenceManagerFactory get() {
return pmfInstance;
}
}

If you are familiar with GWT RPC Service then create a service named CommentService and add a method
List<CommentModel> getAllComment();. Here is the implementation of the method where JDOQL is used to write a query which returns all the comments from the data store.

public List<Commentmodel> getAllComment() 
{
   List<Commentmodel> commentList = new ArrayList<Commentmodel>();
   PersistenceManager pm = PMF.get().getPersistenceManager(); 
   try {
      String query = "select from " + Comments.class.getName()+" order by  postedDate desc"; 
      List<Comments> list = (List<Comments>) pm.newQuery(query).execute();
      if (!list.isEmpty()) {
         for (Comments c : list)
         {
            //convert from entity object to DTO
            commentList.add(CommentConverter.entityToModel(c));
         }
      }
   }catch (Exception ex) {}
   finally {
      pm.close();
   }
   return commentList;
}

CommentConverter is a utility class which converts an object of Comments class to an object of CommentModel class.

public class CommentConverter 
{
   public static CommentModel entityToModel(Comments comment)
   {
      CommentModel model = new CommentModel(comment.getComments(), comment.getPostedBy(), comment.getPostedDate());
      return model;
   }
} 

All the server side coding is done. Let's come to client side.

First create an instance of CommentServiceAsync.
public static final CommentServiceAsync commentService = GWT.create(CommentService.class);
 

Then create a ListStore of CommentModel, commentStore and call the getAllComment method of the commentService. In the onSuccess method add the returned list to the commentStore.
 final Label lbError = new Label();
  final ListStore<Commentmodel> commentStore = new ListStore<Commentmodel>();
  commentService.getAllComment(new AsyncCallback<List<Commentmodel>>() {

   @Override
   public void onFailure(Throwable caught) {
    lbError.setText("data loading failure");

   }

   @Override
   public void onSuccess(List<Commentmodel> result) {
    commentStore.add(result);

   }
  }); 

The rest of the tasks are very familiar with the GXT users. Creating a List of ColumnConfig, a Grid with the commentStore and  ColumnConfig lists, etc.

        List<Columnconfig> configs = new ArrayList<Columnconfig>();
        ColumnConfig column = new ColumnConfig();
        column.setId("comments");
        column.setHeader("Comments");
        column.setWidth(200);
        configs.add(column);

        column = new ColumnConfig("postedBy", "Posted By", 150);
        column.setAlignment(HorizontalAlignment.LEFT);
        configs.add(column);

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

        ColumnModel cm = new ColumnModel(configs);

        final Grid<Commentmodel> grid = new Grid<Commentmodel>(commentStore, cm);
        grid.setBorders(true);
        grid.setAutoExpandColumn("comments");
        grid.setStyleAttribute("borderTop", "none");
        grid.setStripeRows(true);

        ContentPanel cp = new ContentPanel();
        cp.setBodyBorder(false);
        cp.setHeading("Grid with Pagination");
        cp.setButtonAlign(HorizontalAlignment.CENTER);
        cp.setLayout(new FitLayout());
        cp.setSize(700, 300);
        cp.add(grid);

That's all for today. You will get a live example of this tutorial here.
For more about Google App Engine and JDO visit this.

How to Use GXT XTemplate with ListView

XTemplate is a very useful class of GXT that supports auto-filling arrays, conditional processing with basic comparison operators, sub-templates, basic math function support, special built-in template variables, inline code execution and more. Here i am going to illustrate how to use XTemplate with a ListView to customize the look and feel of the ListView.

Create a new project named XTemplateExample and add GXT library in the project. To create a ListView 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 have used in my previous blogs. You will find the code of these classes here.

Now go to the onModuleLoad method of XTemplateExample class. Remove all the auto generated code of this method.
First create a ListStore of Employee model , employeeList and add data to this store which was generated in the TestData class

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

Now Create a ListView of Employee type and set the employeeList as the store of the list view.
   ListView<Employee> lView = new ListView<Employee>();
   //getTemplate() returns the desired template
   lView.setTemplate(getTemplate());
   lView.setStore(employeeList);

   ContentPanel cp = new ContentPanel(); 
   cp.setBodyBorder(false); 
   cp.setHeading("Using XTemplate"); 
   cp.setButtonAlign(HorizontalAlignment.CENTER); 
   cp.setLayout(new FitLayout()); 
   cp.setSize(500, 420);
   cp.add(lView); 
   RootPanel.get().add(cp);

Here goes the definition of the getTemplate() method
private native String getTemplate() /*-{ 
       return ['<tpl for=".">', 
       '<div style="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;">{name}</div>', 
       '<div style="color:green">Department:{department}</div>', 
       '<div style="color:blue">Designation:{designation}</div>',
       '<div style="color:black;padding-bottom:2px;">Salary:{salary}</div>', 
       '</div>', 
       '</tpl>', 
       ''].join(""); 
        
 }-*/;  

Properties of the Employee model are placed between {}. The style will be applied on every element of the employeeList. And the outcome of the work will be like this.


You can give your own look and feel by simply changing the CSS.


Sending Mail Using JavaMail API and Gmail as SMTP server

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The API defines classes such as Message, Session, and Transport. It includes support for the IMAP4, POP3, and SMTP protocols. Here I am going to show you how you can use this API to send mail through SMTP protocol.

First create a MailUtility class which you can use later from your client code.

public class MailUtility {

//Set Gmail as SMTP host 
private String SMTP_HOST_NAME = "smtp.gmail.com";
private String SMTP_AUTH_USER = "yourgmailid@gmail.com";
private String SMTP_AUTH_PWD = "password";

public void postMail(String recipients[], String subject,
String message, String from) throws MessagingException {
boolean debug = false;

//Set the required JavaMail session properties
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.user", SMTP_AUTH_USER);
props.put("mail.smtp.password", SMTP_AUTH_PWD);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.ssl", "true");

props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");

//Create an Authenticator. You will find the SMTPAuthenticator class defination later
Authenticator auth = new SMTPAuthenticator();

//Create a Session from the Properties and the Authenticator
Session session = Session.getInstance(props, auth);
session.setDebug(debug);

// Create a MimeMessage
MimeMessage msg = new MimeMessage(session);

// Set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);

InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);

//Set message subject and text
msg.setSubject(subject);
msg.setText(message);

//Finally now send the message.
try {
Transport.send(msg);
} catch (MessagingException messagingException) {
messagingException.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}

}

//SimpleAuthenticator is used to do simple authentication
//when the SMTP server requires it.

private class SMTPAuthenticator extends javax.mail.Authenticator {

@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
}
And here is the client code that uses the MailUtility class for sending mail.
String emailMsgTxt = "Hello, this is a test mail from my mail application.\n";
String emailSubjectTxt = "Test Mail";
String emailFromAddress = "yourgmailid@gmail.com";
String[] receipentList=
 {
      "abc@gmail.com",
      "wxx@yahoo.com"
 };
try
{
      MailUtility smtpMailSender = new MailUtility();
      smtpMailSender.postMail(receipentList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
} catch (MessagingException messagingException)
{
      messagingException.printStackTrace();
} catch (Exception ex)
{
     ex.printStackTrace();
}
That's all. Another day I will describe how you can send mail asynchronously using this mail API.

How to Call a Servlet in GWT

Sometimes you may need a HttpServlet other than GWT Rpc Service in a real life application. If needed then how to call the Servlet from your GWT client? Here you will find the answer.

Here is a simple HelloServlet

public class HelloServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{ 
String name = request.getParameter("name");
response.getWriter().write("Hello "+name+", Welcome in My Servlet");
}
}
The Servlet uses a request a parameter 'name' and writes it in the response writer.

To call the Servlet from the client first configure the web.xml (war/WEB-INF/web.xml) file to let your GWT client know about the HelloServlet.

 HelloServlet
 org.ratul.servlettest.server.HelloServlet


 HelloServlet
 /hello

Value of the url-pattern node will be used later to call the Servlet.

Now make a simple UI with a TextBox and a Button.
final Button sendButton = new Button("Send");
final TextBox nameField = new TextBox();
RootPanel.get().add(nameField);
RootPanel.get().add(sendButton);

In the Click Handler of the sendButton call the Servlet with the 'name' parameter in the following way
sendButton.addClickHandler(new ClickHandler() {
  public void onClick(ClickEvent event) {
    Window.Location.replace("/hello?name="+nameField.getText());
    //the url-pattern value is used here
  }
});

Thats' all for today. Happy coding with GWT :-)

Getting Started with GXT (Ext GWT) Chart : Crate a Simple Horizontal Bar Chart

Ext GWT is providing us a very handy Chart library based on Open Flash Chart. Here you will find a step by step detail description about creating a simple horizontal bar chart using the GXT chart library.

Create a new project named GXTBascicChart and add GXT library in the project. Go to the GXTBascicChart.gwt.xml file and add this line

<inherits name='com.extjs.gxt.charts.Chart'/>

Now go to the directory where you have extracted the GXT library. In the resource folder you will find all the resources for using GXT. Copy the chart and flash folders in the war folder of you application.

Go to the onModuleLoad method of GXTBascicChart class and remove all the auto generated code of this method. Create a Content Panel to place the chart
ContentPanel cp = new ContentPanel();  
cp.setHeading("Horizontal Bar chart");  
cp.setFrame(true);  
cp.setSize(550, 400);  
cp.setLayout(new FitLayout());

Now create a Chart component by providing the location of the open flash chart Shockwave file which resides in the chart folder.
String url = "chart/open-flash-chart.swf";  
final Chart chart = new Chart(url);



Set a Chart Model for the chart object and add this to the Content Panel
chart.setBorders(true);  
chart.setChartModel(getHorizontalBarChartModel());  
cp.add(chart);      
RootPanel.get().add(cp);

The Chart Model is responsible for the chart title, axes, legends, labels, and draw-able elements in your chart. Here is the getHorizontalBarChartModel method
public ChartModel getHorizontalBarChartModel() 
{ 
  //Create a ChartModel with the Chart Title and some style attributes
  ChartModel cm = new ChartModel("Students by Department", "font-size: 14px; font-family:      Verdana; text-align: center;");
 
  XAxis xa = new XAxis();
  //set the maximum, minimum and the step value for the X axis
  xa.setRange(0, 200, 50);  
  cm.setXAxis(xa);
  
  YAxis ya = new YAxis();
  //Add the labels to the Y axis  
  ya.addLabels("CSE", "EEE", "CE", "ME","CHE");  
  ya.setOffset(true);  
  cm.setYAxis(ya);

  //create a Horizontal Bar Chart object and add bars to the object  
  HorizontalBarChart bchart = new HorizontalBarChart();  
  bchart.setTooltip("#val#Students");  
  bchart.addBars(new HorizontalBarChart.Bar(60, "#ffff00")); 
  //different color for different bars 
  bchart.addBars(new HorizontalBarChart.Bar(180, "#0000ff"));  
  bchart.addBars(new HorizontalBarChart.Bar(180, "#00ff00"));  
  bchart.addBars(new HorizontalBarChart.Bar(120, "#ff0000"));
  bchart.addBars(new HorizontalBarChart.Bar(120, "#333ccc"));

  //add the bchart as the Chart Config of the ChartModel
  cm.addChartConfig(bchart);       
  cm.setTooltipStyle(new ToolTip(MouseStyle.FOLLOW));  
  return cm;  
}

And here is the last step before running your application.
Go to the GXTBascicChart.html file and add the following line in the head section
<script language='javascript' src='flash/swfobject.js'></script>
That's all. Run the application and the output will be like this

How to Use Your Session Beans from GWT Client

Recently we have finished a project in which we were using EJB3.0 in the business tier and a GWT client for the user interface. Here i will share you how we connected them in a very convenient way.

Suppose you have an Entity class, Department and a stateless Session Bean named DepartmentBean which implements a remote interface DepartmentBeanRemote. To save a department the bean class
has a create method

public BigInteger create(Department department)
{
try
{
em.persist(department);
em.flush();
return department.getIdNr();
} catch (InvalidStateException in)
{
in.printStackTrace();
} catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}

Now how to call this create method from your GWT client?

First create a GWT RPC Service named DepartmentService and DepartmentServiceImpl is the implementation class of this service interface. The service implemenltation class will serve as a gateway between client and bean class.

Create an instance of DepartmentBeanRemote by dependency injection in DepartmentServiceImpl.
@EJB
private DepartmentBeanRemote departmentBeanRemote;
Now use this instance to call the methods of the DepartmentBean in the following way

public Long create()
{
try
{
Department department = new Department();
department.setIdNr(null);
department.setDepartmentNameSt("Computer Science");
department.setDepartmentDescriptionSt("Most popular department of the university");
BigInteger returnValue = departmentBeanRemote.create(department);
return new Long(returnValue.toString());
}
catch (Exception e)
{
e.printStackTrace();
return null; 
}
}
Call the service method from the client. You have just made a complete path between your GWT Client and the Session Beans.

How to Run Multiple Domain of GlassFish Simultaneously (Use --portbase option)

In many cases you may need to run multiple domains of GlassFish simultaneously. Few days ago I was in a situation to run 3 domains concurrently. At first I was creating domain with only --adminport option to assign different admin port to different domains. But when I try to run those domains simultaneously I was getting port conflict error. Then I found that there are many other ports in GlassFish for other purposes. Default ports for GlassFish are

4848 Admin port
8080 HTTP Instance port
7676 JMS port
3700 IIOP port
8181 HTTP_SSL port
3820 IIOP_SSL port
3920 IIOP_MUTUALAUTH port
8686 JMX_ADMIN port

So to avoid port conflict you have to assign different port numbers in different domains for each purpose. The easy way of doing this is using portbase option in create-domain command. You just have to set a base port number and the values for the ports are calculated as follows

Admin port: portbase + 48
HTTP listener port: portbase + 80
IIOP listener port: portbase + 37
JMX port: portbase + 86

Here is an example of create-domain command with portbase option

asadmin create-domain --user admin --portbase 2000 --savemasterpassword=true domain2


Remember
-> Adminport should be between 1 and 65535. So choose a portbase value such that the resulting port number doesn't exceed 65535

->The --portbase option can't be used with the --adminport or the --instanceport option

Session Management (Set and Get Data from Session) in GWT

When you think about the Security of a web application 'Session Management' is the first thing that strikes in your head. I am now working with an enterprise web application using GWT and you know security is a very vital issue in an enterprise application. And we have ensured the security by managing session data. Here i will describe how to store and retrieve data from session by using GWT RPC.

Suppose you want to store the user name in session after login to the application and check the session value later. Then what do you do?

First create a GWT RPC Service named 'SessionManagementService'. You can give any other name as you like. In SessionManagementService interface add two methods

public void setUserName(String userName);
public String getUserName();

And synchronize the methods with 'SessionManagementServiceAsync'.
public void setUserName(String userName, AsyncCallback<Void> asyncCallback);
public void getUserName(AsyncCallback<String> asyncCallback);

Now implement the methods in 'SessionManagementServiceImpl'. Let's first talk about the setter method.
public void setUserName(String userName)
{
     HttpSession httpSession = getThreadLocalRequest().getSession(true);
     httpSession.setAttribute("userName", userName);
}

The getThreadLocalRequest method returns you a HttpServletRequest object for the current call. For simultaneous invocation you will get different request object. And the getSession method returns you the current HttpSession for the associated request. So you can get the current session of the current call by getThreadLocalRequest().getSession(true).



The setAttribute method binds an object to the associated session. It stores the object's value as a Name-Value pair. You can put any thing as the value of the object. A String value or List<String> any thing. Here the name of the object is "useName" and the object is bound to this session with this name.

Now come to the getter method.
public String getUserName()
{
    HttpSession session = getThreadLocalRequest().getSession(true);
    if (session.getAttribute("userName") != null)
    {
        return (String) session.getAttribute("userName");
    }
    else 
    {
        return "";
    }
}

Get the current session in the same way as described for the setter method. The getAttribute method returns the value of the object which is bound with this session with the specific name. Then simply cast it with your desired type.

Thats all. Just call the services according to your requirement. Play with GWT and stay in touched. :-D

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers