axis2 webservice学习笔记三

soap协议


1 客户端与服务端使用soap进行通信


示例代码:
service端:
/**
* 使用soap协议进行通信
*
* @time 下午7:40:34
* @author retacn yue
* @Email [email protected]
*/
public class SoapService {
public static OMElement requestSoap = null;


public OMElement request(OMElement soapBody) {
requestSoap = soapBody;


Iterator it = requestSoap.getChildElements();
OMElement issuerElement = (OMElement) it.next();
OMElement serialElement = (OMElement) it.next();
OMElement revocationDateElement = (OMElement) it.next();


String issuer = issuerElement.getText();
String serial = serialElement.getText();
String revocationDate = revocationDateElement.getText();


System.out.println("issuer=" + issuer + "\n serial=" + serial +


"revocationDate=" + revocationDate);


OMFactory factory = OMAbstractFactory.getOMFactory();
OMNamespace namespace = factory.createOMNamespace


("http://soapstyle.axis2service.yue.cn", "");
OMElement soapResponse = factory.createOMElement("SoapResponse",


namespace);


OMElement soaplssuer = factory.createOMElement("Issuer", namespace);
soaplssuer.setText("issuer:" + issuer);
soapResponse.addChild(soaplssuer);


OMElement soapSerial = factory.createOMElement("Serial", namespace);
soapSerial.setText("serial:" + serial);
soapResponse.addChild(soapSerial);


OMElement soapRevokeDate = factory.createOMElement("RevocationDate",


namespace);
soapRevokeDate.setText("RevocationDate" + revocationDate);
soapResponse.addChild(soapRevokeDate);


soapResponse.build();


return soapResponse;


}
}






<service name="SoapService" >
<description>
revoking certificate.
</description>

<parameter name="ServiceClass"


locked="false">cn.yue.axis2service.soapstyle.SoapService</parameter>
<operation name="request">
<messageReceiver
class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
<actionMapping>urn:request</actionMapping>
</operation>
</service>




客户端


/**
* soap协议通信客户端
*
* 非阻塞(异步)全双工
*
* @time 下午4:04:55
* @author retacn yue
* @Email [email protected]
*/
public class SoapServiceDualNonBlock {
private static EndpointReference endpointReference = new EndpointReference


("http://localhost:8089/services/SoapService");
private static boolean finish = false;


public void request() {
OMFactory factory = OMAbstractFactory.getOMFactory();
OMNamespace namespace = factory.createOMNamespace


("http://soapstyle.axis2service.yue.cn", "");


OMElement issuer = factory.createOMElement("Issuer", namespace);
OMElement serial = factory.createOMElement("Serial", namespace);
OMElement revocationDate = factory.createOMElement("RevocationDate",


namespace);


issuer.setText("yuezhenhua");
serial.setText("1234567");
revocationDate.setText("2012-11-21");


OMElement requestSoapMessage = factory.createOMElement("request",


namespace);
requestSoapMessage.addChild(issuer);
requestSoapMessage.addChild(serial);
requestSoapMessage.addChild(revocationDate);
requestSoapMessage.build();


Options options = new Options();
options.setTo(endpointReference);


ServiceClient sender = null;


try {
AxisCallback callback = new AxisCallback() {


@Override
public void onMessage(MessageContext msgContext) {
OMElement result = msgContext.getEnvelope


().getBody().getFirstElement();
System.out.println("result:" + result);
finish = true;
}


@Override
public void onFault(MessageContext msgContext) {
System.out.println("onFault=" +


msgContext.getEnvelope().getBody().getFault().toString());
}


@Override
public void onError(Exception e) {
e.printStackTrace();
}


@Override
public void onComplete() {
System.out.println("onComplete");
}
};
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 (InterruptedException e1) {
e1.printStackTrace();
}
}
if (!finish) {
throw new AxisFault("Server was shutdown as


the async response take too long to complete");
}
}
} catch (AxisFault e1) {
e1.printStackTrace();
} finally {
if (null != sender) {
try {
sender.cleanup();
} catch (AxisFault e) {
e.printStackTrace();
}
}
}


}


public static void main(String[] args) {
SoapServiceDualNonBlock client = new SoapServiceDualNonBlock();
client.request();
}


}


2 服务端将exception以soapFault的形式抛给客户端
/**
* 将exception以soapfault形式抛给客户端
*
* @time 下午9:00:52
* @author retacn yue
* @Email [email protected]
*/
public class SoapFaultService {


private int i = 0;


public OMElement getPrice(OMElement request) throws AxisFault {
if (null == request) {
SOAPFault fault = getSoapFault();
return fault;
}


OMFactory factory = OMAbstractFactory.getOMFactory();
OMNamespace namespace = factory.createOMNamespace


("http://soapstyle.axis2service.yue.cn", "");
OMElement response = factory.createOMElement("Price", namespace);
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 name="SoapFaultService" >
<description>
revoking certificate.
</description>

<parameter name="ServiceClass"


locked="false">cn.yue.axis2service.soapstyle.SoapFaultService</parameter>
<operation name="getPrice">
<messageReceiver
class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
<actionMapping>urn:getPrice</actionMapping>
</operation>
</service>


客户端
/**
* 客户端接收从服务器端传来的以soapfault形式的exception
*
* 非阻塞(异步)全双工
*
* @time 下午4:04:55
* @author retacn yue
* @Email [email protected]
*/
public class SoapFaultServiceDualNonBlock {
private static EndpointReference endpointReference = new EndpointReference


("http://localhost:8089/services/SoapFaultService");
private static boolean finish = false;
ServiceClient sender = null;


public void getPrice() {


try {
OMFactory factory = OMAbstractFactory.getOMFactory();
OMNamespace namespace = factory.createOMNamespace


("http://soapstyle.axis2service.yue.cn", "");


// OMElement request = factory.createOMElement("Price",


namespace);
Options options = new Options();
options.setTo(endpointReference);
options.setAction("urn:getPrice");
options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
options.setUseSeparateListener(true);


AxisCallback callback = new AxisCallback() {


@Override
public void onMessage(MessageContext msgContext) {
OMElement result = msgContext.getEnvelope


().getBody().getFirstElement();
System.out.println("price:" + result);
finish = true;
}


// 用于接收服务端抛过来的exception
@Override
public void onFault(MessageContext msgContext) {
QName errorCode = new QName("faultcode");
QName reason = new QName("faultString");
OMElement faultElement =


msgContext.getEnvelope().getBody().getFault();
System.out.println("ErrorCode[" +


faultElement.getFirstChildWithName(errorCode).getText() + "] caused by:" +


faultElement.getFirstChildWithName(reason).getText());
}


@Override
public void onError(Exception e) {
e.printStackTrace();
}


@Override
public void onComplete() {
System.out.println("onComplete");
}
};
sender = new ServiceClient();
sender.setOptions(options);
sender.engageModule("addressing");
try {
sender.sendReceiveNonBlocking(null, callback);
} catch (Exception e2) {
e2.printStackTrace();
System.out.println(e2.getMessage());
}
synchronized (callback) {
if (!finish) {
try {
callback.wait(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
} catch (AxisFault e) {
e.printStackTrace();
} finally {
try {
sender.cleanup();
} catch (AxisFault e) {
e.printStackTrace();
}
}


}


public static void main(String[] args) {
SoapFaultServiceDualNonBlock client = new


SoapFaultServiceDualNonBlock();
client.getPrice();
}


}




3 使用swa(soap with attachment)来进行附件的传送


axis2有两种附件传输形式
mtom
swa soap with attachment
客户端把要上传的文件,转成二进制码由soap的request一起发送到服务器端(attchmentID)


/**
* 接收客户端上传文件
*
* @time 下午7:47:34
* @author retacn yue
* @Email [email protected]
*/
public class FileUploadService {
public String uploadFile(String name, String attchmentID) {
FileOutputStream fileOutputStream = null;
StringBuffer uploadFilePath = new StringBuffer();
String fileNamePrefix = "";
String fileName = "";


try {
MessageContext context =


MessageContext.getCurrentMessageContext();
Attachments attachments = context.getAttachmentMap();
DataHandler dataHandler = attachments.getDataHandler


(attchmentID);


fileNamePrefix = name.substring(name.indexOf("."),


name.length());
fileName = "11";
System.out.println("fileName:" + fileName);
System.out.println("fileNamePrefix:" + fileNamePrefix);


uploadFilePath.append("d:/");
uploadFilePath.append(fileName);
uploadFilePath.append(fileNamePrefix);
System.out.println("uploadFilePath:" + uploadFilePath);


File file = new File(uploadFilePath.toString());
fileOutputStream = new FileOutputStream(file);
dataHandler.writeTo(fileOutputStream);
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != fileOutputStream) {
fileOutputStream.close();
}
fileOutputStream = null;
} catch (IOException e) {
e.printStackTrace();
}
}


return "success";
}
}




<service name="FileUploadService" >
<parameter name="ServiceClass"


locked="false">cn.yue.axis2service.fileupload.FileUploadService</parameter>
<operation name="uploadFile">
<messageReceiver
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
<actionMapping>urn:uploadFile</actionMapping>
</operation>
</service>




客户端


/**
* 上传文件
*
* @time 下午8:07:05
* @author retacn yue
* @Email [email protected]
*/
public class FileUploadClient {
private static EndpointReference reference = new EndpointReference


("http://localhost:8089/services/FileUploadService");


public void uploadFile() {


try {
String filePath = "d:/AppCan/xizan.jpg";
String destFile = "xizan.jpg";


Options options = new Options();
options.setTo(reference);
options.setProperty(Constants.Configuration.ENABLE_SWA,


Constants.VALUE_TRUE);
options.setSoapVersionURI


(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
options.setTimeOutInMilliSeconds(10000);
options.setAction("urn:uploadFile");


ConfigurationContext context =


ConfigurationContextFactory.createConfigurationContextFromFileSystem


("D:/workspace4/axis2webservice/WebContent/WEB-INF/modules", null);
ServiceClient sender = new ServiceClient(context, null);
OperationClient mepClient = sender.createClient


(ServiceClient.ANON_OUT_IN_OP);
MessageContext messageContext = new MessageContext();
FileDataSource fileDataSource = new FileDataSource(new File


(filePath));


DataHandler handler = new DataHandler(fileDataSource);
String attachmentID = messageContext.addAttachment(handler);


SOAPFactory factory = OMAbstractFactory.getSOAP11Factory();
SOAPEnvelope envelope = factory.getDefaultEnvelope();
OMNamespace namespace = factory.createOMNamespace


("http://fileupload.axis2service.yue.cn", "");
OMElement uploadFile = factory.createOMElement("uploadFile",


namespace);
OMElement nameEle = factory.createOMElement("name",


namespace);
nameEle.setText(destFile);


OMElement idEle = factory.createOMElement("attchmentID",


namespace);
idEle.setText(attachmentID);
uploadFile.addChild(nameEle);
uploadFile.addChild(idEle);
envelope.getBody().addChild(uploadFile);


System.out.println("message==" + envelope);
messageContext.setEnvelope(envelope);


mepClient.addMessageContext(messageContext);
mepClient.execute(true);
MessageContext response = mepClient.getMessageContext


(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
SOAPBody body = response.getEnvelope().getBody();
OMElement element = body.getFirstChildWithName(new QName


("http://fileupload.axis2service.yue.cn", "return"));


System.out.println(element.getText());


} catch (AxisFault e) {
e.printStackTrace();
}


}


public static void main(String[] args) {
FileUploadClient client = new FileUploadClient();
client.uploadFile();
}
}

猜你喜欢

转载自retacn-yue.iteye.com/blog/1735619