JarClassLoader.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. {
  32. private static Logger _log = Logger.getLogger(JarClassLoader.class.getCanonicalName());
  33. HashSet<String> _jars = new HashSet<String>();
  34. public void addJarFile(String filename)
  35. {
  36. _jars.add(filename);
  37. }
  38. @Override
  39. public Class<?> findClass(String name) throws ClassNotFoundException
  40. {
  41. try
  42. {
  43. byte[] b = loadClassData(name);
  44. return defineClass(name, b, 0, b.length);
  45. }
  46. catch (Exception e)
  47. {
  48. throw new ClassNotFoundException(name);
  49. }
  50. }
  51. private byte[] loadClassData(String name) throws IOException
  52. {
  53. byte[] classData = null;
  54. for (String jarFile : _jars)
  55. {
  56. try
  57. {
  58. File file = new File(jarFile);
  59. ZipFile zipFile = new ZipFile(file);
  60. String fileName = name.replace('.', '/') + ".class";
  61. ZipEntry entry = zipFile.getEntry(fileName);
  62. if (entry == null)
  63. continue;
  64. classData = new byte[(int) entry.getSize()];
  65. DataInputStream zipStream = new DataInputStream(zipFile.getInputStream(entry));
  66. zipStream.readFully(classData, 0, (int) entry.getSize());
  67. break;
  68. }
  69. catch (IOException e)
  70. {
  71. _log.log(Level.WARNING, jarFile + ":" + e.toString(), e);
  72. continue;
  73. }
  74. }
  75. if (classData == null)
  76. throw new IOException("class not found in " + _jars);
  77. return classData;
  78. }
  79. }