• SAX:进行XML解析


    package com.yangshan.eship.labelex.service.impl;
    
    import com.jcraft.jsch.ChannelSftp;
    import com.yangshan.eship.labelex.entity.TrackEventActivityEnum;
    import com.yangshan.eship.labelex.entity.TrackInfo;
    import com.yangshan.eship.labelex.repository.b2c.TrackInfoDao;
    import com.yangshan.eship.labelex.service.B2CService;
    import com.yangshan.eship.labelex.util.SFTPUtils;
    import org.apache.http.client.utils.DateUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.List;
    import java.util.Vector;
    import java.util.stream.Collectors;
    
    /**
     * @author: Yifan
     * @Description:
     * @date: 2019/8/9
     * Modified By:
     */
    @Service
    public class B2CServiceImpl extends DefaultHandler implements B2CService {
        private static Logger logger = LoggerFactory.getLogger(B2CService.class);
    
        @Value("${aviaOrderTrack.b2c.labelUrl}")
        private String labelUrl;
        @Value("${aviaOrderTrack.b2c.userName}")
        private String userName;
        @Value("${aviaOrderTrack.b2c.ip}")
        private String ip;
        @Value("${aviaOrderTrack.b2c.port}")
        private String port;
        @Value("${aviaOrderTrack.b2c.cdPath}")
        private String cdPath;
        @Value("${aviaOrderTrack.b2c.key}")
        private String key;
        @Value("${aviaOrderTrack.b2c.keyPass}")
        private String keyPass;
    
        private List<TrackInfo> trackInfoList;
        private TrackInfo trackInfo;
        private String preTag;
    
        @Autowired
        private TrackInfoDao trackInfoDao;
    
        @Override
        public Integer trackInfo() {
            SFTPUtils sftpUtils = new SFTPUtils();
            List<TrackInfo> trackInfoAllList = new ArrayList<TrackInfo>();
            try {
                //建立连接
                ChannelSftp channelSftp = sftpUtils.getChannel(userName, ip, port, key, keyPass);
                channelSftp.cd(cdPath);
                logger.info("B2C追踪抓取,成功进入目录{}", cdPath);
                //获取文件列表
                List<String> fileNameList = getFileNameList(channelSftp);
                fileNameList = fileNameList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
                logger.info("B2C追踪抓取,文件列表共{}个", fileNameList.size());
                //获取最新文件列表
                Long oldMaxFileNo = trackInfoDao.getMaxFileNo();
                if (oldMaxFileNo != null) {
                    fileNameList = fileNameList.stream().filter(fileName -> Long.valueOf(fileName.split("-")[2]) > oldMaxFileNo).collect(Collectors.toList());
                }
                logger.info("B2C追踪抓取,待解析文件列表共{}个", fileNameList.size());
                //解析追踪信息
                for (String fileName : fileNameList) {
                    //获取指定文件
                    InputStream inputStream = channelSftp.get(fileName);
                    List<TrackInfo> trackInfoSubList = getTrackInfoList(inputStream);
    
                    for (TrackInfo trackInfo : trackInfoSubList) {
                        trackInfo.setFileNo(fileName.split("-")[2]);
                    }
                    trackInfoAllList.addAll(trackInfoSubList);
                }
                trackInfoDao.save(trackInfoAllList);
                logger.info("B2C追踪抓取解析完毕,共导入{}条追踪数据", trackInfoAllList.size());
            } catch (Exception e) {
                logger.info(e.getMessage(), e);
            }
    
            return trackInfoAllList.size();
        }
    
        /**
         * @Author: Yifan
         * @Date: 2019/8/9 16:23
         * @Description: 获取TrackInfoList
         */
        public List<TrackInfo> getTrackInfoList(InputStream inputStream) throws Exception {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            B2CServiceImpl handler = new B2CServiceImpl();
            parser.parse(inputStream, handler);
            return handler.getTrackInfoList();
        }
    
        public List<TrackInfo> getTrackInfoList() {
            return trackInfoList;
        }
    
        @Override
        public void startDocument() throws SAXException {
            trackInfoList = new ArrayList<TrackInfo>();
        }
    
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            if ("Event".equals(qName)) {
                trackInfo = new TrackInfo();
            }
            preTag = qName;
        }
    
        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            if ("Event".equals(qName)) {
                trackInfoList.add(trackInfo);
                trackInfo = null;
            }
            preTag = null;
        }
    
        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            if (preTag != null) {
                String content = new String(ch, start, length);
                if ("TrackID".equals(preTag)) {
                    trackInfo.setTrackId(content);
                } else if ("TYPNumber".equals(preTag)) {
                    trackInfo.setTypNumber(content);
                } else if ("PackageNumber".equals(preTag)) {
                    trackInfo.setPackageNumber(content);
                } else if ("OrderNumber".equals(preTag)) {
                    trackInfo.setOrderNumber(content);
                } else if ("ParcelWeight".equals(preTag)) {
                    trackInfo.setParcelWeight(content);
                } else if ("TrackEventActivity".equals(preTag)) {
                    trackInfo.setTrackEventActivity(TrackEventActivityEnum.valueOf(content));
                } else if ("TrackEventCarrier".equals(preTag)) {
                    trackInfo.setTrackEventCarrier(content);
                } else if ("TrackEventNumber".equals(preTag)) {
                    trackInfo.setTrackEventNumber(content);
                } else if ("TrackEventCode".equals(preTag)) {
                    trackInfo.setTrackEventCode(content);
                } else if ("TrackEventStatus".equals(preTag)) {
                    trackInfo.setTrackEventStatus(content);
                } else if ("TrackEventDate".equals(preTag)) {
                    trackInfo.setTrackEventDate(DateUtils.parseDate(content, new String[]{"yyyy-MM-dd HH:mm:ss".intern()}));
                } else if ("TrackEventComment".equals(preTag)) {
                    trackInfo.setTrackEventComment(content);
                } else if ("TrackEventCity".equals(preTag)) {
                    trackInfo.setTrackEventCity(content);
                } else if ("TrackEventLocation".equals(preTag)) {
                    trackInfo.setTrackEventLocation(content);
                } else if ("TrackEventCountry".equals(preTag)) {
                    trackInfo.setTrackEventCountry(content);
                } else if ("TrackURL".equals(preTag)) {
                    trackInfo.setTrackUrl(content);
                }
            }
        }
    
        /**
         * @Author: Yifan
         * @Date: 2019/8/6 15:30
         * @Description: 获取文件名列表
         */
        public List<String> getFileNameList(ChannelSftp channelSftp) throws Exception {
            List<String> fileNameList = new ArrayList<String>();
    
            Vector<String> files = channelSftp.ls("*");
            for (int i = 0; i < files.size(); i++) {
                Object obj = files.elementAt(i);
                if (obj instanceof ChannelSftp.LsEntry) {
                    ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) obj;
                    if (true && !entry.getAttrs().isDir()) {
                        fileNameList.add(entry.getFilename());
                    } else {
                        throw new Exception("发现非法目录");
                    }
                }
            }
    
            return fileNameList;
        }
    
    }
  • 相关阅读:
    15款经典图表软件推荐 创建最漂亮的图表
    CSS+JS打造的自适应宽度的滑动门和选项卡
    兼容多浏览器的加入收藏代码
    指针与引用深层次的区别
    反编译winform资源文件
    程序创业必过三关
    自动ping博客服务程序
    C#批量加水印程序
    C#应用程序随机启动
    失败降临是命中注定
  • 原文地址:https://www.cnblogs.com/yifanSJ/p/11352088.html
Copyright © 2020-2023  润新知