YgcBasicDataServiceImpl.java 13.7 KB
package com.bsth.service.traffic.impl;

import com.bsth.service.impl.TrafficManageServiceImpl;
import com.bsth.service.traffic.YgcBasicDataService;
import com.bsth.util.db.DBUtils_oldSystem;
import org.apache.axiom.om.*;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.activation.DataHandler;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * 运管处基础数据操作类
 * Created by zq on 2017/6/15.
 */
@Service
public class YgcBasicDataServiceImpl implements YgcBasicDataService{
    Logger logger = LoggerFactory.getLogger(TrafficManageServiceImpl.class);

    @Autowired
    JdbcTemplate jdbcTemplate;

    private static String IP = "218.242.195.76:9091";
    private static String downTargetEndpoint = "http://" + IP +"/ygc.TransManager.Basicdown?wsdl";
    private static String upTargetEndpoint = "http://" + IP +"/ygc.TransManager.BasicUpload?wsdl";
    private static String namespace = "http://service.shygc.com";
    private static String userName = "admin";
    private static String passWord = "000000";
    private static EndpointReference downTargetEPR;
    private static EndpointReference upTargetEPR;
    {
        try {
            downTargetEPR = new EndpointReference(downTargetEndpoint);
            upTargetEPR = new EndpointReference(upTargetEndpoint);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新运管处基础数据
     */
    public void updateYgcBasicData(){
        String saveFile = "ygcBasicData.zip";
        String flag = "failure";
        try {
            // 调用接口下载基础数据
            if(download(userName, passWord, saveFile)){
                // 读取基础数据zip
                StringBuffer sb = readZipFile(saveFile);
                // 解析xml
                List<HashMap<String,String>> result = parseXml(sb);
                // 插入数据库
                if(result != null && result.size() > 0){
                    insertRecord(result);
                }
            }
            flag = "success";
        }catch (Exception e){
            e.printStackTrace();
            logger.error("updateYgcBasicData:",e);
        }
        finally {
            // 删除文件
            File fill = new File(saveFile);
            logger.info("updateYgcBasicData:"+fill.getAbsolutePath());
            logger.info("updateYgcBasicData:"+flag);
            if(fill.exists()){
                fill.delete();
            }
        }
    }
    /**
     *  下载基础数据,并生成rar文件
     * @param userName
     * @param password
     * @param saveFile
     * @return
     */
    public boolean download(String userName, String password,  String saveFile)
    {
        try
        {
            password = DigestUtils.md5Hex(password);
            OMElement data = buildDownloadEnvelope(userName, password);
            ServiceClient sender = new ServiceClient();
            Options options = sender.getOptions();
            options.setProperty("SO_TIMEOUT", Integer.valueOf(1800000));
            options.setTo(downTargetEPR);
            sender.setOptions(options);
            System.out.println("The data in method download: " + data);
            data.build();
            OMElement ome = sender.sendReceive(data);

            OMText binaryNode = (OMText)ome.getFirstOMChild();
            binaryNode.setOptimize(true);
            DataHandler actualDH = (DataHandler)binaryNode.getDataHandler();
            FileOutputStream imageOutStream = new FileOutputStream(saveFile);
            InputStream is = actualDH.getInputStream();
            int read ;
            byte[] buffer = new byte[1024];
            while ((read = is.read(buffer)) != -1) {
                imageOutStream.write(buffer, 0, read);
            }
            if(is != null){
                is.close();
            }
            if(imageOutStream != null){
                imageOutStream.close();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }return false;
    }

    /**
     * 构建webservice接口参数
     * @param userName
     * @param password
     * @return
     */
    private OMElement buildDownloadEnvelope(String userName, String password)
    {
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMNamespace omNs = fac.createOMNamespace(namespace,
                "ser");
        OMElement data = fac.createOMElement("downloadAllDataFile", omNs);
        OMElement _userName = fac.createOMElement("userName", omNs);
        _userName.setText(userName);
        OMElement _passWord = fac.createOMElement("passWord", omNs);
        _passWord.setText(String.valueOf(password));

        data.addChild(_userName);
        data.addChild(_passWord);

        OMElement soap = fac.createOMElement("downloadAllDataFile", omNs);
        soap.addChild(data);
        return soap;
    }

    /**
     * 读取zip文件的内容
     * @param file
     * @return
     * @throws Exception
     */
    public StringBuffer readZipFile(String file) throws Exception {
        ZipFile zf = new ZipFile(file);
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        ZipInputStream zin = new ZipInputStream(in);
        ZipEntry ze;
        StringBuffer sb = new StringBuffer();
        while ((ze = zin.getNextEntry()) != null) {
            System.out.print(ze);
            if (ze.isDirectory()) {
            } else {
                System.err.println("file - " + ze.getName() + " : "
                        + ze.getSize() + " bytes");
                long size = ze.getSize();
                if (size > 0) {
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(zf.getInputStream(ze),"GBK"));
                    String line;
                    boolean addFlag = false;
                    while ((line = br.readLine()) != null) {
                        if(line.indexOf("BusLineList") != -1){
                            addFlag = true;
                        }
                        if(addFlag){
                            sb.append(line);
                        }

                        if(line.indexOf("/BusLineList") != -1){
                            break;
                        }
                    }
                    br.close();
                }
            }
        }
        zin.closeEntry();
        return  sb;
    }

    /**
     * 解析xml
     * @param sb
     */
    private List<HashMap<String,String>> parseXml(StringBuffer sb){
        List<HashMap<String,String>> list = new ArrayList<>();
        HashMap<String,String> map;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new ByteArrayInputStream(sb.toString().getBytes()));
            NodeList nl = doc.getElementsByTagName("BusLine");
            String lineName; //线路名称
            String lineId; // 线路ID
            String abbreviation ; // 公司名称
            String ddfs ; // 调度方式
            String lineStandardCode; // 上海市线路编码
            String parentUnitName ; // 总公司
            for (int i = 0; i < nl.getLength(); i++) {
                parentUnitName = doc.getElementsByTagName("ParentUnitName").item(i).getFirstChild() == null ?"":
                        doc.getElementsByTagName("ParentUnitName").item(i).getFirstChild().getNodeValue();
                if(parentUnitName.indexOf("浦东") != -1){// 只查找浦东的数据
                    lineName = doc.getElementsByTagName("LineName").item(i).getFirstChild() == null ?"":
                            doc.getElementsByTagName("LineName").item(i).getFirstChild().getNodeValue();
                    lineId = doc.getElementsByTagName("LineId").item(i).getFirstChild() == null ?"":
                            doc.getElementsByTagName("LineId").item(i).getFirstChild().getNodeValue();
                    abbreviation = doc.getElementsByTagName("Abbreviation").item(i).getFirstChild() == null ?"":
                            doc.getElementsByTagName("Abbreviation").item(i).getFirstChild().getNodeValue();
                    ddfs = doc.getElementsByTagName("DDFS").item(i).getFirstChild() == null ?"":
                            doc.getElementsByTagName("DDFS").item(i).getFirstChild().getNodeValue();
                    lineStandardCode = doc.getElementsByTagName("LineStandardCode").item(i).getFirstChild() == null ?"":
                            doc.getElementsByTagName("LineStandardCode").item(i).getFirstChild().getNodeValue();
                    map = new HashMap<>();
                    map.put("lineName",lineName);
                    map.put("lineId",lineId);
                    map.put("abbreviation",abbreviation);
                    map.put("ddfs",ddfs);
                    map.put("lineStandardCode",lineStandardCode);
                    list.add(map);
                }
            }
        }catch (Exception e){
            e.printStackTrace();;
        }
        return list;
    }

    /**
     * 批量插入用法
     * @param list
     */
    public boolean insertRecord(List<HashMap<String,String>> list)
    {
        boolean flag = false;
        final List<HashMap<String,String>> tempList=list;
        String sql="INSERT INTO JJWGPS_T_SHSXLFILE(XLID,SHSXLBM,XLMC,GSMC,DDFS,CREATETIME,XLMC_ALL) VALUES (?,?,?,?,?,SYSDATE,?)";
        jdbcTemplate = new JdbcTemplate(DBUtils_oldSystem.getDataSource());
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter()
        {
            public void setValues(PreparedStatement ps, int i)throws SQLException
            {
                String lineId =tempList.get(i).get("lineId");
                String lineStandardCode =tempList.get(i).get("lineStandardCode");
                String lineName =tempList.get(i).get("lineName");
                String abbreviation =tempList.get(i).get("abbreviation");
                String ddfs =tempList.get(i).get("ddfs");
                String lineNameAll = lineName;
                if(ddfs.equals("2")){
                    lineNameAll = lineName+"区间(走向部分在全程线路之外)";
                }else if(ddfs.equals("7")){
                    lineNameAll = lineName+"区间(走向在全程线路之内)";
                }
                ps.setString(1, lineId);
                ps.setString(2, lineStandardCode);
                ps.setString(3, lineName);
                ps.setString(4, abbreviation);
                ps.setString(5, ddfs);
                ps.setString(6, lineNameAll);
            }
            public int getBatchSize()
            {
                return tempList.size();
            }
        });
        flag = true;
        return flag;
    }

    /**
     * 调用方法
     * @param methodName 方法名
     * @param param 参数
     * @return
     */
    public String invokeMethod(String methodName,String param){
        String result = null;
        try {
            // 获得客户端
            RPCServiceClient serviceClient = new RPCServiceClient();
            // 可以在该对象中设置服务端的验证信息
            Options options = serviceClient.getOptions();
            options.setTo(upTargetEPR);
            // 在创建QName对象时,QName类的构造方法的第一个参数表示WSDL文件的命名空间名,也就是<wsdl:definitions>元素的targetNamespace属性值
            QName opAddEntry = new QName(namespace,methodName);
            // 参数,如果有多个,继续往后面增加即可,不用指定参数的名称
            Object[] opAddEntryArgs = new Object[] {param };
            // 返回参数类型,这个和axis1有点区别
            // invokeBlocking方法有三个参数,其中第一个参数的类型是QName对象,表示要调用的方法名;
            // 第二个参数表示要调用的WebService方法的参数值,参数类型为Object[];
            // 第三个参数表示WebService方法的返回值类型的Class对象,参数类型为Class[]。
            // 当方法没有参数时,invokeBlocking方法的第二个参数值不能是null,而要使用new Object[]{}
            // 如果被调用的WebService方法没有返回值,应使用RPCServiceClient类的invokeRobust方法,
            // 该方法只有两个参数,它们的含义与invokeBlocking方法的前两个参数的含义相同
            Class[] classes = new Class[] { String.class };
            result = serviceClient.invokeBlocking(opAddEntry,opAddEntryArgs, classes)[0].toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}