Aug 2, 2013

Making AJAX Call in Struts 2

This may be very obvious thing but still this may help newbies in struts 2 and equally applicable for Struts 1.

So lets take a simple example. We will select a country and AJAX call will get following details in a tabular form from DB and populate it on our screen. Simple isn't it?

So first lets create our html file that will have a drop down for countries (this too can be made AJAX filled drop down but lets keep it for self learning)

Once this html is ready lets add an entry in our configuration file for Action to be called from our js function.

Now we will create one JSP which will return response text to our html file which initially sent the AJAX request.

Now we will create one Action class and for the sack of brevity we will just return the flow to jsp created in last step and see what happens.

If you are able to understand the complete flow from this can skip remaining part else go ahead :).

So here is what happened.
  • HTML file requested for AJAX request XMLHttpRequest
  • XMLHttpRequest was made to .action url and App server realizes that this will be handled by Something called Filter dispatcher of Struts2 and sends it to dispatcher class.
  • Dispatcher class identifies which action class is mapped with this action and passes request to it.
  • Action class simply routes the flow to JSP file which will create response for this requests and returns it to Strut 2 dispatcher class via different interceptors.
  • Dispatcher returns this response to XMLHttpRequest in browser and there it (response in terms of text) is returned to javascript which made this call.
  • Javascript gets this text and flushes in to particular html object and since your browser understands this html text it displays you nice tabular format.
So lets move ahead and create our Service classes and DAO class which will actually return us some data to be displayed on screen.

Jul 23, 2013

Must have Open Source Projects for JEE Developer

Being a java developer I always look to something to setup on  my local machine that can help me in developing my applications as quickly as possible. From my experience I feel Following is the set of tools/software that all java developers should always have on his/her machine.

Eclipse JEE IDE: Best IDE for any java application development. You can install n number of plugins freely available either manually or by using feature called Market Place. Can be integrated with any application/Web server.
JBoss Application Server: Open source full fledged Application Server from house of Linux. Alternate to this is much lightweight Tomcat or Tomee
MySQL Community Edition:Now owned by Oracle previously by Sun. Alternate to this is PostgreSQL
Fiddler: Http Traffic monitor and useful in debugging lots of client server communication issues.
WinMerge Compare your files/folder merge, revert etc.
Notepad++ Simple yet powerful editor.
Filezilla: Get your files from ftp server and put it back on it.

If you believe in version control then you may want to try Tortoise SVN

May be you can add more into this list and make it more useful for developer community.

Happy Coding. :)

Apr 25, 2013

Hibernate OnetoMany mapping with composite key

Consider following scenario where we need to map one entity with other where one column of composite primary key of child table is by which we are mapping it with parent entity

Table 1: Employee_Details
Emp_Id (pk/id)

Table 2: Emp_Skill_Level
Emp_Id (pk/id # 1)
Skill_Id (pk/id # 2)

Now here we have a situation where in one table/entity we will have one column and Primary Key (or this will be my id field in mapped entity). The second table/entity has two columns as primary key and in mapped entity both these fields will be used to define id.

But we want to use only one column of Emp_Skill_Level to map with Employee_Details (For now lets assume we do not have any other table which lists details about Skill and all details are present in this second table)

Apr 10, 2013

Java interview questions.

1.    What was your last project?
2.    What was your role in your last project?
3.    What was the architecture of your project?
4.    How data was flowing in your application?
5.    What version of java you were using in your project? What is the latest version of java?
6.    When we say JVM, which command exactly we talk about? Javac, java, javaw?
7.    What are new features in java 5?
8.    What is generics?
9.    What is annotation?
10.    What are new features in java 7?
11.    What will be new features in java 8?
12.    What are the basic concepts of Object Oriented Programming (OOPS)?
13.    What are different ways of creating objects? (new, clone, deserialize)
14.    What is inheritance?
15.    Does java support multiple inheritance?
16.    What is Overloading and Overriding?
17.    What is polymorphism?
18.    What is Abstraction?
19.    What is data encapsulation?
20.    What are different levels of access modifier?
21.    What is different between default and protected access modifier?
22.    What is Exception handling? What are different ways of handling Exceptions?
23.    What is interface and what is marker interface?
24.    Explain Serialization and deserialization.
25.    What is serializable and what is externalizable?
26.    Where you can use Abstract class and where you can use Interface any example?
27.    Can you write GenericInterface intrfc = new ImplClass(); where class ImplClass implements interface GenericInterface?
28.    Can we have constructor in Abstract class? Any use of it?
29.    What do you mean by “String is immutable class”?
30.    What is final, finally and finalize?
31.    What is difference between StringTockenizer, StringBuffer and StringBuilder?
32.    What is Collection API?
33.    What are different classes and interfaces used in Collection API?
34.    What is difference between List and Set?
35.    What is difference between Arraylist and Vector? When to use what?
36.    What is difference between Set and Map?
37.    What is different between HashSet and TreeSet?
38.    What is difference between HashsMap and HashTable?
39.    What is difference between HashMap and TreeMap?
40.    What is Comparable interface and what is Comparator interface?
41.    What is multithreaded environment?
42.    How to create threads?  Which method is preferred and why?
43.    What is notify and notifyall?
44.    What is synchronization?
45.    What is block level and method level synchronization? Which one is preferred?
46.    By synchronization what are you protecting? Methods or data?
47.    Explain different thread states in multithreading.
48.    If there is a static method and you want to synchronize it what will you do?
49.    What if you have four methods and you want to synchronize them in group of two?
50.    What is JDBC?
51.    What do you mean by “Loading JDBC driver”?
52.    What is difference between Statement and Prepared Statement?
53.    Prepared statement is precompiled statement then where it gets compiled? On DB side or Java side?
54.    What is ORM? Do you know any ORM framework?
55.    What are different types of driver?
56.    Where you can find code for java.sql.Connection object?
57.    What are steps in JDBC?
58.    What is connection pooling?
59.    What is callable statement?
60.    What will be sequence of closing JDBC resources?
61.    What is difference between webserver and application server?
62.    What is MVC architecture?
63.    Explain Servlet Life cycle.
64.    What are implicit objects in jsp?
65.    What are different components in web.xml?
66.    What is weblogic.xml/jboss-web.xml?
67.    How you configure security roles in web.xml?
68.    What is design pattern?
69.    Any MVC Framework you are aware of?
70.    What design pattern Struts framework uses?
71.    What is Singleton pattern?
72.    How to handle multithreading in Singleton pattern?
73.    What is Factory Pattern?
74.    What is difference between Factory Pattern and Abstract Factory Pattern?
75.    What is EJB?
76.    What are different types of EJB?
77.    What is MDB?
78.    What is JMS?
79.    What are different ways of implementing JMS? What is P2P and PubSub Communication?
80.    Any middleware you are aware of to use JMS?
81.    What are differences between Struts 1 and 2?
82.    What is request life cycle in Struts 1?
83.    What is custom tag in jsp?
84.    Explain validation framework in Struts 1.
85.    What is IoC and what is Dependency Injection?
86.    What are different types of DI we have?
87.    What is AOP?
88.    What is constructor injection and what is getter injection?
89.    What is auto wiring in Spring framework?
90.    What is Hibernate?
91.    What is Dialect in Hibernate?
92.    Why all Exceptions in Hibernate are Runtime (unchecked) Exception and not checked Exception?
93.    What is difference between get and Load methods of Hibernate?
94.    What is named query in Hibernate?
95.    What are differences between Hibernate 3 and 4?
96.    How to perform JDBC operations in Hibernate 4?
97.    Can you write your own Dialect for any DB in Hibernate?
98.    What is web service?
99.    What are different components in Webservices?
100.    When to use Webservice and when to use EJB?   

Mar 20, 2013

WWW of WordPress

Recently I heard a lot of buzz about a something called WordPress. Being a devoted java developer initially I rejected this framework for any “Serious” application development. But over the period of time as I got a chance to have a closer look at this framework slowly I started having a soft corner for this framework (ok this can’t be compared to my more than 8 years love for gorgeous Java). So let’s see what this new next door cutie is all about? What it’s good at? And when should we consider it?
What is WordPress?
WordPress is a most widely used open source CMS (Content Management System) based on PHP and MySQL. It is also the most widely used blogging system. Its content is stored in form of Blogs and pages. You can divide your blogs in different categories and group similar articles together.
It comes with an army of hooks that can be customized based on your requirement, starting from something called themes which can customize look and feel of site developed in this framework or say plugins which gives it an added strength of performing operations which are not available in framework by default. It also has widgets that can be added or removed on sidebars and performs certain action on its own.
It also has a nice GUI for admin screen where you can decide what theme you want to use or what plugins you want to activate or deactivate (being open source it is blessed by developers all over the world and has sizable number of freely available themes and plugins. Long live Open Source Architecture).
Why WordPress
It’s Free, It’s flexible and it can provide you most of the things you want on your website on few mouse clicks. So you can download WordPress extract is on your system. Select what theme or plugins you want on your site and start creating content for your site. You are good to go live.
When WordPress
In a nutshell this framework is pretty handy when you are developing a site where you do not have too many transactional operations and your main purpose is to display some information (or say content) to site visitor. For an example if you want to developer a site for news content, a site for some yummy recipes, a florist shop, a cake shop (for payment options you may have to buy some plugin that takes care of your transactions but rest WordPress will take care of). Also if you have to many logical decisions to take on your site may be you need to consider developing something out of this framework. For an example if you are planning to develop a site to keep track of user’s stocks this is not your perfect match (this doesn’t mean that you can’t develop in WordPress. You can…but you may not).
It’s always help to choose right technology or framework that best fits for your requirement. You can always drive a Limo (of course if you have one or you can hire one) when you go for buying your grocery but that’s not what it is meant for or you can have better and more suitable options for this purpose. So always remember it’s like “Horses for Courses”. Happy coding J

Feb 28, 2013

Loading unmanaged entities in Hibernate

Before we start let me tell you this is not a best or even say a common practice in Hibernate but this approach is used when there is a sudden addition/change in requirements and you for unavoidable reasons do not want to add a new entity or change existing entities and you want to go ahead with your DTO/VO instead of Hibernate bean classes. One of the example is you are generating some report and client wants you to add few more fields that are not mapped to this entity bean so only option you have is to change your HQL to SQL and load this data in some DTO/VO and print it.
So let’s start with it. For the sack of brevity here we will use simple SQL query but you are free to use any complicated query with this approach. We have a table with following fields
·         EMP_ID
·         EMP_FIRST_NAME
·         EMP_LAST_NAME
·         EMP_DOB
·         EMP_DOJ (Date of Joining)
·         IS_ACTIVE (If employee is still part of organization)
So we have following data in our table.

Now we want to load data from this table to our VO class EmpUnmanagedVO which looks like Table 1

Table 1: VO Class

import java.util.Date;

public class EmpUnmanagedVO {
      private String id;
      private String name;
      private String lastname;
      private Date dob;
      private Date doj;
      private boolean isActive;
      public String getId() {
            return id;
      public void setId(String id) {
   = id;
      public String getName() {
            return name;
      public void setName(String name) {
   = name;
      public String getLastname() {
            return lastname;
      public void setLastname(String lastname) {
            this.lastname = lastname;
      public Date getDob() {
            return dob;
      public void setDob(Date dob) {
            this.dob = dob;
      public Date getDoj() {
            return doj;
      public void setDoj(Date doj) {
            this.doj = doj;
      public boolean isActive() {
            return isActive;
      public void setActive(boolean isActive) {
            this.isActive = isActive;
       public String toString() {
              StringBuilder sbuild = new StringBuilder();
              sbuild.append("Id:").append(id).append(", Name:").append(name).append(", Last Name:").append(lastname);
              return sbuild.toString();            

Now we will write our method to call a simple SQL query to get details from EMP_DETAILS table and load the data in this VO.
public List<EmpUnmanagedVO> getUnmanagedEmpDetails() throws DBException {
      Session sess = null;
            sess = HibernateUtil.getSession();
            Query qry = sess.createSQLQuery("SELECT * FROM EMP_DETAILS");
            qry.setResultTransformer(new ResultTransformer() {
                  public Object transformTuple(Object[] values, String[] colnames) {
                        EmpUnmanagedVO emp = new EmpUnmanagedVO();
                        return emp;
                  public List transformList(List arg0) {
                        return arg0;
            return qry.list();
      catch(HibernateException e)
            throw new DBException("Error occured while loading unmanaged bean",e);

So when we call this method we will have following output.
Feb 28, 2013 7:22:52 AM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Feb 28, 2013 7:22:52 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.7.Final}
Feb 28, 2013 7:22:52 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: not found
Feb 28, 2013 7:22:52 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Feb 28, 2013 7:22:52 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Feb 28, 2013 7:22:52 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Feb 28, 2013 7:22:52 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Feb 28, 2013 7:22:52 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Feb 28, 2013 7:22:52 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
Feb 28, 2013 7:22:52 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
Feb 28, 2013 7:22:52 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/test]
Feb 28, 2013 7:22:52 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
Feb 28, 2013 7:22:52 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: com.hibernate.custom.dialect.CustomMySQLDialect
Feb 28, 2013 7:22:52 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Feb 28, 2013 7:22:52 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Feb 28, 2013 7:22:52 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
[Id:A001, Name:Keyur, Last Name:Joshi]

There is an option for creating a separate class for Result Transformer which will implement org.hibernate.transform.ResultTransformer interface but since this is not what we do as a generic design better we follow inline implementation of this interface. Also you can use second argument of tranformTuple function (i.e. colnames) to understand what is the index of each column.

Happy Coding J