You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ClassPoolTail.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999- Shigeru Chiba. All Rights Reserved.
  4. *
  5. * The contents of this file are subject to the Mozilla Public License Version
  6. * 1.1 (the "License"); you may not use this file except in compliance with
  7. * the License. Alternatively, the contents of this file may be used under
  8. * the terms of the GNU Lesser General Public License Version 2.1 or later,
  9. * or the Apache License Version 2.0.
  10. *
  11. * Software distributed under the License is distributed on an "AS IS" basis,
  12. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  13. * for the specific language governing rights and limitations under the
  14. * License.
  15. */
  16. package javassist;
  17. import java.io.File;
  18. import java.io.FileInputStream;
  19. import java.io.FileNotFoundException;
  20. import java.io.FilenameFilter;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.io.OutputStream;
  24. import java.net.MalformedURLException;
  25. import java.net.URL;
  26. import java.util.Collections;
  27. import java.util.HashSet;
  28. import java.util.Set;
  29. import java.util.jar.JarEntry;
  30. import java.util.jar.JarFile;
  31. final class ClassPathList {
  32. ClassPathList next;
  33. ClassPath path;
  34. ClassPathList(ClassPath p, ClassPathList n) {
  35. next = n;
  36. path = p;
  37. }
  38. }
  39. final class DirClassPath implements ClassPath {
  40. String directory;
  41. DirClassPath(String dirName) {
  42. directory = dirName;
  43. }
  44. @Override
  45. public InputStream openClassfile(String classname) {
  46. try {
  47. char sep = File.separatorChar;
  48. String filename = directory + sep
  49. + classname.replace('.', sep) + ".class";
  50. return new FileInputStream(filename.toString());
  51. }
  52. catch (FileNotFoundException e) {}
  53. catch (SecurityException e) {}
  54. return null;
  55. }
  56. @Override
  57. public URL find(String classname) {
  58. char sep = File.separatorChar;
  59. String filename = directory + sep
  60. + classname.replace('.', sep) + ".class";
  61. File f = new File(filename);
  62. if (f.exists())
  63. try {
  64. return f.getCanonicalFile().toURI().toURL();
  65. }
  66. catch (MalformedURLException e) {}
  67. catch (IOException e) {}
  68. return null;
  69. }
  70. @Override
  71. public String toString() {
  72. return directory;
  73. }
  74. }
  75. final class JarDirClassPath implements ClassPath {
  76. JarClassPath[] jars;
  77. JarDirClassPath(String dirName) throws NotFoundException {
  78. File[] files = new File(dirName).listFiles(new FilenameFilter() {
  79. @Override
  80. public boolean accept(File dir, String name) {
  81. name = name.toLowerCase();
  82. return name.endsWith(".jar") || name.endsWith(".zip");
  83. }
  84. });
  85. if (files != null) {
  86. jars = new JarClassPath[files.length];
  87. for (int i = 0; i < files.length; i++)
  88. jars[i] = new JarClassPath(files[i].getPath());
  89. }
  90. }
  91. @Override
  92. public InputStream openClassfile(String classname) throws NotFoundException {
  93. if (jars != null)
  94. for (int i = 0; i < jars.length; i++) {
  95. InputStream is = jars[i].openClassfile(classname);
  96. if (is != null)
  97. return is;
  98. }
  99. return null; // not found
  100. }
  101. @Override
  102. public URL find(String classname) {
  103. if (jars != null)
  104. for (int i = 0; i < jars.length; i++) {
  105. URL url = jars[i].find(classname);
  106. if (url != null)
  107. return url;
  108. }
  109. return null; // not found
  110. }
  111. }
  112. final class JarClassPath implements ClassPath {
  113. Set<String> jarfileEntries;
  114. String jarfileURL;
  115. JarClassPath(String pathname) throws NotFoundException {
  116. JarFile jarfile = null;
  117. try {
  118. jarfile = new JarFile(pathname);
  119. jarfileEntries = new HashSet<String>();
  120. for (JarEntry je:Collections.list(jarfile.entries()))
  121. if (je.getName().endsWith(".class"))
  122. jarfileEntries.add(je.getName());
  123. jarfileURL = new File(pathname).getCanonicalFile()
  124. .toURI().toURL().toString();
  125. return;
  126. } catch (IOException e) {}
  127. finally {
  128. if (null != jarfile)
  129. try {
  130. jarfile.close();
  131. } catch (IOException e) {}
  132. }
  133. throw new NotFoundException(pathname);
  134. }
  135. @Override
  136. public InputStream openClassfile(String classname)
  137. throws NotFoundException
  138. {
  139. URL jarURL = find(classname);
  140. if (null != jarURL)
  141. try {
  142. if (ClassPool.cacheOpenedJarFile)
  143. return jarURL.openConnection().getInputStream();
  144. else {
  145. java.net.URLConnection con = jarURL.openConnection();
  146. con.setUseCaches(false);
  147. return con.getInputStream();
  148. }
  149. }
  150. catch (IOException e) {
  151. throw new NotFoundException("broken jar file?: "
  152. + classname);
  153. }
  154. return null;
  155. }
  156. @Override
  157. public URL find(String classname) {
  158. String jarname = classname.replace('.', '/') + ".class";
  159. if (jarfileEntries.contains(jarname))
  160. try {
  161. return new URL(String.format("jar:%s!/%s", jarfileURL, jarname));
  162. }
  163. catch (MalformedURLException e) {}
  164. return null; // not found
  165. }
  166. @Override
  167. public String toString() {
  168. return jarfileURL == null ? "<null>" : jarfileURL.toString();
  169. }
  170. }
  171. final class ClassPoolTail {
  172. protected ClassPathList pathList;
  173. public ClassPoolTail() {
  174. pathList = null;
  175. }
  176. @Override
  177. public String toString() {
  178. StringBuffer buf = new StringBuffer();
  179. buf.append("[class path: ");
  180. ClassPathList list = pathList;
  181. while (list != null) {
  182. buf.append(list.path.toString());
  183. buf.append(File.pathSeparatorChar);
  184. list = list.next;
  185. }
  186. buf.append(']');
  187. return buf.toString();
  188. }
  189. public synchronized ClassPath insertClassPath(ClassPath cp) {
  190. pathList = new ClassPathList(cp, pathList);
  191. return cp;
  192. }
  193. public synchronized ClassPath appendClassPath(ClassPath cp) {
  194. ClassPathList tail = new ClassPathList(cp, null);
  195. ClassPathList list = pathList;
  196. if (list == null)
  197. pathList = tail;
  198. else {
  199. while (list.next != null)
  200. list = list.next;
  201. list.next = tail;
  202. }
  203. return cp;
  204. }
  205. public synchronized void removeClassPath(ClassPath cp) {
  206. ClassPathList list = pathList;
  207. if (list != null)
  208. if (list.path == cp)
  209. pathList = list.next;
  210. else {
  211. while (list.next != null)
  212. if (list.next.path == cp)
  213. list.next = list.next.next;
  214. else
  215. list = list.next;
  216. }
  217. }
  218. public ClassPath appendSystemPath() {
  219. if (javassist.bytecode.ClassFile.MAJOR_VERSION < javassist.bytecode.ClassFile.JAVA_9)
  220. return appendClassPath(new ClassClassPath());
  221. ClassLoader cl = Thread.currentThread().getContextClassLoader();
  222. return appendClassPath(new LoaderClassPath(cl));
  223. }
  224. public ClassPath insertClassPath(String pathname)
  225. throws NotFoundException
  226. {
  227. return insertClassPath(makePathObject(pathname));
  228. }
  229. public ClassPath appendClassPath(String pathname)
  230. throws NotFoundException
  231. {
  232. return appendClassPath(makePathObject(pathname));
  233. }
  234. private static ClassPath makePathObject(String pathname)
  235. throws NotFoundException
  236. {
  237. String lower = pathname.toLowerCase();
  238. if (lower.endsWith(".jar") || lower.endsWith(".zip"))
  239. return new JarClassPath(pathname);
  240. int len = pathname.length();
  241. if (len > 2 && pathname.charAt(len - 1) == '*'
  242. && (pathname.charAt(len - 2) == '/'
  243. || pathname.charAt(len - 2) == File.separatorChar)) {
  244. String dir = pathname.substring(0, len - 2);
  245. return new JarDirClassPath(dir);
  246. }
  247. return new DirClassPath(pathname);
  248. }
  249. /**
  250. * This method does not close the output stream.
  251. */
  252. void writeClassfile(String classname, OutputStream out)
  253. throws NotFoundException, IOException, CannotCompileException
  254. {
  255. InputStream fin = openClassfile(classname);
  256. if (fin == null)
  257. throw new NotFoundException(classname);
  258. try {
  259. copyStream(fin, out);
  260. }
  261. finally {
  262. fin.close();
  263. }
  264. }
  265. /*
  266. -- faster version --
  267. void checkClassName(String classname) throws NotFoundException {
  268. if (find(classname) == null)
  269. throw new NotFoundException(classname);
  270. }
  271. -- slower version --
  272. void checkClassName(String classname) throws NotFoundException {
  273. InputStream fin = openClassfile(classname);
  274. try {
  275. fin.close();
  276. }
  277. catch (IOException e) {}
  278. }
  279. */
  280. /**
  281. * Opens the class file for the class specified by
  282. * <code>classname</code>.
  283. *
  284. * @param classname a fully-qualified class name
  285. * @return null if the file has not been found.
  286. * @throws NotFoundException if any error is reported by ClassPath.
  287. */
  288. InputStream openClassfile(String classname)
  289. throws NotFoundException
  290. {
  291. ClassPathList list = pathList;
  292. InputStream ins = null;
  293. NotFoundException error = null;
  294. while (list != null) {
  295. try {
  296. ins = list.path.openClassfile(classname);
  297. }
  298. catch (NotFoundException e) {
  299. if (error == null)
  300. error = e;
  301. }
  302. if (ins == null)
  303. list = list.next;
  304. else
  305. return ins;
  306. }
  307. if (error != null)
  308. throw error;
  309. return null; // not found
  310. }
  311. /**
  312. * Searches the class path to obtain the URL of the class file
  313. * specified by classname. It is also used to determine whether
  314. * the class file exists.
  315. *
  316. * @param classname a fully-qualified class name.
  317. * @return null if the class file could not be found.
  318. */
  319. public URL find(String classname) {
  320. ClassPathList list = pathList;
  321. URL url = null;
  322. while (list != null) {
  323. url = list.path.find(classname);
  324. if (url == null)
  325. list = list.next;
  326. else
  327. return url;
  328. }
  329. return null;
  330. }
  331. /**
  332. * Reads from an input stream until it reaches the end.
  333. *
  334. * @return the contents of that input stream
  335. */
  336. public static byte[] readStream(InputStream fin) throws IOException {
  337. byte[][] bufs = new byte[8][];
  338. int bufsize = 4096;
  339. for (int i = 0; i < 8; ++i) {
  340. bufs[i] = new byte[bufsize];
  341. int size = 0;
  342. int len = 0;
  343. do {
  344. len = fin.read(bufs[i], size, bufsize - size);
  345. if (len >= 0)
  346. size += len;
  347. else {
  348. byte[] result = new byte[bufsize - 4096 + size];
  349. int s = 0;
  350. for (int j = 0; j < i; ++j) {
  351. System.arraycopy(bufs[j], 0, result, s, s + 4096);
  352. s = s + s + 4096;
  353. }
  354. System.arraycopy(bufs[i], 0, result, s, size);
  355. return result;
  356. }
  357. } while (size < bufsize);
  358. bufsize *= 2;
  359. }
  360. throw new IOException("too much data");
  361. }
  362. /**
  363. * Reads from an input stream and write to an output stream
  364. * until it reaches the end. This method does not close the
  365. * streams.
  366. */
  367. public static void copyStream(InputStream fin, OutputStream fout)
  368. throws IOException
  369. {
  370. int bufsize = 4096;
  371. byte[] buf = null;
  372. for (int i = 0; i < 64; ++i) {
  373. if (i < 8) {
  374. bufsize *= 2;
  375. buf = new byte[bufsize];
  376. }
  377. int size = 0;
  378. int len = 0;
  379. do {
  380. len = fin.read(buf, size, bufsize - size);
  381. if (len >= 0)
  382. size += len;
  383. else {
  384. fout.write(buf, 0, size);
  385. return;
  386. }
  387. } while (size < bufsize);
  388. fout.write(buf);
  389. }
  390. throw new IOException("too much data");
  391. }
  392. }