Thursday, 27 September 2012

web service

Sample webservice creation

                                                                WEB SERVICE
Introduction :- Basic concept of webservice and different approch of developing web service using different soap engines like Apache Axis2,Apache CXF and JAX-WS.SOAP Message Transmission Optimization Mechanisum (MTOM),SAAJ API.
                                                Part 1
Introduction :- This part Cover basic concept behaind the web services and showing you how to develop webservice with Axis2.

Webservice can develop using different application protocole like SOAP,XML,JSON,RESTfull HTTP . support various transport protocol like HTTP or JMS(java message service).need SOAP processing engine to parse mesaage that recived and to call the function or methods that message indicates.goal is build the bridge between the SOAP processor and business logic that is running on sever. Normally this bussiness logic is kept separate from the SOAP processing logic.
Web services :-
Web services is a network accessible interface to application functionality built using standard internet technologies.
Move in to web service
1.create a new web service from scratch (contract first) :- Cretate functionality of the service and prepare a document to describe those services.
2.Exposing an exisiting functionality through a web service (Code first): functionality of service already exist.service description only need to be implemented .
3.Integarting web services from other vendores or bussiness partnr (Meet in the middle):- instead of creating webservice from scrach using a service implemented by another is more feasible .  in this situvation organization use others web service .
Code first approch vs Contact first approch
Code first approch(Bottom up) :- reuse your inverstment by exposing your existing application . example our banking application we have a creadit card validation functionality , we need to expose this functionality so need to create this functionality as web service. Implementation calss already exists , all that is need to create a WSDL and expose the class as web service .

Contatc first (Top Down) :- pure approch , this is the correct way to build new web service from scrach.start with WSDL by defining operation message and so forth. Then build end point interface and finally the implementation class.
Axis2 architecture 
Build upon a  module architecture that consist of core module and non-core modules. Core engine said to be a pure SOAP processing engine(JAX-PRC concept burnt into the core ).every message coming to sysytem transfromed in to a soap message before it hand over to the core engine.incoming message either be a SOAP message or a non-SOAP message(REST JSON or JMX).at transport layer it converted in to SOAP message. Following rule were incorprated into the architecture to achieve a highly flexible and extensible SOAP processing engine.
                                Separation of logic and sate to provide a stateless processing mechanisum(this is because web services are ststeless).

                                Single information model in order to enable the system to suspend and resume
                                Ablity to extend support to newer web service specifications with minimal changes made to the core architecture.

     Example of credit card validation web service :-
                                This is code first approch where user will input 16 digit credit card number to validate it .
                                Eclipse IDE :-
                                Tomcate web server :-
                                 (binary Distribution):-consis of  all relevent third party libraries,a set of samples, and the Axis2 runtimes.  For installing binary distribution involving extracting ZIP archive files into desired location .once done this we can able to see a set of subdirectories inside it (bin,lib,sample,repository,webapp).
                                (war distribution) :- useful for deploying Axis2 in application server such as tomcat,jboss,weblogic,and so on.can check whether this is working or not by accessing http://localhost:8080/axis2
                                Main distbutions are
                                Binary distribution
                                War distibution
                                Source distribution
                                JAR distribution

                Set up enviorment
1.       Install JDK1.5 or above in your system .
2.       Download axis2(war version) exstract zip file and copy axis2.war file and past it into <TOMCAT_HOME> webapp directory. Start tomcat and the go to tomcat web app directory inside this you will find a new directory named axis2 .that means axis2 file deployed successfully.
3.       Download and exstract Axis2 binary distribution to a directory which refers as <AXIS

1.       Create directory structure:-
                Create application as Axis2Example then create folder inside as Code first Service create package name
2.       Create a interface within the package

Import javax.jws.webservice;
@webservice (name=”checkcard” targetNamespace=”http:/”)
Public interface CheckSEi{
                Public String doCheck(String targetName);
3. class inside package

Import javax.jws.webservice;
@webservice(serviceName =”checkCardService” , portName =”cport” endpointInterface=””,targetNameSpace=””)

Public class CheckCard implement CheckSEI {
                Public static final int INVALID                      =             -1;
                Public staic 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 DINER_CLUB             =             4;

                Private static final String[] cardName      = {
                “master card” ,
                “American express”,
                “En route”,
                “Dinners CLUB”

Public static boolean validCC(String number) thows exception {
                Int CardID;
                If((CardId = getCardId(number)) !=-1)
                                Return validNumber(number);
                Return false;

Public static boolean validCCNumber(String n){
                                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() +
                                  checksum += Integer.valueOf(s1[i]).intValue() + k;           
                                  checksum += Integer.valueOf(s1[0]).intValue();           
                          return ((checksum % 10) == 0);
                        catch (Exception e) {
                          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) {
                                               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;
                                          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){}

4.       Now creating a service.xml file inside META_INF directory


      This Web Service Validates CreditCard Number.
   <parameter name="ServiceClass"></parameter>
   <operation name="doCheck">

5.       Open command prompt
6.       Move to the directory ccheck and type javac *.java as shown below. (inorder to run javac command from the project directory (Axis2Example you need to set <JAVA_HOME>bin to path of the user variable ))
      Like c:\Axis2Wexample\code Frist service\con\ibm\axis2\ccheck>javac *.java
7.       Move to code first service directory and type jar cvf CreditCardService.aar* a
   Like c:\Axis2Example\code frist Service > jar cvf CheckCardService.aar *

8.       Start tomcat and open browser by typing http://localhost:8080/axis2 and click administration
provide default user name and password admin and axis2 as password
9.       click upload web service and browse the creaditCardService.aar and finally click upload
10.    click available service or past http://localhost:8080/axis2/axis2-admin/listService in browser to find out
  1. click on service to check the WSDL of the CreditCardService  or type following url :- http://localhost:8080/axis2/services/CheckCardService?wsdl

Strub Generation
1.       open command prompt and move to the <AXIS_HOME>bin and type following command

    you will find the stub name : , and are generated inside <AXIS_Home>|bin|src|com|ibm|axis2|ccheck|directory
Developing POJO calss for CreditCardService
1.       Create project name Axis2Client in Eclipse
2.       Create a package inside src file
3.       Now select client project and configure the build path add exsteranal JAR and select all the jar from <axis2_home>lib|and then click OK
4.       Copy Generated Stub and past it in the of Axis2Client
5.       Create inside the package


public class TestClient {
     public static void main(String[] args) throws Exception {
         CheckCardServiceStub stub = new CheckCardServiceStub();
         //Create the request  request = new;
    System.out.println("Enter your Credit Card Number:");
    InputStreamReader isr = new InputStreamReader(;
    BufferedReader br = new BufferedReader(isr);
    String s = br.readLine();
         //Invoke the service response
            = stub.doCheck(request);

4.       Select the and runAs > java application
5.       Enter your credit card number and press enter

Product Catalog Service with Contarct Frist Approch Using AXIS2

In this application , user will input the productid number to find out the desire product name in the catalog.

Ant:- it is a java library and command-line tool whos’s mission to drive process described in build files as targets and extension point dependent upon each other .the main known usage of Ant is the build of java application. Can use any type of application

Setting up Environment
 <ANT_HOME>bin to the path of the user variable .

Developing the WSDL
1.       Creating a file name product.wsdl inside <AXIS_HOME>bin|wsdl directory as shown below


<?xml version="1.0" encoding="UTF-8"?>
<wsdl:definitions xmlns:wsdl=""
        <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified"
            <xs:element name="getProductName">
                        <xs:element minOccurs="0" name="productNumber" type="xs:int"/>
            <xs:element name="getProductNameResponse">
                        <xs:element minOccurs="0" name="return" nillable="true"
    <wsdl:message name="getProductNameRequest">
        <wsdl:part name="parameters" element="ns:getProductName"/>
    <wsdl:message name="getProductNameResponse">
        <wsdl:part name="parameters" element="ns:getProductNameResponse"/>
    <wsdl:portType name="ProductPortType">
        <wsdl:operation name="getProductName">
            <wsdl:input message="ns:getProductNameRequest"
            <wsdl:output message="ns:getProductNameResponse"
    <wsdl:binding name="ProductSoap11Binding" type="ns:ProductPortType">
        <soap:binding transport=""
        <wsdl:operation name="getProductName">
            <soap:operation soapAction="urn:getProductName" style="document"/>
                <soap:body use="literal"/>
                <soap:body use="literal"/>
    <wsdl:binding name="ProductSoap12Binding" type="ns:ProductPortType">
        <soap12:binding transport=""
        <wsdl:operation name="getProductName">
            <soap12:operation soapAction="urn:getProductName" style="document"/>
                <soap12:body use="literal"/>
                <soap12:body use="literal"/>
    <wsdl:binding name="ProductHttpBinding" type="ns:ProductPortType">
        <http:binding verb="POST"/>
        <wsdl:operation name="getProductName">
            <http:operation location="Product/getProductName"/>
                <mime:content type="text/xml" part="getProductName"/>
                <mime:content type="text/xml" part="getProductName"/>
    <wsdl:service name="Product">
        <wsdl:port name="ProductHttpSoap11Endpoint" binding="ns:ProductSoap11Binding">
            <soap:address location="http://localhost:8080/axis2/services/Product"/>
        <wsdl:port name="ProductHttpSoap12Endpoint" binding="ns:ProductSoap12Binding">
            <soap12:address location="http://localhost:8080/axis2/services/Product"/>
        <wsdl:port name="ProductHttpEndpoint" binding="ns:ProductHttpBinding">
            <http:address location="http://localhost:8080/axis2/services/Product"/>

2.       Using the tool <AXIS2_HOME>bin|wsdl2java.bat we will create the skeleton and other supporting files for this service
3.       Open command prompt and move to <AXIS2_HOME>|bin ans execute wsdl2java.bat –uri <AXIS2_HOME>\bin\wsdl\product.wsdl –d adb –s –ss –sd –ssi –o build\service
4.       This will create an out put named service inside <AXIS2_HOME>|bin|build directory

No comments:

Post a Comment