2
0

ScriptEngineManager.java 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. /*
  2. * Copyright © 2004-2019 L2J Server
  3. *
  4. * This file is part of L2J Server.
  5. *
  6. * L2J Server is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * L2J Server is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.l2jserver.gameserver.scripting;
  20. import static com.l2jserver.gameserver.config.Config.SCRIPT_ROOT;
  21. import java.io.BufferedReader;
  22. import java.io.File;
  23. import java.io.FileInputStream;
  24. import java.io.IOException;
  25. import java.io.InputStreamReader;
  26. import java.io.LineNumberReader;
  27. import java.io.Reader;
  28. import java.lang.reflect.Method;
  29. import java.lang.reflect.Modifier;
  30. import java.util.Map;
  31. import java.util.Map.Entry;
  32. import javax.script.ScriptException;
  33. import org.mdkt.compiler.InMemoryJavaCompiler;
  34. import org.slf4j.Logger;
  35. import org.slf4j.LoggerFactory;
  36. import com.l2jserver.gameserver.config.Config;
  37. /**
  38. * Script engine manager.
  39. * @author KenM
  40. * @author Zoey76
  41. */
  42. public final class ScriptEngineManager {
  43. private static final Logger LOG = LoggerFactory.getLogger(ScriptEngineManager.class);
  44. private static final String CLASS_PATH = SCRIPT_ROOT.getAbsolutePath() + System.getProperty("path.separator") + System.getProperty("java.class.path");
  45. private static final String MAIN = "main";
  46. private static final String[] EMPTY_STRING_ARRAY = new String[0];
  47. private static final Class<?>[] ARG_MAIN = new Class[] {
  48. String[].class
  49. };
  50. private static final InMemoryJavaCompiler COMPILER = InMemoryJavaCompiler.newInstance() //
  51. .useOptions("-classpath", CLASS_PATH) //
  52. .ignoreWarnings();
  53. public void executeScriptList(File list) throws Exception {
  54. if (Config.NO_QUESTS) {
  55. if (!Config.NO_HANDLERS) {
  56. addSource(new File(SCRIPT_ROOT, "com/l2jserver/datapack/handlers/MasterHandler.java"));
  57. LOG.info("Handlers loaded, all other scripts skipped!");
  58. }
  59. return;
  60. }
  61. if (list.isFile()) {
  62. try (FileInputStream fis = new FileInputStream(list);
  63. InputStreamReader isr = new InputStreamReader(fis);
  64. LineNumberReader lnr = new LineNumberReader(isr)) {
  65. String line;
  66. while ((line = lnr.readLine()) != null) {
  67. if (Config.NO_HANDLERS && line.contains("MasterHandler.java")) {
  68. continue;
  69. }
  70. String[] parts = line.trim().split("#");
  71. if ((parts.length > 0) && !parts[0].isEmpty() && (parts[0].charAt(0) != '#')) {
  72. line = parts[0];
  73. if (line.endsWith("/**")) {
  74. line = line.substring(0, line.length() - 3);
  75. } else if (line.endsWith("/*")) {
  76. line = line.substring(0, line.length() - 2);
  77. }
  78. final File file = new File(SCRIPT_ROOT, line);
  79. if (file.isDirectory() && parts[0].endsWith("/**")) {
  80. executeAllScriptsInDirectory(file, true);
  81. } else if (file.isDirectory() && parts[0].endsWith("/*")) {
  82. executeAllScriptsInDirectory(file, false);
  83. } else if (file.isFile()) {
  84. addSource(file);
  85. } else {
  86. LOG.warn("Failed loading: ({}) @ {}:{} - Reason: doesnt exists or is not a file.", file.getCanonicalPath(), list.getName(), lnr.getLineNumber());
  87. }
  88. }
  89. }
  90. }
  91. } else {
  92. throw new IllegalArgumentException("Argument must be an file containing a list of scripts to be loaded");
  93. }
  94. final Map<String, Class<?>> classes = COMPILER.compileAll();
  95. for (Entry<String, Class<?>> e : classes.entrySet()) {
  96. runMain(e.getValue());
  97. }
  98. }
  99. private void executeAllScriptsInDirectory(File dir, boolean recurseDown) {
  100. if (dir.isDirectory()) {
  101. final File[] files = dir.listFiles();
  102. if (files == null) {
  103. return;
  104. }
  105. for (File file : files) {
  106. if (file.isDirectory() && recurseDown) {
  107. if (Config.VERBOSE_LOADING) {
  108. LOG.info("Entering folder: {}", file.getName());
  109. }
  110. executeAllScriptsInDirectory(file, recurseDown);
  111. } else if (file.isFile()) {
  112. addSource(file);
  113. }
  114. }
  115. } else {
  116. throw new IllegalArgumentException("The argument directory either doesnt exists or is not an directory.");
  117. }
  118. }
  119. public Class<?> compileScript(File file) {
  120. try (FileInputStream fis = new FileInputStream(file);
  121. InputStreamReader isr = new InputStreamReader(fis);
  122. BufferedReader reader = new BufferedReader(isr)) {
  123. return COMPILER.compile(getClassForFile(file), readerToString(reader));
  124. } catch (Exception ex) {
  125. LOG.warn("Error executing script!", ex);
  126. }
  127. return null;
  128. }
  129. public void executeScript(File file) throws Exception {
  130. final Class<?> clazz = compileScript(file);
  131. runMain(clazz);
  132. }
  133. public void executeScript(String file) throws Exception {
  134. executeScript(new File(SCRIPT_ROOT, file));
  135. }
  136. public void addSource(File file) {
  137. if (Config.VERBOSE_LOADING) {
  138. LOG.info("Loading Script: {}", file.getAbsolutePath());
  139. }
  140. try (FileInputStream fis = new FileInputStream(file);
  141. InputStreamReader isr = new InputStreamReader(fis);
  142. BufferedReader reader = new BufferedReader(isr)) {
  143. COMPILER.addSource(getClassForFile(file), readerToString(reader));
  144. } catch (Exception ex) {
  145. LOG.warn("Error executing script!", ex);
  146. }
  147. }
  148. private static String getClassForFile(File script) {
  149. final String path = script.getAbsolutePath();
  150. final String scpPath = SCRIPT_ROOT.getAbsolutePath();
  151. if (path.startsWith(scpPath)) {
  152. final int idx = path.lastIndexOf('.');
  153. return path.substring(scpPath.length() + 1, idx).replace('/', '.').replace('\\', '.');
  154. }
  155. return null;
  156. }
  157. private static void runMain(Class<?> clazz) throws Exception {
  158. final boolean isPublicClazz = Modifier.isPublic(clazz.getModifiers());
  159. final Method mainMethod = findMethod(clazz, MAIN, ARG_MAIN);
  160. if (mainMethod != null) {
  161. if (!isPublicClazz) {
  162. mainMethod.setAccessible(true);
  163. }
  164. mainMethod.invoke(null, new Object[] {
  165. EMPTY_STRING_ARRAY
  166. });
  167. }
  168. }
  169. private static String readerToString(Reader reader) throws ScriptException {
  170. try (BufferedReader in = new BufferedReader(reader)) {
  171. final StringBuilder result = new StringBuilder();
  172. String line;
  173. while ((line = in.readLine()) != null) {
  174. result.append(line).append(System.lineSeparator());
  175. }
  176. return result.toString();
  177. } catch (IOException ex) {
  178. throw new ScriptException(ex);
  179. }
  180. }
  181. private static Method findMethod(Class<?> clazz, String methodName, Class<?>[] args) {
  182. try {
  183. final Method mainMethod = clazz.getMethod(methodName, args);
  184. final int modifiers = mainMethod.getModifiers();
  185. if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
  186. return mainMethod;
  187. }
  188. } catch (NoSuchMethodException ignored) {
  189. }
  190. return null;
  191. }
  192. public File getCurrentLoadingScript() {
  193. return null;
  194. }
  195. public static ScriptEngineManager getInstance() {
  196. return SingletonHolder.INSTANCE;
  197. }
  198. private static class SingletonHolder {
  199. protected static final ScriptEngineManager INSTANCE = new ScriptEngineManager();
  200. }
  201. }