Developing web services, Part 1: Developing the code and contract first approach web service with Axis2

This tutorial demonstrate how to develop Credit Card Validation web service with Code first (Bottom up) approach and followed by Product Catalog web service development with Contract First (Top Down) approach using Axis2. Code First Approach is the most popular approach of developing a web service, whereas Contract First approach is the correct way to build any new web service.

Kuntal Ganguly, Jr. Developer, Protech Infosystems Pvt. Ltd

Kuntal GangulyCurrently associated as a Junior Developer at Protech Infosystems Pvt. Ltd, Kolkata. Kuntal has expertise in using a wide range of open source and commercial tools (WAS CE, Eclipse, Mule ESB, EZlegacy , Active MQ , Birt , and DB2 express C) and technologies(GWT and Android).



Partha Goswami, Jr. Developer, Protech Infosystems Pvt. Ltd

Partha GoswamiB.Tech with more than 13 months experience in developing J2EE, Web Service (JAX-WS), J2ME and Android application.Currently associated with Protech Infosystems, Kolkata as Junior Consultant.Has expertise in using a wide range of open source and commercial tools (WASCE, Eclipse, Oracle SOA Suite11g, EZlegacy , BIRT and DB2 express C) . Apart from his passion for Latest Technology, he has numerous other interests including Cricket and Tabla.



14 June 2011

Also available in Chinese Japanese

Before you start

This tutorial is for developers who build applications that use web services with different approach. By using web services, your application can publish its function or message to the rest of the world. Web services use XML to code and to decode data, and SOAP to transport it (using open protocols).

About this series

This tutorial series teaches the basic concepts of web services and with different approach of developing web service using different SOAP engines like Apache AXIS2, Apache CXF and JAX-WS. This tutorial series also provides a solution for sending large attachment with SOAP messages by using MTOM (SOAP Message Transmission Optimization Mechanism) which encodes binary data in base64Binary and sends the data as binary attachment rather than keeping it with actual SOAP message. This series also shows that by simply making method calls using the SAAJ API, you can read and write SOAP-based XML messages, and you can optionally send and receive such messages over the Internet.

Part 1 starts simply, explaining the basic concepts behind web services and showing you how to develop web service with Axis2 using Different Approach (Code First and Contract First).

Part 2 starts simply by developing a Hello User web Service with JAX-WS and then takes things a step further by showing an example of File Download web service(where client can download file from web service and store in its location)using MTOM with JAX-WS. It also shows how to invoke web service from SAAJ Client.

Part 3 simply shows how to develop a File uploading web service(where client can Upload file/attachment to Web service) using Apache CXF supports for MTOM with XOP implementation

About this tutorial

This Tutorial series will describes the way of developing web service with different Web Service Engine like (Axis2,JAX-WS and CXF). Web services can be implemented using different application protocols like SOAP, XML, JSON, RESTful HTTP, and support various transport protocols like HTTP or JMS (Java Message Service). In order to create a Web service, you will need some tools. At a minimum, you will need some type of SOAP processing engine to parse the messages that are received and to call the functions or methods that the message indicates. Many products are on the market that provides this processing. The goal of every Web services development tool is to build a bridge between the SOAP processor and the business logic that is running on the server. Normally, this business logic is kept separate from the SOAP processing logic.

In this Part 1 of the tutorial series you will learn how to develop a Credit Card Validation web service with Code first (Bottom up) approach and followed by Product Catalog web service development with Contract First(Top Down) Approach using Axis2.

Objectives

In this tutorial, you will learn how to:

  • Download and install the web servers (Tomcat), if it is not already installed, and make minor additions to it to successfully implement the given examples.
  • Download and install Axis2 engine to generate the Stubs as well as Service skeleton.
  • Download and install Axis2 runtime environment into Tomcat for developing and deploying web service (Credit Card Validation and Product Catalog).
  • Developing POJO Client for the web service (Credit Card Validation) using Eclipse IDE.

Prerequisites

This tutorial assumes familiarity with some basic concepts of the Eclipse IDE, and basic understanding of web service architecture.


Introduction

What is a web service?

A web service is a network accessible interface to application functionality, built using standard Internet technologies.

The web services that we see deployed on the Internet today are HTML web sites. In these, the application services—the mechanisms for publishing, managing, searching, and retrieving content—are accessed through the use of standard protocols and data formats: HTTP and HTML. Client applications (web browsers) that understand these standards can interact with the application services to perform tasks like ordering books, sending greeting cards, or reading news. Because of the abstraction provided by the standards-based interfaces, it does not matter whether the application services are written in Java and the browser written in C++, or the application services deployed on a Unix box while the browser is deployed on Windows. Web services allow for cross-platform interoperability in a way that makes the platform irrelevant. Interoperability is one of the key benefits gained from implementing web services. Java and Microsoft Windows-based solutions have typically been difficult to integrate, but a web services layer between application and client can greatly remove friction.

Benefits of web service

The web service, a very well known open technology standard provides a number of benefits as listed below:

  • Increase competition among vendors, resulting in lower product costs.
  • Ease transition from one product to another, resulting in lower training costs.
  • Increase the ability for parties to interoperate, resulting in lower maintenance costs.
  • Ensure a greater degree of adoption and longevity for a standard. A large degree of usage from the vendors and the users leads to a higher degree of acceptance.

How do organizations move into web service

There are three main ways in which an organization can move into Web Services. These are as follows:

  1. Creating a new web service from scratch (Contract First): The developer creates the functionalities of the services as well as preparing a document to describe those services.
  2. Exposing an existing functionality through a web service (Code First): Here, the functionalities of the service already exist. Only the service description needs to be implemented.
  3. Integrating web services from other vendors or business partners (Meet in the Middle): There are instances where using a service implemented by another is more feasible than building from scratch. On these occasions, the organization will be required to integrate others' or even business partners' Web Services.

The real utility of the Web Service concept is present in the second and the third methods, which leads to other Web Services and applications that can be used in existing applications.

Code first approach versus contract first approach

Code first (Bottom Up) approach allows you to reuse your investment by exposing your existing application. Credit Card System is an existing Application with Proven business value. Competitive pressure is moving Credit Card System to expose some of this business functionality Like (Credit Card Number Validation) as web service. The implementation class already exists, all that is needed is to create a WSDL and expose the class as web service.

Contract First (Top Down) often termed as “Pure Approach” is the correct way to build new web service from scratch. This Approach starts with the WSDL (the contract) by defining operation message and so forth. Then you build the endpoint interface and finally the implementation class.

Axis2 architecture

Axis2 is built upon a modular architecture that consists of core modules and non-core modules. The core engine is said to be a pure SOAP processing engine (there is not any JAX-PRC concept burnt into the core). Every message coming into the system has to be transformed into a SOAP message before it is handed over to the core engine. An incoming message can either be a SOAP message or a non-SOAP message (REST JSON or JMX). But at the transport level, it will be converted into a SOAP message. When Axis2 was designed, the following key rules were incorporated into the architecture to achieve a highly flexible and extensible SOAP processing engine:

  • Separation of logic and state to provide a stateless processing mechanism. (This is because web services are stateless.)
  • A single information model in order to enable the system to suspend and resume.
  • Ability to extend support to newer web service specifications with minimal changes made to the core architecture.

The Apache Axis2 architecture is built on the foundation of a SOAP engine. This engine accepts SOAP messages, parses them, and calls the appropriate methods and functions in the web service. At this level of detail, Axis is just like every other web services engine. The uniqueness of this product, and every other product, lies in how a developer would go about organizing the processing so that the message can be responded to properly.


Configuration and development

Example I – Credit card validation web service using AXIS2

This is a simple Credit Card Validation web service with Code First Approach, where user will input the 16 digit credit card number to validate it and also to find out the credit card vendor. To setup and run this example one need to know few things given below:

Eclipse IDE: An integrated development environment (IDE) is an all-in-one tool for writing, editing, compiling, and running computer programs. And Eclipse provides an excellent integrated development environment. You can find the latest release of eclipse in www.eclipse.org.

Tomcat web server 5.5 or above: The Tomcat servlet engine is an open-source package developed as part of the Apache Software Foundation's Jakarta project. It is the official reference implementation for both the servlet and JSP specifications. Tomcat can act as a stand-alone Web server and also as a servlet/JSP engine. You can download the latest release of Tomcat from http://tomcat.apache.org/download-60.cgi.

Axis2:

(Binary Distribution): An Axis2 binary distribution consists of all the relevant third-party libraries, a set of samples, and the Axis2 runtime. Installing a binary distribution involves extracting ZIP archive files into a desired location. Once we download and extract the binary distribution, then we will be able to see a set of subdirectories inside it (bin, lib, samples, repository, webapp).

(War distribution): The Axis2 WAR distribution is useful for deploying Axis2 in application servers such as Tomcat, Jboss, Weblogic, and so on. We can deploy the Axis2 WAR file into an application server, and check whether it works by typing the server address in a browser. For an example, if you deploy the Axis2 WAR file in Apache Tomcat, by typing http://localhost:8080/axis2, we can figure out whether Axis2 is up and running.

We can download the latest Axis2 release from http://ws.apache.org/axis2/download.cgi. Each Axis2 release consists of four main release artifacts or distributions:

  • Binary distribution
  • WAR distribution
  • Source distribution
  • JAR distribution

Set up the Environment

  1. Install JDK 1.5 or above in your system.
  2. After downloading Axis2 file (war version) extract the zip file to any local directory. After extracting you will find axis2.war file. Copy the file and paste it to the <TOMCAT_HOME>webapp| directory, then start Tomcat. As shown in Figure 1. Tomcat startup console. After this go the <TOMCAT_HOME>webapps| directory, inside this you will find a new directory named axis2, which indicates that the axis2.war file is deployed successfully.
  3. Download and extract Axis2 binary Distribution to a directory, which will be referred as <AXIS2_HOME>.

Developing a CreditCardservice and Deploying in Tomcat

  1. Create a directory structure Axis2Example for our Credit Card Validation Web Service as shown below in Figure 1.
Figure 1. Axis2Example Project Directory Structure
Axis2Example Project Directory Structure
  1. Create a CheckSEI.java interface with within the package com.ibm.axis2.ccheck as shown below.
Listing 1. CheckSEI.java
package com.ibm.axis2.ccheck;

import javax.jws.WebService;

@WebService (name="CheckCard",
		targetNamespace="http://ccheck.axis2.ibm.com")
		
public interface CheckSEI {
	
	public String doCheck(String targetName);
	
}
  1. Create a CheckCard.java class inside com.ibm.axis2.ccheck package as shown in Listing 2.
Listing 2. CheckCard.java
package com.ibm.axis2.ccheck;
import javax.jws.WebService;
@WebService(serviceName = "CheckCardService",
		portName = "cport",
		endpointInterface = "com.ibm.axis2.ccheck.CheckSEI",
		targetNamespace = "http://ccheck.axis2.ibm.com")

public class CheckCard implements CheckSEI{
	
     	  public static final int INVALID          = -1;  
	  public static final int VISA             = 0;
	  public static final int MASTERCARD       = 1;
	  public static final int AMERICAN_EXPRESS = 2;
	  public static final int EN_ROUTE         = 3;
	  public static final int DINERS_CLUB      = 4;
	
	private static final String [] cardNames = 
    {   "Visa" , 
        "Mastercard", 
        "American Express", 
        "En Route", 
        "Diner's CLub/Carte Blanche",
    };

	public static boolean validCC(String number)
    throws Exception {   
    int CardID;
    if ( (CardID = getCardID(number)) != -1)
        return validCCNumber(number);
    return false;
    }

	public static boolean validCCNumber(String n) {
	    try {
	      
	      int j = n.length();
	  
	      String [] s1 = new String[j];
	      for (int i=0; i < n.length(); i++) s1[i] = "" + n.charAt(i);
	  
	      int checksum = 0;         
	    
	      for (int i=s1.length-1; i >= 0; i-= 2) {
	        int k = 0;
	        
	        if (i > 0) {
	           k = Integer.valueOf(s1[i-1]).intValue() * 2;
	           if (k > 9) {
	              String s = "" + k;
	              k = Integer.valueOf(s.substring(0,1)).intValue() + 
	                  Integer.valueOf(s.substring(1)).intValue();
	              }
	              checksum += Integer.valueOf(s1[i]).intValue() + k;            
	           }
	           else
	              checksum += Integer.valueOf(s1[0]).intValue();            
	        }
	      return ((checksum % 10) == 0);
	      }
	    catch (Exception e) {
	      e.printStackTrace();
	      return false;
	      }
	    }

	public static int getCardID(String number) {
	    int valid = INVALID;
	        
	    String digit1 = number.substring(0,1);
	    String digit2 = number.substring(0,2);
	    String digit3 = number.substring(0,3);
	    String digit4 = number.substring(0,4);
	    
	    if (isNumber(number)) {
	      
	      if (digit1.equals("4"))  {  
	        if (number.length() == 13 || number.length() == 16) 
	           valid = VISA;
	        }
	     
	      else if (digit2.compareTo("51")>=0 && digit2.compareTo("55")<=0) {
	        if (number.length() == 16) 
	           valid = MASTERCARD;
	        }
	      
	      else if (digit2.equals("34") || digit2.equals("37")) {
	        if (number.length() == 15) 
	           valid = AMERICAN_EXPRESS;
	        }
	    
	      else if (digit4.equals("2014") || digit4.equals("2149")) {
	         if (number.length() == 15) 
	            valid = EN_ROUTE;
	         }
	      
	      else if (digit2.equals("36") || digit2.equals("38") || 
	        (digit3.compareTo("300")>=0 && digit3.compareTo("305")<=0)) {
	        if (number.length() == 14) 
	           valid = DINERS_CLUB;
	           }
	      
	     	      
	      }           
	      return valid;
	      
	      
	      
	    }
	
	
	 public static boolean isNumber(String n) {
		    try  {
		      double d = Double.valueOf(n).doubleValue();
		      return true;
		      }
		    catch (NumberFormatException e) {
		      e.printStackTrace();
		      return false;
		      }
		    }

	 public static String getCardName(int id) {
		    return (id < -1 && id < cardNames.length ? cardNames[id] : "");
		    }

	
	 public String doCheck(String aCard){
		 
		 String s="";
		 boolean b;
		try{ 
		 if (getCardID(aCard) > -1) 
		 {
			  s="This is a  " + getCardName(getCardID(aCard)) + " Card .";
			if( b=validCC(aCard))
			{
				s=s+"The card number " + aCard + " is VALID " ;
			}
			else{s= s+"The card number " + aCard + " is IN-VALID " ;}
		 }
		
		 else{return("INVALID INPUT");}
		}		
		catch(Exception e){}
		 return(s);
	 }
	
	
	
}
  1. Now create a services.xml file inside META-INF directory as shown in Listing 3.
Listing 3. Services.xml
<service>
   <description>
      This Web Service Validates CreditCard Number.
   </description>
   <parameter name="ServiceClass">com.ibm.axis2.ccheck.CheckCard</parameter>
   <operation name="doCheck">
      <messageReceiver
      class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
   </operation>   
</service>
  1. Now open the command prompt by typing cmd in START > Run. See figure 2.
Figure 2. Opening Command Prompt
Opening Command Prompt
  1. Move to the directory ccheck and type javac *.java as shown below (in order to run javac command from the project directory (Axis2Example, you need to set <JAVA_HOME>bin| to the Path of the user variable).
Figure 3. Compile the CreditCard interface and class
Compile the CreditCard interface and class
  1. Now move to Code First Service directory and type jar cvf CreditCardService.aar * as shown below to generate the aar file. (See Figure 4)
Figure 4. Generate CreditCardService.aar file
Generate CreditCardService.aar file
  1. Start tomcat and open browser by typing http://localhost:8080/axis2 and click on Administration.
Figure 5. Running Axis2 on Tomcat
Running Axis2 on Tomcat

You need to provide the default username: admin and password: axis2 to login as shown below in Figure 6.

Figure 6. Login in Axis2 Administrator
Login in Axis2 Administrator
  1. After sucessfully logging, click on Upload web service and the browse the CreditCardService.aar file in the Axis2Example|Code First Service directory and finally click on Upload (to sucessfully deploy the web service) as shown below in Figure 7.
Figure 7. CreditCardService Uploading
CreditCardService Uploading
  1. Now click on Available Service or paste this link http://localhost:8080/axis2/axis2-admin/listService in the browser to find out the deployed CreditCard web service as shown below in Figure 8.
Figure 8. CreditCard Service Deployment
CreditCard Service Deployment
  1. Clink on the service to check the WSDL of the CreditCardService at http://localhost:8080/axis2/services/CheckCardService?wsdl

Stub Generation

  1. Open command prompt and move to the <AXIS2_HOME>bin| directory and type the following command as shown in Figure 9.

wsdl2java.bat -uri http://localhost:8080/axis2/services/CheckCardService?wsdl -o client

Figure 9. Stub generation for credit Card Service
Stub generation for credit Card Service

(You will find the stubs name : CheckCardServiceCallbackHandler.java, CheckCardServiceStub.java and ExceptionException.java are generated inside <AXIS2_HOME>|bin|src|com|ibm|axis2|ccheck| directory).

Developing POJO Client for the CreditCardService

  1. Create File > New > Java Project name Axis2Client in Eclipse as shown in Figure 10.
Figure 10. Axis2Client Java project in Eclipse
Axis2Client Java project in Eclipse
  1. Create a package com.ibm.axis2.ccheck inside Axis2Client|src folder as shown in Figure 11.
Figure 11. Create a Package for Axis2Client
Create a Package for Axis2Client
  1. Now Select the Axis2Client Project and Configure the build path as shown below in Figure 12.
Figure 12. Configure Build Path for Axis2Client
Configure Build Path for Axis2Client

Click on Add External JARs and select all the jars from <AXIS2_HOME>lib| and then click OK.

  1. Now copy the Generated Stubs and paste it in the com.ibm.axis2.ccheck package of the Axis2Client project as shown in Figure 13.
Figure 13. Copy and Paste the generated Stubs
Copy and Paste the generated Stubs
  1. Now create a TestClient.java class inside the com.ibm.axis2.ccheck package as shown below.
Listing 4. Services.xml
package com.ibm.axis2.ccheck;
import java.io.*;
import com.ibm.axis2.ccheck.*;

public class TestClient {
     public static void main(String[] args) throws Exception {
         CheckCardServiceStub stub = new CheckCardServiceStub();
         //Create the request

    com.ibm.axis2.ccheck.CheckCardServiceStub.DoCheck  request = new 
   com.ibm.axis2.ccheck.CheckCardServiceStub.DoCheck();
    System.out.println("Enter your Credit Card Number:");
    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    String s = br.readLine();
    
        request.setArgs0(s);
         //Invoke the service
        com.ibm.axis2.ccheck.CheckCardServiceStub.DoCheckResponse response 
            = stub.doCheck(request);
        System.out.println(response.get_return());
    }
}
  1. Select TestClient.java and Run As > Java Application (Make sure Tomcat is running).
  2. After running the TestClient, you will be prompted to enter your Credit card Number in the console as shown below:

    (Type your Number for example 4111111111111111 and then Press ENTER to get valid input and valid vendor)
Figure 14. Enter Valid input and vendor in Console
Enter Valid input and vendor in Console

(Type your Number for example 5111111111111111 and then Press ENTER to get invalid input and valid vendor).

Figure 15. Enter invalid input and valid vendor
Enter invalid input and valid vendor

(Type your Number which is not a credit card number, for example 51470965 and then Press ENTER to get invalid input).

Figure 16. Enter invalid input
Enter invalid input

Example II - Developing Product Catalog Service with Contract First Approach using Axis2

This is a very simple Product Catalog web service with Contract First Approach, where user will input the ProductId Number to find out the desired Product Name in the Catalog. To setup and run this example one need to know few things given below:

Ant: Apache Ant is a Java library and command-line tool who's mission is to drive processes described in build files as targets and extension points dependent upon each other. The main known usage of Ant is the build of Java applications. Ant supplies a number of built-in tasks allowing to compile, assemble, test and run Java applications. Ant can also be used effectively to build non Java applications, for instance C or C++ applications. More generally, Ant can be used to pilot any type of process which can be described in terms of targets and tasks. We can download the Latest relase of ANT from http://ant.apache.org/bindownload.cgi..

Setting Up Environment

  1. Set <ANT_HOME>bin| to the path of the user variable. (All other Environment setup is similar to Example-I).

Developing the WSDL

  1. Create a file name product.wsdl inside <AXIS_HOME>bin|wsdl| directory as shown below
Listing 5. product.wsdl
<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"
xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" 
xmlns:ns1="http://org.apache.axis2/xsd"
xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" 
xmlns:ns="http://contract.axis2.ibm.com" 
xmlns:xs="http://www.w3.org/2001/XMLSchema" 
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
    targetNamespace="http://contract.axis2.ibm.com">
    
        <wsdl:types>
        <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified"
targetNamespace="http://contract.axis2.ibm.com">
            <xs:element name="getProductName">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element minOccurs="0" name="productNumber" type="xs:int"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
                        
            <xs:element name="getProductNameResponse">
                <xs:complexType>
                    <xs:sequence>
                        <xs:element minOccurs="0" name="return" nillable="true" 
                                        type="xs:string"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
        </xs:schema>
    </wsdl:types>
        
    <wsdl:message name="getProductNameRequest">
        <wsdl:part name="parameters" element="ns:getProductName"/>
    </wsdl:message>
        
    <wsdl:message name="getProductNameResponse">
        <wsdl:part name="parameters" element="ns:getProductNameResponse"/>
    </wsdl:message>
        
    <wsdl:portType name="ProductPortType">
        <wsdl:operation name="getProductName">
            <wsdl:input message="ns:getProductNameRequest" 
                        wsaw:Action="urn:getProductName"/>
            <wsdl:output message="ns:getProductNameResponse" 
                        wsaw:Action="urn:getProductNameResponse"/>
        </wsdl:operation>
    </wsdl:portType>
        
    <wsdl:binding name="ProductSoap11Binding" type="ns:ProductPortType">
        <soap:binding transport="http://schemas.xmlsoap.org/soap/http" 
                          style="document"/>
        <wsdl:operation name="getProductName">
            <soap:operation soapAction="urn:getProductName" style="document"/>
            <wsdl:input>
                <soap:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
        
    <wsdl:binding name="ProductSoap12Binding" type="ns:ProductPortType">
        <soap12:binding transport="http://schemas.xmlsoap.org/soap/http" 
                          style="document"/>
        <wsdl:operation name="getProductName">
            <soap12:operation soapAction="urn:getProductName" style="document"/>
            <wsdl:input>
                <soap12:body use="literal"/>
            </wsdl:input>
            <wsdl:output>
                <soap12:body use="literal"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
        
    <wsdl:binding name="ProductHttpBinding" type="ns:ProductPortType">
        <http:binding verb="POST"/>
        <wsdl:operation name="getProductName">
            <http:operation location="Product/getProductName"/>
            <wsdl:input>
                <mime:content type="text/xml" part="getProductName"/>
            </wsdl:input>
            <wsdl:output>
                <mime:content type="text/xml" part="getProductName"/>
            </wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
        
    <wsdl:service name="Product">
        <wsdl:port name="ProductHttpSoap11Endpoint" binding="ns:ProductSoap11Binding">
            <soap:address location="http://localhost:8080/axis2/services/Product"/>
        </wsdl:port>
        <wsdl:port name="ProductHttpSoap12Endpoint" binding="ns:ProductSoap12Binding">
            <soap12:address location="http://localhost:8080/axis2/services/Product"/>
        </wsdl:port>
        <wsdl:port name="ProductHttpEndpoint" binding="ns:ProductHttpBinding">
            <http:address location="http://localhost:8080/axis2/services/Product"/>
        </wsdl:port>
    </wsdl:service>
        
</wsdl:definitions>
  1. Using the tool <AXIS2_HOME>|bin|wsdl2java.bat, we will create the Skeleton and other supported files for this service.
  2. Open command Prompt and move to <AXIS2_HOME>|bin| and execute the following command
    wsdl2java.bat –uri <AXIS2_HOME>\bin\wsdl\product.wsdl -d adb -s -ss -sd -ssi -o build\service
  3. This will create an output named service inside <AXIS2_HOME>|bin|build| directory as shown below in Figure 17.
Figure 17. Service skeleton directory structure for Product catalog
Service skeleton directory structure for Product catalog

The contents of target_directory_name are:

build.xml
resources\services.xml
resources\product.wsdl
src|com|ibm|axis2|contract|ExtensionMapper.java
src|com|ibm|axis2|contract|GetProductName.java
src|com|ibm|axis2|contract|GetProductNameResponse.java
src|com|ibm|axis2|contract|ProductMessageReceiverInOut.java
src|com|ibm|axis2|contract|ProductSkeleton.java
src|com|ibm|axis2|contract|ProductSkeletonInterface.java

In the above list, the Java file named src|com|ibm|axis2|contract|ProductSkeleton.java is the one which is used to place our custom Business logic code.

AutoGenerated ProductSkeleton java code

Listing 6. Autogenerated ProductSkeleton.java
/**
 * ProductSkeleton.java
 * This file was auto-generated from WSDL
 * by the Apache Axis2 version: 1.5.2  Built on : Sep 06, 2010 (09:42:01 CEST)
 */
    package com.ibm.axis2.contract;
    /**
     *  ProductSkeleton java skeleton for the axisService
     */
    public class ProductSkeleton implements ProductSkeletonInterface{
     /**
         * Auto generated method signature
          * @param getProductName0
         */
        public com.ibm.axis2.contract.GetProductNameResponse getProductName
                  (
                  com.ibm.axis2.contract.GetProductName getProductName)
                 {
                
                throw new java.lang.UnsupportedOperationException("Please implement " 
                                + this.getClass().getName()
                                + "#getProductName");
        }
}

Let us add our Business logic in the above class to implement our functionality.

Listing 7. Business Logic added in the ProductSkeleton.java
/**
 * ProductSkeleton.java
 * This file was auto-generated from WSDL
 * by the Apache Axis2 version: 1.5.2  Built on : Sep 06, 2010 (09:42:01 CEST)
 */
 package com.ibm.axis2.contract;
import com.ibm.axis2.contract.*;
import java.util.*;
import org.apache.axis2.engine.AxisError;
    /**
     *  ProductSkeleton java skeleton for the axisService
     */
    public class ProductSkeleton implements ProductSkeletonInterface{
        private static HashMap<Integer, String> productMap   = new
HashMap<Integer, String>();
        static
        {   productMap.put(1, "Colgate");
                productMap.put(2, "Pepsodent");
                productMap.put(3, "Neem");    }
      /**
         * Auto generated method signature
          * @param getProductName0
         */      
public com.ibm.axis2.contract.GetProductNameResponse 
        getProductName ( com.ibm.axis2.contract.GetProductName getProductName)
                   {
                 /* Custom Logic - Starts here */
                int inputProductNumber = getProductName.getProductNumber();
                String productName = productMap.get(inputProductNumber);
                GetProductNameResponse response = new GetProductNameResponse();
                if (productName != null)
                {   response.set_return(productName);
                }
                else
                { throw new AxisError("Product Record Not Found");  }
               return response;
                /* Custom Logic - Ends here */
 } 
 }
  1. Now, its time to build and test our web service implementation.
  2. Open command promt and move to <AXIS2_HOME>bin|build|service| and type the following command as shown below.

    Ant jar.server
Figure 18. Build and Test with ANT
Build and Test with ANT

The Above ANT build will create Product.aar file inside <AXIS2_HOME>bin|build|service|build|lib| as shown below

Figure 19. ANT build directory structure and Product.aar file
ANT build directory structure and Product.aar file

Deploying the web service to Tomcat

The Steps for Deploying the Product.aar file is similar to CreditCardService deployment on tomcat.

  1. Start tomcat and open browser by typing http://localhost:8080/axis2 and click on Administration. (You need to provide the default username: admin and password: axis2 to login).
  2. After sucessfully logging, click on Upload web service and the browse the Product.aar file in the <AXIS2_HOME>bin|build|service|build|lib| directory and finally click on Upload(to sucessfully deploy the web service).
  3. Now click on Available Service or paste this link http://localhost:8080/axis2/axis2-admin/listService in the browser to find out the deployed Product Service as shown below.
Figure 20. Product Service Deployment
Product Service Deployment

You can check the WSDL of this Product web service at http://localhost:8080/axis2/services/Product?wsdl


Conclusion and Resource

In this tutorial you just learn to develope Code First and Contract First Approach web service with Axis2 in very short interval of time. In the Part2 of this Tutorial series,you will learn to develope File Download web service with JAX-WS and consuming it with SAAJ client.


Download

DescriptionNameSize
Sample code for this articlecode.zip10KB

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into SOA and web services on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=SOA and web services
ArticleID=680461
ArticleTitle=Developing web services, Part 1: Developing the code and contract first approach web service with Axis2
publish-date=06142011