`
elicer
  • 浏览: 131263 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Axis2 自定义 module 实现 handler 来log soap request and response Message

阅读更多
自定义Module
1.给module写一个单独的配置文件(module.xml),放在source 同目录下的META-INF 文件中
<module name="logging" class="com.bank.webservice.LoggingModule">
    <InFlow>
        <handler name="InFlowLogHandler" class="com.bank.webservice.LogHandler">
            <order phase="loggingPhase"/>
        </handler>
    </InFlow>
    <OutFlow>
        <handler name="OutFlowLogHandler" class="com.bank.webservice.LogHandler">
            <order phase="loggingPhase"/> 
        </handler>
    </OutFlow>

    <OutFaultFlow>
        <handler name="FaultOutFlowLogHandler" class="com.bank.webservice.LogHandler">
            <order phase="loggingPhase"/>
        </handler>
    </OutFaultFlow>
    <InFaultFlow>
        <handler name="FaultInFlowLogHandler" class="com.bank.webservice.LogHandler">
            <order phase="loggingPhase"/>
        </handler>
    </InFaultFlow>
</module>



2.实现你的自己的Module extends from org.apache.axis2.modules.Module
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.AxisDescription;
import org.apache.axis2.description.AxisModule;
import org.apache.axis2.modules.Module;
import org.apache.neethi.Assertion;
import org.apache.neethi.Policy;

public class LoggingModule implements Module
{
    // initialize the module
    public void init(ConfigurationContext configContext, AxisModule module)
            throws AxisFault
    {
        System.out.println("init");
    }
    public void engageNotify(AxisDescription axisDescription) throws AxisFault
    {
    }
    // shutdown the module
    public void shutdown(ConfigurationContext configurationContext)
            throws AxisFault
    {
        System.out.println("shutdown");
    }
    public String[] getPolicyNamespaces()
    {
        return null;
    }
    public void applyPolicy(Policy policy, AxisDescription axisDescription)
            throws AxisFault
    {
    }
    public boolean canSupportAssertion(Assertion assertion)
    {
        return true;
    }
}



3.实现你的handler记录SOAP request and response Message.
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;

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
    {
        //  向Tomcat控制台输出请求和响应SOAP消息
    	System.out.println("Soap Request" + msgContext.getEnvelope().toString());
        log.info(msgContext.getEnvelope().toString());
        return InvocationResponse.CONTINUE;
    }
    public void revoke(MessageContext msgContext)
    {
    	System.out.println("Soap Response" + msgContext.getEnvelope().toString());
        log.info(msgContext.getEnvelope().toString());
    }
    public void setName(String name)
    {
        this.name = name;
    }
}
[b]把以上module相关的东西用 "jar cvf logging.mar ." 打成一个mar的包。
注意一定要把module.xml放在跟source同目录的META-INF 文件中。然后把mar文件放在
tomcat下的webapp/axis2/WEB-INF/modules下。[/b]
[img]
d:/source.JPG
[/img]

Service Class的实现类
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.xmlbeans.xml.stream.XMLStreamException;

public class SampleService {

	public OMElement sayHello(OMElement element) {
		element.build();
		element.detach();

		String rootName = element.getLocalName();
		System.out.println("Reading " + rootName + " element");

		OMElement childElement = element.getFirstElement();
		String personToGreet = childElement.getText();

		OMFactory fac = OMAbstractFactory.getOMFactory();
		OMNamespace omNs = fac.createOMNamespace(
				"http://example1.org/example1", "example1");
		OMElement method = fac.createOMElement("sayHelloResponse", omNs);
		OMElement value = fac.createOMElement("greeting", omNs);
		value.addChild(fac.createOMText(value, "Hello," + personToGreet));
		method.addChild(value);

		return method;
	}

}


部署此service需要的services.xml
<service name="SampleService">
    <description>
        This is a sample service created in the Axis2 User's Guide
    </description>
    <module ref="logging"/>
    <parameter name="ServiceClass">com.bank.webservice.SampleService</parameter>
    <operation name="sayHello">
     <messageReceiver class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
     <actionMapping>urn:sayHello</actionMapping>
    </operation>
    <operation name="ping">
     <messageReceiver class="org.apache.axis2.receivers.RawXMLINOnlyMessageReceiver"/>
     <actionMapping>urn:ping</actionMapping>
    </operation>
</service>

注意<module ref="logging"/>配置来在此service中使用logging 这个module
用jar cvf 命令把此service打成一个aar包部署在tomcat 下的webapp/axis2/WEB-INF/services 文件下。

此外还要修改axis2.xml 加入我们的handler起作用的phase "loggingPhase"(红色配置).

    <phaseOrder type="InFlow">
        <!--  System predefined phases       -->
        <phase name="Transport">
            <handler name="RequestURIBasedDispatcher"
                     class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher">
                <order phase="Transport"/>
            </handler>
            <handler name="SOAPActionBasedDispatcher"
                     class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher">
                <order phase="Transport"/>
            </handler>
        </phase>
        <phase name="Addressing">
             <handler name="AddressingBasedDispatcher"
                     class="org.apache.axis2.dispatchers.AddressingBasedDispatcher">
                 <order phase="Addressing"/>
            </handler>
        </phase>
        <phase name="Security"/>
        <phase name="PreDispatch"/>
        <phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase">
            <handler name="RequestURIBasedDispatcher"
                     class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"/>
            <handler name="SOAPActionBasedDispatcher"
                     class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"/>
            <handler name="RequestURIOperationDispatcher"
                     class="org.apache.axis2.dispatchers.RequestURIOperationDispatcher"/>
            <handler name="SOAPMessageBodyBasedDispatcher"
                     class="org.apache.axis2.dispatchers.SOAPMessageBodyBasedDispatcher"/>
            <handler name="HTTPLocationBasedDispatcher"
                     class="org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher"/>
            <handler name="GenericProviderDispatcher"
                     class="org.apache.axis2.jaxws.dispatchers.GenericProviderDispatcher"/>
            <handler name="MustUnderstandValidationDispatcher"
                     class="org.apache.axis2.jaxws.dispatchers.MustUnderstandValidationDispatcher"/>
        </phase>
        <phase name="RMPhase"/>
        <!--  System predefined phases       -->
        <!--   After Postdispatch phase module author or service author can add any phase he want      -->
        <phase name="userDefinedMessageInPhase"/>
        <phase name="loggingPhase"/>
        <phase name="OperationInPhase">
            <handler name="MustUnderstandChecker"
                     class="org.apache.axis2.jaxws.dispatchers.MustUnderstandChecker">
                <order phase="OperationInPhase"/>
            </handler>
        </phase>
        <phase name="soapmonitorPhase"/>
    </phaseOrder>
    <phaseOrder type="OutFlow">
        <!--      user can add his own phases to this area  -->
        <phase name="userDefinedMessageOutPhase"/>
       <phase name="loggingPhase"/>
        <phase name="soapmonitorPhase"/>
        <phase name="OperationOutPhase"/>
        <!--system predefined phase-->
        <!--these phase will run irrespective of the service-->
        <phase name="RMPhase"/>
        <phase name="PolicyDetermination"/>
        <phase name="MessageOut"/>
        <phase name="Security"/>
    </phaseOrder>
    <phaseOrder type="InFaultFlow">
        <phase name="Addressing">
             <handler name="AddressingBasedDispatcher"
                     class="org.apache.axis2.dispatchers.AddressingBasedDispatcher">
                 <order phase="Addressing"/>
            </handler>
        </phase>
        <phase name="Security"/>
        <phase name="PreDispatch"/>
        <phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase">
            <handler name="RequestURIBasedDispatcher"
                     class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"/>
            <handler name="SOAPActionBasedDispatcher"
                     class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"/>
            <handler name="RequestURIOperationDispatcher"
                     class="org.apache.axis2.dispatchers.RequestURIOperationDispatcher"/>
            <handler name="SOAPMessageBodyBasedDispatcher"
                     class="org.apache.axis2.dispatchers.SOAPMessageBodyBasedDispatcher"/>
            <handler name="HTTPLocationBasedDispatcher"
                     class="org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher"/>
            <handler name="GenericProviderDispatcher"
                     class="org.apache.axis2.jaxws.dispatchers.GenericProviderDispatcher"/>
            <handler name="MustUnderstandValidationDispatcher"
                     class="org.apache.axis2.jaxws.dispatchers.MustUnderstandValidationDispatcher"/>
        </phase>
        <phase name="RMPhase"/>
        <!--      user can add his own phases to this area  -->
        <phase name="loggingPhase"/>
        <phase name="OperationInFaultPhase"/>
        <phase name="soapmonitorPhase"/>
    </phaseOrder>
    <phaseOrder type="OutFaultFlow">
        <!--      user can add his own phases to this area  -->
       <phase name="loggingPhase"/>
        <phase name="soapmonitorPhase"/>
        <phase name="OperationOutFaultPhase"/>
        <phase name="RMPhase"/>
        <phase name="PolicyDetermination"/>
        <phase name="MessageOut"/>
        <phase name="Security"/>
    </phaseOrder>

好大功告成。写一个call service的client 类
import javax.xml.stream.XMLStreamException;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.Constants;
import org.apache.axis2.client.ServiceClient;

public class SampleClient {

       private static EndpointReference targetEPR = 
             new EndpointReference(
               "http://localhost:8080/axis2/services/SampleService");

        public static OMElement greetUserPayload(String personToGreet) {
            OMFactory fac = OMAbstractFactory.getOMFactory();
            OMNamespace omNs = fac.createOMNamespace(
                    "http://example1.org/example1", "example1");
            OMElement method = fac.createOMElement("sayHello", omNs);
            OMElement value = fac.createOMElement("personToGreet", 
omNs);
            value.addChild(fac.createOMText(value, personToGreet));
            method.addChild(value);
            return method;
        }

        public static void main(String[] args) {
            try {
                OMElement payload = 
SampleClient.greetUserPayload("John");
                Options options = new Options();
                options.setTo(targetEPR);
                
options.setTransportInProtocol(Constants.TRANSPORT_HTTP);

                ServiceClient sender = new ServiceClient();
                sender.setOptions(options);
                OMElement result = sender.sendReceive(payload);

                String response = result.getFirstElement().getText();
                System.out.println(response);

            } catch (Exception e) { //(XMLStreamException e) {
                System.out.println(e.toString());
            }
        }
    
}



如果call完后你的log文件中出现了一下log证明我们的handler已经起作用了,记录了soap response and request message。 如果你想在别的service中使用这个module中的handler 只要在那个services.xml中引用logging这个module就ok了。

Soap Request[color=darkred][/color]<?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><example1:sayHello xmlns:example1="http://example1.org/example1"><example1:personToGreet>John</example1:personToGreet></example1:sayHello></soapenv:Body></soapenv:Envelope>
[INFO] <?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><example1:sayHello xmlns:example1="http://example1.org/example1"><example1:personToGreet>John</example1:personToGreet></example1:sayHello></soapenv:Body></soapenv:Envelope>
Reading sayHello element
Soap Response<?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><example1:sayHelloResponse xmlns:example1="http://example1.org/example1"><example1:greeting>Hello,John</example1:greeting></example1:sayHelloResponse></soapenv:Body></soapenv:Envelope>
[INFO] <?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><example1:sayHelloResponse xmlns:example1="http://example1.org/example1"><example1:greeting>Hello,John</example1:greeting></example1:sayHelloResponse></soapenv:Body></soapenv:Envelope>

经验总结,在许多情况下我们打出来的aar,跟mar 放在axis2的web-inf目录下,在axis在启动时会报aar中的services.xml 找不到,同样在mar中报module.xml找不到,在这种情况下,你直接把aar,或者mar解压开来放一个普通的文件夹中,直接把这个文件夹放到axis2的相应目录下,就ok了。

2
0
分享到:
评论
1 楼 ade921068180 2012-11-07  
我几乎按照你的配置完了,程序是自己写的,可以总是报下面的错:

[ERROR] The logging.mar module, which is not valid, caused server.Authentication
Handler cannot be cast to org.apache.axis2.modules.Module

org.apache.axis2.deployment.DeploymentException: server.AuthenticationHandler ca
nnot be cast to org.apache.axis2.modules.Module
        at org.apache.axis2.deployment.repository.util.ArchiveReader.readModuleA
rchive(ArchiveReader.java:531)
        at org.apache.axis2.deployment.ModuleDeployer.deploy(ModuleDeployer.java
:71)
        at org.apache.axis2.deployment.repository.util.DeploymentFileData.deploy
(DeploymentFileData.java:136)
        at org.apache.axis2.deployment.DeploymentEngine.doDeploy(DeploymentEngin
e.java:597)
        at org.apache.axis2.deployment.RepositoryListener.init(RepositoryListene
r.java:237)
        at org.apache.axis2.deployment.RepositoryListener.init2(RepositoryListen
er.java:68)
        at org.apache.axis2.deployment.RepositoryListener.<init>(RepositoryListe
ner.java:63)
        at org.apache.axis2.deployment.DeploymentEngine.loadRepository(Deploymen
tEngine.java:147)
        at org.apache.axis2.deployment.WarBasedAxisConfigurator.getAxisConfigura
tion(WarBasedAxisConfigurator.java:229)
        at org.apache.axis2.context.ConfigurationContextFactory.createConfigurat
ionContext(ConfigurationContextFactory.java:68)
        at org.apache.axis2.transport.http.AxisServlet.initConfigContext(AxisSer
vlet.java:516)
        at org.apache.axis2.transport.http.AxisServlet.init(AxisServlet.java:436
)
        at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.
java:1048)
        at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:95
0)
        at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContex
t.java:4074)
        at org.apache.catalina.core.StandardContext.start(StandardContext.java:4
379)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase
.java:791)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:77
1)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)

        at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.jav
a:920)
        at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.j
ava:883)
        at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492
)
        at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
        at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java
:311)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(Lifecycl
eSupport.java:117)
        at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)

        at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
        at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)

        at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443
)
        at org.apache.catalina.core.StandardService.start(StandardService.java:5
23)
        at org.apache.catalina.core.StandardServer.start(StandardServer.java:709
)
        at org.apache.catalina.startup.Catalina.start(Catalina.java:572)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
sorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: org.apache.axis2.deployment.DeploymentException: server.Authenticatio
nHandler cannot be cast to org.apache.axis2.modules.Module
        at org.apache.axis2.deployment.ModuleBuilder.populateModule(ModuleBuilde
r.java:221)
        at org.apache.axis2.deployment.repository.util.ArchiveReader.readModuleA
rchive(ArchiveReader.java:518)
        ... 37 more
Caused by: org.apache.axis2.deployment.DeploymentException: server.Authenticatio
nHandler cannot be cast to org.apache.axis2.modules.Module
        at org.apache.axis2.deployment.ModuleBuilder.loadModuleClass(ModuleBuild
er.java:84)
        at org.apache.axis2.deployment.ModuleBuilder.populateModule(ModuleBuilde
r.java:102)
        ... 38 more
Caused by: java.lang.ClassCastException: server.AuthenticationHandler cannot be
cast to org.apache.axis2.modules.Module
        at org.apache.axis2.deployment.ModuleBuilder$1.run(ModuleBuilder.java:74
)
        at org.apache.axis2.java.security.AccessController.doPrivileged(AccessCo
ntroller.java:132)
        at org.apache.axis2.deployment.ModuleBuilder.loadModuleClass(ModuleBuild
er.java:72)
        ... 39 more

这是为什么呀?

相关推荐

Global site tag (gtag.js) - Google Analytics