1. 程式人生 > >java+maven工程 實現 自動對war包進行復制並修改和替換每個的配置檔案

java+maven工程 實現 自動對war包進行復制並修改和替換每個的配置檔案

   在工作中碰到一個比較苦惱的事情,(這裡以7條線為例子)同一個war包 需要部署7條生產線,但是每個生產線的編號以及ip都不同,導致我們手動的每個包去替換配置檔案和配           置ip的js檔案

        並且每次釋出,還需要手動去修改配置檔案裡面的版本號,這樣十分的繁瑣。因此該小程式實現對同一個war包進行自動替換裡面的配置和js檔案加入相關的版本號,

        生成對應的7個war,可以減少很多的時間成本。

       此功能配合jenkis 自動部署 生成的war目錄,即tomcat/webapps的目錄下  xxx.war (jenkis 自動化部署下章在做筆記) ,使用該程式自動生成的war  1.war、2.war ...

        7條線別對應的配置 以及js檔案 在當前專案裡面建立好。

  原理很簡單:原有的war包,複製7份並且替換包裡面的配置檔案以及js檔案。

一、專案resources 下面建立資料夾 如下面的7條線,每條線對應的propertie 和 js 檔案都不一樣(此專案是前後端分離的)

   

二、加入壓縮和解壓縮工具類

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.archivers.jar.JarArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.io.FileUtils; /** * 處理WAR檔案工具類。可壓縮或解壓縮WAR檔案。 * * @author Xiong Shuhong([email protected]) */ public class DeCompressUtil { public static void unzip(String warPath, String unzipPath) { File warFile = new File(warPath); try { BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(warFile)); ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.JAR, bufferedInputStream); JarArchiveEntry entry = null; while ((entry = (JarArchiveEntry) in.getNextEntry()) != null) { if (entry.isDirectory()) { new File(unzipPath, entry.getName()).mkdir(); } else { OutputStream out = FileUtils.openOutputStream(new File(unzipPath, entry.getName())); IOUtils.copy(in, out); out.close(); } } in.close(); } catch (FileNotFoundException e) { System.err.println("未找到war檔案"); } catch (ArchiveException e) { System.err.println("不支援的壓縮格式"); } catch (IOException e) { e.printStackTrace(); System.err.println("檔案寫入發生錯誤"); } } public static void zip(String destFile, String zipDir) { File outFile = new File(destFile); try { outFile.createNewFile(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outFile)); ArchiveOutputStream out = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.JAR, bufferedOutputStream); if (zipDir.charAt(zipDir.length() - 1) != '/') { zipDir += '/'; } Iterator<File> files = FileUtils.iterateFiles(new File(zipDir), null, true); while (files.hasNext()) { File file = files.next(); ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file, file.getPath().replace( zipDir.replace("/", "\\"), "")); out.putArchiveEntry(zipArchiveEntry); IOUtils.copy(new FileInputStream(file), out); out.closeArchiveEntry(); } out.finish(); out.close(); } catch (IOException e) { System.err.println("建立檔案失敗"); } catch (ArchiveException e) { System.err.println("不支援的壓縮格式"); } } }

三、加入檔案讀寫工具類

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
/**
 * java讀寫檔案,複製檔案
 * 讀取d:/1.txt檔案內容,寫入f:/text.txt檔案中.
 * @author young
 *
 */
public class FileUtil {
    // 讀寫檔案
    public static void copyFile(InputStream targetInputStream, String destFile){
        FileWriter fw = null;
        BufferedReader br = null;
        try {
            fw = new FileWriter(destFile, false);
            br = new BufferedReader(new InputStreamReader(targetInputStream));
            String line = null;
            while ((line = br.readLine()) != null) {
                fw.write(line + "\n");
                fw.flush();
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
    // 讀寫檔案
    public static void appendFile(String appendContent, String destFile){
        FileWriter fw = null;
        if(appendContent != null) {
            try {
                fw = new FileWriter(destFile, true);
                fw.write(appendContent + "\n");
                fw.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fw != null) {
                    try {
                        fw.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

四、該程式的配置檔案

  配置檔案只有源目錄 和 目標目錄

五、替換目標檔案業務程式碼 (程式碼裡面有詳細的註釋)

 

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import com.hxzhishi.odf.pcp.utils.DeCompressUtil;
import com.hxzhishi.odf.pcp.utils.FileUtil;



public class Main {
    
    //打包原始檔路徑
    private static String sourceFilePath;
    
    //打包原始檔路徑
    private static String replaceFilePath;
    
    private static void readProperties() {
        Properties properties = new Properties();
        // 使用ClassLoader載入properties配置檔案生成對應的輸入流
        InputStream in = Main.class.getClassLoader().getResourceAsStream("application.properties");
        // 使用properties物件載入輸入流
        try {
            properties.load(in);
            //獲取key對應的value值
            sourceFilePath = properties.getProperty("app.target.file.path");
            replaceFilePath = properties.getProperty("app.replace.file.path");
        } catch (IOException e) {
            System.out.println(e.getMessage());    
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /**
     * 獲得pc的版本號
     * @param sourceFile
     * @return
     */
    private static String getPcVersion(String sourceFile) {
        String pcVersion = null;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(sourceFile));
            String line = null;
            while((line = br.readLine()) != null) {
                if(line.indexOf("version") >= 0) {  //從原始的war裡面獲取版本號
                    pcVersion = line;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("獲取version資訊失敗.");
        } finally {
            if(br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return pcVersion;
    }
    
    public static void main(String[] args) {
        //1. 讀取配置資訊
        readProperties();
        String sourcePath = sourceFilePath;
        File file = new File(sourcePath);
        //2. 獲取version資訊
        String pcVersion = getPcVersion(sourcePath + File.separator + "WEB-INF" + File.separator + "classes" + File.separator + "application.properties");
        if(file.exists()) {
            if(file.isDirectory()) {
                File replaceFilesFold = new File(replaceFilePath);
                if(replaceFilesFold.exists() && replaceFilesFold.isDirectory()) {
                    File[] companyFoldArr = replaceFilesFold.listFiles();
                    if(companyFoldArr != null && companyFoldArr.length > 0) {
                        for(File companyFold : companyFoldArr) {
                            if(companyFold.isDirectory() && companyFold.getName().indexOf("svn") < 0) {//公司名稱
                                File[] factoryFoldArr = companyFold.listFiles();
                                if(factoryFoldArr != null && factoryFoldArr.length > 0) {
                                    for(File factoryFold : factoryFoldArr) {
                                        if(factoryFold.isDirectory() && factoryFold.getName().indexOf("svn") < 0) {//工廠名稱
                                            File[] lineFoldArr = factoryFold.listFiles();
                                            if(lineFoldArr != null && lineFoldArr.length > 0) {
                                                for(File lineFold : lineFoldArr) {
                                                    if(lineFold.isDirectory() && lineFold.getName().indexOf("svn") < 0) {//線別名稱
                                                        String fileName = companyFold.getName() + factoryFold.getName() + lineFold.getName() + ".war";
                                                        File[] replaceFileArr = lineFold.listFiles();
                                                        if(replaceFileArr != null && replaceFileArr.length >= 2) {
                                                            boolean isFailure = false;
                                                            for(File replaceFile : replaceFileArr) {
                                                                if("application.properties".equals(replaceFile.getName())) {
                                                                    try {
                                                                        InputStream inputStream = new FileInputStream(replaceFile);
                                                                        String destFile = sourcePath + File.separator + "WEB-INF" + File.separator + "classes" + File.separator + "application.properties";
                                                                        FileUtil.copyFile(inputStream, destFile);
                                                                        FileUtil.appendFile(pcVersion, destFile);
                                                                    } catch (FileNotFoundException e) {
                                                                        e.printStackTrace();
                                                                        System.out.println(replaceFile.getAbsolutePath() + "檔案讀取失敗.");
                                                                        isFailure = true;
                                                                    }
                                                                }
                                                                if("window-global.js".equals(replaceFile.getName())) {
                                                                    try {
                                                                        InputStream inputStream = new FileInputStream(replaceFile);
                                                                        FileUtil.copyFile(inputStream, sourcePath + File.separator + "static" + File.separator + "js" + File.separator + "window-global.js");
                                                                    } catch (FileNotFoundException e) {
                                                                        e.printStackTrace();
                                                                        System.out.println(replaceFile.getAbsolutePath() + "檔案讀取失敗.");
                                                                        isFailure = true;
                                                                    }
                                                                }
                                                            }
                                                            if(!isFailure) {//打包
                                                                generateLineWar(sourcePath, fileName);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                System.out.println("源目錄不是一個目錄.");    
            }
        } else {
            System.out.println("源目錄不存在.");    
        }
        System.out.println("打包結束");
    }
    
    /**
     * 生產打包檔案
     * @param sourcePath
     * @param fileName
     */
    private static void generateLineWar(String sourcePath, String fileName) {
        try {
            DeCompressUtil.zip(fileName, sourcePath);
            System.out.println(fileName + "檔案生成成功.");
        } catch (Exception e) {
            System.out.println(fileName + "檔案解壓失敗.");
            e.printStackTrace();
        }
    }
}

 

 六、把此程式放到tomcat下面 當jenkis 重新編譯的時候 便會生成7個對應的war包 包名就是生產線的名稱 防止拿錯包。