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 .
                Enviorments:-
                                Eclipse IDE :-
                                Tomcate web server :-
                                AXIS2
                                 (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
_HOME>

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


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);
}
               
3.       CheckCard.java class inside com.ibm.axis2.ccheck package

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 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      = {
                “visa”,
                “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){
                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);
                     }
                   
                   
                   
} 

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

    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>

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 : checkCardserviceCallbackHandler.java , CheckCardServiceStub.java and ExceptionException.java 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 com.ibm.axis2.ccheck 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 com.ibm.axis2.ccheck of Axis2Client
5.       Create TestClient.java inside the package
TestClient.java

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());
    }
}

 
4.       Select the testClient.java 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


   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>

 
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