webservice 返回 字节流

组装一个xml(dom4j的document),转成二进制,然后加密,压缩。返回byte[]

1.接口类:


package gov.mof.fasp.ifmis.acal.common.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import gov.mof.fasp.AppException;
import gov.mof.fasp.dic.IDictionaryService;
import gov.mof.fasp.dic.elementcode.dto.CommonElementDTO;
import gov.mof.fasp.dic.table.dto.TableDTO;
import gov.mof.fasp.fm.util.FmUtil;
import gov.mof.fasp.ifmis.acal.common.expxml.ExpXmlDAO;
import gov.mof.fasp.ifmis.acal.common.expxml.ExpXmlUtil;
import gov.mof.fasp.ifmis.cal.CalUtil;
import gov.mof.fasp.ifmis.cal.acctset.acctterm.bo.AcctTermBO;
import gov.mof.fasp.ifmis.cal.acctset.acctterm.dto.AcctTermDTO;
import gov.mof.fasp.ifmis.cal.acctset.acctterm.dto.NewFmTermDTO;
import gov.mof.fasp.ifmis.cal.common.CalServiceFactory;
import gov.mof.fasp.ifmis.common.ServiceFactory;
import gov.mof.fasp.ifmis.common.bo.VoucherUtil;
import gov.mof.fasp.systemset.bo.SystemSetBO;
import gov.mof.fasp.systemset.dto.SystemSetDTO;

public class ExpXmlServiceImpl implements ExpXmlService {
    private ExpXmlDAO expXmlDAO;

    public void setExpXmlDAO(ExpXmlDAO expXmlDAO) {
        this.expXmlDAO = expXmlDAO;
    }

    /**
     * 使用xfire导出xml.
     * <p>
     * Title: expXml
     * </p>
     * <p>
     * Description:
     * </p>
     * @param acctsystype
     * @param hsagency
     * @param startterm
     * @param endterm
     * @param flag
     * @return
     * @see gov.mof.fasp.ifmis.acal.common.service.ExpXmlService#expXml(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
     */
    public byte[] expXml(String flag, String acctsystype, String hsagency, String start, String end, String acctyyear) {
        byte[] xml = null;
        xml = expSumVchXml(acctsystype, hsagency, start, end);
        return xml;

    }


    /**
     * 总账类xml
     * @param acctsystype
     * @param hsagency
     * @param start
     * @param end
     * @return
     * @throws
     */
    public byte[] expSumVchXml(String acctsystypecode, String hsagencycode, String start, String end) {
        String msg = "";
        String xml = "";
        String time = CalUtil.getCurrTime();
        int startterm = (null == start || "".equals(start)) ? 1 : Integer.parseInt(start);
        int endterm = (null == end || "".equals(end)) ? 12 : Integer.parseInt(end);
        String termfilter = " ((term between " + startterm + " and " + endterm + ") or term = 0)";

        String filename="总账类.xml";
        String path = System.getProperty("user.dir");
        Document document = DocumentHelper.createDocument();
        // 开始创建xml
        // 报文头信息
        Element rootElmt = document.addElement("总账",
                "http://sxbw.audit.gov.cn/AccountingSoftwareDataInterfaceStandard/2010/PSGA/XMLSchema");
        rootElmt.addNamespace("行政事业单位",
                "http://sxbw.audit.gov.cn/AccountingSoftwareDataInterfaceStandard/2010/PSGA/XMLSchema");
        rootElmt.addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        rootElmt.addAttribute("xsi:schemaLocation",
                "http://sxbw.audit.gov.cn/AccountingSoftwareDataInterfaceStandard/2010/PSGA/XMLSchema 总账.xsd");

        List accountSysList = expXmlDAO.getAccountsystemtype(acctsystypecode);// 账套信息
        if(null==accountSysList || accountSysList.size()==0){
            msg = "没有"+acctsystypecode+"账套信息!";
            document = DocumentHelper.createDocument();
            rootElmt = document.addElement("RESULT");
            rootElmt.addElement("STATUS").setText("0");
            rootElmt.addElement("MESSAGE").setText(msg);
            xml = document.asXML();
            expXmlDAO.insertLog(time, "0", msg, xml);
            byte[] formatDocument = FormatDocument(filename, path, document);
            return formatDocument;
        }
        Map map = (Map) accountSysList.get(0);
        String codeformat = (String) map.get("codeformat");
        String curracctyear = (String) map.get("curracctyear");
        String acctsystype = (String) map.get("acctsystypeid");

        List hsAgencyList = expXmlDAO.getHsAgency(hsagencycode);// 单位信息
        if(null==hsAgencyList || hsAgencyList.size()==0){
            msg = "没有"+hsagencycode+"单位信息!";
            document = DocumentHelper.createDocument();
            rootElmt = document.addElement("RESULT");
            rootElmt.addElement("STATUS").setText("0");
            rootElmt.addElement("MESSAGE").setText(msg);
            xml = document.asXML();
            expXmlDAO.insertLog(time, "0", msg, xml);
            byte[] formatDocument = FormatDocument(filename, path, document);
            return formatDocument;
        }
        Map map1 = (Map)hsAgencyList.get(0);
        String hsagency = (String) map1.get("itemid"); 
        String hsagencyname = (String) map1.get("name"); 
        try {
            /*** 总账基础信息 **/
            Element accttypeElement = rootElmt.addElement("总账基础信息");
            accttypeElement.addElement("结构分隔符").setText("-");
            accttypeElement.addElement("会计科目编号规则").setText(codeformat);
            accttypeElement.addElement("凭证头可扩展字段结构").setData(null);
            accttypeElement.addElement("凭证头可扩展结构对应档案").setData(null);
            accttypeElement.addElement("分录行可扩展字段结构").setData(null);
            accttypeElement.addElement("分录行可扩展字段对应档案").setData(null);
            /*** 记账凭证类型 **/
            List vchcls = expXmlDAO.findVouchcls(acctsystype);
            Map vchclsMap = new HashMap();
            Map _tempVchCls = null;
            for (int i = 0; i < vchcls.size(); i++) {}

            /*** 封装会计科目 **/
            List accountList = expXmlDAO.findAccount(acctsystype, hsagency, termfilter);
            /** 报表集 */
            Element reportElement = rootElmt.addElement("报表集");
            reportElement.addElement("报表编号");
            reportElement.addElement("报表名称").setText("资产负债表");
            reportElement.addElement("报表报告日").setText(FmUtil.format(new Date()));
            reportElement.addElement("报表报告期").setText(FmUtil.format(new Date()).substring(0, 6));
            reportElement.addElement("编制单位").setText(hsagencyname);
            reportElement.addElement("货币单位").setText("人民币");
            /** 报表项数据 */
            Element reportItemElement = rootElmt.addElement("报表项数据");
            reportItemElement.addElement("报表编号").setText("1");
            reportItemElement.addElement("报表项编号").setText("1");
            reportItemElement.addElement("报表项名称").setText("1");
            reportItemElement.addElement("报表项公式").setText("1");
            reportItemElement.addElement("报表项数值").setText("1.00");
            // xml = document.asXML();
            expXmlDAO.insertLog(time, "2", "总账类xml生成成功", xml);
        } catch (Exception e) {
            document = DocumentHelper.createDocument();
            rootElmt = document.addElement("RESULT");
            rootElmt.addElement("STATUS").setText("0");
            rootElmt.addElement("MESSAGE").setText(e.getMessage());
            xml = document.asXML();
            expXmlDAO.insertLog(time, "0", "总账类xml生成失败", xml);
            e.printStackTrace();
        }
        byte[] formatDocument = FormatDocument(filename, path, document);
        return formatDocument;
    }


    /**
     * 处理接口返回的xml
     * @param filename
     * @param path
     * @param document
     * @return
     * @throws
     */
    public byte[] FormatDocument(String filename,String path,Document document){
        return document.asXML().getBytes();
/*        byte[] compress = null;
        try {
            //1.导出到本地
            expExcelTemplate(filename, path, document);
            File file = new File(path+"\\"+filename);
            //2.读取本地xml
            byte[] b = getFileToByte(file);
            //3.加密
//            byte[] encodeBase64  = Base64.encodeBase64(b); 
            //4.压缩
//            compress= GZipUtils.compress(b);
            compress= b;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return compress;*/
    }    

    /**
     * 导出xml到本地
     */
    public void expExcelTemplate(String filename ,String path,Document document) throws IOException {
        File f = new File(path);
        f.mkdirs();
        path = path+"\\"+filename;
        // 封装xml报文数据
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");// 设置XML文件的编码格式
        format.setNewLineAfterDeclaration(false);//声明之后不换行
        format.setIndent(false); //设置是否缩进
        format.setNewlines(true); //设置是否换行

        XMLWriter writer = null;
        try {
          writer = new XMLWriter(new FileWriter(path), format);//写入指定的文件
          writer.write(document);
      } catch (IOException e) {
          e.printStackTrace();
      } finally {
          try {
              writer.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
    }
    /**
     * 将生成文件, 转为二进制
     * @param file
     * @return
     * @throws
     */
    public byte[] getFileToByte(File file) {
        byte[] by = new byte[(int) file.length()];
        try {
            InputStream is = new FileInputStream(file);
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            byte[] bb = new byte[2048];
            int ch;
            ch = is.read(bb);
            while (ch != -1) {
                bytestream.write(bb, 0, ch);
                ch = is.read(bb);
            }
            by = bytestream.toByteArray();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return by;
    }
}

2.压缩工具类:


package gov.mof.fasp.ifmis.acal.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
 * @ClassName: GZipUtils
 * @Description: Description of this class
 * @author <a href="mailto:[email protected]"></a>于 2017-12-18 上午10:42:36
 */
public abstract class GZipUtils {

    public static final int BUFFER = 1024;
    public static final String EXT = ".gz";

    /**
     * 数据压缩
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] compress(byte[] data) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // 压缩
        compress(bais, baos);

        byte[] output = baos.toByteArray();

        baos.flush();
        baos.close();

        bais.close();

        return output;
    }

    /**
     * 文件压缩
     * @param file
     * @throws Exception
     */
    public static void compress(File file) throws Exception {
        compress(file, true);
    }

    /**
     * 文件压缩
     * @param file
     * @param delete 是否删除原始文件
     * @throws Exception
     */
    public static void compress(File file, boolean delete) throws Exception {
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(file.getPath() + EXT);

        compress(fis, fos);

        fis.close();
        fos.flush();
        fos.close();

        if (delete) {
            file.delete();
        }
    }

    /**
     * 数据压缩
     * @param is
     * @param os
     * @throws Exception
     */
    public static void compress(InputStream is, OutputStream os) throws Exception {

        GZIPOutputStream gos = new GZIPOutputStream(os);

        int count;
        byte data[] = new byte[BUFFER];
        while ((count = is.read(data, 0, BUFFER)) != -1) {
            gos.write(data, 0, count);
        }

        gos.finish();

        gos.flush();
        gos.close();
    }

    /**
     * 文件压缩
     * @param path
     * @throws Exception
     */
    public static void compress(String path) throws Exception {
        compress(path, true);
    }

    /**
     * 文件压缩
     * @param path
     * @param delete 是否删除原始文件
     * @throws Exception
     */
    public static void compress(String path, boolean delete) throws Exception {
        File file = new File(path);
        compress(file, delete);
    }

    /**
     * 数据解压缩
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] decompress(byte[] data) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // 解压缩

        decompress(bais, baos);

        data = baos.toByteArray();

        baos.flush();
        baos.close();

        bais.close();

        return data;
    }

    /**
     * 文件解压缩
     * @param file
     * @throws Exception
     */
    public static void decompress(File file) throws Exception {
        decompress(file, true);
    }

    /**
     * 文件解压缩
     * @param file
     * @param delete 是否删除原始文件
     * @throws Exception
     */
    public static void decompress(File file, boolean delete) throws Exception {
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(file.getPath().replaceAll(EXT, ""));
        decompress(fis, fos);
        fis.close();
        fos.flush();
        fos.close();

        if (delete) {
            file.delete();
        }
    }

    /**
     * 数据解压缩
     * @param is
     * @param os
     * @throws Exception
     */
    public static void decompress(InputStream is, OutputStream os) throws Exception {

        GZIPInputStream gis = new GZIPInputStream(is);

        int count;
        byte data[] = new byte[BUFFER];
        while ((count = gis.read(data, 0, BUFFER)) != -1) {
            os.write(data, 0, count);
        }

        gis.close();
    }

    /**
     * 文件解压缩
     * @param path
     * @throws Exception
     */
    public static void decompress(String path) throws Exception {
        decompress(path, true);
    }

    /**
     * 文件解压缩
     * @param path
     * @param delete 是否删除原始文件
     * @throws Exception
     */
    public static void decompress(String path, boolean delete) throws Exception {
        File file = new File(path);
        decompress(file, delete);
    }

    /**
     * 将16进制转换为二进制
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 将二进制转换成16进制
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
}

3.测试类:

/**
 * @Title: ExpXmlTest.java
 * @Copyright (C) 2017 龙图软件
 * @Description:
 * @Revision History:
 * @Revision 1.0 2017-12-14  张志广
 */

package gov.mof.fasp.ifmis.acal.common.service;

import freemarker.template.Environment;
import gov.mof.fasp.ifmis.acal.common.GZipUtils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.codehaus.xfire.util.Base64;
import org.junit.Test;

import sun.misc.BASE64Decoder;

/**
 * @ClassName: ExpXmlTest
 * @Description: Description of this class
 * @author <a href="mailto:[email protected]">xx</a>于 2017-12-14 下午03:38:15
 */

public class ExpXmlTest {
    @Test
    public void axisToAsset() throws Exception {
        String serviceUrl = "http://localhost:7001/services//ExpXmlService";
        Service service = new Service();
        Call call = (Call) service.createCall();
        call.setTimeout(new Integer("10000")); // 设置超时
        call.setTargetEndpointAddress(new URL(serviceUrl));
        String targetNamespace = "http://service.common.acal.ifmis.fasp.mof.gov";
        QName qName = new QName(targetNamespace, "expXml");
        call.setOperationName(qName);
        String message = null;
        try {
            String flag = "2";//2:导出总账类,1:导出公共档案
            String acctsystypecode = "XZ";//账套code XZ_1
            String hsagency = "005001";//单位code--005001
            String startterm = "1";//开始期间
            String endterm = "12";//默认期间
            String acctyear = "2017";//年度
            call.addParameter(new QName(targetNamespace, "flag"), XMLType.XSD_STRING, ParameterMode.IN);
            call.addParameter(new QName(targetNamespace, "acctsystypecode"), XMLType.XSD_STRING, ParameterMode.IN);
            call.addParameter(new QName(targetNamespace, "hsagency"), XMLType.XSD_STRING, ParameterMode.IN);
            call.addParameter(new QName(targetNamespace, "startterm"), XMLType.XSD_STRING, ParameterMode.IN);
            call.addParameter(new QName(targetNamespace, "endterm"), XMLType.XSD_STRING, ParameterMode.IN);
            call.addParameter(new QName(targetNamespace, "acctyear"), XMLType.XSD_STRING, ParameterMode.IN);
             call.setReturnType(XMLType.XSD_BASE64);
            Object[] obj = {flag, acctsystypecode, hsagency, startterm, endterm, acctyear };
            try {
                // String ret = (String) call.invoke(obj);
                //
                // System.out.println("Get   result   :" + ret);

                /**
                 * 解码, 并读入文件
                 */
                long start = System.currentTimeMillis();
                byte[] bytes = (byte[]) call.invoke(obj);
                long end = System.currentTimeMillis();
                System.out.println(end-start);
                //8876 3741

//                byte[] decompress = GZipUtils.decompress(bytes);
                FileOutputStream fileOutPutStream = new FileOutputStream("D:\\我是下载的文件.xml");
                // 将字节数组bytes中的数据,全部写入输出流fileOutPutStream中
                fileOutPutStream.write(bytes);
                fileOutPutStream.flush();
                fileOutPutStream.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        return message;
    }

    // 将 s 进行 BASE64 编码
    public static String getBASE64(String s) {
        if (s == null)
            return null;
        return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
    }

    // 将 BASE64 编码的字符串 s 进行解码
    public static String getFromBASE64(String s) {
        if (s == null)
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return new String(b);
        } catch (Exception e) {
            return null;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/waei08/article/details/78889582