CustomResponseAnalysisServiceImp.java 14.9 KB
package com.tianbo.analysis.service.imp;

import com.tianbo.analysis.handle.AgentXmlHandle;
import com.tianbo.analysis.model.*;
import com.tianbo.analysis.service.CustomResponseAnalysisService;
import com.tianbo.analysis.tools.AWBTools;
import com.tianbo.util.Date.DateUtil;
import com.tianbo.util.XML.XMLXPath;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileExistsException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.xml.sax.SAXParseException;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Service
@Slf4j
public class CustomResponseAnalysisServiceImp implements CustomResponseAnalysisService {


    //解析出错转移目录
    @Value("${custom.errBakDir}")
    private String errBakDir;

    @Value("${custom.receptBakDir}")
    private String receptBakDir;

    /**
     * 单一窗口回执的技术回执
     */
    public final static String DONT_NEED =      "<Code>0</Code><Text>接收成功</Text>";

    //海关新舱单回执报头
    public final static String MessageID =      "//Manifest/Head/MessageID";
    public final static String FunctionCode =   "//Manifest/Head/FunctionCode";
    public final static String MessageType =    "//Manifest/Head/MessageType";
    public final static String SenderID =       "//Manifest/Head/SenderID";
    public final static String ReceiverID =     "//Manifest/Head/ReceiverID";
    public final static String SendTime =       "//Manifest/Head/SendTime";
    public final static String Version =        "//Manifest/Head/Version";


    /**
     * 海关普通业务新舱单回执报体
     */
    public final static String JourneyID =      "//Manifest/Response/BorderTransportMeans/JourneyID";
    public final static String WaybillMaster =  "//Manifest/Response/Consignment/TransportContractDocument/ID";
    public final static String WaybillSecond =  "//Manifest/Response/Consignment/AssociatedTransportDocument/ID";
    public final static String ResponseCode =   "//ResponseType/Code";
    public final static String ResponseText =   "//ResponseType/Text";

    /**
     * 海关国际转运业务回执报体
     */
    public final static String ImportJourneyID = "//Manifest/Response/ImportInformation/BorderTransportMeans/JourneyID";
    public final static String ImportWaybillMaster = "//Manifest/Response/ImportInformation/Consignment/TransportContractDocument/ID";
    public final static String ImportWaybillSecond = "//Manifest/Response/ImportInformation/Consignment/AssociatedTransportDocument/ID";
    public final static String ExportJourneyID = "//Manifest/Response/ExportInformation/BorderTransportMeans/JourneyID";
    public final static String ExportWaybillMaster = "//Manifest/Response/ExportInformation/Consignment/TransportContractDocument/ID";
    //    public final static String TransResponseCode =   "//Manifest/Response/ResponseType/Code";
//    public final static String TransResponseText =   "//Manifest/Response/ResponseType/Text";
    public final static String TransResponseCode =   "//ResponseType/Code";
    public final static String TransResponseText =   "//ResponseType/Text";


    @Override
    public boolean xmlAnalysis(String xmlStr) {
        String today = DateUtil.getTodayBy_yyyyMMdd();
        String errDirByDay = errBakDir + "/" + today;
        String failDirByDay = errBakDir+ "Fail" + "/" + today;
        String successDir = receptBakDir + "/" + today;
        if(xmlStr.contains(DONT_NEED)){
//            bakXml(xmlStr,errDirByDay);
            log.info("报文为技术回执备份成功..开始解析下一文件,当前线程即将结束");
        }
        else
        {
            try{

                int i =handelXmlDocument(xmlStr);
                //操作成功,则转移剪切解析文件到备份目录,否则转移到error目录备份
                if(i>0){
//                    bakXml(xmlStr,successDir);
                    log.info("报文解析入库成功");
                    return true;
                }else {
//                    bakXml(xmlStr,errDirByDay);
                    return true;
                }
            }catch (Exception e){
                log.error("报文备份异常",e);
                bakXml(xmlStr,failDirByDay);
                e.printStackTrace();
                return false;
            }

        }
        log.info("线程结束");

        return false;
    }

    private int handelXmlDocument(String xml) throws DocumentException, UnsupportedEncodingException, SAXParseException, FileNotFoundException {

        int i = 0;
        String secondSplit = "_";
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
        Element contentRoot = document.getRootElement();

        String flightNo = "UNKONW";
        String flightDate = "20101010";

        //开始解析
        String msgType = XMLXPath.getSingleValueByPath(document,MessageType);
        String journeyid = XMLXPath.getSingleValueByPath(document,JourneyID);
//            XMLXPath.getSingleValueByPath(document, )


        String awbA = XMLXPath.getSingleValueByPath(document,WaybillMaster);
        //全格式的分单 如 17212345678_ADBD
        String awbH = XMLXPath.getSingleValueByPath(document,WaybillSecond);
        String resCode = XMLXPath.getSingleValueByPath(document,ResponseCode);
        String resText = XMLXPath.getSingleValueByPath(document,ResponseText);
        String messageId = XMLXPath.getSingleValueByPath(document, MessageID);
        String sendTime = XMLXPath.getSingleValueByPath(document,SendTime);
        String sendId = XMLXPath.getSingleValueByPath(document,SenderID);
        String reciveId = XMLXPath.getSingleValueByPath(document,ReceiverID);
        String version = XMLXPath.getSingleValueByPath(document,Version);
        String functionCode = XMLXPath.getSingleValueByPath(document,FunctionCode);



        CustomReception customReception = new CustomReception(  msgType,
                flightNo,
                flightDate,
                awbA,
                awbH,
                resCode,
                resText,
                messageId,
                sendTime,
                sendId,
                reciveId,
                version,
                functionCode);

        /**
         * 如果回执中没有携带航班信息节点,说明是出错报文
         * 到发送日志表根据messageid 找到相应的发送日志报文的航班及运单信息,再进行解析
         */
        if(!StringUtils.isEmpty(journeyid)){

            String[] flightList = journeyid.split("/");
            if(flightList.length > 0){
                flightNo = flightList[0];
                flightDate = flightList[1];
                customReception.setFlightNo(flightNo);
                customReception.setFlightDate(flightDate);
            }
        }else {
            CUSTOMSMESSAGE customsmessage = new CUSTOMSMESSAGE();
            customReception = customsmessage.getWaybillInfoByCutomResponse(customReception);
        }

        switch (msgType){
            case "MT9999":
                if (customReception.getWayBillSecond()!=null && customReception.getWayBillSecond().contains(secondSplit)){
                    PREPARESECONDARY preparesecondary = new PREPARESECONDARY(customReception);
                    int pre_i = preparesecondary.secondAnalysisReception();

                    if (pre_i>0){
                        i=1;
                    }else {
                        Originmanifestsecondary originmanifestsecondary = new Originmanifestsecondary(customReception);
                        int org_i=originmanifestsecondary.secondAnalysisReception();
                        if (org_i>0){
                            i= 1;
                        }else {
                            ARRIVEDSECONDARY arrivedsecondary = new ARRIVEDSECONDARY(customReception);
                            int arr_i=arrivedsecondary.secondAnalysisReception();
                            if (arr_i>0){
                                i=1;
                            }
                        }
                    }
                }else{
                    ORIGINMANIFESTMASTER originmanifestmaster = new ORIGINMANIFESTMASTER(customReception);
                    PREPAREMASTER preparemaster= new PREPAREMASTER(customReception);
                    ARRIVEDMASTER arrivedmaster9999 = new ARRIVEDMASTER(customReception);
                    if(originmanifestmaster.masterAnalysisReception()>0){
                        i=1;
                    }else if(preparemaster.masterAnalysisReception()>0){
                        i=1;
                    }else {
                        i=arrivedmaster9999.masterAnalysisReception();
                    }
                }
                AgentXmlHandle agentXmlHandle=new AgentXmlHandle();
                agentXmlHandle.Http_resolver(customReception);
                break;
            case "MT3201":
                if (customReception.getWayBillSecond()!=null && customReception.getWayBillSecond().contains(secondSplit)){
                    ARRIVEDSECONDARY arrivedsecondary = new ARRIVEDSECONDARY(customReception);
                    i=arrivedsecondary.secondAnalysisReception();
                }else {
                    ARRIVEDMASTER arrivedmaster = new ARRIVEDMASTER(customReception);
                    i=arrivedmaster.masterAnalysisReception();
                }
                break;
            case "MT5202":
            case "MT5201":
                if (customReception.getWayBillSecond()!=null && customReception.getWayBillSecond().contains(secondSplit)){
                    TALLYSECONDARY tallysecondary = new TALLYSECONDARY(customReception);
                    i=tallysecondary.secondAnalysisReception();
                }else {
                    TALLYMASTER tallymaster= new TALLYMASTER(customReception);
                    i = tallymaster.masterAnalysisReception();
                }
                break;
            case "MT4201":
                DEPARTURESLOADING departuresloading = new DEPARTURESLOADING(customReception);
                i=departuresloading.masterAnalysisReception();
                break;
            case "MT1201":
                if (customReception.getWayBillSecond()!=null && customReception.getWayBillSecond().contains(secondSplit)){
                    Originmanifestsecondary originmanifestsecondary = new Originmanifestsecondary(customReception);
                    i=originmanifestsecondary.secondAnalysisReception();
                }else {
                    ORIGINMANIFESTMASTER originmanifestmaster1201 = new ORIGINMANIFESTMASTER(customReception);
                    i = originmanifestmaster1201.masterAnalysisReception();
                }
                break;
            case "MT2201":
                if (customReception.getWayBillSecond()!=null && customReception.getWayBillSecond().contains(secondSplit)){
                    PREPARESECONDARY preparesecondary = new PREPARESECONDARY(customReception);
                    i = preparesecondary.secondAnalysisReception();
                }else {
                    PREPAREMASTER preparemaster1201= new PREPAREMASTER(customReception);
                    i = preparemaster1201.masterAnalysisReception();
                }
                break;
            case "MT6202":
                INPORTALLOCATE inportallocate = new INPORTALLOCATE(customReception);
                i = inportallocate.masterAnalysisReception();
                break;
            case "MT3202":
                ALLOCATEARRIVAL allocatearrival = new ALLOCATEARRIVAL(customReception);
                i= allocatearrival.masterAnalysisReception();
                break;
            case "MT8205":
                i = transXmlHandel(document,customReception);
                break;
            case "MT8202":
                MANIFESTLOAD manifestload = new MANIFESTLOAD(customReception);
                i= manifestload.secondAnalysisReception();
                break;
            case "MT8203":
                MANIFESTLOSTCHANGE manifestlostchange = new MANIFESTLOSTCHANGE(customReception);
                i= manifestlostchange.secondAnalysisReception();
                break;
            default:
                break;

        }

        updateCustomMessage(customReception);
        return i;

    }


    /**
     * 国际转运回执处理,特殊业务
     * @param document
     * @param customReception
     * @return
     */
    private int transXmlHandel(Document document,CustomReception customReception){

        String importJourneyID = XMLXPath.getSingleValueByPath(document,ImportJourneyID);
        String importFlightNo = "UNKONW";
        String importFlightDate = "20101010";
        if(!StringUtils.isEmpty(importJourneyID)){
            importFlightNo = AWBTools.splitFlightAndDate(importJourneyID)[0];
            importFlightDate = AWBTools.splitFlightAndDate(importJourneyID)[1];
        }


        String importWaybillMaster= XMLXPath.getSingleValueByPath(document,ImportWaybillMaster);
        String importWaybillSecond= XMLXPath.getSingleValueByPath(document,ImportWaybillSecond);
        String transResponseCode=XMLXPath.getSingleValueByPath(document,TransResponseCode);
        String transResponseText=XMLXPath.getSingleValueByPath(document,TransResponseText);
        CustomReception transCustomReception = new CustomReception(  customReception.getMessageType(),
                importFlightNo,
                importFlightDate,
                importWaybillMaster,
                importWaybillSecond,
                transResponseCode,
                transResponseText,
                customReception.getMessageID(),
                customReception.getSendTime(),
                customReception.getSenderID(),
                customReception.getReceiverID(),
                customReception.getVersion(),
                customReception.getFunctionCode());
        INTERNATIONALTRANSIT internationaltransit = new INTERNATIONALTRANSIT(transCustomReception);

        int i=internationaltransit.masterAnalysisReception();

        return i;

    }

    public int updateCustomMessage(CustomReception customReception){
        CUSTOMSMESSAGE customsmessage = new CUSTOMSMESSAGE(customReception);
        return customsmessage.updateMessageByMessageid();
    }

    @Override
    public void bakXml(String responseText, String dir){
        try {

            File errfile = new File(dir + "/" + UUID.randomUUID().toString()+".xml");
            FileUtils.writeStringToFile(errfile,responseText,"UTF-8");
        }catch (FileExistsException e){
            e.printStackTrace();
            log.error("文件重名,备份失败");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}