Spring boot Jar 解压缩压缩

Spring boot Jar 解压缩压缩

前言

前面转载了一篇关于jar压缩解压缩,修改 jar 内部内容的,当时没有使用,后来在 spring boot 之中使用后发现了问题,重新修改一下上传。

代码

使用 commons-compress-1.18.jar 来压缩,因为 jdk 自带压缩类无法直接使用 JarEntry new 新类会报字节大小错误;
取消对 jar/war 包之中子 jar 包的解压和压缩,子 jar 包重新打包会报无法引用的错误。
这些修改是对 spring boot 打包出来的包进行解压压缩修改,其余方式没有测试。


package configuration.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;

import org.apache.commons.compress.archivers.jar.JarArchiveEntry;
import org.apache.commons.compress.archivers.jar.JarArchiveOutputStream;

/**
 * @author Chenfei
 */
public class JarArchiveUtils {

    @SuppressWarnings("unused")
    private JarArchiveUtils() {

    }

    // the war file to write at last
    private File warFile;
    // the temp directory to pre-write...
    private File tempDir;

    private byte[] buf = new byte[1048576];// the writing buffer

    /**
     * create a war writer upon a war file... should also works for a jar file
     * @param warPath the absolute path of the underlying war file
     */
    public JarArchiveUtils(String warPath) {
        File f = new File(warPath);
        if (!f.exists())
            throw new RuntimeException("file does not exist: " + warPath);
        // test if zip format
        JarInputStream i = null;
        try {
            i = new JarInputStream(new FileInputStream(f));
            if (i.getNextEntry() == null) {
                throw new RuntimeException("Not jar/war format: " + warPath);
            }
        } catch (Exception e) {
            throw new RuntimeException("Not jar/war format: " + warPath);
        } finally {
            try {
                if (i != null)
                    i.close();
            } catch (IOException e) {
            }
        }
        this.warFile = f;
        // create temp directory
        this.tempDir = createTempDirectory(f.getName());
    }

    private File createTempDirectory(String warName) {
        final File temp;

        try {
            temp = File.createTempFile(warName, Long.toString(System.currentTimeMillis()));
            temp.deleteOnExit();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (!(temp.delete())) {
            throw new RuntimeException("Could not delete temp file: " + temp.getAbsolutePath());
        }

        if (!(temp.mkdir())) {
            throw new RuntimeException("Could not create temp directory: " + temp.getAbsolutePath());
        }

        return temp;
    }

    /**
     * default false, don't decompress sub jar files in jar/war file
	 * just use InputStream write to new jar/war file
     * @throws IOException
     */
    public void done() throws IOException {
        done(false);
    }

	/**
     * Complete writing, rebuild the final result jar/war file and do cleaning.
     * @throws IOException
     */
    public void done(boolean decompressionSubJar) throws IOException {
        // really writing to the war file, in fact a merging from the temp dir
        // writing to war
        // // listing temp dir files in jar entry naming style
        Map<String, File> tempDirFiles = listFilesInJarEntryNamingStyle(this.tempDir, this.tempDir.getAbsolutePath());
        // // create temp war
        File tempWar = File.createTempFile(this.warFile.getName(), null);
        // // merging write to the temp war
        JarArchiveOutputStream jos = new JarArchiveOutputStream(new FileOutputStream(tempWar));
        JarFile jf = new JarFile(this.warFile);
        try {
            Enumeration<JarEntry> iter = jf.entries();
            while (iter.hasMoreElements()) {
                JarEntry e = iter.nextElement();
                String name = e.getName();
                if (decompressionSubJar && !e.isDirectory() && name.endsWith(".jar")) {
                    writeJarEntry(e, filterByDirName(tempDirFiles, name), jf, jos);
                } else {
                    // prefer file in dir to war
                    InputStream fin = null;
                    if (tempDirFiles.containsKey(name)) {
                        File f = tempDirFiles.get(name);
                        if (!e.isDirectory())
                            fin = new FileInputStream(f);
                        addEntry(name, fin, f.lastModified(), jos);
                        tempDirFiles.remove(name);
                    } else {
                        if (!e.isDirectory())
                            fin = jf.getInputStream(e);
                        addEntry(e, fin, e.getTime(), jos);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jf != null)
                jf.close();
        }
        // // writing remained files in dir
        for (Map.Entry<String, File> remain : tempDirFiles.entrySet()) {
            String dirFileName = remain.getKey();
            File dirFile = remain.getValue();
            InputStream in = null;
            if (!dirFile.isDirectory())
                in = new FileInputStream(dirFile);
            addEntry(dirFileName, in, dirFile.lastModified(), jos);
        }
        // // replace the target war using the temp war
        jos.close();
        moveTo(tempWar, warFile);
        // clean
        // // cleaning temp dir
//        recurDel(this.tempDir);
    }

    // move from to files
    private void moveTo(File from, File to) throws IOException {
        // try rename directly
        if (!from.renameTo(to)) {
            // renameTo failed, fallback to file flowing...
            System.out.println("File.renameTo failed, fallback to file streaming...");
            if (!from.exists())
                throw new IOException("From file does not exist: " + from.getAbsolutePath());
            if (!to.exists() && !to.createNewFile())
                throw new IOException("To from does not exist and cannot be created: " + to.getAbsolutePath());
            OutputStream o = new FileOutputStream(to);
            try {
                flowTo(new FileInputStream(from), o);
            } finally {
                from.delete();
                o.close();
            }
            System.out.println("File stream flowing moving done!");
        }
    }

    /*
     * list the files&dirs in the specified dir, in a jar entry naming style: 1)
     * all file names come with no preceding '/' 2) all file names of
     * directories must be suffixed by a '/'
     */
    private Map<String, File> listFilesInJarEntryNamingStyle(File f, String basePath) {
        Map<String, File> ret = new HashMap<String, File>();
        String name = f.getAbsolutePath().substring(basePath.length());
        name = name.replace("\\", "/");
        if (name.startsWith("/"))
            name = name.substring(1);
        if (f.isDirectory()) {
            if (!name.endsWith("/"))
                name += "/";
            for (File sub : f.listFiles()) {
                ret.putAll(listFilesInJarEntryNamingStyle(sub, basePath));
            }
        }
        // add the current level directory itself except for the root dir
        if (!"/".equals(name))
            ret.put(name, f);
        return ret;
    }

    public void recurDel() {
        recurDel(this.tempDir);
    }

    private void recurDel(File file) {
        if (file.isDirectory()) {
            for (File item : file.listFiles())
                recurDel(item);
        }
        file.delete();
    }

    // merging write jar entry
    private void writeJarEntry(JarEntry origJarEntry, Map<String, File> mergingFiles, JarFile origWar,
        JarArchiveOutputStream targetWarStream) throws IOException {
        // if there's no merging file for this jar entry, write the original jar
        // data directly
        if (mergingFiles == null || mergingFiles.isEmpty()) {
            JarArchiveEntry je = new JarArchiveEntry(origJarEntry.getName());
            je.setTime(origJarEntry.getTime());
            targetWarStream.putArchiveEntry(je);
            flowTo(origWar.getInputStream(origJarEntry), targetWarStream);
            targetWarStream.closeArchiveEntry();
        } else {
            String origJarEntryName = origJarEntry.getName();
            long modTime = -1;
            String mergingDirName = origJarEntryName + "/";
            if (mergingFiles.containsKey(mergingDirName)) {
                modTime = mergingFiles.get(mergingDirName).lastModified();
            } else {
                modTime = origJarEntry.getTime();
            }

            JarArchiveEntry je = new JarArchiveEntry(origJarEntryName);
            je.setTime(modTime);
            targetWarStream.putArchiveEntry(je);

            mergingFiles.remove(mergingDirName);

            // build the jar data
            String jarSimpleName = origJarEntryName.contains("/")
                ? origJarEntryName.substring(origJarEntryName.lastIndexOf("/") + 1)
                : origJarEntryName;
            // // build the tmp jar file to write to
            File tmpOutputJarFile = File.createTempFile(jarSimpleName, null);
            JarArchiveOutputStream tmpOutputJar = new JarArchiveOutputStream(new FileOutputStream(tmpOutputJarFile));

            // // dump the original jar file to iterate over
            File tmpOrigJarFile = buildTempOrigJarFile(jarSimpleName + "_orig", origWar.getInputStream(origJarEntry));
            JarFile tmpOrigJar = new JarFile(tmpOrigJarFile);

            for (Enumeration<JarEntry> e = tmpOrigJar.entries(); e.hasMoreElements();) {
                JarEntry origJarItemEntry = e.nextElement();
                String origJarItemEntryName = origJarItemEntry.getName();
                String mergingFileName = mergingDirName + origJarItemEntryName;
                InputStream itemIn = null;
                long itemModTime = -1;
                // prefer dir files to origJar entries
                if (mergingFiles.containsKey(mergingFileName)) {
                    File f = mergingFiles.get(mergingFileName);
                    if (!origJarItemEntry.isDirectory())
                        itemIn = new FileInputStream(f);
                    itemModTime = f.lastModified();
                    mergingFiles.remove(mergingFileName);
                } else {
                    if (!origJarItemEntry.isDirectory())
                        itemIn = tmpOrigJar.getInputStream(origJarItemEntry);
                    itemModTime = origJarItemEntry.getTime();
                }
                addEntry(origJarItemEntry, itemIn, itemModTime, tmpOutputJar);
            }
            tmpOrigJar.close();
            tmpOrigJarFile.delete();

            // check&write remained dir files
            for (Map.Entry<String, File> remain : mergingFiles.entrySet()) {
                String dirFileName = remain.getKey();
                File dirFile = remain.getValue();
                InputStream in = null;
                if (!dirFile.isDirectory())
                    in = new FileInputStream(dirFile);
                addEntry(dirFileName.substring(mergingDirName.length()), in, dirFile.lastModified(), tmpOutputJar);
            }
            tmpOutputJar.close();

            // write to war
            InputStream jarData = new FileInputStream(tmpOutputJarFile);
            flowTo(jarData, targetWarStream);
            jarData.close();
            tmpOutputJarFile.delete();

            targetWarStream.closeArchiveEntry();
        }
    }

    // build a temp file containing the given inputStream data
    private File buildTempOrigJarFile(String name, InputStream in) throws IOException {
        File f = File.createTempFile(name, null);
        OutputStream out = new FileOutputStream(f);
        try {
            flowTo(in, out);
        } finally {
            out.close();
        }
        return f;
    }

    // data stream 'flow' from in to out, pseudo-zero-copy
    private void flowTo(InputStream in, OutputStream out) throws IOException {
        try {
            for (int count = in.read(buf); count != -1; count = in.read(buf)) {
                out.write(buf, 0, count);
            }
        } finally {
            in.close();
        }
    }

    // collect entries which contain the specified dir path segment, and also
    // delete from the original map
    private Map<String, File> filterByDirName(Map<String, File> nameFileMapping, String pathSegment) {
        if (nameFileMapping == null || nameFileMapping.isEmpty())
            return Collections.emptyMap();
        Map<String, File> ret = new HashMap<String, File>();
        if (!pathSegment.endsWith("/"))
            pathSegment += "/";
        for (Iterator<Map.Entry<String, File>> iter = nameFileMapping.entrySet().iterator(); iter.hasNext();) {
            Map.Entry<String, File> e = iter.next();
            if (e.getKey().contains(pathSegment)) {
                ret.put(e.getKey(), e.getValue());
                iter.remove();
            }
        }
        return ret;
    }

    private void addEntry(JarEntry inputEntry, InputStream in, long modTime, JarArchiveOutputStream target)
        throws IOException {
        JarArchiveEntry e = new JarArchiveEntry(inputEntry);
//        e.setTime(modTime);
        target.putArchiveEntry(e);
        if (in != null) {
            flowTo(in, target);
        }
        target.closeArchiveEntry();
    }

    private void addEntry(String entryName, InputStream in, long modTime, JarArchiveOutputStream target)
        throws IOException {
        JarArchiveEntry e = new JarArchiveEntry(entryName);
        e.setTime(modTime);
        target.putArchiveEntry(e);
        if (in != null) {
            flowTo(in, target);
        }
        target.closeArchiveEntry();
    }

    /**
     * create outputStream writing to the specified war/jar file, all paths
     * specified here are relative to the root of the war/jar.
     */
    public OutputStream getFileOutputStream(String relPath) throws IOException {
        File f = getFile(relPath);
        return new FileOutputStream(f);
    }

    private File getFile(String relPath) throws IOException {
        if (relPath.startsWith("/")) {
            relPath = relPath.substring(1);
        }
        if (relPath.endsWith("/")) {
            relPath = relPath.substring(0, relPath.length() - 1);
        }
        File f = new File(this.tempDir.getAbsolutePath() + "/" + relPath);
        File p = f.getParentFile();
        if (p != null && !p.exists()) {
            p.mkdirs();
        }
        if (!f.exists())
            f.createNewFile();
        return f;
    }

    public String loadFile(String relPath) throws IOException {
        if (relPath.startsWith("/") || relPath.startsWith("\\")) {
            relPath = relPath.substring(1);
        }
        File f = getFile(relPath);

        FileOutputStream os = new FileOutputStream(f);

        JarArchiveEntry entry = new JarArchiveEntry(relPath.replace("\\", "/"));
        JarFile jf = new JarFile(this.warFile);
        InputStream ins = jf.getInputStream(entry);

        flowTo(ins, os);
        jf.close();

        os.flush();
        os.close();

        return f.getAbsolutePath();
    }

    /**
     * get the temporarily pre-writing directory
     */
    public String getTempPrewriteDir() {
        return this.tempDir.getAbsolutePath();
    }

    /**
     * return the current writing war file path
     */
    public String getWarFilePath() {
        return this.warFile.getAbsolutePath();
    }

    public static void main(String[] args) {
        String warPath = "D:\\RUNJAR\\PEIM_WEB_BOOT-1.3.0-SNAPSHOT.war";
        JarArchiveUtils jarUtils = new JarArchiveUtils(warPath);
        try {
//            String tmpDir = jarUtils.loadFile("WEB-INF\\classes\\config.xml");
//            System.out.println(tmpDir);
            jarUtils.done();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值