Develop Web services through AXIS2, part 1th: Deploy and use simple Web services through AXIS2 runtime

Source: Internet
Author: User
Tags gettext soap tomcat wsdl
Develop Web services through AXIS2, part 1th: Deploy and use simple Web services through AXIS2 runtime
Document Options

send this page as an e-mail message



Level: Intermediate

Gopalakrishnan U (ugopalak@in.ibm.com), software engineer, IBM India software Labs
Shreevidya Rao (ugopalak@in.ibm.com), software engineer, IBM

June 13, 2006 This article describes the new architecture of Axis2 and explains how to deploy and use WEB services through AXIS2. This article is part 1th of a series of articles about developing WEB services through the AXIS2 runtime (a total of two parts). Axis2 is the next generation Apache Axis simple Object Access Protocol (SOAP) runtime.

Introduction

Axis2 is the next generation of Apache Axis. Although supported by the Axis 1.x handler model, AXIS2 is more flexible and extensible to the new architecture. Axis2 is written on a new architecture and is not using the usual code of Axis 1.x. The power to support the development of AXIS2 is to explore a more modular, flexible, and efficient architecture that can easily be plugged into implementations of other relevant WEB service standards and protocols such as Ws-security, ws-reliablemessaging, and so on.

AXIS2 features include the following: The new core XML processing model named AXIOM (AXIs Object MOdel,axis object model) supports IN-ONLY and in-out message exchange patterns (m EP) blocking and non-blocking client API (Application programming Interface) supports built-in WEB service Addressing (ws-addressing) support for XMLBeans data binding new deployment model supports Hypertext Transfer Protocol (HTTP), Simple Mail Transfer Protocol (SMTP), and Transmission Control Protocol (TCP) and other transport protocols

This series of articles is based on the Axis2 0.92 release. You can get the latest version of Axis2 on the Apache website.




Back to top of page


Axis Architecture Overview
Figure 1. AXIS2 Architecture

The AXIS2 architecture separates logic from state; This allows logic to be executed in parallel threads. The static state and dynamic state of the service and invocation are stored in the Description and context classes, respectively. The AXIS2 architecture is implemented using 7 separate modules.Information Model:This module manages the state of the SOAP engine. The model defines a set of classes for storing states, and the engine manages the life cycle of those information objects. The information model contains two classes for storing states. The Description class holds data that is essentially static and exists throughout the life cycle of an Axis engine instance, such as the configuration of transports, services, and operations. The context class holds dynamic information about the services and operations that are valid in the invocation context, such as the current request and response SOAP message, from address, to address, and other elements.XML processing Model:AXIS2 introduces a new model called AXIOM, which is used to process SOAP messages. AXIOM uses StAX (streaming API for XML) to parse the XML. The StAX is a standard streaming pull resolver java™api. AXIOM is very ingenious and does not slow down the construction of the XML information set-in other words, objects are created only when absolutely necessary. Overall, AXIOM and Axis2 occupy less memory than Axis 1 occupies.SOAP processing Model:The AXIS2 architecture defines two pipelines (or streams), respectively known as inpipe (inflow) and outpipe (outflow), for processing server-side request and response messages. On the client side, the two pipelines are reversed-in other words, the SOAP request message flows through the outpipe, while the response message flows through the inpipe. A pipeline or flow contains a series of stages-divided handlers. The stages are executed in a predefined order, as shown in Figure 1 above. Users can configure user stages and related handlers at the operation level, service level, or global level, in addition to pre-defined stages and processing assemblies. Handlers act as interceptors for SOAP messages and can handle headers or Body of SOAP messages. Inpipe is configured through the following stages: Transportin predispatch Dispatch postdispatch policydetermination User Phases Message Validation we will The above phases are described in detail in part 2nd of this series of articles. The request message arrives at Messagereceiver after all phases configured through Inpipe, and then the actual service implementation is invoked by Messagereceiver. The outpipe of the server consists of the following stages: Message initialization Policy Determination user phases messageout the stage in which users are configured is located at the user stage of both pipelines (users phases) Score of If an error occurs during the execution of these pipelines, these errors will pass through the Infaultpipe or Outfaultpipe pipeline. When a Fault message is received, Infaultpipe is called on the client, and Outfaultpipe is called on the server side if a call causes an error to be sent to the client. Users can add handlers to predefined stages and configure them in the order in which they are run.Deployment module:This module configures the Axis engine and deploys services and modules. Axis2.xml (in Webapps/axis2/web-inf) contains the global configuration of the Axis2 engine, including: Global module (globally modules) global receiver (globally receivers) transfer (transports) user The configuration of the stage definition (User phase Definitions) for each service is included in the Services.xml file of the service archive. This file will be discussed in more detail later in this article.WSDL and code generation:This module generates the client stub and the server skeleton code from the WSDL file. The AXIS2 code generator emits an XML file with the correct XML style sheet to generate code in the desired language.Client API:The AXIS2 client API call follows the operation of the in-only and in-out message patterns defined by WSDL 2.0. The client API supports blocking and non-blocking calls to in-out operations.Transmission:This module contains handlers that interact with the transport layer. There are two types of transport handlers: Transportlistener and Transportsender. Transportlistener receives a SOAP message from the transport layer and then transmits it to inpipe for processing. Transportsender sends a SOAP message received from Outpipe by specifying the transport. AXIS2 provides handlers for HTTP, SMTP, and TCP. For HTTP transports, Axisservlet on the server side and a simple standalone HTTP server on the client (provided by AXIS2) Act as transportreceiver.




Back to top of page


Deploying AXIS2

Deploying the AXIS2 is as simple as deploying Axis 1. First, look for the Axis2 Web application Axis2.war under the WebApps directory of the AXIS2 binary code distribution package. Deploy this war file in the Servlet container. In Tomcat, if Unpackwars is set to True in the server configuration, you can deploy AXIS2 by simply copying the Axis2.war to the $TOMCAT _home/webapps directory. Please start Tomcat now and Access Http://localhost:<port>/axis2. The Axis2 Welcome page is displayed, and you click the Validate link on this page. You should arrive at the Axis2 Happiness pagewithout any errors.




Back to top of page


Development StockQuoteService

The following describes how to develop StockQuoteService using in-only subscribe () and In-out getquote (). The subscribe () operation will book an hourly quote for the specified designator, and GetQuote () will receive the current quote for the specified code name.

Listing 1 Below is an example implementation of StockQuoteService:
Listing 1. StockQuoteService Implementation

Package stock;
Import Org.apache.axis2.om.OMAbstractFactory;
Import org.apache.axis2.om.OMElement;
Import Org.apache.axis2.om.OMFactory;
		
Import Org.apache.axis2.om.OMNamespace; public class StockQuoteService {Public void Subscribe (omelement in) {String symbol = In.gettext ();
    SYSTEM.OUT.PRINTLN ("Subscription Request for symbol =" +symbol); Put the actual subscribe code here ...}Public omelement GetQuote (omelement in) {Get the symbol from request message String symbol = In.gettext ();
    int quote = 0;
    if (Symbol.equals ("IBM")) {quote = 100;
    }//Put more quotes here ...//Create response omfactory FAC = Omabstractfactory.getomfactory ();
    Omnamespace omns = Fac.createomnamespace ("Http://www.developerworks.com/example", "example");
    Omelement resp = fac.createomelement ("Getquoteresponse", omns);
    Resp.settext (string.valueof (quote));      
  Return resp; }
}

I was puzzled by the method signature. We will discuss the omelement in the above method.




Back to top of page


Deployment Services

Deployment Descriptor

In Axis2, the service deployment information is included in the Services.xml file (in the previous version of 0.92, this file is named Service.xml). For the above StockQuoteService, the service deployment descriptor is similar to the following Listing 2.
Listing 2. Services.xml

				
<service name="StockQuoteService">
  <parameter name= "ServiceClass" locked= "Xsd:false" >
    stock. StockQuoteService
  </parameter>
		
  <operation name= "GetQuote" >
    < Messagereceiver 
      class= "Org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
  </ operation>
		
  <operation name= "Subscribe" >
    <messagereceiver 
      class= " Org.apache.axis2.receivers.RawXMLINOnlyMessageReceiver "/>
  </operation>
</service >

The Name property of the service defines the names of the services. Axis2 uses the name of the service to create the endpoint address of the service, such as http://localhost:<port>/axis2/services/<nameofservice>. Therefore, for StockQuoteService, the service endpoint is http://localhost:<port>/axis2/services/StockQuoteService. The ServiceClass parameter specifies the service implementation class.

Each <operation> element defines the configuration of an operation in the service. The Name property of <operation> should be set to the names of the methods in the service implementation class. The Messagereceiver element defines the message sink that is used to handle this operation. The AXIS2 provides two built-in messagereceivers;org.apache.axis2.receivers.rawxmlinonlymessagereceiver for in-only and in-out operations without data binding for In-only operations, while Org.apache.axis2.receivers.RawXMLINOutMessageReceiver is used for in-out operations. If Messagereceiver is not specified, AXIS2 will attempt to use Org.apache.axis2.receivers.RawXMLINOutMessageReceiver as the default messagereceiver. The above Rawxml message receiver passes the contents of the <Body> of the incoming SOAP message as omelement (Omelement is the AXIOM abbreviation of the XML Element) to the service implementation. This action should be the XML content contained in the <Body> element that returns the SOAP response as Omelement. This explains why the subscribe () and getquote () operations take and return omelement.

Services.xml can also contain multiple services that are divided into servicegroup.

Packing

The Axis 2 service is packaged as Axis Archive (. aar). This is a jar file (created with a jar or zip utility) that packages the Services.xml file in the archived Meta-inf directory. StockQuoteService will have the following structure when packaged into Stockquoteservice.aar:

./stock/stockquoteservice.class

./meta-inf/services.xml

Pre-packaged StockQuoteService archives can be found in the downloads section of this article.

Deployment

Deploying the service in Axis2 is fairly straightforward, just copy the. aar file to the Axis2/web-inf/services directory in the Axis2 Web application of the servlet container. For Tomcat, this location is $TOMCAT _home/webapps/axis2/web-inf/services.

Another good way to deploy a service is to use the Upload Service tool in the AXIS2 Management console. Go to Http://localhost:<port>/axis2 and select the administration link. Enter the user name and password admin/axis2, and then log in. (You can configure the username/password in axis2.xml.) In the Tools section, select the Upload Service link, select the . AAR file, and then click Upload. It's that simple. If the upload succeeds, a green success message is displayed. The service is deployed and can be called at any time. This is handy if you want to deploy the service on a remote AXIS2 server.




Back to top of page


Using Web services through AXIS2

The attributes of a WEB service invocation are determined by the MEP, the transport protocol, and the synchronous and/or asynchronous behavior of the client API. Axis2 currently supports the in-only and in-out MEP defined in WSDL 2.0. The AXIS2 client API supports synchronous and asynchronous invocation of services. Provides asynchronous behavior at the API level and at the transport level when invoking the in-out operation. The API-level async is obtained by rolling back, which uses a transport connection to transmit requests and responses at the same time (for example, transfer requests and responses over an HTTP connection). In transport-level asynchrony, different transport connections are used to send requests and receive responses individually, such as when using SMTP for transport.

The following is the details of calling In-only and in-out operations using the AXIS2 client API.

invoke In-only Action

The Org.apache.axis2.clientapi.MessageSender class is used to invoke the in-only operation (as shown in Listing 3 below), while the in-only operation invokes the subscribe () operation of StockQuoteService.
Listing 3. Calling the In-only action

				
try{
  endpointreference targetepr = new EndpointReference (
      "http://localhost:8080/axis2/services/ StockQuoteService ");
          
  Make the request message
  omfactory FAC = omabstractfactory.getomfactory ();
  Omnamespace omns = Fac.createomnamespace (
      "Http://www.developerworks.com/example", "example");
  Omelement payload = fac.createomelement ("subscribe", omns);
  Payload.settext ("IBM"); 
          
  Send the request
  messagesender Msgsender = new Messagesender ();
  Msgsender.setto (TARGETEPR);
  Msgsender.setsendertransport (constants.transport_http);
  Msgsender.send ("subscribe", payload);         
  } catch (Axisfault axisfault) {
      axisfault.printstacktrace ();
  }

Messagesender.send () sends a request message and returns it immediately. The transport to be used is specified by Messagesender.setsendertransport (). This example sends a message over HTTP.

invoke In-out Action

The Org.apache.axis2.clientapi.Call class makes it easy to invoke the in-out operation. This call class supports the following 4 modes when invoking the In-out operation:

blocking single transfer mode : This is the simplest way to invoke in-out Web service operations. The service call is blocked until the operation completes and the response or error is received. It uses a transport connection to send and receive responses at the same time, as shown in Listing 4 below.

Listing 4. Blocking single transfer mode

						
try {
                 
  EndpointReference targetepr = new EndpointReference (
      "http://localhost:8080/axis2/services/ StockQuoteService ");
               
  Create Request message
  omfactory FAC = omabstractfactory.getomfactory ();
  Omnamespace omns = Fac.createomnamespace (
      "Http://www.developerworks.com/example", "example");
    Omelement payload = fac.createomelement ("GetQuote", omns);
  Payload.settext ("IBM");

  Create the call "call"
  = new Call ();
  Call.setto (TARGETEPR);
			
  Call.settransportinfo (Constants.transport_http,
    constants.transport_http, false);
  Invoke blocking
  omelement result = call.invokeblocking ("GetQuote", payload);
               
  System.out.println ("Quote =" +result.gettext ());
} catch (Axisfault axisfault) {
    axisfault.printstacktrace ();
}

The first part of the code uses AXIOM to create the request message. Call.settransportinfo () Sets the transport used to send requests and get responses. The Boolean parameter of the Call.settransportinfo () operation indicates whether to use a different transport connection to send the request and receive the response separately. In this example, a request is sent with an HTTP connection and a response is received.

non-blocking single transfer mode : In this invocation mode, only the following transport connection is used to obtain a non-blocking call. This behavior is required if you want to complete multiple Web service calls in one client application, and you do not want each call to block the client. At this point, if the response is available, the call returns immediately and the client is rolled back, as shown in Listing 5 below.

Listing 5. Non-blocking single transfer mode

						
try {endpointreference Targetepr = new EndpointReference ("Http://localhost:8080/axis2/services/StockQuote
            
  Service ");
  Create the request omfactory FAC = Omabstractfactory.getomfactory ();
  Omnamespace omns = Fac.createomnamespace ("Http://www.developerworks.com/example", "example");
  Omelement payload = fac.createomelement ("GetQuote", omns);
      
            
    Payload.settext ("IBM");
    Create the call "call" = new Call ();
            
    Call.setto (TARGETEPR);
    Set the transport info. Call.settransportinfo (Org.apache.axis2.Constants.TRANSPORT_HTTP, Org.apache.axis2.Constants.TRANSPORT_HTTP,
            
  FALSE); Callback to handle the response Callback Callback = new Callback () {public void oncomple TE (AsyncResult result) {System.out.println ("Quote =" + Result.getresponseenvelope (). GetBody (). GetFirst
      Element (). GetText ()); } public void ReportError (Exception e) {e.printstacktrace ();
            
            
  }
    };
            
     Invoke Non Blockingcall.invokenonblocking ("GetQuote", payload, callback);Wait till the callback receives the response.while (!callback.iscomplete ()) {thread.sleep (1000); }Call.close (); } catch (Axisfault Axisfault) {axisfault.printstacktrace ();} catch (Exception ex) {ex.printstacktrace ();}

The Call.invokenonblocking () method returns immediately without blocking. Call.invokenonblocking () uses the Org.apache.axis2.clientapi.CallBack object, which is triggered if the response comes from the service. CallBack has two abstract methods OnComplete (Asynchresult) and ReportError (Exception), which need to be implemented by specific CallBack classes. The AXIS2 engine calls the OnComplete () method after the service call is completed properly. After getting the error message from the server, call Callback's ReportError () method. Callback.iscomplete () will indicate whether the operation call is complete.

Because the two methods above use a transport connection to send and receive messages, these methods are not suitable for long-running transactions. The reason is that the transport connection may time out before the response is available. To resolve this issue, you can use two different connections to send requests and receive responses, respectively. However, because other transport connections are used to obtain a response, the request and response need to be correlated. AXIS2 supports ws-addressing, which resolves this issue by using the <wsa:MessageID> and <wsa:RelatesTo> headers. Therefore, if you use two transports, you support addressing the module, as shown in the following two modes.

Blocking Dual Transfer Mode : This mode is useful in cases where the service operation is in-out in nature, but the transport used is unidirectional (such as SMTP) or the service execution takes a long time and the HTTP connection times out. See listing 6 below.

Listing 6. Blocking Dual Transfer Mode

						
try{
  endpointreference targetepr = new EndpointReference (
      "http://localhost:8080/axis2/services/ StockQuoteService ");
                
  Omfactory FAC = Omabstractfactory.getomfactory ();
  Omnamespace omns = Fac.createomnamespace (
      "Http://www.developerworks.com/example", "example");
  Omelement payload = fac.createomelement ("GetQuote", omns);
  Payload.settext ("IBM");
        
  Call call = new Call ();
    Call.setto (TARGETEPR);

    Call.settransportinfo (
      constants.transport_http, constants.transport_http, true);

    Blocking invocation
    omelement result = call.invokeblocking ("GetQuote", payload);
  System.out.println ("Quote =" +result.gettext ());
	
} catch (Axisfault axisfault) {
    axisfault.printstacktrace ();
} catch (Exception ex) {
    ex.printstacktrace ();
}

non-blocking dual transfer Mode : This mode provides maximum flexibility in terms of API level and transport level non-blocking, as shown in Listing 7 below.

Listing 7. Non-blocking dual transfer mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.