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包 包名就是生产线的名称 防止拿错包。

原文地址:https://www.cnblogs.com/citime/p/10059737.html

时间: 2024-10-10 23:46:39

java+maven工程 实现 自动对war包进行复制并修改和替换每个的配置文件的相关文章

java web项目使用IDEA打成war包

步骤: 1.点击 File -->Project Structure...如下图: 2.出现如下界面后点击 Artifacts--> 绿色加号-->Web Application:Archive-->For'项目名:war exploded' 如下图: 3.出现如下界面后 Output directory=war包生成的位置  Include in project build=tomcat每次启动后自动打war包   下面还会介绍手动打war包的步骤: 4.之后点击下图绿色加号:

Eclipse下maven项目自动打war包丢失jar包问题解决方法

以前用Eclipse测试maven 的web工程,在eclipse内部tomcat右键上点一下"clean"就可以把工作空间的web项目代码自动发布到"F:\IWorkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps"这个路径,十分的方便.如果tomcat里部署的war包选择的是"Add External Web Module"的话,那测试的话,就要哭了.每次

maven web project打包为war包,目录结构的变化

一个maven web project工程目录: 资源管理器中的目录层级如下: 导出为war包之后的目录层级为: 我们会发现,其实并没有如下的这些目录层级: 所以这两个目录层级只是IDE为我们添加的,便于编程而添加的.Java Resource 目录是Source Folder,该目录下的资源都会被打包到:WEB-INF/classes 文件夹下.注意:你会发现在Java Resource下的文件夹下创建的jsp,html等网页文件都会被自动放置到src/main/webapp文件夹下,因为在这

我爱Java系列之---【SpringBoot打成war包部署】

1.把下面这句话放入pom.xml中,放上边 <packaging>war</packaging> 2.war包要部署到tomcat服务器中,而springboot中自带了一个,这时候要去掉. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclus

maven项目中自动下载jar包的pom.xml配置

用 maven2 ,pom.xml中设置了依赖,会帮你下载所有依赖的.jar到 M2_REPO 指向的目录 -------------------------------------------------------------------------------------------- M2_REPO是一个用来定义 maven 2仓库在硬盘中的存储位置,windows默认是C:\Users\机器名\.m2\repository.按道理安装了m2eclipse插件就会在eclipse有了相应

Tomcat自动发布war包

有两种方法: 1.将项目打成war包,复制到${tomcat.home}\webapps目录下.当tomcat启动时会自动将其解包. 有人说,不能直接将war文件夹直接复制到${tomcat.home}\webapps目录下. 但是我试过之后,可以.将war包解压,解压出的文件夹要和war文件同名(后面可没有 .war),然后将文件夹放到webapps下面就可以了 2.修改${tomcat.home}\conf\server.xml文件.在Host节点下增加如下参考代码: <Context do

maven中打包项目为war包的pom.xml配置

maven中打包成war包的pom.xml配置(1)完整配置:这个是使用servlet的完整配置,其他的类似. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven

Maven项目不自动下载jar包的解决办法

1.手动更新idea里的本地仓库 Setting --> Build,Execution,Deployment --> Maven --> Repositories 点击UPDATE进行更新 2.更新不完整依赖命令 打开maven命令框 ---> 输入 -U idea:idea 命令--->点击Execute等待命令运行完成 3.取消选中Work offline选项 Setting --> Build,Execution,Deployment --> Maven

eclipse利用maven自动打war包部署到tomcat7上

环境: eclipse 版本 Eclipse Java EE IDE for Web Developers.Version: Kepler Service Release 2 maven版本:Apache Maven 3.2.5 tomcat7版本:Apache Tomcat/7.0.54 建立web工程,在pox.xml中进行配置 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://