1. 程式人生 > >將資料庫查詢資料封裝到XML檔案中,進行格式化處理,並進行加密操作,和解密操作

將資料庫查詢資料封裝到XML檔案中,進行格式化處理,並進行加密操作,和解密操作

1.pom檔案

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <!-- https://mvnrepository.com/artifact/xerces/xercesImpl -->
    <dependency>
      <groupId>xerces</groupId>
      <artifactId>xercesImpl</artifactId>
      <version>2.9.1</version>
    </dependency>

    <!-- JSONObject物件依賴的jar包 開始-->
    <dependency>
      <groupId>commons-beanutils</groupId>
      <artifactId>commons-beanutils</artifactId>
      <version>1.9.3</version>
    </dependency>
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.2.1</version>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.6</version>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1.1</version>
    </dependency>
    <dependency>
      <groupId>net.sf.ezmorph</groupId>
      <artifactId>ezmorph</artifactId>
      <version>1.0.6</version>
    </dependency>
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.2.3</version>
      <classifier>jdk15</classifier><!-- jdk版本 -->
    </dependency>
    <!-- Json依賴架包下載結束 -->
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>


        <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <configuration>
            <descriptorRefs>
              <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
          </configuration>
        </plugin>


      </plugins>
    </pluginManagement>
  </build>

2.將查詢資料封裝到XML檔案中,並進行格式化處理

package com.zcl.util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * sql查詢資料封裝到xml檔案中
 */
public class DataToXml {
    //預設值
    private static final String JSON="json";
    private static final String XML="xml";


    /**
     *  工具類入口
     * @param type 資料型別   json / xml
     * @return  字串
     */
    public static void DataToJsonOrXml(Object obj,String type) throws Exception{
        //大小寫不影響
        String str="";
        if(JSON.equalsIgnoreCase(type)&&JSON.equals(type)){
            //生成json資料
            str=toJsonString(obj);
        }else if(XML.equalsIgnoreCase(type)&&XML.equals(type)){
            //生成xml資料
            str=toXml(obj);
        }else{
            //預設使用 json , 引數錯誤的話 ,預設 為json
            str=toJsonString(obj);
        }
        str = XmlFormatter.format(str);
        writeToXml(str);
    }
    /**
     * 轉 json 物件
     * @param obj  資料
     * @return json物件 字串
     */
    private static String toJsonString(Object obj){

        if(obj==null) {
            obj="";
        }
        Map<String, Object> map=toKeyVal(obj);
        JSONObject jsonObject=JSONObject.fromObject(map);
        return jsonObject.toString();
    }
    /**
     *  轉xml 格式 :字串拼裝的格式
     * @param obj  資料
     * @return xml資料
     */
    private static String toXml(Object obj){
        if(obj==null) {
            obj="";
        }
        Map<String,Object> map=toKeyVal(obj);
        JSONObject object=JSONObject.fromObject(map);

        StringBuilder builder=new StringBuilder("<?xml version='1.0' encoding='UTF-8'?>");
        builder.append("<root>");
        builder.append(mapToxml(object));
        builder.append("</root>");

        return builder.toString();
    }
    /**
     * 用來封裝資料
     * @param obj 資料
     * @return
     */
    private static Map<String, Object> toKeyVal(Object obj){
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("data", obj);
        return map;
    }
    /**
     * 生成 xml
     * @param object
     * @return
     */
    private static String mapToxml(JSONObject object){
        StringBuilder builder=new StringBuilder();
        @SuppressWarnings("unchecked")
        Iterator<String> iterator=object.keys();
        while(iterator.hasNext()){
            String key=iterator.next();
            builder.append("<"+key+">");
            if(object.get(key) instanceof JSONObject){
                //如果是 JSONObject的話
                //遞迴 呼叫
                builder.append(mapToxml((JSONObject) object.get(key)));
            }else if(object.get(key) instanceof JSONArray){
                //如果是 JSONArray的話
                StringBuilder builder2=new StringBuilder();
                JSONArray array=(JSONArray) object.get(key);

                if(array.isArray()){
                    int i=0;
                    for(Object obj : array) {
                        JSONObject objitem=(JSONObject) obj;
                        String attr="num='"+i+"'";
                        builder2.append("<item "+attr+">");
                        builder2.append(mapToxml(objitem));
                        builder2.append("</item>");
                        i++;
                    }
                }
                builder.append(builder2.toString());
            }else{
                builder.append(object.get(key));
            }
            builder.append("</"+key+">");
        }
        return builder.toString();
    }

    private static void writeToXml(String str) throws  Exception{
        //專案根路徑
        String relativelyPath=System.getProperty("user.dir");
        String fileName = relativelyPath+"\\"+new SimpleDateFormat("yyyyMMdd").format(new Date())+".xml";
        //1.生成xml檔案
        FileWriter fw=new FileWriter(fileName);
        BufferedWriter bw=new BufferedWriter(fw);
        bw.write(str);
        bw.close();
        fw.close();
    }

}

3.XML檔案的格式化操作

package com.zcl.util;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

/**
 * 格式化xml
 */
public class XmlFormatter {
    public static String format(String unformattedXml) {
        try {
            final Document document = parseXmlFile(unformattedXml);
            OutputFormat format = new OutputFormat(document);
            format.setLineWidth(65);
            format.setIndenting(true);
            format.setIndent(2);
            Writer out = new StringWriter();
            XMLSerializer serializer = new XMLSerializer(out, format);
            serializer.serialize(document);
            return out.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static Document parseXmlFile(String in) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(in));
            return db.parse(is);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

4.DES方式加密和解密檔案

package com.zcl.util;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class DESCryptoXml {

    /**
     * 檔案加密
     */
    public static void encrypt(String fileName) {
        try {
            String key = "abf894ba2a0e798f";
            // 再把我們的字串轉變為位元組陣列,可以用於另一方使用,驗證
            byte[] decodeHex = Hex.decodeHex(key.toCharArray());
            // 生成金鑰物件
            SecretKeySpec secretKeySpec = new SecretKeySpec(decodeHex, "DES");

            // 獲取加解密例項
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            // 初始化加密模式
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

            // 讀入並加密檔案
            try {
                // 輸入流
                BufferedInputStream in = new BufferedInputStream(
                        new FileInputStream(fileName));
                // 輸出流
                //新檔名
                String fileNewName = fileName.substring(0,fileName.indexOf("."))+"Encrypt"+fileName.substring(fileName.indexOf("."));
                CipherOutputStream out = new CipherOutputStream(
                        new BufferedOutputStream(new FileOutputStream(fileNewName)), cipher);
                int i;
                do {
                    i = in.read();
                    if (i != -1)
                        out.write(i);
                } while (i != -1);

                in.close();
                out.close();
                System.out.println("success when encrypt the file");
            } catch (Exception ey5) {
                System.out.println("error when encrypt the file");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 檔案解密
     * @param fileName
     */
    public static void decrypt(String fileName) {
        try {
            String key = "abf894ba2a0e798f";
            // 再把我們的字串轉變為位元組陣列,可以用於另一方使用,驗證
            byte[] decodeHex = Hex.decodeHex(key.toCharArray());
            // 生成金鑰物件
            SecretKeySpec secretKeySpec = new SecretKeySpec(decodeHex, "DES");

            // 獲取加解密例項
            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
            // 初始化加密模式
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            try {
                // 輸入流
                CipherInputStream in = new CipherInputStream(
                        new BufferedInputStream(new FileInputStream(fileName)), cipher);
                // 輸出流
                //新檔名
                String fileNewName = fileName.substring(0,fileName.indexOf("."))+"Decrypt"+fileName.substring(fileName.indexOf("."));
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(fileNewName));

                int i;
                do {
                    i = in.read();
                    if (i != -1)
                        out.write(i);
                } while (i != -1);

                in.close();
                out.close();
                System.out.println("success when decrypt the file");
            } catch (Exception ey5) {
                System.out.println("error when decrypt the file");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /***
     * 生成祕鑰字串
     */
    public static void main(String[] args) throws Exception{
        // 以DES的方式初始化Key生成器
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
        keyGenerator.init(56);// 設定金鑰的長度為56位
        // 生成一個Key
        SecretKey generateKey = keyGenerator.generateKey();
        // 轉變為位元組陣列
        byte[] encoded = generateKey.getEncoded();
        // 生成金鑰字串
        String encodeHexString = Hex.encodeHexString(encoded);
        System.out.println("Key : " + encodeHexString);
    }
}

5.測試

 @Test
    public void shouldAnswerWithTrue() throws Exception
    {
       /* List<Object> list = new ArrayList<>();
        Map<String,String> map1 = new HashMap<>();
        map1.put("username","張三");
        map1.put("password","李四");
        Map<String,String> map2 = new HashMap<>();
        map2.put("username","張三");
        map2.put("password","李四");
        list.add(map1);
        list.add(map2);*/
        //第一步:生成xml檔案
        //DataToXml.DataToJsonOrXml(list,"xml");
        //加密
        //DESCryptoXml.encrypt("F:\\IDEAWorkspaces\\ceshiDataToXml\\20180822.xml");
        //解密
        //DESCryptoXml.decrypt("F:\\IDEAWorkspaces\\ceshiDataToXml\\20180822Encrypt.xml");
    }