January 15, 2012

Deploying an Apache Axis2 Web Service - Hello World Example

1) Setup Apache Axis2 in the web application - follow the steps here

2) Create a POJO - HelloWorldService.java - in the src folder of the web application

package info.icontraining.ws.axis2;

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

3) In the WebContent/WEB-INF/services folder, create a new folder and name it 'HelloWorld'.
In this folder create a sub-folder and name it 'META-INF'.
In the META-INF folder create a new XML file - name it 'services.xml'.

4) Add the following configuration to the services.xml file created in the step above,

<service>
   <parameter name="ServiceClass" locked="false">info.icontraining.ws.axis2.HelloWorld</parameter>
   <operation name="sayHello">
      <messageReceiver class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
   </operation> 
</service>

5) Now go to the build/classes folder of the web application. Copy the folder named 'info' and paste it into the services/HelloWorld folder created in step 3.

So, now in the services/HelloWorld folder, there are 2 folders - META-INF and info
The META-INF folder contains the services.xml file.
The info folder contains the following hierarchy of sub-folders - icontraining/ws/axis2/HelloWorldService.class

6) Deploy the Web Application to the server, and access the following URL in the browser,

http://localhost:8080/WebAppName/services/listServices

The HelloWorld service will be present in the list of services.

7) Invoke the Web Service with the following URL in the browser,

http://localhost:8080/WebAppName/services/HelloWorld/sayHello?name=dinesh

Setting up Apache Axis2 in a Web Application

1) Download the required resources for the Apache Axis2 installation from the link here. Unzip the contents of the downloaded zip file.

2) Copy all the jars in the lib folder in the zip file into the WebContent/WEB-INF/lib folder of the web application.

3) Copy the folder axis2-web (and its contents) into the WebContent folder of the web application

4) Copy the conf, modules and services folders into the WebContent/WEB-INF folder of the web application

5) The structure of the Web Application project after the above steps will look like this,

WebAppName
   |
   |--- WebContent
            |
            |--- axis2-web (and all contents of this folder)
            |
            |---WEB-INF
                   |
                   |--- conf (axis2.xml file in this folder)
                   |
                   |--- lib (all jars files in this folder)
                   |
                   |--- modules (*.mar files in this folder)
                   |
                   |--- services (and its contents in this folder)

6) Add the following configuration to the WebContent/WEB-INF/web.xml file of the web application and within its root <web-app> element

<servlet>
   <servlet-name>AxisServlet</servlet-name>
   <servlet-class>org.apache.axis2.transport.http.AxisServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>
<servlet>
   <servlet-name>AxisAdminServlet</servlet-name>
   <servlet-class>org.apache.axis2.webapp.AxisAdminServlet</servlet-class>
</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>AxisAdminServlet</servlet-name>
   <url-pattern>/axis2-admin/*</url-pattern>
</servlet-mapping>

<mime-mapping>
   <extension>inc</extension>
   <mime-type>text/plain</mime-type>
</mime-mapping>

<welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
   <welcome-file>index.html</welcome-file>
   <welcome-file>/axis2-web/index.jsp</welcome-file>
</welcome-file-list>

<error-page>
   <error-code>404</error-code>
   <location>/axis2-web/Error/error404.jsp</location>
</error-page>

<error-page>
   <error-code>500</error-code>
   <location>/axis2-web/Error/error500.jsp</location>
</error-page>


7) Deploy the Web Application to the server. Test the installation was successful by accessing the following URL through the browser,

http://localhost:8080/WebAppName/axis2-web/index.jsp

8) Click on the links - Services, Validate and Administration - and check each of the links work.

Note: Use admin/axis2 as username/password to log in as Administrator

Note: If Validate link displays an error message for the Version service, resolve the error from this post here

9) Invoke the Version Web Service with this URL in the browser:

http://localhost:8080/WebAppName/services/Version/getVersionRequest

getVersion Service method error in Apache Axis2 - There was a problem in Axis2 version service , may be the service not available or some thing has gone wrong.

Topic: Apache Axis2

Application Server: JBoss 4.2.2GA

Exception:

Clicking on the Validate link during Apache Axis2 installation shows the following error message:

There was a problem in Axis2 version service , may be the service not available or some thing has gone wrong. But this does not mean system is not working ! Try to upload some other service and check to see whether it is working.

and shows the following stack trace on the server console log:

14:20:11,065 INFO  [STDOUT] 14:20:11,065 ERROR [RPCMessageReceiver] Exception occurred while trying to invoke service method getVersion
org.apache.axis2.AxisFault: namespace mismatch require http://axisversion.sample found http://axisversion.sample/xsd
 at org.apache.axis2.rpc.receivers.RPCUtil.invokeServiceClass(RPCUtil.java:190)
 at org.apache.axis2.rpc.receivers.RPCMessageReceiver.invokeBusinessLogic(RPCMessageReceiver.java:117)
 at org.apache.axis2.receivers.AbstractInOutMessageReceiver.invokeBusinessLogic(AbstractInOutMessageReceiver.java:40)
 at org.apache.axis2.receivers.AbstractMessageReceiver.receive(AbstractMessageReceiver.java:110)
 at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:181)
 at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:172)
 at org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:146)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
 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)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
 at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:179)
 at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
 at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:262)
 at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
 at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
 at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:446)
 at java.lang.Thread.run(Unknown Source)

Resolution:

Open the axis2-web/HappyAxis.jsp and find the following line of code:

OMNamespace omNs = fac.createOMNamespace("http://axisversion.sample/xsd", "ns1");

Modify the above line to the following:

OMNamespace omNs = fac.createOMNamespace("http://axisversion.sample", "ns1");

January 11, 2012

Database Connection Pool Code Example with Apache DBCP and Oracle 10g

1) Download the Apache Commons DBCP and Commons Pool jars from the link here and add them to the classpath / build path of the Java Application / Project.

2) Add the jboss-j2ee.jar file to the class path/build path of the Java Application/Project. The jboss-j2ee.jar file is present in the $JBOSS_HOME/server/default/lib folder of the JBoss Installation folder.

3) Complete the JDBC example at the link here

4) Create a java class - ConnectionPoolExample.java - in the src folder of the Java Application / Project

package info.icontraining.jdbc;

import java.sql.*;
import javax.sql.*;
import org.apache.commons.pool.*;
import org.apache.commons.pool.impl.*;
import org.apache.commons.dbcp.*;

public class ConnectionPoolExample {
 
   private static GenericObjectPool genericPool = new GenericObjectPool();

   public static void main(String[] args) throws Exception {

      try {
         Class.forName("oracle.jdbc.OracleDriver");
      } catch (ClassNotFoundException e) {
         e.printStackTrace();
      }

      DataSource dataSource = setupDataSource("jdbc:oracle:thin:system/system@localhost:1521:xe");

      Connection conn = null;
      Statement stmt = null;
      ResultSet rs = null;

      try {
         conn = dataSource.getConnection();
         stmt = conn.createStatement();
         rs = stmt.executeQuery("SELECT * FROM DUAL");
            
         while(rs.next()) {
            for(int i=1; i<=rs.getMetaData().getColumnCount(); i++) {
               System.out.println(rs.getString(i));
            }
         }
            
         System.out.println("Active Connections: " + genericPool.getNumActive() + ", Idle Connections: " + genericPool.getNumIdle());
            
      } catch(SQLException e) {
         e.printStackTrace();
      } finally {
         try { if (rs != null) rs.close(); } catch(Exception e) { }
         try { if (stmt != null) stmt.close(); } catch(Exception e) { }
         try { if (conn != null) conn.close(); } catch(Exception e) { }
      }
        
      System.out.println("Active Connections: " + genericPool.getNumActive() + ", Idle Connections: " + genericPool.getNumIdle());
   }

   public static DataSource setupDataSource(String connectURI) throws Exception {
      ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI,null);
      KeyedObjectPoolFactory kopf =new GenericKeyedObjectPoolFactory(null);

      PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory( connectionFactory, genericPool, kopf, null, false, true);

      for(int i = 0; i < 5; i++) {
         genericPool.addObject();
      }

      System.out.println("Active Connections: " + genericPool.getNumActive() + ", Idle Connections: " + genericPool.getNumIdle());
        
      PoolingDataSource dataSource = new PoolingDataSource(genericPool);
      return dataSource;
   }
}


5) Run the code as a standalone Java Application

January 1, 2012

JDBC Code to read BLOB data type from database table

0) Complete the example to store an image (BLOB data) to a table at the link here

1) Create a Java class - JdbcBlobReader.java - in the src folder of the Java Project / application

package info.icontraining.jdbc;

import java.io.*;
import java.sql.*;

public class JdbcBlobReader {
 
   public static void main(String[] args) throws Exception, IOException, SQLException {
   
      Class.forName("oracle.jdbc.OracleDriver");
      Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","system");

      PreparedStatement pstmt = conn.prepareStatement("Select name, image from MyImages");
      ResultSet rs = pstmt.executeQuery();
      
      while (rs.next()) {
         String name = rs.getString(1);
         String description = rs.getString(2);
         File image = new File("src/icon-training-downloaded.jpg");
         FileOutputStream fos = new FileOutputStream(image);

         byte[] buffer = new byte[1];
         InputStream is = rs.getBinaryStream(2);

         while (is.read(buffer) > 0) {
            fos.write(buffer);
         }

         fos.close();
      }

      conn.close();    
   }
}

2) Run the code as a standalone Java Application

JDBC Code to insert an image in a BLOB column

0) Complete the first 5 steps in the JDBC code example at the link here

1) Create a new table in the database using the following CREATE TABLE command

create table MyImages (
   name VARCHAR(1000),
   image BLOB
);

2) Add the image file to the src folder of the Java Project/Application







3) Create a Java class - JdbcBlobExample.java - to the src folder of the Java Project/Application

package info.icontraining.jdbc;

import java.io.*;
import java.sql.*;

public class JdbcBlobExample {
 
   public static void main(String[] args) throws Exception, IOException, SQLException {
   
      Class.forName("oracle.jdbc.OracleDriver");
      Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","system");

      FileInputStream fis = null;
      PreparedStatement pstmt = null;
    
      try {
         conn.setAutoCommit(false);
      
         File file = new File("src/icon-training.jpg");
         fis = new FileInputStream(file);
      
         pstmt = conn.prepareStatement("insert into MyImages(name, image) values (?, ?)");
      
         pstmt.setString(1, "Icon Training Logo");
         pstmt.setBinaryStream(2, fis, (int) file.length());
      
         pstmt.executeUpdate();
         conn.commit();
      
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         pstmt.close();
         fis.close();
      }
   }
}

4) Run the code as a standalone Java Application

JDBC Transaction Management Code Example

0) Complete the first 6 steps in the JDBC Code example at the link here

1) Create a Java class - JdbcTransactionMgmt.java - in the src folder of the Java Project /Application

package info.icontraining.jdbc;

import java.sql.*;

public class JdbcTransactionMgmt {

   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");
      PreparedStatement pstmt = null;
  
      conn.setAutoCommit(false); // start of transaction
  
      try {
         pstmt = conn.prepareStatement("insert into jdbcdemo values (?, ?, ?, ?)");

         pstmt.setString(1, "Ramesh");
         pstmt.setString(2, "PC");
         pstmt.setInt(3, 32);

         Date d = new Date(0);
         pstmt.setDate(4, d.valueOf("1978-9-28"));

         int rowsAffected = pstmt.executeUpdate();
         System.out.println(rowsAffected + " rows affected.");

         // deliberately cause an exception to be thrown
         int i = 3/0;    // comment this line for commit to happen 

         pstmt.setString(1, "Gunjan");
         pstmt.setString(2, "C");
         pstmt.setInt(3, 26);
         pstmt.setDate(4, d.valueOf("1984-10-30"));

         rowsAffected = pstmt.executeUpdate();
         System.out.println(rowsAffected + " rows affected.");

         conn.commit();

         pstmt.close();

      } catch (Exception e) {
         conn.rollback();
         System.err.println("Caught Exception & transaction rollbacked");
      }

      conn.close(); 
   }
}

2) Run the code as a standalone Java application.
Since the code throws an exception, which is caught, and the transaction is rolled-back, no changes reflect in the database table, even though one row was, apparently, successfully inserted.

3) Comment the line that deliberately throws an exception and run the code as a standalone Java application.
Now, both rows are inserted because the transaction gets committed successfully.

JDBC Prepared Statement Code Example

0) Complete the first 6 steps in the JDBC Code Example at the link here

1) Create a java class - JdbcPSExample.java - to the src folder of the Java Project / Application


package info.icontraining.jdbc;

import java.sql.*;

public class JdbcPSExample {

   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");
      PreparedStatement pstmt = conn.prepareStatement("insert into jdbcdemo values (?, ?, ?, ?)");
  
      pstmt.setString(1, "Dinesh");
      pstmt.setString(2, "PC");
      pstmt.setInt(3, 32);
  
      Date d = new Date(0);
      pstmt.setDate(4, d.valueOf("1978-9-28"));

      int rowsAffected = pstmt.executeUpdate();
      System.out.println(rowsAffected + " rows affected.");

      pstmt.setString(1, "Tanvi");
      pstmt.setString(2, "C");
      pstmt.setInt(3, 26);
      pstmt.setDate(4, d.valueOf("1984-10-30"));
  
      rowsAffected = pstmt.executeUpdate();
      System.out.println(rowsAffected + " rows affected.");

      pstmt.close();
      conn.close(); 
   }
}


3) Run the Example as a standalone Java Application