1 17 package org.apache.geronimo.kernel.classloader; 18 19 import java.io.File ; 20 import java.io.IOException ; 21 import java.io.FileNotFoundException ; 22 import java.net.MalformedURLException ; 23 import java.net.URL ; 24 import java.net.URLConnection ; 25 import java.net.URLStreamHandler ; 26 import java.util.jar.JarEntry ; 27 import java.util.jar.JarFile ; 28 29 32 public class JarFileUrlStreamHandler extends URLStreamHandler { 33 public static URL createUrl(JarFile jarFile, JarEntry jarEntry) throws MalformedURLException { 34 return createUrl(jarFile, jarEntry, new File (jarFile.getName()).toURL()); 35 } 36 37 public static URL createUrl(JarFile jarFile, JarEntry jarEntry, URL codeSource) throws MalformedURLException { 38 JarFileUrlStreamHandler handler = new JarFileUrlStreamHandler(jarFile, jarEntry); 39 URL url = new URL ("jar", "", -1, codeSource + "!/" + jarEntry.getName(), handler); 40 handler.setExpectedUrl(url); 41 return url; 42 } 43 44 private URL expectedUrl; 45 private final JarFile jarFile; 46 private final JarEntry jarEntry; 47 48 public JarFileUrlStreamHandler(JarFile jarFile, JarEntry jarEntry) { 49 if (jarFile == null) throw new NullPointerException ("jarFile is null"); 50 if (jarEntry == null) throw new NullPointerException ("jarEntry is null"); 51 52 this.jarFile = jarFile; 53 this.jarEntry = jarEntry; 54 } 55 56 public void setExpectedUrl(URL expectedUrl) { 57 if (expectedUrl == null) throw new NullPointerException ("expectedUrl is null"); 58 this.expectedUrl = expectedUrl; 59 } 60 61 public URLConnection openConnection(URL url) throws IOException { 62 if (expectedUrl == null) throw new IllegalStateException ("expectedUrl was not set"); 63 64 if (!expectedUrl.equals(url)) { 66 if (!url.getProtocol().equals("jar")) { 68 throw new IllegalArgumentException ("Unsupported protocol " + url.getProtocol()); 69 } 70 71 String path = url.getPath(); 73 String [] chunks = path.split("!/", 2); 74 75 if (chunks.length == 1) { 77 throw new MalformedURLException ("Url does not contain a '!' character: " + url); 78 } 79 80 String file = chunks[0]; 81 String entryPath = chunks[1]; 82 83 if (!file.startsWith("file:")) { 85 return new URL (url.toExternalForm()).openConnection(); 87 } 88 file = file.substring("file:".length()); 89 90 if (!jarFile.getName().equals(file)) { 92 return new URL (url.toExternalForm()).openConnection(); 94 } 95 96 JarEntry newEntry = jarFile.getJarEntry(entryPath); 98 if (newEntry == null) { 99 throw new FileNotFoundException ("Entry not found: " + url); 100 } 101 return new JarFileUrlConnection(url, jarFile, newEntry); 102 } 103 104 return new JarFileUrlConnection(url, jarFile, jarEntry); 105 } 106 } 107 | Popular Tags |