package com.ctrip.framework.xpipe.redis.utils;

import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class JarFileUrlJar {

    public static final String TMP_PATH = "/tmp/redis/proxy/";

    private JarFile jarFile;

    private JarEntry entry;

    private String fileName;

    public JarFileUrlJar(URL url) throws IOException {
        try {
            // jar:file:...
            JarURLConnection jarConn = (JarURLConnection) url.openConnection();
            jarConn.setUseCaches(false);
            jarFile = jarConn.getJarFile();
            entry = jarConn.getJarEntry();
            fileName = TMP_PATH + entry.getName();
        } catch (Exception e) {
            throw new IOException(jarFile.getName() + ":" + jarFile.size(), e);
        }
    }

    public void close() {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }

    private InputStream getEntryInputStream() throws IOException {
        if (entry == null) {
            return null;
        } else {
            return jarFile.getInputStream(entry);
        }
    }

    public String getJarFilePath() throws IOException {
        InputStream inputStream = getEntryInputStream();
        Files.copy(inputStream, getDistFile(fileName));
        return fileName;
    }

    private Path getDistFile(String path) throws IOException {

        Path dist = Paths.get(path);
        Path parent = dist.getParent();
        if (parent != null) {
            Files.deleteIfExists(parent);
            Files.createDirectories(parent);
        }
        return dist;
    }
}

@@ -41,16 +41,37 @@
 utils;%0A%0A
+import java.io.File;%0A
 import j
@@ -316,16 +316,48 @@
 JarFile;
+%0Aimport java.util.stream.Stream;
 %0A%0Apublic
@@ -1814,35 +1814,229 @@
     
-Files.deleteIfExists(parent
+Stream%3CPath%3E children =  Files.list(parent);%0A            children.forEach(p -%3E %7B%0A                try %7B%0A                    Files.deleteIfExists(p);%0A                %7D catch (IOException e) %7B%0A                %7D%0A            %7D
 );%0A 

remove child file of tmp path