⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 structmo.java

📁 中国联通短信通信协议
💻 JAVA
字号:
package com.wireless.sms.unsoap.workthread;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.wireless.sms.gwif.smsagent.global.GetMoMtGlobalForUsual;
import com.wireless.sms.gwif.smsagent.global.LoggerConstant;
import com.wireless.sms.pub.entity.MO;
import com.wireless.sms.pub.entity.Stat;
import com.wireless.sms.pub.mq.MOQueue;
import com.wireless.sms.pub.mq.ObjectQueue;
import com.wireless.sms.unsoap.global.Constant;

public class StructMO {
	//DeliveryStatus
	public static final String _DeliveredToNetwork = "DeliveredToNetwork";
	public static final String _DeliveryUncertain = "DeliveryUncertain";
	public static final String _DeliveryImpossible = "DeliveryImpossible";
	public static final String _MessageWaiting = "MessageWaiting";
	public static final String _DeliveredToTerminal = "DeliveredToTerminal";
	public static final String _DeliveryNotificationNotSupported = "DeliveryNotificationNotSupported";
	//notify type
	public static final String _notifySmsReception = "notifySmsReception";
	public static final String _notifySmsDeliveryStatus = "notifySmsDeliveryStatus";
	public static final String _ServiceException = "ServiceException";
	public static final String _PolicyException = "PolicyException";
	
	protected MOQueue moqueue = GetMoMtGlobalForUsual.moqueue;
    protected ObjectQueue objqueue = ObjectQueue.getInstance();
    
    private Logger molog = LoggerConstant.mo_log;
    
    //NotifySOAPHeader
	String spRevId = "";//SP反向调用名,可选 
	String spRevpassword = "";//SP反向调用密码,可选 
	String spId = "";//SP
	String spNumber = "";//分析判断应该就是文档中的SPNumber
	String serviceId = "";//业务ID
	String sessionId = "";//业务流水号,用于组合业务。可选
	String linkId = "";//事务关联ID,用于点播业务的事务关联,由平台产生。格式为:MMDDHHMMSS+10

	public StructMO(){
		
	}
	
	/**
	 * 处理过程:从webService接收到的SOAP信封只有两种格式,一个是notifySmsDeliveryReceipt--Stat,
	 * 另一个是notifySmsReception--MO,前者传送的是MT下发的状态,后者传送的是用户上行MO;同时这两种SOAP信封具有相同的SOAP Header,
	 * 只是在SOAP Body有不同之处,所以可以通过分别解析的方式过滤出MO或Stat.
	 * @param xml
	 * @return
	 */
	public String process(byte[] xml){
		Document doc = null;
		Element root = null;
		Element notifySOAPBodyChild = null;
		String soapBodyChild_name = "";
		String response = "";
		try {
			SAXReader saxReader = new SAXReader();
			doc = saxReader.read(new ByteArrayInputStream(xml));
			root = doc.getRootElement();
			String soapHeaderChild_name;
			try {
				soapHeaderChild_name = ((Element) root.element("Header")
						.elements().get(0)).getName().trim();
				soapBodyChild_name = ((Element) root.element("Body").elements()
						.get(0)).getName().trim();
			} catch (java.lang.NullPointerException e) {
				return this.faultString("error SOAPFormat(None Body or None Header)");
			}			
			Element notifySOAPHeader = root.element("Header").element(soapHeaderChild_name);//"NotifySOAPHeader");
			notifySOAPBodyChild = root.element("Body").element(soapBodyChild_name);
			if(!"NotifySOAPHeader".equalsIgnoreCase(soapHeaderChild_name)){
				molog.info("notifySOAPHeader is null!");
//				return this.faultString("notifySOAPHeader is null!");
			}
			//parse soapHeader
			spRevId = notifySOAPHeader.elementTextTrim("spRevId");
			spRevpassword = notifySOAPHeader.elementTextTrim("spRevpassword");
			spId = notifySOAPHeader.elementTextTrim("spId");
			spNumber = notifySOAPHeader.elementTextTrim("SPNumber");
			serviceId = notifySOAPHeader.elementTextTrim("serviceId");
			sessionId = notifySOAPHeader.elementTextTrim("sessionId");
			linkId = notifySOAPHeader.elementTextTrim("linkId");
			//parse soapBody
			if(notifySOAPBodyChild == null){
				molog.info("notifySOAPBodyChild is null!");
				return this.faultString("notifySOAPBody's Child is null!");
			}else if(_notifySmsReception.equalsIgnoreCase(soapBodyChild_name)){//mo
				this.parseMO(notifySOAPBodyChild);
			}else if(_notifySmsDeliveryStatus.equalsIgnoreCase(soapBodyChild_name)){//stat
				this.parseStat(notifySOAPBodyChild);
			}else if("sendSms".equalsIgnoreCase(soapBodyChild_name)){//测试用,测试接受MT信息
				String message = notifySOAPBodyChild.elementTextTrim("message");
				molog.info("message = " + message);
				try{
					molog.info("message(Trans) = " + this.charTransform(message));
				}catch(Exception e){
					e.printStackTrace();
				}
			}else{
				molog.info("unacquainted soapBodyChild_name = " + soapBodyChild_name);
			}
						
		} catch (DocumentException e) {
			molog.error("DocumentException:",e);
//			e.printStackTrace();
			return this.faultString("XML document structures must start and end within the same entity");
//			org.apache.commons.httpclient.HttpException
		} finally{
//			struct response
			if (root != null) {
				root.remove(root.element("Header"));
				if (notifySOAPBodyChild != null) {
					root.element("Body").remove(notifySOAPBodyChild);
					root.element("Body").addElement(
							soapBodyChild_name + "Response");
					/////TEST CODE below
//					root.element("Body").element(soapBodyChild_name + "Response").addText("");
//					root.element("Body").element(soapBodyChild_name + "Response")
//						.addElement("result");
//					root.element("Body").element(soapBodyChild_name + "Response").element("result").addText("123456");
				}

				response = new String(doc.asXML().replaceAll("\n", ""));
			}
		}
		return response;
	}
	
	/**notifySmsReception MO SOAP数据包*/
	public void parseMO(Element notifySOAPBodyChild){
		MO mo = new MO();
		System.out.println("---this is a mo deliver---");
		//registrationIdentifier-连接到预先注册过的通知的句柄。本参数区分指向同一个应用 web service 的不同注册
		String registrationIdentifier = notifySOAPBodyChild.elementTextTrim("registrationIdentifier");
		Element ns2_message = notifySOAPBodyChild.element("message");
		String message = "";//短消息中的文本
		String senderAddress = "";//指示短消息发送者的名称,即作为消息发起者显示在用户终端上的名称。
		String smsServiceActivationNumber = "";//与被调用的消息业务相关的号码,即,终端用来发送消息的目标地址。
		if(ns2_message != null){
			message = ns2_message.elementTextTrim("message");
			senderAddress = ns2_message.elementTextTrim("senderAddress");
			smsServiceActivationNumber = ns2_message.elementTextTrim("smsServiceActivationNumber");
		}
		if(message != null){
//			message = this.charTransform(message);
		} else{
			message = "";
		}
		mo.setMsgContent(message);
		
		if(senderAddress == null)
			senderAddress = "";
		else if(senderAddress.startsWith("tel:86"))
			senderAddress = senderAddress.substring(6);//tel:86
		else if(senderAddress.startsWith("tel:"))
			senderAddress = senderAddress.substring(4);//tel:
		mo.setSrcTermID(senderAddress);
		
		if(smsServiceActivationNumber == null)
			smsServiceActivationNumber = "";
		else if(smsServiceActivationNumber.startsWith("tel:"))
			smsServiceActivationNumber = smsServiceActivationNumber.substring(4);
		mo.setDestTermID(smsServiceActivationNumber);
		
		mo.setLinkID(this.linkId);
		mo.setRemark5(registrationIdentifier==null?"":registrationIdentifier);
		
		Timestamp time = new Timestamp(System.currentTimeMillis());
        mo.setRemark1(time.toLocaleString());
        mo.setGatewayID(Constant.GATEWAYID);
        mo.setMsgLen(String.valueOf(mo.getMsgContent().getBytes().length));

		molog.info("---this is a mo deliver---");
        this.writeLog();
        molog.info("registrationIdentifier = "+registrationIdentifier);
        molog.info("senderAddress = "+senderAddress);
        molog.info("smsServiceActivationNumber = "+smsServiceActivationNumber);
        molog.info("message = "+message);
        molog.info("-------end of MO delivery-------");
        
		moqueue.add(mo);
	}
	
	/**notifySmsDeliveryReceipt Stat SOAP数据包*/
	public void parseStat(Element notifySOAPBodyChild){
//		parse soapBody
		Stat stat = new Stat();
		System.out.println("---this is a stat report---");
		try {
			String correlator = notifySOAPBodyChild
					.elementTextTrim("correlator");
			Element ns2_deliveryStatus = notifySOAPBodyChild
					.element("deliveryInformation");
			String address = "";//目的地址信息
			String deliveryStatus = "";//传送状态,枚举类型
			if (ns2_deliveryStatus != null) {
				address = ns2_deliveryStatus.elementTextTrim("address");
				deliveryStatus = ns2_deliveryStatus
						.elementTextTrim("deliveryStatus");
			}
			if(address == null)
				address = "";
			else if(address.startsWith("tel:86"))
				address = address.substring(6);//tel:86
			else if(address.startsWith("tel:"))
				address = address.substring(4);//tel:
			stat.setDestTermID(address);
			stat.setSrcTermID(address);
			
			stat.setMsgID(correlator == null ? "" : correlator);
			stat.setGatewayID(Constant.GATEWAYID);
			if (_DeliveredToTerminal.equalsIgnoreCase(deliveryStatus)) {
				stat.setStat("DELIVRD");
			} else {
				stat.setStat(deliveryStatus == null ? "" : deliveryStatus);
			}
			molog.info("---this is a stat report---");
			this.writeLog();
			molog.info("correlator = " + correlator);
			molog.info("address = " + address);
			molog.info("deliveryStatus = " + deliveryStatus);
			molog.info("-----end of stat report-----");
			System.out.println("out:\nspRevId = " + spRevId + "\n"
					+ "spRevpassword = " + spRevpassword + "\n" + "spId = "
					+ spId + "\n" + "san = " + spNumber + "\n" + "serviceId = "
					+ serviceId + "\n" + "transactionId = " + sessionId
					+ "\n" + "linkId = " + linkId + "\n" + "correlator = "
					+ correlator + "\n" + "address = " + address + "\n"
					+ "deliveryStatus = " + deliveryStatus);
		} catch (Exception e) {
			molog.error("Exception:",e);
		}		
		objqueue.add(stat);
	}
	
	public String charTransform(String s) throws UnsupportedEncodingException{
//        try {
            if(s==null)
              return null;
            else
              return new String(s.getBytes("ISO-8859-1"),"GBK");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//            molog.error("UnsupportedEncodingException:",e);
//            return "error encode";
//        }
    }
	
	protected void writeLog(){
		molog.info("spRevId = "+spRevId);
		molog.info("spRevpassword = "+spRevpassword);
		molog.info("spId = "+spId);
		molog.info("san = "+spNumber);
		molog.info("serviceId = "+serviceId);
		molog.info("transactionId = "+sessionId);
		molog.info("linkid = "+linkId);
	}
	
	protected String faultString(String faultstring){
		String fault = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
				"<soap:Body>" +
				"<soap:Fault>" +
				"<faultcode>soap:Server</faultcode>" +
				"<faultstring>" + faultstring + "</faultstring>" +
				"<detail></detail>"+
				"</soap:Fault>" +
				"</soap:Body></soap:Envelope>";
		
		return fault;
	}
		
	public static void main(String[] args){
		try {
			java.io.BufferedInputStream bin = new java.io.BufferedInputStream(
					new java.io.FileInputStream(new java.io.File("D:\\work\\unsoap_moStatus.txt")));
			int len = bin.available();
			byte[] temp = new byte[len];
			bin.read(temp);
			temp = new String(temp).trim().getBytes();
			String xml = new String(temp);
			System.out.println(xml);
			String resp_xml = new StructMO().process(xml.getBytes());
			System.out.println(resp_xml);
//			new StructMO().process(temp);
			bin.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -