Wednesday, January 22, 2014

J2EE Web Service Example implementing DAO and DTO design patterns

In this post I will explain a complete example implementing JAX-WS that utilizing J2EE design patterns, specifically, DAO and DTO design patterns.

In the previous posts I have talked in detail about DAO and DTO design patterns, I recommend you to read these posts firsts; J2EE DAOexample, and J2EE DTO Example, and If you have any question just drop me a question in the contact form or post a comment under the desired topic.

Example Description
The following example is a simple Web Application that exposes JAX-WS to the outside world. The application is implemented using JAX-WS and using Eclipse IDE.
The web service simply accepts a request from the client to inquire about the existed employees under a specific department. Oracle database and HR schema are used as our backend; that our web service needs to access to execute user request.

Designing the Application
Our application is a web application that exposes a web service to clients; the client can call this web service to inquire about the details of the employees under a given department.

The web service contains one single method; getEmployeeInfo() method. This method accepts the user data and executes these data against HR database; specifically, Departments and Employees table.
In our application we are using two famous design patterns; DAO and DTO. We need to create GetEmployeeInfoDAO class that represents the Data Access Object, to access the database.

To enable user from passing and receiving data to the method with a single method call, we need to implement Data Transfer Object, so we have created to classes, one for request GetEmployeeInfoRequestDTO and one for response, GetEmployeeInfoResponseDTO.

Class GetEmployeeInfoRequestDTO contains the fields that the customer has to pass to the web service, and GetEmployeeInfoReponse contains the required response fields.

 Building the application
Now, we are going to build the application, follow the following steps.
1.       Open Eclipse IDE and choose File Menu item > New > Other.


2.       From the wizard screen choose web category > Dynamic Web Application, click Next.


3.       Enter the name of you project; EmployeesDetailsWS and check the box of Add this project to EmployeesDetailsEAR to create an ear file to contains your project. Accept the defaults and click Finish.


4.       Now, your projects will be shown in the Project Explorer on the left panel of the eclipse IDE, expand EmployeesDetailsWS project > Java Resources > src folder, create the following packages as shown in the following figure.

Note that it is a best practice to organize your files under packages with meaningful names; from the following figure, you can notice that we have a package for DAO, DTO, and WS. Under DAO package we will create GetEmployeeInfoDAO class that will implement the business of accessing the database.
Under DTO package, we placed all the data transfer object classes, note that from the following figure that we have created two classes for our web service; one for request, and the other for response.
The final package is the Web Service package; it contains our web service class that have special icon, to mark this class as a web service.


5.       To create the classes, write click on the package name > Class. Then provide the name for your class as shown in the above figure.

EmployeeInfoDAO Class
The first thing you need to do is to create the data access object class that will encapsulate the database connection details, and will prevent users from directly hitting the database.
Following is the full implementation of the DAO class.

package zabin.com.jee.examples.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import zabin.com.jee.examples.dto.GetEmployeeInfoResponseDTO;

public class GetEmployeeInfoDAO {
       
        public Vector<GetEmployeeInfoResponseDTO> getEmployeeInfo( String empID ) throws Exception {
               
        Vector<GetEmployeeInfoResponseDTO>  employeesVect = new Vector<GetEmployeeInfoResponseDTO>();
               
        ResultSet rs = null;
        Connection connection = null;
        PreparedStatement pStmt = null;
               
        try {
                       
             /** Get the data source which is used as a bridge to your database */
                Context ctx = new InitialContext();
                       
                /** The following datasource must be defined in your server */
                DataSource ds = (DataSource)ctx.lookup("HR_DATASOURCE");
                connection = ds.getConnection();
                       
                       
                /** Now, create your sql to get the required data from database */
                String sqlStr = "SELECT * FROM employees emp, departments dept"
                        + " WHERE emp.department_id = dept.department_id AND dept.department_id = ?";
                       
        /** Create a prepared statement object that will be evaluated each time you pass new parameter */
                pStmt = connection.prepareStatement( sqlStr );
                pStmt.setInt( 1,Integer.parseInt(empID) );
                       
        /** Execute the query */
                rs = pStmt.executeQuery();
                       
        /** Loop through the record set and fill each record inside a new instance of OUTDTO object */
                while( rs.next() ) {
                   GetEmployeeInfoResponseDTO response = new GetEmployeeInfoResponseDTO();
                               
                   response.setFirstName( rs.getString("FIRST_NAME") );
                   response.setLastName( rs.getString("LAST_NAME") );
                   response.setEmail( rs.getString("EMAIL") );
                   response.setPhoneNumber( rs.getString("PHONE_NUMBER") );
                   response.setDepartmentName( rs.getString("DEPARTMENT_NAME") );
                               
                   /** add employee instance into vector list */
                   employeesVect.add(response);
                }
                } catch( SQLException sqle ) {
                        sqle.printStackTrace();
                        /** Mark your resources for garabage collection,
                         * by calling connection.close() method, which
                         * will mark your resource for garbage collection.
                         */
                } finally{
                        /** call close() method to close the resource */
                        if( rs != null ) {
                                rs.close();
                        }                      
                        //pStmt.close();
                        connection.close();
                }
               
                /** This will be your final results */
                return employeesVect;
        }

}


EmployeeInfoWebService Class
This is the web service class that will be interpreted by the server to generate a WSDL file to make our web service available for consuming.
Note that the Web Service class is a normal java class, but it is annotated class. To mark a class as web service class, we need to add some annotations to tell the compiler that this class is a web service.



EmployeeInfoRequestDTO Class
This class encapsulates the values or data that client needs to pass, we read clients values and populate the required fields in the RequestDTO class. Note that in this class we have only one value for the purpose of simpleiciy, the user pass the department ID to get the employees under this department.

package zabin.com.jee.examples.dto;

public class GetEmployeeInfoRequestDTO {
        private String departementID;

        public String getEmployeeID() {
                return departementID;
        }

        public void setEmployeeID(String employeeID) {
                this.departementID = employeeID;
        }
}


EmployeeInfoResponseDTO Class
This class encapsulates the values or data that the system will respond with to the client. The dao class will open a connection to the database, execute a specific query against the database, then we ill populate an instance of the response DTO class. Note that this class contains five fields as shown below, these fields will be read from database, as shown in DAO class.

package zabin.com.jee.examples.dto;

public class GetEmployeeInfoResponseDTO {

        private String firstName;
        private String lastName;
        private String email;
        private String phoneNumber;
        private String departmentName;
       
        public String getFirstName() {
                return firstName;
        }
        public void setFirstName(String firstName) {
                this.firstName = firstName;
        }
        public String getLastName() {
                return lastName;
        }
        public void setLastName(String lastName) {
                this.lastName = lastName;
        }
        public String getEmail() {
                return email;
        }
        public void setEmail(String email) {
                this.email = email;
        }
        public String getPhoneNumber() {
                return phoneNumber;
        }
        public void setPhoneNumber(String phoneNumber) {
                this.phoneNumber = phoneNumber;
        }
        public String getDepartmentName() {
                return departmentName;
        }
        public void setDepartmentName(String departmentName) {
                this.departmentName = departmentName;
        }
}


Running the application
1.       After finishing creating the above classes save your work, then right-click on EmployeeDetailsWS and choose build project.
2.       Then right-click on server and choose publish, to publish your application to deploy it on the server.




3.       Go to the application server console, in the left panel, in the first box, choose deployments. Note that you have deployed the EmployeeDetailsEAR file which contains EmployeeDetailsWS application.


6.       To access the WSDL file of the web service, from the previous figure, choose EmployeesDetailsEAR file from Deployments box, and expand the plus box like following, then click on EmployeeDetailsWebService as shown below.



7.       Choose Testing tab, and click on ?WSDL to open the wsdl of your Web Service.

   


8.       Your WSDL will be shown on your default browser as following.