JarClassLoader.java 2.4 KB

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