JarClassLoader.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 com.l2jserver.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. final String fileName = name.replace('.', '/') + ".class";
  55. for (String jarFile : _jars)
  56. {
  57. final File file = new File(jarFile);
  58. try (ZipFile zipFile = new ZipFile(file);)
  59. {
  60. final ZipEntry entry = zipFile.getEntry(fileName);
  61. if (entry == null)
  62. {
  63. continue;
  64. }
  65. classData = new byte[(int) entry.getSize()];
  66. try (DataInputStream zipStream = new DataInputStream(zipFile.getInputStream(entry)))
  67. {
  68. zipStream.readFully(classData, 0, (int) entry.getSize());
  69. }
  70. break;
  71. }
  72. catch (IOException e)
  73. {
  74. _log.log(Level.WARNING, jarFile + ": " + e.getMessage(), e);
  75. continue;
  76. }
  77. }
  78. if (classData == null)
  79. {
  80. throw new IOException("class not found in " + _jars);
  81. }
  82. return classData;
  83. }
  84. }