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

Total Pageviews

Tags

Twitter Updates
    follow me on Twitter

    Followers