Tuesday, November 24, 2009

Modular application development using Struts - SwitchAction

Action classes are the important part of the Struts framework. Action classes are where your presentation logic resides. Struts 1.1 (and higher) provides some types of Action out-of-the-box, so you don't have to build them from the scratch. The Actions provided by Struts are ForwardAction, IncludeAction, DispatchAction, LookupDispatchAction and SwitchAction. All these classes are defined in org.apache.struts.actions package. These built-in actions are very helpful to address some problems faced in day to day programming. Understanding them is the key to using them effectively. All of these the Actions are frequently used, except for IncludeAction.

The SwitchAction class allows you to configure multiple application modules. In Struts1.0 (and earlier), a single config file was supported. This file, normally called struts-config.xml, was specified in web.xml as an initialization parameter for the ActionServlet as follows:
<servlet>

    <servlet-name>mybank</servlet-name>  
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

    <init-param>  
        <param-name>config</param-name>

        <param-value>/WEB-INF/struts-config.xml</param-value>  
    </init-param>

</servlet>


The single configuration file is bottleneck in large projects as all developers had to contend to modify this resource. In addition managing a monolithic file is painful and error prone. With Struts1.1 (and higher) this problem has been resolved by the addition of multiple sub application support better known as application modules. You can now have multiple configuration files, one for each module or logical group of forms. The configuration files are specified in web.xml file using multiple <init-param> - initialization parameters.

An example of the how to do this in a web.xml file is as below:




<servlet> 
    <servlet-name>action</servlet-name>

    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>  
    <init-param>

      <param-name>config</param-name>  
      <param-value>/WEB-INF/struts-config.xml</param-value>

    </init-param>  
    <init-param>

      <param-name>config/views/module1</param-name>  
      <param-value>/WEB-INF/struts-config-module1.xml</param-value>

    </init-param>  
    <init-param>

      <param-name>debug</param-name>  
      <param-value>3</param-value>

    </init-param>  
    <init-param>

      <param-name>detail</param-name>  
      <param-value>3</param-value>

    </init-param>

    <load-on-startup>1</load-on-startup>  
</servlet>
<servlet-mapping>  
    <servlet-name>action</servlet-name>

    <url-pattern>*.action</url-pattern>  
</servlet-mapping>

The above web.xml defines the servlet mapping for the action servlet to all URL patterns that ends with ‘.action’, and /WEB-INF/struts-config.xml to be the struts configuration file. You might be wondering what does the below configuration do:




<init-param> 

      <param-name>config/views/Module1</param-name>  
      <param-value>/WEB-INF/struts-config-module1.xml</param-value>  
</init-param>

The above initialization parameter name begins with ‘config/’. ‘config/’ is treated as a keyword for defining a new module. It is interpreted as a configuration for a separate module. Its corresponding value – /WEB-INF/struts-config-module1.xml is the struts configuration file containing Form bean definitions and ActionMappings for the module module1. If the URLs in the default struts-config.xml were accessed as http://localhost:8080/App1/start.action, and the corresponding ActionMapping were moved to struts-module1-config.xml then the URL would be accessed as http://localhost:8080/App1/module1/start.action where App1 is the web application context. Notice that the application URL contains the module name after the web application context as if it is a sub directory name.

The benefits of application modules are immediately obvious. You can now split your monolithic struts application into logical modules thus making maintenance easier. It will cause less contention during development time as developers working on different modules get to work on their own struts configuration files. Each Struts Configuration file and hence each application module can choose its own RequestProcessor, MessageResources and PlugIn. You can now choose to implement one or more modules with Tiles. If you find this convenient and useful then you can migrate your application to Tiles or JSF or plug in any other Struts extensions for one module at a time.

Now, lets look like how the struts-config.xml and struts-config-module1.xml files look like. Below is an extract from the struts-config.xml file:




<struts-config>

    <global-forwards>  

        <forward name="Module1" 

            path="/switch.action? page=/CreateCertificate.action&amp;prefix=/views/module1" /> 

    </global-forwards>

    <action-mappings>

        <action path="/switch"  
            type="org.apache.struts.actions.SwitchAction" />

    </action-mappings>    
    <controller processorClass="org.apache.struts.action.RequestProcessor" /> 
</struts-config>


struts-config-module1.xml file:



<struts-config>  
    <form-beans>

        <form-bean name="Form1"  
                    type="com.example.Form1"/>

        <form-bean name="Form2"

                    type="com.example.Form2"/>  
    </form-beans>


    <global-forwards>

        <forward name="mainpage" path="/"/>  
    </global-forwards>

    <action-mappings>

         <action path="/switch"

                type="org.apache.struts.actions.SwitchAction" />

         <action path="/start"  
                type="com.example.Module1Start"

                name="Form2"  
                scope="request"

                validate="true"  
                input="/input.jsp">

            <forward name="success" path="/switch.action?page=/success.jsp&amp;prefix=/views/module1"></forward>

            <forward name="failure" path="/switch.action?page=/error.jsp&amp;prefix=/views/module1"></forward>

        </action>

You might have noticed that




<action path="/switch"  
                type="org.apache.struts.actions.SwitchAction" /> 

has been defined in both the configuration files. This is important for the code to work properly.


Note: Source of most of the content- Struts Survival Guide, Author: Srikanth Shenoy.

Monday, November 23, 2009

Fixing your Windows Vista Sidebar

Since last two weeks the vista sidebar wasn't loading on my computer. Searching for a solution on google wasn't easy. However, I found a solution today so I thought to save it in my blog.

The problem was resolved after following these steps:

Click Start, All Programs, Accessories, right-click Command Prompt and select "Run as administrator".

Type these commands one by one:
Regsvr32 atl.dll
Regsvr32 "%ProgramFiles%\Windows Sidebar\sbdrop.dll"
Regsvr32 "%ProgramFiles%\Windows Sidebar\wlsrvc.dll"

Tuesday, November 3, 2009

Ubuntu - How to change the Display Manager

A Display Manager provides a graphical login screen. Ubuntu comes with default GUI - Gnome and 'gdm' as Display Manager. You may also choose to install K.D.E on Ubuntu to get an option to login into one out of two different GUI's. K.D.E comes with 'kdm' as the display manager. When you install K.D.E you are asked if you want to change the display manager to 'kdm'. If later you want to switch to the other available display manager then you can do so by using the following command in a terminal window:

$ sudo dpkg-reconfigure gdm

Monday, October 19, 2009

JDBC Connectivity

The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL statements to almost any relational database. JDBC is a Java API for executing SQL statements and supports basic SQL functionality. It provides RDBMS access by allowing you to embed SQL inside Java code. Because Java can run on a thin client, applets embedded in Web pages can contain downloadable JDBC code to enable remote database access.

Although JDBC was designed specifically to provide a Java interface to relational databases, you may find that you need to write Java code to access non-relational databases as well.
JDBC Architecture

Java application calls the JDBC library. JDBC loads a driver which talks to the database. We can change database engines without changing database code.

JDBC Basics - Java Database Connectivity Steps


Before you can create a java jdbc connection to the database, you must first import the

java.sql package.

import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are to be imported.

Below is a list of classes and interfaces that are commonly used for writing JDBC code:

java.sql.Connection
java.sql.PreparedStatement
java.sql.ResultSet
java.sql.SQLException
java.sql.DriverManager
javax.sql.DataSource

Following are the classes / interfaces that will be used for doing a lookup for the DataSource in the servers context (JNDI Lookup).

javax.naming.Context
javax.naming.InitialContext
javax.naming.NamingException

Using Java there are two ways for connecting to a database. Either the DataManager class can be used or JNDI lookup can be done. JNDI lookup is mostly used in web based applications. Let us first look at how DataManager class can be used to connect to the database.



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

public class TestDBConnectivity
{
public static void main(String argv[])
{
Connection con = null;
Statement stmt = null;
ResultSet rs = null;

String url = "jdbc:oracle:thin:@server:1521:TESTDB"
String sql = "Select count(*) as total from Books";
int totalBooks=0;

try
{
Class.forName("oracle.jdbc.driver.OracleDriver"); //load the driver
con = DriverManager.getConnection(url, "dbuser", "dbpasswd");
stmt = con.CreateStatement();
rs = stmt.executeQuery(sql);

if(rs.next())
totalBooks = rs.getInt("total");

System.out.println("Total number of books : " + total);
}
catch(ClassNotFoundException ex)
{System.out.println("ClassNotFoundException:\n"+ex);}
catch(SQLException ex)
{System.out.println("SQLException:\n"+ex);}
finally
{
try
{
stmt.close();
rs.close();
con.close();
}
catch(SQLException ex)
{System.out.println("SQLException:\n"+ex);}
}
}
}







Now, let us look at how JNDI lookup works. For a small tutorial on JNDI please visit here.










For using a JNDI lookup first a resource has to be defined which can be done in the '\META-INF\context.xml' file. A sample of the 'context.xml' file is shown below:










import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DAGConnection
{
private DAGConnection(){}

public static java.sql.Connection getConnection()
{
Connection con=null;
Context ctx=null;
DataSource ds=null;
try
{
ctx = new InitialContext();
if(ctx == null)
{
System.out.println("Lookup failed!");
throw new RuntimeException("JNDI resource can not be found!");
}

ds = (DataSource) ctx.lookup("java:comp/env/jdbc/DBTEST");
if(ds==null)
{
System.out.println("DataSource could not be found!");
throw new RuntimeException("DataSource could not be found!");
}

con = ds.getConnection();
}
catch(NamingException ex)
{
System.out.println(ex);
return null;
}
catch(SQLException ex)
{
System.out.println(ex);
return null;
}

return con;
}
}





In the above example, the method getConnection() does a JNDI lookup and returns an object of type java.sql.Connection. Doing  JNDI lookup returns an object of type DataSource which in turn is used to create a connection to the database. You will need to place the JDBC drivers for the database in the classpath while using DriverManager and in the '\WEB-INF\lib' folder while doing a JNDI lookup.

Thursday, October 15, 2009

Aligning text in a HTML textbox

There is often a need to align text in a HTML textbox especially when the text to be entered are always numbers. In case of numbers the preferable alignment is ‘right’.

The ‘text-align’ property can be used to align text in a textbox or in fact in any element which supports the ‘style’ property.

An example to right align a text in a HTML textbox is as below:

The 'text-align' property describes how inline content of a block is aligned. Values have the following meanings:


left, right, center, justify, inherit


The 'inherit' value


Each property may also have a specified value of 'inherit', which means that, for a given element, the property takes the same computed value as the property for the element's parent. The 'inherit' value can be used to strengthen inherited values, and it can also be used on properties that are not normally inherited.


If the 'inherit' value is set on the root element, the property is assigned its initial value.


In the example below, the 'color' and 'background' properties are set on the BODY element. On all other elements, the 'color' value will be inherited and the background will be transparent. If these rules are part of the user's style sheet, black text on a white background will be enforced throughout the document.

body {
color: black !important; 
background: white !important;
}

* { 
color: inherit !important; 
background: transparent !important;
}