April 14, 2011

Auto-generate Client Code with WSDL2Java tool of Apache Axis 1.4

0) We shall create a Web Service client for the web service created in this post by auto-generating code with the WSDL2Java tool of Apache Axis 1.4

Copy the WSDL file from the URL into a text file with the extension *.wsdl and save it in a folder on your hard disk (outside the web application structure), for example, C:\my-wsdl-files

1) Repeat step 3 from the following post - http://www.javaissues.com/2011/04/deploying-wsdd-web-services-with-apache.html

2) Open the command prompt (Start > Run):

- change directory to the C:\my-wsdl-files folder (the folder which contains the saved wsdl file/s)

- issue the following command at the command prompt:
java org.apache.axis.wsdl.WSDL2Java HelloWorld.wsdl

Note: Remove the <?xml ... ?> processing instruction lines from the top of the wsdl file, if present.

3) This will generate the client code in the package: localhost.WebAppName.services.HelloWorld
Copy all the 4 classes into a Java project / application (retain the package name)

4) Create a new class - WSClientTest.java - in the same Java project / application (in which the auto-generated code was added) as follows,


package info.icontraining.wsclient;


import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import localhost.WebAppName.services.HelloWorld.*;


public class WSClientTest
{
    public static void main (String args[]) 
         throws ServiceException, RemoteException {
       
         HelloWorldService service = new HelloWorldServiceLocator(); 
         HelloWorld port = service.getHelloWorld(); 
         System.out.println(port.sayHello());
    }
}


5) Execute the WSClientTest class by running it as a standalone Java Application

Deploying WSDD Web Services with Apache Axis 1.4 - Hello World Example

1) Create a HelloWorld.java service class in the src folder of the web application. The public methods of this class will be exposed as a web service.


package info.icontraining.ws;


public class HelloWorld 

     public String sayHello() 
     { 
         return "Hello World"; 
     } 



2) Create a HelloWorld.wsdd file in a local folder (not inside the application but anywhere on your hard disk, for example, C:\my-wsdd-files) to configure the web service and register with with the Apache Axis deployment


<deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java"> 
   <service name="HelloWorld" provider="java:RPC"> 
      <parameter name="className" value="info.icontraining.ws.HelloWorld"/> 
      <parameter name="allowedMethods" value="*"/> 
   </service> 
</deployment> 


Note: Deploy the application to the Application Server at this time.

3) Register this web service by following the below steps,

a) Go to the "Run" menu in Eclipse and select the "Open Run Dialog..." option

b) In the Project, add the WebAppName; In the Main Class add: org.apache.axis.client.AdminClient

c) Click on the "Arguments" tab and in the Program Arguments, add the following:
-lhttp://localhost:8080/WebAppName/services/AdminService C:\path-to-wsdd-folder\HelloWorld.wsdd

Replace WebAppName and the path-to-wsdd-folder appropriately.

- The web service is registered if you see the output message:
<Admin>Done Processing</Admin>

Note: Re-starting of the JBoss Server will undo the registration of the web service.

4) To access the web service WSDL, invoke the following URL in the browser,
http://localhost:8080/WebAppName/services/HelloWorld?wsdl

Mapping Entity and Value types in Hibernate

Create a User Entity type persistent class and an Address Value type persistent class. Create the User.hbm.xml mapping file for the Entity type. Add the mapping for the value type in the User.hbm.xml.
Persist an object of type User.
Retrieve the same object and print a property from the Address value type.

1) Create the User.java persistent class of type entity in the src folder of the web application. The class will have a property of type Address which is a persistent class of value type.


package info.icontraining.hibernate;

public class User {
 
   private Long id;
   private String name;
   private HomeAddress address;
 
   public String getName() {
       return name;
   }
   public void setName(String name) {
       this.name = name;
   }
   public HomeAddress getAddress() {
       return address;
   }
   public void setAddress(HomeAddress address) {
       this.address = address;
   }
   public Long getId() {
       return id;
   }
   public void setId(Long id) {
       this.id = id;
   }
}

2) Create the HomeAddress.java persistent class of type value in the src folder of the web application.

package info.icontraining.hibernate;

public class HomeAddress {

   private String street;
   private String city;
   private String zipCode;
   private User user;
 
   public String getStreet() {
       return street;
   }
   public void setStreet(String street) {
       this.street = street;
   }
   public String getCity() {
       return city;
   }
   public void setCity(String city) {
       this.city = city;
   }
   public String getZipCode() {
       return zipCode;
   }
   public void setZipCode(String zipCode) {
       this.zipCode = zipCode;
   }
   public User getUser() {
       return user;
   }
   public void setUser(User user) {
       this.user = user;
   } 
}


3) Create the User.hbm.xml mapping file in the same folder/package as the User.java class - this file will contain the mapping information for the entity and the value types

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.User" table="USER_TABLE"> 
      <id name="id" column="USER_ID"> 
         <generator class="native" /> 
      </id> 
      <property name="name" column="USER_NAME" /> 
      <component name="address" class="info.icontraining.hibernate.HomeAddress">
         <parent name="user" />
         <property name="street" column="STREET" />
         <property name="city" column="CITY" />
         <property name="zipCode" column="ZIPCODE" />
      </component> 
   </class> 
</hibernate-mapping> 


4) Modify the hibernate.cfg.xml file in the WebContent/WEB-INF folder to add the User.hbm.xml as a mapping resource,

<mapping resource="info/icontraining/hibernate/User.hbm.xml" /> 


5) Create a UserServlet.java class to execute the code to save a User object.

package info.icontraining.servlets;

import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.* ; 
import org.hibernate.*; 
import info.icontraining.hibernate.*;

public class UserServlet extends HttpServlet { 
  
   public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{ 
  
      PrintWriter out = res.getWriter(); 

      Session session = HibernateUtil.getSessionFactory().openSession(); 
      Transaction tx = session.beginTransaction(); 
  
      User user = new User();
      user.setName("Dinesh");
  
      HomeAddress address = new HomeAddress();
      address.setCity("Mumbai");
      address.setStreet("Worli");
      address.setZipCode("400040");
      address.setUser(user);
      user.setAddress(address);
  
      session.save(user); 
      tx.commit(); 
      session.close(); 

      Session newSession = HibernateUtil.getSessionFactory().openSession(); 
      Transaction newTransaction = newSession.beginTransaction(); 
  
      List users = newSession.createQuery("from User as u").list(); 
      out.println( users.size() + " user/s found" ); 
  
      for ( Iterator iter = users.iterator(); iter.hasNext(); ) { 
         User user2 = iter.next(); 
         out.println( user2.getName() +": " + user2.getAddress().getCity());   
      }

      newTransaction.commit(); 
      newSession.close(); 
   } 
}


6) Configure the UserServlet.java in the web.xml file,

<servlet>
   <servlet-name>UserServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>UserServlet</servlet-name>
   <url-pattern>/userServlet.hibernate</url-pattern>
</servlet-mapping>


7) Test the code by typing the following URL in the browser,

http://localhost:8080/WebAppName/userServlet.hibernate

Hibernate 3.0 - Hello World Example

0) Download Oracle Express 10g Express Edition and setup according to instructions on this link.
Copy the Oracle JDBC jar into the lib folder of the web application.

1) Download the hibernate_jars.zip from this link, unzip and paste the jar files into the WebContent/WEB-INF/lib folder of the web application

2) Create the persistent class, Message.java in the src folder of the web application

package info.icontraining.hibernate;
public class Message { 
  
   private Long id; 
   private String text; 
   private Message nextMessage; 
  
   private Message() {} 
     
   public Message(String text) { 
      this.text = text; 
   } 
   public Long getId() { 
      return id; 
   } 
   private void setId(Long id) { 
      this.id = id; 
   } 
   public String getText() { 
      return text; 
   } 
   public void setText(String text) { 
      this.text = text; 
   } 
   public Message getNextMessage() { 
      return nextMessage; 
   } 
   public void setNextMessage(Message nextMessage) { 
      this.nextMessage = nextMessage; 
   }   
} 


3) Create the Message.hbm.xml file in the same folder (package) as the Message.java class - this is the hibernate mapping file for the persistent class Message.java.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.Message" table="MESSAGES"> 
      <id name="id" column="MESSAGE_ID"> 
         <generator class="native"/> 
      </id> 
      <property name="text" column="MESSAGE_TEXT"/> 
      <many-to-one name="nextMessage" cascade="all" column="NEXT_MESSAGE_ID"/> 
   </class> 
</hibernate-mapping>


4) Create the hibernate.cfg.xml file in the WebContent/WEB-INF folder - this file holds the Hibernate configuration. Make sure that the username, password, the database connection string and the JDBC driver class name in this file are appropriate for your database installation.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC 
"-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration> 

<session-factory>  
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property> 
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property> 
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> 
<property name="hibernate.connection.username">system</property> 
<property name="hibernate.connection.password">system</property> 
<property name="show_sql">true</property> 
<property name="hibernate.use_sql_comments">true</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> 
<property name="hibernate.hbm2ddl.auto">create</property> 
<property name="hibernate.current_session_context_class">thread</property> 
<property name="hibernate.generate_statistics">true</property> 
<property name="hibernate.format_sql">true</property> 

<!-- Mapping files --> 
<mapping resource="info/icontraining/hibernate/Message.hbm.xml" /> 

</session-factory>
  
</hibernate-configuration>  


5) Create a HibernateUtil.java utility class in the src folder of the web application. This class abstracts the loading of the Hibernate configuration and procuring the SessionFactory object

package info.icontraining.hibernate;

import org.hibernate.*; 
import org.hibernate.cfg.*; 

public class HibernateUtil { 

   private static SessionFactory sessionFactory; 

   static { 
      try { 
         sessionFactory = new Configuration().configure("/WEB-INF/hibernate.cfg.xml").buildSessionFactory(); 
      } catch (Throwable ex) { 
         ex.printStackTrace(); 
      } 
   } 

   public static SessionFactory getSessionFactory() { 
      return sessionFactory; 
   } 
   public static void shutdown() { 
      getSessionFactory().close(); 
   } 
} 


6) Create the MessageServlet.java servlet class in the src folder of the web application. This class contains code to persist/retrieve the persistent objects.

package info.icontraining.servlets;

import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.* ; 
import org.hibernate.*; 
import info.icontraining.hibernate.*;

public class MessageServlet extends HttpServlet { 
  
   public void doGet(HttpServletRequest req, HttpServletResponse res) 
                        throws IOException, ServletException{ 
  
      PrintWriter out = res.getWriter(); 

      Session session = HibernateUtil.getSessionFactory().openSession(); 
      Transaction tx = session.beginTransaction(); 
      Message message1 = new Message("Hello World"); 
      session.save(message1); 
      tx.commit(); 
      session.close(); 

      Session newSession = HibernateUtil.getSessionFactory().openSession(); 
      Transaction newTransaction = newSession.beginTransaction(); 
      List messages = newSession.createQuery("from Message as m order by m.text asc").list(); 
      out.println( messages.size() + " message(s) found:" ); 

      for (Iterator iter = messages.iterator(); iter.hasNext(); ) { 
         Message message2 = iter.next(); 
         out.println( message2.getText() ); 
      }

      newTransaction.commit(); 
      newSession.close();  
   } 
}


7) Configure the servlet class in the web.xml file

<servlet>
   <servlet-name>MessageServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.MessageServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>MessageServlet</servlet-name>
   <url-pattern>/messageServlet.hibernate</url-pattern>
</servlet-mapping>


8) Test the code by typing the following URL in the browser,

http://localhost:8080/WebAppName/messageServlet.hibernate

April 13, 2011

Struts 2 - Transferring data onto JavaBean objects

1) Create a Register.jsp page as shown in the code below,

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Register Page</title>
</head>
<body>
<h4>Enter Registration Information!</h4>
  
   <s:form action="doRegister">
      <s:textfield name="person.firstname" label="First Name"/>
      <s:textfield name="person.lastname" label="Last Name"/>
      <s:textfield name="person.age" label="Age"/>
      <s:submit/>
   </s:form>

</body>
</html>

2) Create the Register.java action class that contains the JavaBean object into the properties of which the incoming request data is to be transferred.


package info.icontraining.struts2;

import com.opensymphony.xwork2.*;

public class Register extends ActionSupport {

   public String execute() {
       return Action.SUCCESS;
   }
 
   private PersonBean person;

   public PersonBean getPerson() {
       return person;
   }
   public void setPerson(PersonBean person) {
       this.person = person;
   }
 
   public void validate() {
  
       if ( person.getFirstname().length() == 0 ){ 
            addFieldError( "person.firstname", "First name is required." );
       }
       if ( person.getLastname().length() == 0 ){ 
            addFieldError( "person.lastname", "Last name is required." );
       }
       if ( person.getAge() < 18 ){ 
            addFieldError( "person.age", "Age required & must be > 18" );
       }
   }  
}


3) Create the PersonBean.java class that is the JavaBean class in question,

package info.icontraining.struts2;

public class PersonBean {
 
   private String firstname;
   private String lastname;
   private int age;
 
   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 int getAge() {
       return age;
   }
   public void setAge(int age) {
       this.age = age;
   }
}

4) Create the RegisterDone.jsp page that displays the incoming request data,

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Register Done</title>
</head>
<body>
<h1>Thank You</h1>
<h3>for Registering!</h3>
<s:property value="person.firstname"/>
<s:property value="person.lastname"/>
<s:property value="person.age"/>

</body>
</html>

5) Configure the struts2 actions in the struts.xml file,

<action name="Register">
     <result>/Register.jsp</result>
</action>
  
<action name="doRegister" class="info.icontraining.struts2.Register">
     <result>/RegisterDone.jsp</result>
     <result name="input">/Register.jsp</result>
</action>

6) Test the code by typing the following URL in the browser,

http://localhost:8080/WebAppName/Register.action

Struts 2 - Externalizing String literals using Resource Bundles

Modify the example code at the following link - http://www.javaissues.com/2011/04/struts-2-basic-validation-with-validate.html

1) In the Login.java class modify the validate() method as follows:

public void validate() {
  
   boolean flag = false;
  
   if (getUsername().length() == 0) {
      addFieldError("username", getText("username.required"));
      flag = true;
   }
  
   if (getPassword().length() == 0) {
      addFieldError("password", getText("password.required"));
      flag = true;
   }
  
   if (!flag) 
      if (!getUsername().equals("dinesh") && !getPassword().equals("dinesh")) {
         addActionError(getText("username.password.incorrect"));
      }
   }

2) Add 2 resource bundles (.properties files) in the same package as the Login.java class. The details of the files are below,

Login.properties

username.required=Username is required
password.required=Password is required
username.password.incorrect=Username and/or Password is Incorrect

Login_hi.properties

username.required=Username is required in Hindi
password.required=Password is required in Hindi
username.password.incorrect=Username and/or Password is Incorrect in Hindi

3) Test the code by typing the following URL in the browser

http://localhost:8080/WebAppName/Login.action

Now, change the language setting in the browser to Hindi [hi] and type the above URL again in the browser.

April 12, 2011

Struts 2 Basic Validation with validate() method

1) Create a login.jsp page in the WebContent folder of the web application. The struts tag <s:actionerror> will display any validation error messages in the input.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h4>Enter your Username and Password!</h4>
<s:actionerror />
<s:form action="doLogin">
     <s:textfield name="username" label="Username"/>
     <s:password name="password" label="Password"/>
     <s:submit/>
</s:form>
</body>
</html>

2) Add a Login.java action class in the src folder - the action class must extend the ActionSupport class in order to avail of the basic (programmatic) validation support of Struts2.

package info.icontraining.struts2;

import com.opensymphony.xwork2.*;

public class Login extends ActionSupport {

   public String execute() {
      return Action.SUCCESS;
   }
 
   private String username;
   private String password;
 
   public String getUsername() {
      return username;
   }
   public void setUsername(String username) {
      this.username = username;
   }
   public String getPassword() {
      return password;
   }
   public void setPassword(String password) {
      this.password = password;
   }
 
   public void validate() {
  
      boolean flag = false;
  
      if (getUsername().length() == 0) {
         addFieldError("username", "Username is required");
         flag = true;
      }
  
      if (getPassword().length() == 0) {
         addFieldError("password", "Password is required");
         flag = true;
      }
  
      if (!flag) 
         if (!getUsername().equals("dinesh") && !getPassword().equals("dinesh")) {
            addActionError("Username and/or Password incorrect. Please try again!");
         }
      }
}

The validate() method within the action class contains the code to validate the incoming user data. If validation errors occur it invokes the addFieldError() or the addActionError() methods.

3) Configure the struts.xml for the 2 actions, as follows,

<action name="Login">
 <result>/login.jsp</result>
</action>
  
<action name="doLogin" class="info.icontraining.struts2.Login">
 <result>/welcome.jsp</result>
 <result name="input">/login.jsp</result>
</action>

4) Create the welcome.jsp page which will be displayed when the user data is successfully validated

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
<h1>Welcome!</h1>
<h3>You have successfully logged in.</h3>
</body>
</html>

5) Test the code example by typing the following URL in the browser

http://localhost:8080/WebAppName/Login.action

- Press Submit without typing anything in the text fields
- Press Submit after typing in any one of the text fields
- Press Submit after typing something in both the text fields
- Press Submit after typing 'dinesh' in both the text fields

JDBC Code Example

1) Download and install Oracle 10g Express edition from the following link (note down the admin password chosen during installation).
Verify that the installation was successful - in the Start > Programs > 'Oracle Database 10g Express Edition' should show up.

2) Start the Oracle 10g Services by following the steps,
- Go to Start > Run
- Type services.msc and click OK
- In the Services window find the 5 Oracle services and start all of them, starting with the OracleServiceXE service

3) Change Oracle's Web Manager Application port number:
- Open the SQL*Plus Command Prompt window
- Type the command: connect
- Log in as user 'system' and type the password chosen during installation
- Execute the following command at the SQL prompt, (where 8090 is the new port number),

SQL> EXEC DBMS_XDB.SETHTTPPORT(8090);

4) Add the ojdbc14.jar file from the following path of the installed Database folder:
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib into the build path of the Java Application

5) The Oracle JDBC driver class is oracle.jdbc.OracleDriver and the JDBC connection string to be used in the DriverManager.getConnection() method is jdbc:oracle:thin:@localhost:1521:xe

Note: This information is procured from vendor documentation, in this case, Oracle 10g documentation.

6) At the SQL command prompt, paste the following SQL statement to create a new table,

create table jdbcdemo ( 
    firstname varchar2(25),
    lastname varchar2(25),
    age number(2),
    dob date
);

Next, at the SQL prompt, execute the following command, 

commit;

7) Create a java class, JDBCdemo.java and add the following code,

package info.icontraining.jdbc;

import java.sql.*;

public class JDBCdemo {

   public static void main(String[] args) throws SQLException, ClassNotFoundException {

      Class.forName("oracle.jdbc.OracleDriver");
      Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "system");
      Statement stmt = conn.createStatement();
  
      stmt.executeUpdate("insert into jdbcdemo values ('Dinesh', 'PC', 32, '1-JAN-1978')");
      stmt.executeUpdate("insert into jdbcdemo values ('Tanvi', 'DC', 27, '1-JAN-1984')");
      stmt.executeUpdate("insert into jdbcdemo values ('Laksh', 'DC', 2, '1-MAY-2009')");
  
      ResultSet rs = stmt.executeQuery("select * from jdbcdemo");
  
      while (rs.next()) {  
         System.out.println("Name: " + rs.getString(1) + " " + rs.getString(2));
         System.out.println("Age: " + rs.getInt("age"));
         System.out.println("DOB: " + rs.getDate(4).toString());
         System.out.println();
      }
  
      rs.close();
      stmt.close();
      conn.close();  
   }
}

8) Run the code as a standalone Java application

Apache Axis 1.4 - Hello World JWS Web Service Client

In this post, we will create the Web Service Client for the Apache Axis JWS Web Service at this link

1) Create a class HelloWorldClient.java in the src folder of the web application. This class will be a standalone class with a main method and will run in its own JVM


package info.icontraining.ws.client;


import org.apache.axis.client.*;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;


public class HelloWorldClient {


  public static void main(String[] args) throws Exception{
String endpoint = "http://localhost:8080/WebAppName/HelloWorld.jws";


Service  service = new Service();
Call call = (Call) service.createCall();


call.setTargetEndpointAddress( new java.net.URL(endpoint) );
call.setOperationName( "sayHello" );
call.setReturnType( XMLType.XSD_STRING );


String ret = (String) call.invoke( new Object [] { });
System.out.println("Got result : " + ret);
  }
}


2) Run this class as a 'Java Application' (and will not execute on the server)

Apache Axis 1.4 - Hello World Example JWS web service

1) Download the following resources:
Apache Axis Jar Files - Click here
WebContent Files - Click here
Resources Files - Click here

2) Unzip the Axis_jars.zip file and copy the Axis jars to the WebContent/WEB-INF/lib folder of the Web Application.
Unzip the web_content_files.zip file and copy the contents to the WebContent folder of the Web Application.
In the src folder create a new package named 'resources'. Unzip the resources_files.zip file and copy the contents to the src folder within the package 'resources'.

3) Add the following configuration to the WebContent/WEB-INF/web.xml file of the Web Application


<listener>
   <listener-class>org.apache.axis.transport.http.AxisHTTPSessionListener</listener-class>
</listener>



<servlet>
    <servlet-name>AxisServlet</servlet-name>
    <servlet-class>org.apache.axis.transport.http.AxisServlet</servlet-class>
</servlet>


<servlet>
    <servlet-name>AdminServlet</servlet-name>
    <servlet-class>org.apache.axis.transport.http.AdminServlet</servlet-class>
    <load-on-startup>100</load-on-startup>
</servlet>


<servlet>
    <servlet-name>SOAPMonitorService</servlet-name>
    <servlet-class>org.apache.axis.monitor.SOAPMonitorService</servlet-class>
    <init-param>
      <param-name>SOAPMonitorPort</param-name>
      <param-value>5001</param-value>
    </init-param>
    <load-on-startup>100</load-on-startup>
</servlet>



<servlet-mapping>
    <servlet-name>AxisServlet</servlet-name>
    <url-pattern>/servlet/AxisServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>AxisServlet</servlet-name>
    <url-pattern>*.jws</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>AxisServlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
</servlet-mapping>


<servlet-mapping>
    <servlet-name>AdminServlet</servlet-name>
    <url-pattern>/servlet/AdminServlet</url-pattern>
</servlet-mapping>


<servlet-mapping>
    <servlet-name>SOAPMonitorService</servlet-name>
    <url-pattern>/SOAPMonitor</url-pattern>
</servlet-mapping>


<mime-mapping>
    <extension>wsdl</extension>
    <mime-type>text/xml</mime-type>
</mime-mapping>


<mime-mapping>
    <extension>xsd</extension>
    <mime-type>text/xml</mime-type>
</mime-mapping>

4) Test the Axis setup by typing the following URL in the browser:

http://localhost:8080/WebAppName/happyaxis.jsp

5) To deploy a JWS Web Service, create a file, HelloWorld.jws, in the WebContent folder of the web application with the following code

public class HelloWorld { 
  
  public String sayHello() { 
     return "Hello World"; 
  } 


6) Deploy the Web Application and access the following URL in the browser:

http://localhost:8080/WebAppName/HelloWorld.jws

To access the WSDL for the web service, type the following URL in the browser:

http://localhost:8080/WebAppName/HelloWorld.jws?wsdl


Resolution to the Error:




java.lang.RuntimeException: No compiler found in your classpath! (you may need to add 'tools.jar')

Copy the tools.jar file from the JDK/lib folder into the %JBOSS HOME%\server\default\lib folder.

Expression Language (EL) implicit objects

1) Create a JSP page, elImplicitObjects.jsp in the WebContent folder of the Web Application

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>EL Implicit Objects Demo</title>
</head>
<body>
<%
   application.setAttribute("test","test-value");
   request.setAttribute("test2","test-value2");
   
   Cookie c = new Cookie("testCookie", "testCookieValue");
   response.addCookie(c);
%>

applicationScope implicit Object: ${applicationScope.test} <br/>
requestScope implicit Object: ${requestScope.test2} <br/>
<br/>

initParam implicit Object: ${initParam.paramName} <br/>
<br/>

param implicit Object: ${param.username} <br/>
paramValues implicit Object: ${paramValues.colors[1]} <br/>
<br/>

header implicit Object: ${header.host} <br/>
cookie implicit Object: ${cookie.testCookie.value} <br/>

</body>
</html>

2) Add the following configuration to the WebContent/WEB-INF/web.xml file of the web application

<context-param>
    <param-name>contextParam</param-name>
    <param-value>contextValue</param-value>
</context-param>


3) Test the page by typing the following URL in the browser (with no whitespaces in the URL):

http://localhost:8080/TestWebApp/elImplicitObjects.jsp?username=dinesh&colors=red&colors=saffron

Note: To see cookie value, refresh the page that shows up after typing the above link

Setting up JSTL in JBoss 4.2.2GA

The JBoss4.2.2GA Application Server contains the dependent jar/s for JSTL support in JSPs. The dependent jar - jstl.jar - is present in the following folder of JBoss4.2.2GA:

%JBOSS_HOME%/server/default/deploy/jboss-web.deployer/jstl.jar

1) Open the jstl.jar with an archiving tool such as WinRar. Explore into the META-INF folder within the jstl.jar

2) The META-INF contains the tld files for all the JSTL tag libraries such as the core, fmt, xml, sql and functions tag libraries.

3) To use JSTL tags for a particular library, for example, the core library, open the c.tld file and look for the <uri> element in the tld file.

For the c.tld in JBoss4.2.2GA, the <uri> element is the following:
<uri>http://java.sun.com/jsp/jstl/core</uri>

The contents of the <uri> element is needed for the taglib directive in the JSP that will contain the core library JSTL tags.

4) In the JSP which contains the JSTL tags from the core library, add the following taglib directive. The contents of the <uri> element are the value of the uri attribute in the taglib directive.
Note: Create a new JSP in your web application and add this taglib directive at the top of that JSP.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


5) Test if JSTL has successfully been setup by put the following out tag in the JSP as follows:

<body>
   <c:out value="Testing JSTL" /> 
</body>

JSP Scripting Elements Demo


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%-- This is a JSP Comment. And above this is a JSP directive (page) --%>
<html>
<head>
<title>Scripting Elements Demo</title>
</head>
<body>
<p><% out.println("This is a scriplet. It can contain any Java code " +
" which lands up in the service method of the translated JSP Servlet"); %>
</p>
<br/>
<p><%= "This is a JSP Expression" %></p>
<br/>
<p><%! 
    public void m1() {
       System.out.println("Inside the method in a JSP Declaration");
    }
%>
</p>
<br/>
<% this.m1(); %>
</body>
</html>

Error Handling by Error codes in a Web Application

Error Handling in JSPs can be configured to set up custom error pages to be rendered to the response for a particular error code (of the status code) of the HTTP response message.

Status codes from 400 to 499 are designated as error codes.

1) Configure error handling for the error code 404 (resource not available) in the WebContent/WEB-INF/web.xml file, as follows,

<error-page>
    <error-code>404</error-code>
    <location>/my404page.jsp</location>
</error-page>


2) Create a custom error page for error code 404 - my404page.jsp - in the WebContent folder. Make sure that the isErrorPage attribute of the page directive is set to true to designate the page as an error page.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isErrorPage="true" %>
<html>
<head>
<title>My 404 Page</title>
</head>
<body>

<p>This is a custom 404 page</p>

</body>
</html>


3) Test the code by typing the following URL (of an unavailable JSP) in the browser,

http://localhost:8080/WebAppName/notthere.jsp

Note:
If the custom error page does not show up in Internet Explorer, do the following:
- Go to 'Tools' menu and under it 'Internet Options'
- Click on "Advanced"
- Scroll down and uncheck the checkbox, "Show friendly HTTP error messages"

If the custom error page does not show up in Google Chrome, do the following:
- Go to Options
- Click on "Under the Hood"
- Uncheck the checkbox, "Use a web service to help resolve navigation errors"

Exception Handling in a JSP


Write a JSP - test.jsp. Within a scriptlet in this JSP, write code that throws an Exception (for example: divide by zero Arithmetic Exception). Write another JSP - error.jsp. Display a message in this JSP that says "An unexpected error occured"
Make the error.jsp display when the client requests test.jsp

Solution


1) Create a JSP - test.jsp - in the WebContent folder with the following code that throws an ArithmeticException

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Test Page</title>
</head>
<body>

<% int i = 3/0; %>
<%-- This line will throw an ArithmeticException --%>

</body>
</html>

2) Configure exception-handling for ArithmeticException in the WebContent/WEB-INF/web.xml file

<error-page>
   <exception-type>java.lang.ArithmeticException</exception-type>
   <location>/error.jsp</location>
</error-page>

3) Create an error.jsp JSP in the WebContent folder with the isErrorPage attribute of the page directive set to true. This JSP has access to the exception JSP implicit object since it is now a designated error page.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isErrorPage="true" %>
<html>
<head>
<title>Custom Error Page</title>
</head>
<body>

<p>This is a custom error page that displays when an ArithmeticException is thrown in any JSP</p>

<br/>
${pageContext.exception.message}

</body>
</html>

4) Test the code by typing the following URL in the browser

http://localhost:8080/WebAppName/test.jsp

Note: If the EL expression ${ ... } does not print anything, set the isELIgnored attribute of the page directive to false as follows,

<%@ page ... isELIgnored="false" %>

Java Server Pages (JSP) - Hello World Example

Create a new file - HelloWorld.jsp - in the WebContent folder of the web application and add the following code in it,

<html> 
<body> 
<%  int i = 3;  %> 
Writing the value of i = <%= i %>
</body> 
</html> 


Test the JSP by typing the following URL in the browser

http://localhost:8080/WebAppName/HelloWorld.jsp 

Expression Language (EL) Code Example

Write a Servlet - MyServlet.java. From this servlet, dispatch the request to a JSP - MyJsp.jsp.
Write a JavaBean - Person.java with 2 properties - name (String) and age (int).
Before dispatching, set an attribute on the request object with an instance of the bean as the attribute value.
In the JSP, use EL constructs/expressions to use the bean. Add a new property, address, to the Person bean. The address property is itself a bean with properties city (String), street (String), state (String). In the JSP retrieve the person's name, age, city and state.


In MyServlet.java set an application attribute "customers" which is an ArrayList. Each element of the ArrayList is a Person object. Add 2 different persons to the Arraylist.
In the MyJsp.jsp retrieve the states of person-2


Solution


1) Create the MyServlet.java servlet class in the src folder of the web application

package info.icontraining.servlets;

import java.io.IOException;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {
 
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
      Person person = new Person();
      person.setName("Dinesh");
      person.setAge(32);
  
      Address address = new Address();
      address.setCity("Mumbai");
      address.setState("MH");
      address.setStreet("Main Street");
  
      person.setAddress(address);
  
      List<Person> list = new ArrayList<Person>();
      list.add(person);
  
      Person person2 = new Person();
      Address address2 = new Address();
      address2.setState("KA");
      person2.setAddress(address2);
  
      list.add(person2);
  
      request.setAttribute("personBean", person);
      getServletContext().setAttribute("customers",list);
  
      RequestDispatcher rd = request.getRequestDispatcher("/MyJsp.jsp");
      rd.forward(request, response); 
   }
}


2) Configure the MyServlet class in the WebContent/WEB-INF/web.xml

<servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>info.icontraining.servlets.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/myServlet</url-pattern>
</servlet-mapping>


3) Create the Person.java JavaBean class in the src folder of the web application

package info.icontraining.servlets;

public class Person {
 
   private String name;
   private int age;
   private Address address;
 
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
 
   public int getAge() {
      return age;
   } 
   public void setAge(int age) {
      this.age = age;
   }
 
   public Address getAddress() {
      return address;
   }
   public void setAddress(Address address) {
      this.address = address;
   }
}


4) Create the Address.java JavaBean class in the src folder of the web application

package info.icontraining.servlets;

public class Address {

   private String state;
   private String city;
   private String street;
 
   public String getState() {
      return state;
   }
   public void setState(String state) {
      this.state = state;
   }
 
   public String getCity() {
      return city;
   }
   public void setCity(String city) {
      this.city = city;
   }
 
   public String getStreet() {
      return street;
   }
   public void setStreet(String street) {
      this.street = street;
   }
}


5) Create the MyJsp.jsp in the WebContent folder of the web application

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>MyJsp</title>
</head>
<body>

Name of Person is: ${requestScope.personBean.name} <br/>
Age of Person is: ${requestScope.personBean.age} <br/>

<br/>

City of Person is: ${requestScope.personBean.address.city} <br/>
State of Person is: ${requestScope.personBean.address.state}<br/>
<br/>

State of Person-2 is: ${applicationScope.customers[1].address.state}

</body>
</html>


6) Test the code by typing the following URL in the browser

http://localhost:8080/WebAppName/myServlet


Note: If the EL expression ${ ... } does not print anything, set the isELIgnored attribute of the page directive to false as follows,

<%@ page ... isELIgnored="false" %>

April 11, 2011

Struts 2 - There is no Action mapped for namespace / and action name

Exception:


There is no Action mapped for namespace / and action name Name. - [unknown location]
at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:178)
at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:47)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:478)
at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)



Application Server: JBoss 4.2.2GA / Tomcat

Resolution:

Unlike Struts 1, where the struts configuration file (struts-config.xml) is put in the WEB-INF folder of the web application, in Struts 2, the struts configuration file (struts.xml) should be present in the base class directory (or the root of the application classpath), i.e., in the WEB-INF/classes directory of the Application Deployment.

The resolution is to add the struts.xml file in the src folder of the Web Application in Eclipse (in the default package) instead of in the WebContent/WEB-INF of the application project in Eclipse

Struts 2 - Hello World Example

1) Download the Struts 2 framework jars and other dependent jars from the link here and copy them into the WebContent/WEB-INF/lib folder of the web application (in Eclipse).

2) Copy the following configuration for the Struts2 FilterDispatcher (which acts as the Controller) in the web.xml file of the Web Application

<filter>
  <filter-name>struts2</filter-name>
  <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
   
<filter-mapping>
  <filter-name>struts2</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

3) Create the HelloWorld.java class which is a POJO (and acts as the action class in Struts 2)

package info.icontraining.struts2;

public class HelloWorld {
 
   private static final String GREETING = "Hello ";

   public String execute()  {   
      setCustomGreeting( GREETING + getName() );
      return "success";
   }

   private String name;    

   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
    
   private String customGreeting;
    
   public String getCustomGreeting() {
      return customGreeting;
   }
   public void setCustomGreeting( String customGreeting ) {
      this.customGreeting = customGreeting;
   }
}

4) Create the NameCollector.jsp in the WebContent folder

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
  <head>
    <title>Name Collector</title>
  </head>
  <body>
    <h4>Enter your name!</h4>  
    <s:form action="HelloWorld">
      <s:textfield name="name" label="Your name"/>
      <s:submit/>
    </s:form>
  </body> 
</html>

5) Create the Hello.jsp in the WebContent folder

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
  <head>
    <title>HelloWorld</title>
  </head>
  <body>
     <h1><s:property value="customGreeting"/></h1>
  </body> 
</html>

6) Create the Struts2 Configuration file, struts.xml in the src folder of the Web Application (in the default package)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
   <constant name="struts.devMode" value="true" />
 
   <package name="myPackage" extends="struts-default">
    
      <action name="Name">
         <result>/NameCollector.jsp</result>
      </action>
  
      <action name="HelloWorld" class="info.icontraining.struts2.HelloWorld">
         <result name="success">/Hello.jsp</result>
      </action>

  </package>

</struts>

7) Test the code by typing the following URL in the browser:

http://localhost:8080/WebAppName/Name.action

April 10, 2011

Set a Cookie in a Servlet

1) Create the CookieDemo.java Servlet class with code to set a cookie header in the response

package info.icontraining.servlets;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class CookieDemo extends HttpServlet {
 
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
      Cookie cookie = new Cookie("cookiedemo","cookievalue");
      response.addCookie(cookie);
      PrintWriter out = response.getWriter();
      response.setContentType("text/html");
      out.println("Sending response with Cookie<br/>");
      out.println("<a href=\"cookieDemo2\">Click Link</a>");
   }
}


2) Create the CookieDemo2.java Servlet class with code to retrieve from the request that was set/sent in the previous Servlet.

import javax.servlet.http.*;
import java.io.*;

public class CookieDemo2 extends HttpServlet {
 
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
      PrintWriter out = response.getWriter();
      Cookie[] cookies = request.getCookies();
  
      for (Cookie c: cookies) {
         out.println("Cookie Name is " + c.getName() + "<br/>");
         out.println("Cookie Value is " + c.getValue() + "<br/><br/>");
      }

      response.setContentType("text/html");
   }
}


3) Configure both servlets in the web.xml

<servlet>
   <servlet-name>CookieDemo</servlet-name>
   <servlet-class>info.icontraining.servlets.CookieDemo</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>CookieDemo</servlet-name>
   <url-pattern>/cookieDemo</url-pattern>
</servlet-mapping>

<servlet>
   <servlet-name>CookieDemo2</servlet-name>
   <servlet-class>info.icontraining.servlets.CookieDemo2</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>CookieDemo2</servlet-name>
   <url-pattern>/cookieDemo2</url-pattern>
</servlet-mapping>


4) Test the code with the following URL in the browser

http://localhost:8080/WebAppName/cookieDemo

Forwarding request from Servlet with RequestDispatcher

The RequestDispatcher object is used to forward a request from one web component (Servlet or JSP) to another web component. The forward() method in the RequestDispatcher class does the actual forwarding.

1) Write the code for setting the request attribute and request forward in the FirstServlet.java

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.*;

public class FirstServlet extends HttpServlet {

   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

      System.out.println("Received request in FirstServlet");
      System.out.println("Setting  attribute in FirstServlet");
      request.setAttribute("test-attribute", "test-attribute-value");

      RequestDispatcher rd = request.getRequestDispatcher("/secondServlet");
      System.out.println("Forwarded request to SecondServlet");
      
      rd.forward(request, response);
   }
}


2) Write the code to retrieve the request attribute in the code for SecondServlet.java

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;

public class SecondServlet extends HttpServlet implements Servlet {
   
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

      System.out.println("Received request in SecondServlet");
      String value = (String) request.getAttribute("test-attribute");
      PrintWriter out = response.getWriter();
      out.println("Retrieving attribute in Second Servlet: " + value);
   }
}


3) Configure both the servlets in the web.xml

<servlet>
   <servlet-name>FirstServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>FirstServlet</servlet-name>
   <url-pattern>/firstServlet</url-pattern>
</servlet-mapping>

<servlet>
   <servlet-name>SecondServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>SecondServlet</servlet-name>
   <url-pattern>/secondServlet</url-pattern>
</servlet-mapping>


4) Access the following URL through the browser to test the code

http://localhost:8080/WebAppName/firstServlet

April 7, 2011

SAX Parser in Java

The code example below is of a SAX Parser in Java that is a validating parser (validation by DTD but not by W3C Schema), but not a namespace-aware parser.

To make the parser namespace-aware, add any one of the following lines of code,

factory.setFeature("http://xml.org/sax/features/namespaces", true);

OR

factory.setNamespaceAware(true);


To make the parser a validating parser by W3C Schema, add the following code,

//set the validation to be against W3C XML Schema
saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");

OR

//set the schema against which the validation is to be done
saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", new File("myschema.xsd"));

SAX Parser code:

package info.icontraining.parsers;

import java.io.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.DefaultHandler;

public class MySAXParser extends DefaultHandler implements LexicalHandler {

   private StringBuffer textBuffer;
   private Locator locator;

   public static void main(String[] args) {

      MySAXParser handler = new MySAXParser();
      SAXParserFactory factory = SAXParserFactory.newInstance();

      try {
         factory.setFeature("http://xml.org/sax/features/validation", true);
   
         SAXParser saxParser = factory.newSAXParser();
         saxParser.getXMLReader().setErrorHandler(handler);
         saxParser.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
         saxParser.parse( new File("FileName.xml"), handler );
      }
      catch (Throwable t) {
         t.printStackTrace();
      }
   }

   public void startDocument() throws SAXException {
      System.out.println("START DOCUMENT");
   }

   public void endDocument() throws SAXException { 
      System.out.println("END DOCUMENT");
   }

   public void startElement(String namespaceURI, String sName, String qName, Attributes attrs) throws SAXException {

      System.out.print("ELEMENT: ");
      String eName = sName;

      if ("".equals(eName)) 
         eName = qName;
      System.out.print("<"+eName);
  
      if (attrs != null) {
         for (int i = 0; i < attrs.getLength(); i++) {
            System.out.println();
            String aName = attrs.getLocalName(i);
            if ("".equals(aName)) 
               aName = attrs.getQName(i);
            System.out.println(" ATTR: " + aName + "\t\"" 
                 + attrs.getValue(i) + "\"");
         }
      }
  
      if (attrs.getLength() > 0) 
         System.out.println();
      System.out.print(">");
      System.out.println();
   }

   public void endElement(String namespaceURI, String sName, String qName) {

      System.out.print("END_ELEMENT: ");
      String eName = sName; // element name

      if ("".equals(eName)) 
         eName = qName;

      System.out.println("</"+eName+">");
   }

   public void characters(char buf[], int offset, int len) throws SAXException {
  
      String s = new String(buf, offset, len);

      if (textBuffer == null) {
         textBuffer = new StringBuffer(s);
      } else {
         textBuffer.append(s);
      }
  
      if (textBuffer == null) 
         return;  

      System.out.print("CHARACTERS: ");
      String str = ""+textBuffer;
      System.out.println(str);
      textBuffer = null;
   }

   public void setDocumentLocator(Locator l) {
      locator = l;
   }

   public void error(SAXParseException exception)  {
      System.out.println("My Error: " + exception.getLineNumber() +  
          ":" + exception.getMessage());
   }
 
   public void fatalError(SAXParseException exception) {
      System.out.println("My Fatal Error: " + exception.getLineNumber() +  
          ": " + exception.getMessage());
   }

   public void warning(SAXParseException exception) {
      System.out.println("My Warning: " + exception.getLineNumber() +  
          ": " + exception.getMessage());
   }

   public void comment(char[] ch, int start, int length) throws SAXException {
      String text = new String(ch, start, length);
      System.out.println("COMMENT: "+text);
   }

   public void endCDATA() throws SAXException {
      System.out.println("CDATA Section ended");
   }

   public void endDTD() throws SAXException {
      System.out.println("DTD Ended");
   }

   public void endEntity(String name) throws SAXException {
      System.out.println("End Entity: " + name);
   }

   public void startCDATA() throws SAXException {
      System.out.println("CDATA section started");
   }

   public void startDTD(String name, String publicId, String systemId) throws SAXException {
      System.out.println("DTD Started");
   }

   public void startEntity(String name) throws SAXException {
      System.out.println("Start Entity: " + name);
   }
}

April 4, 2011

Generics Example with wildcards


package info.icontraining.collections;


import java.util.*;


public class Animal {


   public static void main(String args[]) {


List<Cat> listCats = new ArrayList<Cat>();
List<Dog> listDogs = new ArrayList<Dog>();

listCats.add(new Cat());
listCats.add(new Cat());

listDogs.add(new Dog());
listDogs.add(new Dog());
listDogs.add(new Dog());

m1(listCats);
m1(listDogs);
   }

   public void eat() {

   }

   public static void m1(List<? extends Animal> l) {
// cannot add any new objects to 
// list in this method

for(Animal i : l) {
i.eat();
}
   }
}


class Dog extends Animal {
    public void eat() {
System.out.println("Dog");
    }
}


class Cat extends Animal {
    public void eat() {
System.out.println("Cat");
    }
}

Java Collections Framework: PriorityQueue Example

package info.icontraining.collections;

import java.util.*;

public class PriorityQueueExample {

   public static void main(String args[]) {

      Queue<Test> queue = new PriorityQueue<Test>();
  
      queue.offer(new Test(3));
      queue.offer(new Test(1));
      queue.offer(new Test(2));
  
      while (queue.size()!= 0) {
         System.out.println(queue.poll().getPriority());
      }
   }
}

class Test implements Comparable<Test> {
   private int priority;
 
   public Test(int priority) {
      this.priority = priority;
   }

   public int compareTo(Test o) {
      if (this.priority < o.priority)
         return -1;
      else if (this.priority > o.priority)
         return 1;
      return 0;
   }
 
   public int getPriority() {
      return this.priority;
   }
}

Java Collections Framework: List Example


package info.icontraining.collections;

import java.util.*;

public class ListExample {

   public static void main(String[] args) {

      List list = new ArrayList();
  
      list.add("Be");
      list.add("The");
      list.add("Change");
      list.add("You");
      list.add("Wish");
      list.add("Wish");
      list.add("To");
      list.add("See.");
  
      System.out.println("Size: " + list.size());
  
      System.out.println("List Contains \"You\": " + list.contains("You"));
      System.out.println("Index 6: " + list.get(6));
      System.out.println("indexOf \"Change\": " +list.indexOf("Change"));
  
      Iterator iterator = list.iterator();
      for( ; iterator.hasNext(); ) {
         System.out.print(iterator.next() + " ");
      }
  
      System.out.println("toString(): " + list.toString());
  
      list.clear();
      System.out.println("Size after clear(): " + list.size());
   }
}

April 3, 2011

Java Message Service (JMS) Queue - Hello World Example

1) Configure the JMS Queue in the JBoss 4.2.2GA Server, in the file ${JBOSS_SERVER}/server/default/deploy/jms/jbossmq-destinations-service.xml

<mbean code="org.jboss.mq.server.jmx.Queue"
  name="jboss.mq.destination:service=Queue,name=myQueue1">
  <depends optional-attribute-
  name="DestinationManager">jboss.mq:service=DestinationManager</depends>
</mbean>

The name myQueue1 should be unique within the XML file

2) The ConnectionFactory administered object is pre-configured with the default JNDI name 'ConnectionFactory' in JBoss

Note: Add the following jar file to the classpath / build path of the Java Project / Application:

%JBOSS_HOME%\client\jbossall-client.jar

3) Create the QueueSenderClient.java

package info.icontraining.queue;

import javax.jms.*;
import javax.jms.Queue;
import javax.naming.*;
import java.util.*;

public class QueueSenderClient {

   public static void main(String[] args) {
      QueueConnection conn = null;
      QueueSession session = null;
      Queue que;
   
      try {
         Hashtable props = new Hashtable();
         props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.NamingContextFactory");
         props.put(Context.URL_PKG_PREFIXES, "jboss.naming:org.jnp.interfaces");
         props.put(Context.PROVIDER_URL, "localhost:1099");
         props.put("java.naming.rmi.security.manager", "yes");

         InitialContext iniCtx = new InitialContext(props);
         Object tmp = iniCtx.lookup("ConnectionFactory");
         QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
    
         conn = qcf.createQueueConnection();
         que = (Queue) iniCtx.lookup("queue/myQueue1");

         session = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
   
         conn.start();

         QueueSender queueSender = session.createSender(que);
    
         TextMessage message = session.createTextMessage();
         message.setText("This is a TextMessage from QueueSenderClient");

         queueSender.send(message);
 
         queueSender.close();
 
      } catch (NamingException e) {
         e.printStackTrace();
      } catch (JMSException e) {
         e.printStackTrace();
      } finally {
         if (conn != null) {
            try {
               conn.close();
            } catch (JMSException e) {
               e.printStackTrace();
            }
         }  
      }
   }
}

4) Create the QueueReceiverClient.java

package info.icontraining.queue;

import javax.jms.*;
import javax.jms.Queue;
import javax.naming.*;
import java.util.*;

public class QueueReceiverClient {
   public static void main(String[] args) {
      QueueConnection queueConnection = null;

      try {
         Hashtable props = new Hashtable();

         props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.NamingContextFactory");
         props.put(Context.URL_PKG_PREFIXES, "jboss.naming:org.jnp.interfaces");
         props.put(Context.PROVIDER_URL, "localhost:1099");
         props.put("java.naming.rmi.security.manager", "yes");

         Context context = new InitialContext(props);

         QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory");

         String queueName = "queue/myQueue1";
         Queue queue = (Queue) context.lookup(queueName);
         queueConnection = queueConnectionFactory.createQueueConnection();

         QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
         QueueReceiver queueReceiver = queueSession.createReceiver(queue);

         queueConnection.start();

         Message message = queueReceiver.receiveNoWait();

         if (message != null) {
            if (message instanceof TextMessage) {
               TextMessage textMessage = (TextMessage) message;
               System.out.println("Received: " + textMessage.getText());
            }
         }
      } catch (NamingException e) {
         e.printStackTrace();
      } catch (JMSException e) {
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (queueConnection != null) {
            try {
               queueConnection.close();
            } catch (JMSException e) {
               e.printStackTrace();
            }
         }
      }
   }
}

5) Run QueueSenderClient first to send the message to the JMS Queue. Next, run QueueReceiverClient to receive the message.

April 1, 2011

Java Serialization Example

Java's Serialization mechanism saves the current state of an object(s) to a stream of bytes and restore an equivalent object(s) from that stream. For an object to become capable of getting serialized, it needs to implement the Serializable interface.

Java Serialization takes care of saving the object's entire "object graph", that is, a deep copy of everything the saved object needs to be restored. For this to be possible, all the objects in the object graph will need to implement Serializable.


package info.icontraining.serialization;

import java.io.*;

public class TestClass implements Serializable {

   private A a;
   private int i;
   private String s;
 
   public TestClass() {
      a = new A();
      i = 10;
      s = "Hello";
   }
 
   public A getA() {
      return a;
   }
 
   public static void main(String args[]) 
     throws IOException, ClassNotFoundException {

      TestClass t = new TestClass(); 
      serializeObject(t);
      deserializeObject();
   }

   private static void serializeObject(TestClass t) 
                throws IOException {
      FileOutputStream fs = new FileOutputStream("test.ser");
      ObjectOutputStream os = new ObjectOutputStream(fs);
      os.writeObject(t);
      os.close();
   }
 
   private static void deserializeObject() 
       throws IOException, ClassNotFoundException {

      FileInputStream fis = new FileInputStream("test.ser");
      ObjectInputStream ois = new ObjectInputStream(fis);
      TestClass t = (TestClass) ois.readObject();
      ois.close();
  
      System.out.println("i of TestClass = " + t.i);
      System.out.println("i of B = " + t.getA().getB().getI())
   }
}

class A implements Serializable {
   private B b;
   A() {
      b = new B();
   }
   public B getB() {
      return b;
   }
}

class B implements Serializable {
   private int i;
   B() {
      i = 20;
   }
   public int getI() {
      return i;
   }
}

Thread Join - joining at the end of a thread

The join() method on a Thread instance is used to join the current thread at the end of the thread on which the  join is invoked. That is, the current thread will suspend its execution (and will not resume execution) until the thread instance on which the join is invoked completes its execution.

In the example code below, the 2 thread instances t1 and t2 are names run-1 and run-2 respectively and invoked. In the run, the join() method is invoked on the thread instance t2 if the currently executing thread is t1, that is, thread t1 joins on thread t2. Therefore, execution of thread t1 is suspended and does not resume until thread t2 completes execution. After t2 completes its execution, thread t1 can then resume its execution.


package info.icontraining.threads;

public class Test implements Runnable {

   private static Thread t1, t2;
 
   public void run() {
      try {
         if (Thread.currentThread().getName().equals("run-1") {
            t2.join();
         }
   
         for (int i=0;i<50;i++) {
            System.out.println(i + ": In " + 
               Thread.currentThread().getName() + " thread");
         }
   
      } catch (InterruptedException e) {
         e.printStackTrace();
      }    
   }
     
   public static void main(String[] args)
             throws InterruptedException {
  
      t1 = new Thread(new Test());
      t1.setName("run-1");
      t1.start();
  
      t2 = new Thread(new Test());
      t2.setName("run-2");
      t2.start();
   }
}

Application of Inner Classes in Java - Swing Example

One of the most popular applications of Inner Classes is to handle events in Java to put the event-handling code in a separate event-handing class. This allows separating the event-handling code from the event-generating code. Since the event-handling code is in a separate class, if frees up the event-handling class to inherit from another class.

In the following example code, the class InnerClassExample is the event-generating class (it has JButton object as an instance variable) and the inner class MyEventHandler is the event-handling class (an instance of this class is added to the JButton object as an action listener (or simple, an event-handler).

Since InnerClassExample extends another class, if the InnerClassExample is also implemented as an event-handling class (instead of using an inner class to do the event-handling), it would not be possible to inherit (or reuse) from another class that contains event-handling code.

In the example, MyEventHandler extends TestClass and inherits its methods. The MyEventHandler can then reuse those methods for event-handling. If there was no inner class, then inheriting event-handling code from TestClass would not be possible.


package info.icontraining.basic;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class InnerClassExample extends JFrame  {

   private JButton testButton;
   private JTextArea textArea;
   private JPanel panel;
    
   public InnerClassExample() {
        
      panel = new JPanel (new GridLayout(2,1));

      add(panel, BorderLayout.CENTER);
     
      testButton = new JButton("Test Button");
      testButton.setSize(75, 30);
      panel.add(testButton);
 
      MyEventHandler ic = new MyEventHandler();
      testButton.addActionListener(ic);
  
      textArea = new JTextArea();
      textArea.setSize(100, 50);
      textArea.setVisible(true);
      panel.add(textArea);
     
      setTitle("Inner Class as Event Handler");
   }

   public class MyEventHandler extends TestClass implements ActionListener {
   
      public void actionPerformed(ActionEvent ae) {

         // invoke method inherited from Test Class

         if (ae.getSource().equals(testButton)) {
            textArea.setText("Hello World");    
         }
      }
   }

   public static void main(String[] args) {
  
      InnerClassExample frame = new InnerClassExample();
      frame.setSize(200,200);
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }
}

Multi-dimensional Arrays in Java

Multi-dimensional arrays are actually arrays of arrays. For example, a 2-dimensional array of type String is really an object that refers to an array, each element of which is referring to another String array.

The second dimension actually refers to the actual String objects.

Example of a 2-dimensional array:

public class Test {
     
   public static void main(String args[]) {
         
      String[][] strArr2d = new String[3][];

      strArr2d[0] = new String[2];
      strArr2d[1] = new String[3];
      strArr2d[2] = new String[4];

      strArr2d[0][0] = "Hello";
      strArr2d[0][1] = "World";

      strArr2d[1][0] = "Thou";
      strArr2d[1][1] = "Art";
      strArr2d[1][2] = "That";

      strArr2d[2][0] = "Truth";
      strArr2d[2][1] = "Shall";
      strArr2d[2][2] = "Always";
      strArr2d[2][3] = "Prevail";
   }
}

Example of a 3-dimensional array:


public class Test {
     
   public static void main(String args[]) {
         
      int[][][] strArr3d = new int[2][][];

      strArr3d[0] = new int[2][];
      strArr3d[1] = new int[2][];

      strArr3d[0][0] = new int[2];
      strArr3d[0][1] = new int[2];
         
      strArr3d[1][0] = new int[2];
      strArr3d[1][1] = new int[2];

      strArr3d[0][0][0] = 1;
      strArr3d[0][0][1] = 2;

      strArr3d[0][1][0] = 3;
      strArr3d[0][1][1] = 4;

      strArr3d[1][0][0] = 5;
      strArr3d[1][0][1] = 6;

      strArr3d[1][1][0] = 7;
      strArr3d[1][1][1] = 8;
   }
}