Saturday, 26 October 2013

Struts 1.3 with COBOL Stored Procedure Implementation with searching, Pagination, Export to Excel and Multilingual



Struts 1.3 with COBOL Stored Procedure Implementation with searching, Pagination, Export to Excel and Multilingual


Hi  Reader,

   I am continuing from my previous blog. In this blog we will be discussed about searching,export to excel,pagination and multilingual.

Searching :

   Here we will use struts logic:iterate tag in the JSP page for searching. Mainly we will discuss <logic:equal>,<logic:greaterThan> and <logic:greaterEqual>.

We are using the same searchReasonCodesForm from the previous blog.

<logic:equal  name="searchReasonCodesForm" property="defectslno"  value="511">
    displaying sl no 511.data.
</logic:equal>

<logic:greaterThan name="searchReasonCodesForm" property="defectslno" value="511">
      displaying data greater than sl no 511.
</logic:greaterThan>

<logic:greaterEqual name="searchReasonCodesForm" property="defectsslno"  value="511">
     displaying data greater than equal to sl no 511.
</logic:greaterEqual>

Export to Excel :

  We are using the same <logic:iterate> tag to display data in the JSP page. We are using same form(searchReasonCodesForm) and id holds the instance of the data present in the form.

Here we are using the content type as contentType="application/vnd.ms-excel" for exporting data as excel format in the JSP page.

Export Excel JSP Page :



<%@page contentType="application/vnd.ms-excel" pageEncoding="UTF-8"%>

<%@taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html>
<head>
<title>User Details</title>
</head>
<body>
<table cellpadding="3" cellspacing="3" border="1">
    <tr>
        <th>
        DefectSLNo
        </th>
        <th>
                Description
        </th>
    </tr>
    <logic:iterate id="data" name="searchReasonCodesForm" scope="session">
        <tr>
            <td>
            <bean:write name="data" property="defectslno" />
            </td>
            <td>
            <bean:write name="data" property="description" />
            </td>
        </tr>
    </logic:iterate>
</table>
</body>
</html>

Multilingual :

 Multilingual is used for displaying content specific to the local based on their language and formatting.

We can do multilingual in two ways by setting org.apache.struts.action.LOCAL  to the corresponding language and other way by setting the language preference in the browser.

Resource Bundle is the file that contains the key/value pairs for the default language. The naming format of the Application Resource file is of type

                     bundlename_language_country_variant.properties

We need to link the resource Bundle with the Application using <message-resources> tag in the struts-config configuration file.

                          <message-resources    parameter="com/satya/ApplicationResource"/>

Here we are going to create four Application Resource properties file.

   1.  ApplicationResource_en_US_WIN.properties.

   2.  ApplicationResource_en_FR_WIN.properties.

   3.  ApplicationResource_en_GR_WIN.properties.

   4.  ApplicationResource_en_IT_WIN.properties.

We need to put all the ApplicationResource.properties file in the struts.config.xml file.

        <message-resources parameter="com/satya/ApplicationResource_en_US_WIN.properties"/>
        <message-resources parameter="com/satya/ApplicationResource_en_FR_WIN.properties"/>
        <message-resources parameter="com/satya/ApplicationResource_en_GR_WIN.properties"/>
        <message-resources parameter="com/satya/ApplicationResource_en_IT_WIN.properties"/>

Application Resource Properties

1. ApplicationResource_en_US_WIN.properties.

                   label.welcome = Welcome.

2. ApplicationResource_en_FR_WIN.properties.

                   label.welcome = J'aime Struts

3. ApplicationResource_en_GR_WIN.properties.

                    label.welcome = Ich liebe Struts

4. ApplicationResource_en_IT_WIN.properties.

                    label.welcome = ti amo Struts

We need to use the Dispatch  Action depending upon the language selected by the user the corresponding method in the LocalAction is called.

LocalAction :


public class LocaleAction extends DispatchAction {
 
    private final static String SUCCESS = "success";
 
    public ActionForward english(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        HttpSession session = request.getSession();
        session.setAttribute("org.apache.struts.action.LOCALE", Locale.ENGLISH);
        return mapping.findForward(SUCCESS);
    }
 
    public ActionForward french(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        HttpSession session = request.getSession();
        session.setAttribute("org.apache.struts.action.LOCALE", Locale.FRENCH);
        return mapping.findForward(SUCCESS);
    }
 
    public ActionForward german(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        HttpSession session = request.getSession();
        session.setAttribute("org.apache.struts.action.LOCALE", Locale.GERMAN);
        return mapping.findForward(SUCCESS);
    }
 
    public ActionForward italian(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        HttpSession session = request.getSession();
        session.setAttribute("org.apache.struts.action.LOCALE", Locale.ITALIAN);
        return mapping.findForward(SUCCESS);
    }
}

Based on the value set in the org.apache.struts.action.Local  variable the corresponding Application Resource properties file will be used to display the appropriate data.

             


I will continue pagination in my next blog..........
   

   

Struts 1.3 with COBOL Stored Procedure Implementation with searching, Pagination, Export to Excel and Multilingual

     Struts 1.3 with COBOL Stored Procedure Implementation  


Struts 1.3 is the MVC framework to reduce the work of the developers to develop the web application.


ActionForm : Forms in Struts 1 framework are the java bean classes that extends ActionForm class.

Model : Model classes holds the state of the internal and external system.

View : Views are web components that are shown to the web browser users. In Struts 1, it can be jsp page or any view render technique such as Tiles.

Controller : Controllers are the components that handles are the requests that comes from users and decides which view is to send back to the use as response. In Struts 1 the controller part is handled by ActionServlet class and a subclass of Action class that is developer defined. The controller may interact with the application specific business logic or some code that persists data in database or with an EJB.

Flow of Struts 1.2 


1. When first time user request comes from the browser, ActionServlet invoked which reads struts-config.xml configuration file and creates configuration objects. struts-config.xml contains information about the FormBeans, that are subclasses of ActionForm, Actions and view that can be send as response to the browser.
2. In the second step ActionServlet instantiate the specified form bean and puts the value of the form attributes, submitted by the browser, to form bean.
3. Then ActionServlet calls the Action class’s execute method, which returns ActionForward instance. ActionForward instance contains the detail of the view to be return as response.
4. ActionServlet renders the view and return to the browser as response.

Flow of Struts 1.3
1. When first time user request comes from the browser, ActionServlet invoked which reads struts-config.xml configuration file and creates configuration objects. struts-config.xml contains information about the FormBeans, that are subclasses of ActionForm.
2. In the second step ActionServlet instantiate the specified form bean and puts the value of the form attributes, submitted by the browser, to form bean.
3. Then FormBean calls the Delegate class and delegate class call’s DAO class which return as response.
4. ActionServlet renders the view and return to the browser as response.
We will perform following changes to the application to make it work with LookupDispatchAction.
Our action class  will extend LoopupDispatchAction instead of DispatchAction.
Add a application properties file that will contain the detail of the method to be executed when a particular value will come from the request parameter which is defined in attribute parameter in action tag.
Some basic changes to jsp for making the ui more perfect.
       
Stored Procedure

A stored procedure is a subroutine available to the applications that access relational database systems. Stored procedure used for data validation and access mechanism.
Stored procedure mainly used for centralize the logic that is originally implemented in applications.

Extensive and complex processing that requires execution of several sql statements is moved into stored procedure and all the application will call the stored procedure.

Procedure Wrapper :

Wrapper class is used to execute stored procedure  doesn't have exactly one out parameter.
The default number of output parameters is one.

The database connection is acquired using ConnectionFactory. Default connection factory is used for connecting to the database.

public class ProceedureWrapper{
     
 private static ConnectionFactory defaultConnectionFactory = new  SRSConnectionFactory(); private ConnectionFactory connectionFactory=defaultConnectionFactory;

private String name;
private ProceedureCommand command;
private int outputParameterCount=1;    

// For one portion key

public ProceedureResult execute(Caller sourceUser, String key, String inParameter,List errorsList, ResultSetConsumer resultSetConsumer) throws Exception{

      return execute(sourceUser,true,key,inParameter,errorsList,resultSetConsumer); 
  } 

// Not contain any one portion key

public ProceedureResult execute(Caller sourceUser, String inParameter,List errorsList, ResultSetConsumer resultSetConsumer) throws Exception{

      return execute(sourceUser,false,null,inParameter,errorsList,resultSetConsumer); 
  } 
       
}

FormBean :

   Formbean class will contain the getter and setter code for input data. Formbean is used to call the handler class. We need to instantiate handler class in the Formbean class.

public class SearchReasonCodesForm  extends SRSForm{

     public static final String CLASS_NAME=SearchReasonCodesForm.class.getName();  
     
      SearchReasonCodesHandler handler=new  SearchReasonCodesHandler(); 

      public void populateSearchReasonCodes(){

                 handler.populateSearchReasonCodes();
           }

Action Class :

     Action class is used for the navigation of the request. Action class will not contain any business logic. We will use addNavigationMethods for navigation in the action class.

  public class SearchReasonCodesAction extends Action{

     protected void addNavigationMethods(){
       }

Inquiry Object :

  All the input data is used to capture in the getter and setter methods of the inquiry object.

   public class inquiry implements Serializable{

         }

PartsConstant :

  We need to create constant value class for the field parameters. These parameters are passed to the COBOL store procedure as input parameter in the DAO class.

public class PartsConstant{

       private PartsConstant(){}
       public static final String PLANT_CODE="plantCode";
    }

PartsFieldConstant :

   We need to create field parameter class which describes the length of the field input parameters we are passing to the COBOL store procedure for processing.

The field constant will pass to the DAO class as input parameter along with the constant field.

public class PartsFieldConstant{

              public static final int PLANT_CODE_LENGTH=5;     

         }

          
PartsBO :

   Business object class will call the DAO class.

public class PartsBO{

    public List populateSearchReasonCodes(){

                 PartsDAO.populateSearchReasonCodes();
           }
  }

PartsDAO :

   PartsDAO class will invoke the store procedure using inquiry,parts constant and partsfields constant.

 We are populating errors from the COBOL store procedure  using the ArrayList.

public class PartsDAO{

          public List<PartsBO> populateSearchReasonCodes(){

                 final String METHOD_NAME="populateSerachReasonCodes";
                 List<PartsBO> parts=null;
                 ProceedureWrapper wrapper=new ProceedureWrapper(PROCEEDURE_NAME,                          ProceedureCommand.Inquiry);
                 ProceedureResult result=wrapper.execute(inqury.getCaller(),ALL_PARTS.getString(inquiry), new ArrayList(),  new GenericResultSetConsumer(new PartRecordFactory()));

                 parts=result.getResults();
                 return parts;
                 
           

Struts-Config.xml

   We need to configure the form bean class in the struts configuration file.

   <form-bean name="searchReasonCodesForm"  type="com.satya.form.searchReasonCodesForm"/>

JSP Page :

  We can populate data in the JSP page using struts logic tag.

<logic:iterate id="result" name="searchReasonCodesForm" scope="session">
     <tr>
          <td>
                    <bean:write name="result" property="description"/>
             </td>
       </tr>
</logic:iterate>


    

    

   

   


Friday, 4 October 2013

Axis2 WebService Client using Struts2 and DAO with MYSQL and Glassfish

                        AXIS2 WEBSERVICE CLIENT USING STRUTS2 AND DAO WITH MYSQL

Hi  Reader,

      Now, lets discuss about Axis2 Webservice Client Withs Struts2 and MySql and Glassfish from my previous blog.

Step 4 :

    We need to start the MySql server.

     URL - jdbc:mysql://localhost:3306/satya
     UserName - root
     Password - root

   From Glassfish server Resource to JDBC and JDBC Connection Pools. Create a new JDBC Resource and provide JNDI Name as jdbc/mysql.

  We need to provide datasource classname as com.mysql.jdbc.jdbc2.optional.MysqlDataSource. in order to communicate with MySQL database.    

Step 5 :
        BaseDAO is used to get the connection from the datasource object, closing statement and resultset object. We  need to set the dataSource object in BaseDAO class.

BaseDAO :

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;

public class BaseDAO {
 private static final String CLASSNAME = BaseDao.class.getName();
 private DataSource datasource;

 public void setDataSource(DataSource dataSource){

                 this.dataSource=dataSource;
               }

 public static Connection getConnection() {
  Connection connection = null;
  try {
  
   connection = dataSource.getConnection();
  } catch (SQLException e) {
   System.out.println("Error getting connection. Data Source = "
     + e.toString());
  }
  return connection;
 }

 public static void closeConnection(Connection connection) {
  if (connection != null) {
   try {
         connection.close();
   } catch (Exception e) {
    System.out.println("Error closeDbConnection = " + e.toString());
   }
  }
 }

 public static void closeStatement(Statement stmt) {
  if (stmt != null) {
   try {
        stmt.close();
   } catch (Exception e) {

   }
  }
 }

 public static void closeResultSet(ResultSet rs) {
  if (rs != null) {
   try {
         rs.close();
   } catch (Exception e) {
    System.out.println("Error closeResultSet. " + e.toString());
   }
  }
 }

}

  
Step 6 :

      For database access we need to implement our own DAO class by extending BaseDAO.
We need to use DataSouce in BaseDAO for getting the connection  object.

AllPoliceDAO :

   public class AllPoliceDAO extends BaseDAO{

                     public final String CLASS_NAME=AllPoliceDAO.class.getName();
                     Connection connection=null;
                     PreparedStatement preparedStatement=null;
                     ResultSet  resultSet=null;
                   
                      public PoliceBean dbconn(AllPoliceBean bean) throws DBException{
   
                                                       connection = getConnection();
                                                       String query="select * from ipp_Date";
                                                        preparedStatement = connection.prepareStatement(query);
                                                        resultSet = preparedStatement(query);
                                                        while(resultSet.next()){
                                                                  validdate = resultSet.getString("ipp_date");
                                                               }catch(Exception e){
                                                                                           e.toString();
                                                                             }finally{
                                                                                connection.close();
                                                                                preparedStatement.close();
                                                                                resultSet.close();
                                                                              }
                                         LoggerMSG.info(CLASSNAME + " " + METHOD_NAME + " : " + "Ends");
                                                         return bean;
                                           }


Step 7 :

     We need to create the bean class using struts2 by extending the BaseModel bean. Bean class will contain all the user input information.

PoliceBean :

      public class PoliceBean extends BaseModelBean{

                               String policeName;
                               int policeNumber;

                         // getter and setter methods.
               }

 Step 8 :

      Action class is used to call the Delegate class to get the response object. Finally Action class send the response to the JSP page.

Creating Action class using Struts 2 extending BaseAction and implementing ModelDriven. 

PoliceAction : 

        package com.satya;         public class PoliceAction extends BaseAction implements ModelDriven<policebean>
                     {
                            PoliceBean pe = new PoliceBean();
                            public policebean getModel(){

                                             return pe ;
                                        }
                           public String getPoliceInfo(pb){
                                             
                                              return page;
                                           }
                                          
Step 9 :

     We need to create struts2 Action to redirect the request to the PoliceAction class. We are implementing the wildcard method selection technique to enable the struts2 framework to dynamically select the correct method to call at runtime we need to use wildcard character "*" in your name value and an attribute value place holder {1} for the method value.

ipp.xml

      <action name="police"  method="{1}"  class="com.satya.PoliceAction">
      <result name="homepage"  type="tiles">homepage</result>
      </action>

Step 9 :

    Create the tile definition to forward to the JSP page. We need to create base tile definition layout and extends the layout definition  in all forward call to JSP page.

ipp.tiles.xml

   <tiles-definitions>
        <definitions name="layout" templet="/jsp/layout/logout.jsp">
         <put-attribute name="header"   value="/jsp/layout/header.jsp"/>
         <put-attribute name="footer"     value="/jsp/layout/footer.jsp"/>
    </tiles-definitions>
    <definition name="homepage" extends="layout">
    <put-attribute name="body"  value="/jsp/ipp/Multiple.jsp"/>
    </definition>
    
Finally we will display the result in the JSP page using tiles in struts2.


        
        

Spring 3 Rest Web Service Batch Update with JQuery & Ajax Integration

                      Spring 3  Rest Web Service Batch Update with JQuery & Ajax Integration Hi     In this blog I will describe the...