System.out.println("Completed!!!");
}
};
sender = new ServiceClient();
sender.setOptions(options);
System.out.println("-------Invoke the service---------");
sender.sendReceiveNonBlocking(requestSoapMessage, callback);
synchronized (callback) {
if (!finish) {
try {
callback.wait(1000);
} catch (Exception e) {
}
}
if (!finish) {
throw new AxisFault(
"Server was shutdown as the async response take too long to complete");
}
}
} catch (AxisFault e) {
e.printStackTrace();
} finally {
if (sender != null)
try {
sender.cleanup();
} catch (Exception e) {
}
}
}
public static void main(String[] args) {
orderRequest();
}
}
上述代码和前两天的客户端代码没啥区别,我已经把核心代码用红色给标粗了。
运行后行得到输出
客户端运行后的输出:
服务端的输出:
三、服务端将Exception以SOAPFault的形式抛给客户端
上面这个例子很简单,它展示了一个客户端向服务端发送一个request,服务端接收到客户端的Request(OMElement类型)后解析并根据相应的业务逻辑向客户端再返回一个response(OMElement类型)的完整过程。
下面我们要来看的是,如果客户端在调用服务器时发生任何错误,服务端如何把这个错误经过包装后再返回给客户端的例子。
还记得我们在非阻塞式客户端中有如下这样的触发器吗?
public void onMessage(MessageContext msgContext) {
}
public void onFault(MessageContext msgContext) {
}
public void onError(Exception e) {
}
public void onComplete() {
}
此处的onFault就是用于接受从服务端抛过来的Exception的,我们把它称为SOAPFault。
下面来看一个例子,先来看Service端
org.sky.axis2.soap.SoapFaultService
package org.sky.axis2.soap;
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.axiom.soap.SOAPFactory;
import org.apache.axiom.soap.SOAPFault;
import org.apache.axiom.soap.SOAPFaultCode;
import org.apache.axiom.soap.SOAPFaultReason;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
public class SoapFaultService {
private int i = 0;
public OMElement getPrice(OMElement request) throws AxisFault {
if (request == null) {
SOAPFault fault = getSOAPFault();
return fault;
}
OMFactory factory = OMAbstractFactory.getOMFactory();
OMNamespace ns = factory.createOMNamespace("", "");
OMElement response = factory.createOMElement("Price", ns);
response.setText(String.valueOf(i++));
return response;
}
private SOAPFault getSOAPFault() {
MessageContext context = MessageContext.getCurrentMessageContext();
SOAPFactory factory = null;
if (context.isSOAP11()) {
factory = OMAbstractFactory.getSOAP11Factory();
} else {
factory = OMAbstractFactory.getSOAP12Factory();
}
SOAPFault fault = factory.createSOAPFault();
SOAPFaultCode faultCode = factory.createSOAPFaultCode(fault);
faultCode.setText("13");
factory.createSOAPFaultValue(faultCode);
SOAPFaultReason faultReason = factory.createSOAPFaultReason(fault);
faultReason.setText("request can not be null");
factory.createSOAPFaultText(faultReason);
factory.createSOAPFaultDetail(fault);
return fault;
}
}
注意加粗部分的代码,由其是标成红色的代码为核心代码。
来看Service描述:
<service name="SoapFaultService">
<Des