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

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

classes cep res 發生 分離 sys span 一個 pla

在工作中碰到一個比較苦惱的事情,(這裏以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包 包名就是生產線的名稱 防止拿錯包。

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