精彩的人生

好好工作,好好生活

BlogJava 首页 新随笔 联系 聚合 管理
  147 Posts :: 0 Stories :: 250 Comments :: 0 Trackbacks

作者:李红霞
时间:2006-10-19

声明:本文可以算作Axis2用户手册的翻译,但是翻译后的文本是经过作者理解写出来的,可能有些偏差,欢迎讨论。本文属作者原创,允许转载,但请注明出处。

英文原文http://ws.apache.org/axis2/1_0/userguide.html

 


概述
这个说明文档涉及以下内容:

Ø    如何使用 axis2 创建 web service 和客户端程序

Ø    如何定制一个模块 (Module) 并在 web service 中使用它

Ø    Samples discussion

Ø    Advanced Topics

 

第一部分:简介

 

Axis2 是重新设计的一个架构,它没有基于 Axis1.* 的结构,这种新的架构 much more flexible, efficient and configurable

 

Axis2 的特性有:

Speed                                                采用自己的对象模型,利用 StAX 解析

Low memory foot print                    Axis2 在设计过程中一直遵循 low memory cost 的理念

AXIOM                                             采用自己的轻量级的对象模型,使得消息处理过程可扩展、性能高,对开发者来说更加简单。

Hot Deployment                              Axis2 装备了在系统运行时部署服务和处理器的能力。也就是说,新的服务新服务的添加不再需要重启服务器。将服务的发布包放在服务部属文件夹中,部署模型将自动部署该服务。

Asynchronous Web Services          Axis2 现在可以通过 non-blocking clients and transports 支持异步的服务和异步的服务调用。(?什么是异步的服务 ?

MEP Support                                   Axis2 具备良好的伸缩性来支持 MEPs ,因为它内置了对 WSDL2.0 MEPs 的支持。

Flexibility                                          Axis2 的架构使得程序员能自由的对 Axis 添加扩展,这些扩展包括对自定义 Header 的处理,系统管理,甚至是任何一件你可以想象的到的事情

Stability                                             Axis2 定义了一套公共接口,这些接口相对于其他代码而言改动很小

Component-oriented Deployment    你可以自定义一些在处理过程中常用的可重用的处理器,并可以将这些处理器发布出来供其它人使用

Transport Framework                       定义了一个干净、简单的抽象作品来集成任意的传输协议,引擎的核心部分的实现是与传输协议无关的

Add-ons                                               一些 web service 相关的协议也合并了进来。如安全方面的 WSS4J(Rampart), 可靠消息传输的 Sandesha ,封装了 WS-Coordination, WS-AtomicTransaction WS-BusinessActivity Kandula

Composition and Extensibility          模块和层支持可扩展性和可组合性( composability )。模块支持可组合性,对添加新的 web service 规范的支持的方式非常简单和干净。但是他们并不是热部署的,因为他们影响整个系统的功能。

 

Tips:

WSS4J: http://ws.apache.org/wss4j/

Apache WSS4J is an implementation of the OASIS Web Services Security (WS-Security) from OASIS Web Services Security TC. WSS4J is a primarily a Java library that can be used to sign and verify SOAP Messages with WS-Security information. WSS4J will use Apache Axis and Apache XML-Security projects and will be interoperable with JAX-RPC based server/clients and .NET server/clients.

这个项目提供了在 Axis 上部署的帮助文档和例子

Rampart

这是 Axis2 的一个 Module (现在 Axis2 有两个可选的 Module ,分别是 Addressing Security Addressing 包含在 Standard 版本中,但是 Rampart 需要单独下载),目前作用不详,猜测是与 WSS4J 合作完成 WS-Security

Sendesha: http://ws.apache.org/sandesha/

Sandesha2 is an implementation of WS-ReliableMessaging specification published by IBM, Microsoft, BEA and TIBCO. Sandesha2 was built on top of Axis2. Therefore by using Sandesha2 you can add reliable messaging capability to the web services hosted using Axis2. Sandesha2 can also be used with Axis2 client to interact with already hosted web services in a reliable manner. Please see sandesha2 user guide for more information on using Sandesha2.

Kandula: http://ws.apache.org/kandula/2/index.html

Kandula will provide an open-source implementation of WS-Coordination, WS-AtomicTransaction and WS-BusinessActivity based on Axis. The initial implementation will be in Java using Axis/Java. In addition to providing an implementation, a major focus of this project would be to ensure interoperability with other implementations of above specifications, particularly those by Microsoft (.NET) and IBM.

 

第二部分:使用 Axis2 开发 web services


首先你需要在
Servlet 容器中部署 axis2.war

 

可以通过两种方式来创建 web services

 

1.       使用 Axis2 API ,实现业务代码

2.       WSDL 开始,生成代码框架,然后实现业务逻辑

 

1 )使用 Axis2 API

首先,计划生成一个服务 MyService ,它有两个方法:

public void ping(OMElement element){} //IN-ONLY operation, just accepts the OMElement and do some processing.

public OMElement echo(OMElement element){}//IN-OUT operation, accepts an OMElement and 

                                          // sends back the same again

从例子里找到实现的代码: "Axis2Home/samples/userguide/src" 中的 "userguide/example1"

 

创建一个服务分 4 个步骤

a.       编写实现代码

b.       service.xml 来解释这个服务

c.       创建一个 *.aar 的服务部署包

d.       发布服务

 

Step 1: 实现代码

public class MyService{

    public void ping(OMElement element){

     ......

    }

    public OMElement echo(OMElement element){

     ......

    }

}

 

Step 2: 通过 service.xml 来描述服务

<service >

    <description>

        This is a sample Web Service with two operations, echo and ping.

    </description>

    <parameter name="ServiceClass" locked="false">userguide.example1.MyService</parameter>

    <operation name="echo">

        <messageReceiver class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>

        <actionMapping>urn:echo</actionMapping>

    </operation>

     <operation name="ping">

        <messageReceiver class="org.apache.axis2.receivers.RawXMLINOnlyMessageReceiver"/>

        <actionMapping>urn:ping</actionMapping>

    </operation>

 </service>

 

说明: For the "echo" operation we have used a RawXMLINOutMessageReceiver since it is an IN-OUT operation. For IN-ONLY operation "ping", we have used RawXMLINOnlyMessageReceiver as the message receiver.

The actionMapping is required only if you want to enable WS-Addressing.

 

还可以用这个文件来描述一组服务,这组服务之间可以共享 ServiceGroupContext

<serviceGroup>

  <service name="Service1">

    <!-- details for Service1 -->

  </service>

  <service name="Service2">

    <!-- details for Service2 -->

  </service>

  <module ref="ModuleName" />

  <parameter name="serviceGroupParam1" locked="false">value 1</parameter>

</serviceGroup>

 

 

Step 3: 创建服务发布包

这个服务发布包的结构如图所示。将这些文件按照图中的结构组织好,然后打包成 jar 或者 rar ,然后修改后缀名为 aar 即可。

 

Step 4: 部属服务

将服务发布包放到 "\webapps\axis2\WEB-INF" 中的 "services" 文件夹下,然后在 Axis2 的首页 (http://localhost:8080/axis2/index.jsp) ’services’ 连接下察看服务发布情况

 

 

 

2 )用服务代码生成的方式创建服务

首先要写好服务的 wsdl

 

然后利用 WSDL2Java 工具

该工具的命令有:

Usage WSDL2Code -uri <Location of WSDL> : WSDL file location

-o <output Location> : output file location

-a : Generate async style code only. Default is off

-s : Generate sync style code only. Default is off. takes precedence over -a

-p <package name> : set custom package name

-l <language> : valid languages are java and csharp. Default is java

-t : Generate TestCase to test the generated code

-ss : Generate server side code (i.e. skeletons). Default is off

-sd : Generate service descriptor (i.e. services.xml). Default is off. Valid with -ss

-d <databinding> : valid databinding(s) are adb, xmlbeans and jaxme. Default is adb

-g Generates all the classes. valid only with the -ss

-pn <port_name> : name of port in the presence of multiple ports

-sn <service_name> : name of service in the presence of multiple services

-u : unpacks the databinding classes

-r <repository_path> : path of the repository against which code is generated

 

windows 平台下可以用

WSDL2Java -uri ..\samples\wsdl\Axis2SampleDocLit.wsdl -ss -sd -d xmlbeans -o ..\samples -p org.apache.axis2.userguide

 

Linux 平台下可以用

WSDL2Java -uri ../samples/wsdl/Axis2SampleDocLit.wsdl -ss -sd -d xmlbeans -o ../samples -p org.apache.axis2.userguide

于是生成了服务的代码框架,在代码框架中填入代码

 

第三部分:用 Axis2 创建服务客户端


服务可以完成各种各样的功能,有的简单,时间消费比较低,有的复杂,时间消费比较高。我们不能采用一个统一的机制来调用这些时间消费区别很大的服务。例如:我们用
HTTP 协议来带调用一个 IN-OUT 类型的服务,而这个服务的执行时间很长,于是我们可能得到一个 connection time out 的结果。而且,在一个客户端同时发出两个服务调用请求的情况下,使用 ’blocking’ 的客户端 API 将降低客户端程序的性能。类似的,当我们使用 One-Way 传输的时候还可能有很多其他的后果产生。

 

Blocking API:            当服务调用请求发出后,客户端等待服务结果的返回,这期间不能再发出服务调用请求。

Non-Blocking API:    这是一个基于 callback 或者 polling API ,让客户端发出服务调用请求的时候,客户端程序立刻得到控制权,服务的调用结果由 callback 对象来接收。这样,客户端就可以同时调用多个服务而不进行阻止。

 

Axis 将利用 Non-Blocking API 方式的异步叫做 API Level Asynchrony

 

前面提到的两个机制在 Request Response 上使用了一个的传输连接,他们限制了服务调用在请求与结果返回使用两个传输连接的情况 ( either One-Way or Two-Way ) 。所以这两种机制都无法解决在长时间运行的事务中的寻址问题(传输连接可能在操作结束前就已经 timeout 了)。一种解决方案是在 request response 中使用两个不同的传输连接。

 

在这个级别上得到的异步属性,称为 Transport Level Asynchrony

 

将前面的 2 种异步结合起来,就有了四种不同的调用模式

API (Blocking/Non-Blocking)

 Dual Transports (Yes/No)

Description

Blocking

No

Simplest and the familiar invocation pattern

Non-Blocking

No

Using callbacks or polling

Blocking

Yes

This is useful when the service operation is IN-OUT in nature but the transport used is One-Way (e.g. SMTP)

Non-Blocking

Yes

This is can be used to gain the maximum asynchronous behavior. No blocking in the API level and also in the transport level

 

服务的调用代码:

blocking invocation

try {

OMElement payload = ClientUtil.getEchoOMElement();

Options options = new Options();

options.setTo(targetEPR); // this sets the location of MyService service

ServiceClient serviceClient = new ServiceClient();

serviceClient.setOptions(options);

OMElement result = sender.sendReceive(payload);

System.out.println(result);

} catch (AxisFault axisFault) {

axisFault.printStackTrace();

}

 

IN-ONLY

try {

OMElement payload = ClientUtil.getPingOMElement();

Options options = new Options();

options.setTo(targetEPR);

ServiceClient serviceClient = new ServiceClient();

serviceClient.setOptions(options);

serviceClient.fireAndForget(payload);

/**We have to block this thread untill we send the request , the problemis if we go out of the

*main thread , then request wont send ,so you have to wait some time :) */

Thread.sleep(500);

} catch (AxisFault axisFault) {

axisFault.printStackTrace();

}

 

You can test this client by running the target "testPingClient" of the ant build file at "Axis2Home/samples/userguide".

 

EchoBlockingClient

将第一段代码的调用代码改为 serviceClient.sendReceiveNonblocking(payload, callback);

具体的例子在 "Axis2Home/samples/userguide/src/userguide/clients"

Axis 提供三个方法来接收 callback 对象

public abstract void onComplete(AsyncResult result);

public abstract void onError(Exception e);

public boolean isComplete() {}

其中,前面两个是需要用户来实现的

 

EchoNonBlockingDualClient

try {

OMElement payload = ClientUtil.getEchoOMElement();

Options options = new Options();

options.setTo(targetEPR);

options.setTransportInProtocol(Constants.TRANSPORT_HTTP);

options.setUseSeparateListener(true);

options.setAction("urn:echo");  // this is the action mapping we put within the service.xml

//Callback to handle the response

Callback callback = new Callback() {

public void onComplete(AsyncResult result) {

System.out.println(result.getResponseEnvelope());

}

public void onError(Exception e) {

e.printStackTrace();

}

};

//Non-Blocking Invocation

sender = new ServiceClient();

sender.engageModule(new QName(Constants.MODULE_ADDRESSING));

sender.setOptions(options);

sender.sendReceiveNonBlocking(payload, callback);

//Wait till the callback receives the response.

while (!callback.isComplete()) {

Thread.sleep(1000);

}

//Need to close the Client Side Listener.

} catch (AxisFault axisFault) {

axisFault.printStackTrace();

} catch (Exception ex) {

ex.printStackTrace();

} finally {

try {

sender.finalizeInvoke();

} catch (AxisFault axisFault) {

//have to ignore this

}

}

 

Server 端添加 Addressing 支持的方式是,在 Addressing Module 中,将 Handlers 的描述放在 ”pre-dispatch” 语句中,那么它的加载则需要通过在 "/webapps/axis2/WEB-INF" 文件夹下的 axis2.xml 中增加一句话来完成: <module ref="addressing"/>

 

客户端支持 Addressing 的方式,一种是将 addressing-<version>.mar 放在 classpath 中,另一种就是根据给定的库位置创建一个 ConfigurationContext

具体的做法是在 sender = new ServiceClient(); 之前加上

ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(< Axis2RepositoryLocation >, null);

然后将 "sender = new ServiceClient();" 改为 "sender = new ServiceClient(configContext, null);"

 

EchoBlockingDualClient

示例代码可以在 "Axis2Home/samples/userguide/src/userguide/clients/" 中找到,它与 EchoNonBlockingDualClient 相似,在这种情况下不再需要 callback 来处理 response 。这个机制非常适用于处理 IN-OUT 类型的调用,而传输协议却是 One-Way(SMTP) 的情况。我们可以用 "Axis2Home/samples/userguide" 中的 "echoBlockingDualClient" 来测试

 

第四部分: Module

构造和部署 Module 分为以下几个步骤:

a.       创建 Module 的实现

b.       创建 Handlers

c.       创建 module.xml

d.       修改 axis2.xml (如果你需要定制的语句)

e.       修改 services.xml Axis 部署的时候使用这些 Modules

f.        Axis2 中部署这些 Modules

 

现在来创建一个简单的 Logging Module ,这个 Module 包含一个 Hander ,它的作用就是纪录通过它的消息。 Axis 通过 *.mar 来部署 Modules ,下图就是这个部署包的结构


Step 1:
创建 LoggingModule Class

Logging Module Axis2 Module 的实现,它必须实现 org.apache.axis2.modules.Module 接口:

 

Step 2: 创建 LogHandler

Axis 的一个 Module 可以包含一个或者多个 Handler 。这些 Handler 将处理 Soap 头文件中的不同 phases 。一个 Handler 必须实现 org.apache.axis2.engine.Handler 接口,或者通过另一种简单方式,继承 org.apache.axis2.handlers.AbstractHandler

public class LogHandler extends AbstractHandler implements Handler {

private Log log = LogFactory.getLog(getClass());

    private QName name;

public QName getName() {

        return name;

    }

    public void invoke(MessageContext msgContext) throws AxisFault {

        log.info(msgContext.getEnvelope().toString());

    }

    public void setName(QName name) {

        this.name = name;

    }

}

 

Step 3: module.xml

这个文件包含了一个特定 Module 的部署配置。

<module name="logging" class="userguide.loggingmodule.LoggingModule ">

   <inflow>

        <handler name="InFlowLogHandler" class="userguide.loggingmodule.LogHandler">

        <order phase="loggingPhase" />

        </handler>

   </inflow>

   <outflow>

        <handler name="OutFlowLogHandler" class="userguide.loggingmodule.LogHandler">

        <order phase="loggingPhase"/>

        </handler>

   </outflow>

   <Outfaultflow>

        <handler name="FaultOutFlowLogHandler" class="userguide.loggingmodule.LogHandler">

        <order phase="loggingPhase"/>

        </handler>

   </Outfaultflow>

   <INfaultflow>

        <handler name="FaultInFlowLogHandler" class="userguide.loggingmodule.LogHandler">

        <order phase="loggingPhase"/>

        </handler>

   </INfaultflow>

</module>

 

a.       inflow - Represents the handler chain that will run when a message is coming in.

b.       outflow - Represents the handler chain that will run when the message is going out.

c.       Outfaultflow - Represents the handler chain that will run when there is a fault and the fault is going out

d.       INfaultflow - Represents the handler chain that will run when there is a fault and the fault is coming in

 

"<order phase="loggingPhase" />" describes the phase in which this handler runs.

 

Step 4: 修改 axis2.xml

在前面用的 ”loggingPhase” 不是一个 pre-defined handler phase ,因此, module 的创建者需要将它介绍给 axis2.xml 于是 Axis 引擎就可以知道在不同的 ’flow’ 中如何放那些 handlers

这些增加是在 axis2.xml Phases 部分,在标志了 <!--      user can add his own phases to this area  --> 之后加入 <phase name=" loggingPhase"/>

这样,这个 phase 将在引擎的任何消息流中调用

 

Step 5: 修改 service.xml

到目前为止, logging module 已经做好了,现在需要在服务中使用这个 module ,那么就要修改服务的 service.xml 。在该文件中加上了 "<module ref="logging"/>"

 

Step 6: 打包

将这个包打成 jar 或者 rar ,然后改后缀名为 mar

 

Step 7: Axis2 中部署这个 Module

首先要在 "webapps/axis2/WEB-INF" 目录下创建一个 modules 文件夹,然后将 *.mar 文件放在这个文件夹中,然后重启 Axis 并运行服务进行测试

 

第五部分:其他的例子

Google Spell Checker, Google Search, Amazon Queuing Service 的例子

 

posted on 2006-10-23 16:46 hopeshared 阅读(7822) 评论(9)  编辑  收藏 所属分类: Web Service

Feedback

# re: 读Axis2用户帮助文档 2006-10-24 10:54 冰川
恩,很好的资料。
严重支持!!!  回复  更多评论
  

# re: 读Axis2用户帮助文档 2006-11-11 14:04 shrimplucky
不错,我做到第四步了,还在自己的机器上类似作了标记
问一个问题,我现在想打开例子中给的logging.mar文件,可是在我机器上显示的是mar文件属于 microsoft office access report shortcut ,怎么将其变成是压缩文件使用 类似winrar的文件打开啊,谢谢  回复  更多评论
  

# re: 读Axis2用户帮助文档 2006-11-11 14:05 shrimplucky
我的联系方式
xxwan@njupt.edu.cn  回复  更多评论
  

# re: 读Axis2用户帮助文档 2006-11-18 20:00 neusoft
异步双通道始终不成功!
你试过了么?  回复  更多评论
  

# re: 读Axis2用户帮助文档 2006-11-20 13:24 万里
axis1可以实现对ws-addressig吗   回复  更多评论
  

# re: 读Axis2用户帮助文档 2006-12-01 17:17 Goingmm
Step 4: 修改 axis2.xml
--> 加入<phase name=" loggingPhase"/> // 如果你决定Ctrl+C这里, 注意去掉名称( loggingPhase)前面的空格



  回复  更多评论
  

# re: 读Axis2用户帮助文档[未登录] 2007-08-07 20:55 andrew
可以加载spring吗?
我有一个工厂类,调用spring  回复  更多评论
  

# re: 读Axis2用户帮助文档 2008-08-01 01:03 Charles.
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.engine.Handler;
import org.apache.axis2.handlers.AbstractHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.xml.namespace.QName;

public class LogHandler extends AbstractHandler implements Handler {
private static final Log log = LogFactory.getLog(LogHandler.class);
private String name;

public String getName() {
return name;
}

public InvocationResponse invoke(MessageContext msgContext) throws AxisFault {
log.info(msgContext.getEnvelope().toString());
return InvocationResponse.CONTINUE;
}

public void revoke(MessageContext msgContext) {
log.info(msgContext.getEnvelope().toString());
}

public void setName(String name) {
this.name = name;
}

}

他的这个类写错了,,,并且是从sample里面拷贝的,这么不负责任呀,!!!!!!!!  回复  更多评论
  

# re: 读Axis2用户帮助文档 2008-08-01 01:07 Charles.
本人正从事,Axis2 Based Project ,from America.

我发现需要重新写一个扩展的Handler,因为我们的soap协议是客户自己定制开发的,

有兴趣的,并且对Axis2有深度研究的,同行,欢迎交流。

#changhongzuo##126.com#

将#换成邮件符号  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: