1 15 16 package javassist; 17 18 import java.io.*; 19 import java.net.*; 20 21 28 public class URLClassPath implements ClassPath { 29 protected String hostname; 30 protected int port; 31 protected String directory; 32 protected String packageName; 33 34 51 public URLClassPath(String host, int port, 52 String directory, String packageName) { 53 hostname = host; 54 this.port = port; 55 this.directory = directory; 56 this.packageName = packageName; 57 } 58 59 public String toString() { 60 return hostname + ":" + port + directory; 61 } 62 63 68 public InputStream openClassfile(String classname) { 69 try { 70 URLConnection con = openClassfile0(classname); 71 if (con != null) 72 return con.getInputStream(); 73 } 74 catch (IOException e) {} 75 return null; } 77 78 private URLConnection openClassfile0(String classname) throws IOException { 79 if (packageName == null || classname.startsWith(packageName)) { 80 String jarname 81 = directory + classname.replace('.', '/') + ".class"; 82 return fetchClass0(hostname, port, jarname); 83 } 84 else 85 return null; } 87 88 93 public URL find(String classname) { 94 try { 95 URLConnection con = openClassfile0(classname); 96 InputStream is = con.getInputStream(); 97 if (is != null) { 98 is.close(); 99 return con.getURL(); 100 } 101 } 102 catch (IOException e) {} 103 return null; 104 } 105 106 109 public void close() {} 110 111 121 public static byte[] fetchClass(String host, int port, 122 String directory, String classname) 123 throws IOException 124 { 125 byte[] b; 126 URLConnection con = fetchClass0(host, port, 127 directory + classname.replace('.', '/') + ".class"); 128 int size = con.getContentLength(); 129 InputStream s = con.getInputStream(); 130 try { 131 if (size <= 0) 132 b = ClassPoolTail.readStream(s); 133 else { 134 b = new byte[size]; 135 int len = 0; 136 do { 137 int n = s.read(b, len, size - len); 138 if (n < 0) 139 throw new IOException("the stream was closed: " 140 + classname); 141 142 len += n; 143 } while (len < size); 144 } 145 } 146 finally { 147 s.close(); 148 } 149 150 return b; 151 } 152 153 private static URLConnection fetchClass0(String host, int port, 154 String filename) 155 throws IOException 156 { 157 URL url; 158 try { 159 url = new URL("http", host, port, filename); 160 } 161 catch (MalformedURLException e) { 162 throw new IOException("invalid URL?"); 164 } 165 166 URLConnection con = url.openConnection(); 167 con.connect(); 168 return con; 169 } 170 } 171 | Popular Tags |