2
0

JarClassLoader.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package net.sf.l2j.gameserver.util;
  16. import java.io.DataInputStream;
  17. import java.io.File;
  18. import java.io.IOException;
  19. import java.util.HashSet;
  20. import java.util.logging.Level;
  21. import java.util.logging.Logger;
  22. import java.util.zip.ZipEntry;
  23. import java.util.zip.ZipFile;
  24. /**
  25. * This is a class loader for the dynamic extensions used by DynamicExtension class.
  26. *
  27. * @version $Revision: $ $Date: $
  28. * @author galun
  29. */
  30. public class JarClassLoader extends ClassLoader {
  31. private static Logger _log = Logger.getLogger(JarClassLoader.class.getCanonicalName());
  32. HashSet<String> _jars = new HashSet<String>();
  33. public void addJarFile(String filename) {
  34. _jars.add(filename);
  35. }
  36. @Override
  37. public Class<?> findClass(String name) throws ClassNotFoundException {
  38. try {
  39. byte[] b = loadClassData(name);
  40. return defineClass(name, b, 0, b.length);
  41. } catch (Exception e) {
  42. throw new ClassNotFoundException(name);
  43. }
  44. }
  45. private byte[] loadClassData(String name) throws IOException {
  46. byte[] classData = null;
  47. for (String jarFile : _jars) {
  48. try {
  49. File file = new File(jarFile);
  50. ZipFile zipFile = new ZipFile(file);
  51. String fileName = name.replace('.', '/') + ".class";
  52. ZipEntry entry = zipFile.getEntry(fileName);
  53. if (entry == null)
  54. continue;
  55. classData = new byte[(int)entry.getSize()];
  56. DataInputStream zipStream = new DataInputStream(zipFile.getInputStream(entry));
  57. zipStream.readFully(classData, 0, (int) entry.getSize());
  58. break;
  59. } catch (IOException e) {
  60. _log.log(Level.WARNING, jarFile + ":" + e.toString(), e);
  61. continue;
  62. }
  63. }
  64. if (classData == null)
  65. throw new IOException("class not found in " + _jars);
  66. return classData;
  67. }
  68. }