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

import java.io.File;
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;
import java.util.stream.Stream;

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) {
            Stream<Path> children =  Files.list(parent);
            children.forEach(p -> {
                try {
                    Files.deleteIfExists(p);
                } catch (IOException e) {
                }
            });
            Files.createDirectories(parent);
        }
        return dist;
    }
}

@@ -45,29 +45,8 @@
 s;%0A%0A
-import java.io.File;%0A
 impo
@@ -1773,32 +1773,253 @@
  != null) %7B%0A    
+        if (Files.exists(parent)) %7B%0A                delete(parent);%0A            %7D%0A            Files.createDirectories(parent);%0A        %7D%0A        return dist;%0A    %7D%0A%0A    private void delete(Path root) throws IOException %7B%0A
         Stream%3CP
@@ -2046,29 +2046,23 @@
 es.list(
-parent);%0A    
+root);%0A
         
@@ -2089,36 +2089,32 @@
 %3E %7B%0A            
-    
 try %7B%0A          
@@ -2115,28 +2115,24 @@
             
- 
-   
 Files.delete
@@ -2144,20 +2144,16 @@
 sts(p);%0A
-    
         
@@ -2190,34 +2190,26 @@
             
-   
- 
 %7D%0A
-    
         %7D);%0A
@@ -2212,84 +2212,8 @@
 %7D);%0A
-            Files.createDirectories(parent);%0A        %7D%0A        return dist;%0A
     

check exist for first deploy