Java 以XML格式的http请求 客户端请求报文框架搭建

来源:互联网 发布:mysql statistics状态 编辑:程序博客网 时间:2024/06/06 04:48

//供调用的类


/**
 * 平台交互控制中心
 */
public abstract class PlatformController {

    private static Logger logger = LoggerFactory.getLogger(PlatformController.class);

    private String comCode = null;
    private String areaCode = null;
    private RequestType requestType;
    private PlatformUnMarshaller umMarsh = null;

    public PlatformController(String comCode,RequestType requestType){
        this.comCode = comCode;
        this.requestType = requestType;
    }
    
    public PlatformController(String comCode,String areaCode,RequestType requestType){
        this.comCode = comCode;
        this.areaCode = areaCode;
        this.requestType = requestType;
    }

    protected abstract Object getHeadVo(RequestType requestType,String... params);

    protected abstract String getUrl(String comCode,RequestType requestType);
    
    /**
     * 初始化平台日志Vo,根据不同平台,得到ClaimSeqNo,BussNo
     * @param comCode
     * @param requestType
     * @param bodyVo
     * @return
     * @modified: ☆LiuPing(2016年6月24日 ): <br>
     */
    protected abstract CiClaimPlatformLogVo initPlatformLogVo(RequestType requestType,Object bodyVo);

    /**
     * 发送平台
     * @param bodyVo
     * @throws Exception
     * @modified: ☆LiuPing(2016年4月5日 ): <br>
     */
    public CiClaimPlatformLogVo callPlatform(Object bodyVo) {

        String url = getUrl(comCode,requestType);
        Object headVo = null ;
        
        PlatfromType platfromType = requestType.getPlatformType();
        if(platfromType==PlatfromType.CA || platfromType ==PlatfromType.HS){
            headVo = getHeadVo(requestType,comCode,areaCode);
        }else{
            headVo = getHeadVo(requestType,comCode);
        }
        
        CiClaimPlatformLogVo logVo = initPlatformLogVo(requestType,bodyVo);
        logVo.setComCode(comCode);
        logVo.setAreaCode(areaCode);

        try{
            PlatformMarshaller marsh = new PlatformMarshaller(headVo,bodyVo);
            String requestXML = marsh.toXml();
            logVo.setRequestXml(requestXML);
            logVo.setRequestTime(new Date());
            logger.info(requestType.getName()+",requestXML=: \n"+requestXML);
            String responseXml = requestPlatform(requestXML,url,5);
            logger.info(requestType.getName()+",responseXml=: \n"+responseXml);
            logVo.setResponseXml(responseXml);
            logVo.setResponseTime(new Date());

            logVo.setStatus("1");// 成功
            // 解析结果
            umMarsh = new PlatformUnMarshaller(requestType);
            umMarsh.parseXml(responseXml);

            String errorCode = umMarsh.getErrorCode();
            if(StringUtils.isNotBlank(errorCode)){
                logVo.setStatus("0");// 失败
                logVo.setErrorCode(errorCode);
                logVo.setErrorMessage(umMarsh.getErrorMessage());
//                throw new IllegalArgumentException("平台返回异常信息:"+logVo.getErrorMessage());
            }
            
            //保存报案的理赔编码
            if (RequestType.RegistInfoBI.getCode().equals(requestType.getCode())||
                RequestType.RegistInfoCI.getCode().equals(requestType.getCode())||
                RequestType.RegistInfoBI_SH.getCode().equals(requestType.getCode())){
                String claimSeqNo = umMarsh.getClaimSeqNo();
                if (StringUtils.isNotBlank(claimSeqNo)) {
                    logVo.setClaimSeqNo(claimSeqNo);
                }
            }
            
        }catch(IllegalArgumentException e){
            throw e;
        }catch(Exception e){
            logger.error("平台交互异常:RequestType="+requestType.name()+",error"+e.getMessage());
            logVo.setStatus("0");// 失败
            logVo.setErrorMessage("系统异常"+e.getMessage());
//            throw new RuntimeException(logVo.getErrorMessage(),e);
        }
        finally{
            PlatformLogUtil.saveLog(logVo);
        }
        return logVo;
    }

    public <T> T getHeadVo(Class<T> valueType) {
        return umMarsh.getHeadVo(valueType);
    }
    
    public <T> T getBodyVo(Class<T> valueType) {
        return umMarsh.getBodyVo(valueType);
    }

    private String requestPlatform(String requestXML,String urlStr,int seconds) throws Exception {
        long t1 = System.currentTimeMillis();
        try {
            BufferedReader reader = null;
            HttpURLConnection connection = null;
            StringBuffer buffer = new StringBuffer();
            URL url = new URL(urlStr);
            try {
                connection = (HttpURLConnection)url.openConnection();
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                // post方式不能使用缓存
                connection.setUseCaches(false);
                // 配置本次连接的Content-Type,配置为text/xml
                connection.setRequestProperty("Content-Type","text/xml;charset=GBK");
                // 维持长连接
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setConnectTimeout(seconds * 1000);
                connection.setAllowUserInteraction(true);
                connection.connect();
            } catch (Exception ex) {
                throw new Exception("与平台连接失败,请稍候再试", ex);
            }

            try {
                OutputStream outputStream = connection.getOutputStream();
                DataOutputStream out = new DataOutputStream(outputStream);
                out.write(requestXML.getBytes("GBK"));
                out.flush();
                out.close();
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"GBK"));
                String strLine = "";
                while ((strLine = reader.readLine()) != null) {
                    buffer.append(strLine);
                }
                if (buffer.length() < 1) {
                    throw new Exception("平台返回数据失败");
                }
            } catch (IOException e) {
                throw new Exception("读取平台返回数据失败", e);
            } finally {
                if (reader != null) {
                    reader.close();
                }
            }
            return buffer.toString();
        } finally {
            logger.warn("平台({})调用耗时{}ms",urlStr,System.currentTimeMillis()-t1);
        }
    }

}


/**
 * 交易请求类型
 *
 */
public enum RequestType {
    
    /** 报案登记 */
    RegistInfoCI("50","交强报案登记 ",PlatfromType.CI),
    
    /** 报案登记 */
    RegistInfoBI("V3101","商业报案登记 ",PlatfromType.BI),
    
    /** 交强立案登记 */
    ClaimCI("51","交强立案登记",PlatfromType.CI),
    
    /** 商业立案登记 */
    ClaimBI("V3102","商业立案登记",PlatfromType.BI),
    
    /** 交强结案登记 */
    EndCaseCI("52","交强结案登记",PlatfromType.CI),
    
    /** 商业结案登记 */
    EndCaseBI("V3104","商业结案登记",PlatfromType.BI),

}



/**
 * 车险平台将xml准话为对象
 * @CreateTime 2016年3月15日
 */
public class PlatformUnMarshaller {

    private Node headElm;
    private Node bodyElm;
    private RequestType requestType;

    public PlatformUnMarshaller(RequestType requestType){
        headElm = null;
        bodyElm = null;
        this.requestType = requestType;
    }

    public void parseXml(String xmlStr) throws SAXException,IOException,Exception {

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
        InputSource source = new InputSource(new StringReader(xmlStr));
        Document doc = dbBuilder.parse(source);
        if(PlatfromType.CI==requestType.getPlatformType()){
            headElm = doc.getElementsByTagName("HEAD").item(0);
            bodyElm = doc.getElementsByTagName("BODY").item(0);
        }else{
            headElm = doc.getElementsByTagName("Head").item(0);
            bodyElm = doc.getElementsByTagName("Body").item(0);
        }

    }

    public <T> T getHeadVo(Class<T> valueType) {
        return nodeToObj(headElm,valueType);
    }

    public <T> T getBodyVo(Class<T> valueType) {
        return nodeToObj(bodyElm,valueType);
    }

    private static <T> T nodeToObj(Node node,Class<T> valueType) {
        try{
            JAXBContext context = JAXBContext.newInstance(valueType);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            return unmarshaller.unmarshal(node,valueType).getValue();
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    public String getClaimSeqNo(){
        String elmName = "CLAIM_CODE";
        if(RequestType.RegistInfoBI.getCode().equals(requestType.getCode())
                &&PlatfromType.BI==requestType.getPlatformType()){
            elmName = "ClaimSequenceNo";
        }
        Element elm = (Element)bodyElm;
        String claimSequenceNo = "";
        if(elm!=null){
            claimSequenceNo = elm.getElementsByTagName(elmName).item(0).getTextContent();
        }
        if(StringUtils.isEmpty(claimSequenceNo)){//
            return null;
        }
        return claimSequenceNo;
    }
    
    public String getErrorCode() {
        String elmName = "ErrorCode";
        String reqType = requestType.toString();
        if("SH".equals(reqType.substring(reqType.length()-2,reqType.length()))){
            elmName = "RESPONSE_CODE";//上海平台
        }else{
            if(PlatfromType.CI==requestType.getPlatformType()){
                elmName = "ERROR_CODE";
            }
        }
        
        Element elm = (Element)headElm;
        String errorCode = elm.getElementsByTagName(elmName).item(0).getTextContent();
        if(errorCode==null||errorCode.equals("0000")||"1".equals(errorCode)){// 成功的error返回空
            return null;
        }
        return errorCode;
    }

    public String getErrorMessage() {
        String elmName = "ErrorMessage";
        String reqType = requestType.toString();
        if("SH".equals(reqType.substring(reqType.length()-2,reqType.length()))){
            elmName = "ERROR_MESSAGE";
        }else{
            if(PlatfromType.CI==requestType.getPlatformType()){// 交强平台
                elmName = "ERROR_MESSAGE";
            }else if(PlatfromType.CA==requestType.getPlatformType() || PlatfromType.HS==requestType.getPlatformType()){// 结算平台
                elmName = "ErrorDesc";
            }
        }
        String errorMsg = ( (Element)headElm ).getElementsByTagName(elmName).item(0).getTextContent();
        return errorMsg;
    }
    
}

/******************************************************************************
* CREATETIME : 2016年4月5日 上午8:52:16
******************************************************************************/
package ins.sino.claimcar.carplatform.controller;

import ins.sino.claimcar.carplatform.constant.RequestType;
import ins.sino.claimcar.carplatform.util.XmlElementParser;
import ins.sino.claimcar.carplatform.vo.BiRequestHeadVo;
import ins.sino.claimcar.carplatform.vo.CiClaimPlatformLogVo;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.SpringProperties;


/**
 * 商业险平台
 * @CreateTime 2016年4月5日
 */
public class BIPlatformController extends PlatformController {

    private static Logger logger = LoggerFactory.getLogger(BIPlatformController.class);

    public BIPlatformController(String comCode,RequestType requestType){
        super(comCode,requestType);
    }

    @Override
    protected String getUrl(String comCode,RequestType requestType) {
        String url = SpringProperties.getProperty("BI_"+comCode.substring(0,2)+"_URL");
        if(url==null||url.trim().length()==0){
            logger.error("机构【"+comCode+"】平台URL不存在");
            throw new IllegalArgumentException("机构【"+comCode+"】平台URL不存在,请联系管理员配置");
        }

        return url;
    }

    @Override
    protected Object getHeadVo(RequestType requestType,String... params) {
        BiRequestHeadVo head = new BiRequestHeadVo();
        String comCode = params[0].substring(0,2);
        head.setPassword(SpringProperties.getProperty("BI_"+comCode+"_PWD"));
        head.setUser(SpringProperties.getProperty("BI_"+comCode+"_USER"));
        head.setRequestType(requestType.getCode());

        return head;
    }

    /*
     * 初始化平台日志vo,从bodyVo获取对应注解的值,赋值到CiClaimPlatformLogVo上
     * @see ins.sino.claimcar.carplatform.controller.PlatformController#initPlatformLogVo(ins.sino.claimcar.carplatform.constant.RequestType, java.lang.Object)
     * @param requestType
     * @param bodyVo
     * @return
     */
    @Override
    protected CiClaimPlatformLogVo initPlatformLogVo(RequestType requestType,Object bodyVo) {
        CiClaimPlatformLogVo logVo = new CiClaimPlatformLogVo();
        logVo.setRequestType(requestType.getCode());
        logVo.setRequestName(requestType.getName());

        XmlElementParser xmlElmParser = new XmlElementParser();
        xmlElmParser.findElementValue(bodyVo,"ClaimNotificationNo","ClaimRegistrationNo","ClaimSequenceNo","ConfirmSequenceNo");
        String registNo = xmlElmParser.getString(1);// 报案号注解 ClaimNotificationNo
        String claimNo = xmlElmParser.getString(2);// 立案号 注解ClaimRegistrationNo
        String claimSeqNo = xmlElmParser.getString(3);// 理赔编号 注解 ClaimSequenceNo
        String confirmSequenceNo = xmlElmParser.getString(4);//投保确认码 注解ConfirmSequenceNo
        if(StringUtils.isNotBlank(claimNo)){// 有立案号优先使用立案号
            logVo.setBussNo(claimNo);
        }else{
            logVo.setBussNo(registNo);
        }
        logVo.setClaimSeqNo(claimSeqNo);
        logVo.setValidNo(confirmSequenceNo);
        return logVo;
    }

}


/**
 * 商业险平台
 * @CreateTime 2016年4月5日
 */
public class BIPlatformController extends PlatformController {

    private static Logger logger = LoggerFactory.getLogger(BIPlatformController.class);

    public BIPlatformController(String comCode,RequestType requestType){
        super(comCode,requestType);
    }

    @Override
    protected String getUrl(String comCode,RequestType requestType) {
        String url = SpringProperties.getProperty("BI_"+comCode.substring(0,2)+"_URL");
        if(url==null||url.trim().length()==0){
            logger.error("机构【"+comCode+"】平台URL不存在");
            throw new IllegalArgumentException("机构【"+comCode+"】平台URL不存在,请联系管理员配置");
        }

        return url;
    }

    @Override
    protected Object getHeadVo(RequestType requestType,String... params) {
        BiRequestHeadVo head = new BiRequestHeadVo();
        String comCode = params[0].substring(0,2);
        head.setPassword(SpringProperties.getProperty("BI_"+comCode+"_PWD"));
        head.setUser(SpringProperties.getProperty("BI_"+comCode+"_USER"));
        head.setRequestType(requestType.getCode());

        return head;
    }

    /*
     * 初始化平台日志vo,从bodyVo获取对应注解的值,赋值到CiClaimPlatformLogVo上
     * @see ins.sino.claimcar.carplatform.controller.PlatformController#initPlatformLogVo(ins.sino.claimcar.carplatform.constant.RequestType, java.lang.Object)
     * @param requestType
     * @param bodyVo
     * @return
     */
    @Override
    protected CiClaimPlatformLogVo initPlatformLogVo(RequestType requestType,Object bodyVo) {
        CiClaimPlatformLogVo logVo = new CiClaimPlatformLogVo();
        logVo.setRequestType(requestType.getCode());
        logVo.setRequestName(requestType.getName());

        XmlElementParser xmlElmParser = new XmlElementParser();
        xmlElmParser.findElementValue(bodyVo,"ClaimNotificationNo","ClaimRegistrationNo","ClaimSequenceNo","ConfirmSequenceNo");
        String registNo = xmlElmParser.getString(1);// 报案号注解 ClaimNotificationNo
        String claimNo = xmlElmParser.getString(2);// 立案号 注解ClaimRegistrationNo
        String claimSeqNo = xmlElmParser.getString(3);// 理赔编号 注解 ClaimSequenceNo
        String confirmSequenceNo = xmlElmParser.getString(4);//投保确认码 注解ConfirmSequenceNo
        if(StringUtils.isNotBlank(claimNo)){// 有立案号优先使用立案号
            logVo.setBussNo(claimNo);
        }else{
            logVo.setBussNo(registNo);
        }
        logVo.setClaimSeqNo(claimSeqNo);
        logVo.setValidNo(confirmSequenceNo);
        return logVo;
    }

}



1 0
原创粉丝点击