L2ScriptEngineManager.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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.scripting;
  16. import java.io.BufferedReader;
  17. import java.io.File;
  18. import java.io.FileInputStream;
  19. import java.io.FileOutputStream;
  20. import java.io.IOException;
  21. import java.io.InputStreamReader;
  22. import java.io.LineNumberReader;
  23. import java.util.LinkedList;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.logging.Level;
  27. import java.util.logging.Logger;
  28. import javax.script.Compilable;
  29. import javax.script.CompiledScript;
  30. import javax.script.ScriptContext;
  31. import javax.script.ScriptEngine;
  32. import javax.script.ScriptEngineFactory;
  33. import javax.script.ScriptEngineManager;
  34. import javax.script.ScriptException;
  35. import javax.script.SimpleScriptContext;
  36. import javolution.util.FastMap;
  37. import com.l2jserver.Config;
  38. import com.l2jserver.script.jython.JythonScriptEngine;
  39. /**
  40. * Caches script engines and provides functionality for executing and managing scripts.
  41. * @author KenM
  42. */
  43. public final class L2ScriptEngineManager
  44. {
  45. private static final Logger _log = Logger.getLogger(L2ScriptEngineManager.class.getName());
  46. public static final File SCRIPT_FOLDER = new File(Config.DATAPACK_ROOT.getAbsolutePath(), "data/scripts");
  47. public static L2ScriptEngineManager getInstance()
  48. {
  49. return SingletonHolder._instance;
  50. }
  51. private final Map<String, ScriptEngine> _nameEngines = new FastMap<>();
  52. private final Map<String, ScriptEngine> _extEngines = new FastMap<>();
  53. private final List<ScriptManager<?>> _scriptManagers = new LinkedList<>();
  54. private File _currentLoadingScript;
  55. // Configs
  56. // TODO move to config file
  57. /**
  58. * Informs(logs) the scripts being loaded.<BR>
  59. * Apply only when executing script from files.<BR>
  60. */
  61. private final boolean VERBOSE_LOADING = false;
  62. /**
  63. * If the script engine supports compilation the script is compiled before execution.<BR>
  64. */
  65. private final boolean ATTEMPT_COMPILATION = true;
  66. /**
  67. * Clean an previous error log(if such exists) for the script being loaded before trying to load.<BR>
  68. * Apply only when executing script from files.<BR>
  69. */
  70. private final boolean PURGE_ERROR_LOG = true;
  71. protected L2ScriptEngineManager()
  72. {
  73. ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
  74. List<ScriptEngineFactory> factories = scriptEngineManager.getEngineFactories();
  75. for (ScriptEngineFactory factory : factories)
  76. {
  77. try
  78. {
  79. ScriptEngine engine = factory.getScriptEngine();
  80. boolean reg = false;
  81. for (String name : factory.getNames())
  82. {
  83. ScriptEngine existentEngine = _nameEngines.get(name);
  84. if (existentEngine != null)
  85. {
  86. double engineVer = Double.parseDouble(factory.getEngineVersion());
  87. double existentEngVer = Double.parseDouble(existentEngine.getFactory().getEngineVersion());
  88. if (engineVer <= existentEngVer)
  89. {
  90. continue;
  91. }
  92. }
  93. reg = true;
  94. _nameEngines.put(name, engine);
  95. }
  96. if (reg)
  97. {
  98. _log.info("Script Engine: " + factory.getEngineName() + " " + factory.getEngineVersion() + " - Language: " + factory.getLanguageName() + " - Language Version: " + factory.getLanguageVersion());
  99. }
  100. for (String ext : factory.getExtensions())
  101. {
  102. if (!ext.equals("java") || factory.getLanguageName().equals("java"))
  103. {
  104. _extEngines.put(ext, engine);
  105. }
  106. }
  107. }
  108. catch (Exception e)
  109. {
  110. _log.log(Level.WARNING, "Failed initializing factory: " + e.getMessage(), e);
  111. }
  112. }
  113. preConfigure();
  114. }
  115. private void preConfigure()
  116. {
  117. // java class path
  118. // Jython sys.path
  119. String dataPackDirForwardSlashes = SCRIPT_FOLDER.getPath().replaceAll("\\\\", "/");
  120. String configScript = "import sys;sys.path.insert(0,'" + dataPackDirForwardSlashes + "');";
  121. try
  122. {
  123. eval("jython", configScript);
  124. }
  125. catch (ScriptException e)
  126. {
  127. _log.severe("Failed preconfiguring jython: " + e.getMessage());
  128. }
  129. }
  130. private ScriptEngine getEngineByName(String name)
  131. {
  132. return _nameEngines.get(name);
  133. }
  134. private ScriptEngine getEngineByExtension(String ext)
  135. {
  136. return _extEngines.get(ext);
  137. }
  138. public void executeScriptList(File list) throws IOException
  139. {
  140. File file;
  141. if (!Config.ALT_DEV_NO_HANDLERS && Config.ALT_DEV_NO_QUESTS)
  142. {
  143. file = new File(SCRIPT_FOLDER, "handlers/MasterHandler.java");
  144. try
  145. {
  146. executeScript(file);
  147. _log.info("Handlers loaded, all other scripts skipped");
  148. return;
  149. }
  150. catch (ScriptException se)
  151. {
  152. _log.log(Level.WARNING, "", se);
  153. }
  154. }
  155. if (Config.ALT_DEV_NO_QUESTS)
  156. {
  157. return;
  158. }
  159. if (list.isFile())
  160. {
  161. try (FileInputStream fis = new FileInputStream(list);
  162. InputStreamReader isr = new InputStreamReader(fis);
  163. LineNumberReader lnr = new LineNumberReader(isr))
  164. {
  165. String line;
  166. while ((line = lnr.readLine()) != null)
  167. {
  168. if (Config.ALT_DEV_NO_HANDLERS && line.contains("MasterHandler.java"))
  169. {
  170. continue;
  171. }
  172. String[] parts = line.trim().split("#");
  173. if ((parts.length > 0) && !parts[0].isEmpty() && (parts[0].charAt(0) != '#'))
  174. {
  175. line = parts[0];
  176. if (line.endsWith("/**"))
  177. {
  178. line = line.substring(0, line.length() - 3);
  179. }
  180. else if (line.endsWith("/*"))
  181. {
  182. line = line.substring(0, line.length() - 2);
  183. }
  184. file = new File(SCRIPT_FOLDER, line);
  185. if (file.isDirectory() && parts[0].endsWith("/**"))
  186. {
  187. executeAllScriptsInDirectory(file, true, 32);
  188. }
  189. else if (file.isDirectory() && parts[0].endsWith("/*"))
  190. {
  191. executeAllScriptsInDirectory(file);
  192. }
  193. else if (file.isFile())
  194. {
  195. try
  196. {
  197. executeScript(file);
  198. }
  199. catch (ScriptException e)
  200. {
  201. reportScriptFileError(file, e);
  202. }
  203. }
  204. else
  205. {
  206. _log.warning("Failed loading: (" + file.getCanonicalPath() + ") @ " + list.getName() + ":" + lnr.getLineNumber() + " - Reason: doesnt exists or is not a file.");
  207. }
  208. }
  209. }
  210. }
  211. }
  212. else
  213. {
  214. throw new IllegalArgumentException("Argument must be an file containing a list of scripts to be loaded");
  215. }
  216. }
  217. public void executeAllScriptsInDirectory(File dir)
  218. {
  219. executeAllScriptsInDirectory(dir, false, 0);
  220. }
  221. public void executeAllScriptsInDirectory(File dir, boolean recurseDown, int maxDepth)
  222. {
  223. executeAllScriptsInDirectory(dir, recurseDown, maxDepth, 0);
  224. }
  225. private void executeAllScriptsInDirectory(File dir, boolean recurseDown, int maxDepth, int currentDepth)
  226. {
  227. if (dir.isDirectory())
  228. {
  229. for (File file : dir.listFiles())
  230. {
  231. if (file.isDirectory() && recurseDown && (maxDepth > currentDepth))
  232. {
  233. if (VERBOSE_LOADING)
  234. {
  235. _log.info("Entering folder: " + file.getName());
  236. }
  237. executeAllScriptsInDirectory(file, recurseDown, maxDepth, currentDepth + 1);
  238. }
  239. else if (file.isFile())
  240. {
  241. try
  242. {
  243. String name = file.getName();
  244. int lastIndex = name.lastIndexOf('.');
  245. String extension;
  246. if (lastIndex != -1)
  247. {
  248. extension = name.substring(lastIndex + 1);
  249. ScriptEngine engine = getEngineByExtension(extension);
  250. if (engine != null)
  251. {
  252. executeScript(engine, file);
  253. }
  254. }
  255. }
  256. catch (ScriptException e)
  257. {
  258. reportScriptFileError(file, e);
  259. // _log.log(Level.WARNING, "", e);
  260. }
  261. }
  262. }
  263. }
  264. else
  265. {
  266. throw new IllegalArgumentException("The argument directory either doesnt exists or is not an directory.");
  267. }
  268. }
  269. public void executeScript(File file) throws ScriptException
  270. {
  271. String name = file.getName();
  272. int lastIndex = name.lastIndexOf('.');
  273. String extension;
  274. if (lastIndex != -1)
  275. {
  276. extension = name.substring(lastIndex + 1);
  277. }
  278. else
  279. {
  280. throw new ScriptException("Script file (" + name + ") doesnt has an extension that identifies the ScriptEngine to be used.");
  281. }
  282. ScriptEngine engine = getEngineByExtension(extension);
  283. if (engine == null)
  284. {
  285. throw new ScriptException("No engine registered for extension (" + extension + ")");
  286. }
  287. executeScript(engine, file);
  288. }
  289. public void executeScript(String engineName, File file) throws ScriptException
  290. {
  291. ScriptEngine engine = getEngineByName(engineName);
  292. if (engine == null)
  293. {
  294. throw new ScriptException("No engine registered with name (" + engineName + ")");
  295. }
  296. executeScript(engine, file);
  297. }
  298. public void executeScript(ScriptEngine engine, File file) throws ScriptException
  299. {
  300. if (VERBOSE_LOADING)
  301. {
  302. _log.info("Loading Script: " + file.getAbsolutePath());
  303. }
  304. if (PURGE_ERROR_LOG)
  305. {
  306. String name = file.getAbsolutePath() + ".error.log";
  307. File errorLog = new File(name);
  308. if (errorLog.isFile())
  309. {
  310. errorLog.delete();
  311. }
  312. }
  313. try (FileInputStream fis = new FileInputStream(file);
  314. InputStreamReader isr = new InputStreamReader(fis);
  315. BufferedReader reader = new BufferedReader(isr))
  316. {
  317. if ((engine instanceof Compilable) && ATTEMPT_COMPILATION)
  318. {
  319. ScriptContext context = new SimpleScriptContext();
  320. context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE);
  321. context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
  322. context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
  323. context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
  324. context.setAttribute(JythonScriptEngine.JYTHON_ENGINE_INSTANCE, engine, ScriptContext.ENGINE_SCOPE);
  325. setCurrentLoadingScript(file);
  326. ScriptContext ctx = engine.getContext();
  327. try
  328. {
  329. engine.setContext(context);
  330. Compilable eng = (Compilable) engine;
  331. CompiledScript cs = eng.compile(reader);
  332. cs.eval(context);
  333. }
  334. finally
  335. {
  336. engine.setContext(ctx);
  337. setCurrentLoadingScript(null);
  338. context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
  339. context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
  340. }
  341. }
  342. else
  343. {
  344. ScriptContext context = new SimpleScriptContext();
  345. context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE);
  346. context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
  347. context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
  348. context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
  349. setCurrentLoadingScript(file);
  350. try
  351. {
  352. engine.eval(reader, context);
  353. }
  354. finally
  355. {
  356. setCurrentLoadingScript(null);
  357. engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
  358. engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
  359. }
  360. }
  361. }
  362. catch (IOException e)
  363. {
  364. _log.log(Level.WARNING, "Error executing script!", e);
  365. }
  366. }
  367. public static String getClassForFile(File script)
  368. {
  369. String path = script.getAbsolutePath();
  370. String scpPath = SCRIPT_FOLDER.getAbsolutePath();
  371. if (path.startsWith(scpPath))
  372. {
  373. int idx = path.lastIndexOf('.');
  374. return path.substring(scpPath.length() + 1, idx);
  375. }
  376. return null;
  377. }
  378. public ScriptContext getScriptContext(ScriptEngine engine)
  379. {
  380. return engine.getContext();
  381. }
  382. public ScriptContext getScriptContext(String engineName)
  383. {
  384. ScriptEngine engine = getEngineByName(engineName);
  385. if (engine == null)
  386. {
  387. throw new IllegalStateException("No engine registered with name (" + engineName + ")");
  388. }
  389. return getScriptContext(engine);
  390. }
  391. public Object eval(ScriptEngine engine, String script, ScriptContext context) throws ScriptException
  392. {
  393. if ((engine instanceof Compilable) && ATTEMPT_COMPILATION)
  394. {
  395. Compilable eng = (Compilable) engine;
  396. CompiledScript cs = eng.compile(script);
  397. return context != null ? cs.eval(context) : cs.eval();
  398. }
  399. return context != null ? engine.eval(script, context) : engine.eval(script);
  400. }
  401. public Object eval(String engineName, String script) throws ScriptException
  402. {
  403. return eval(engineName, script, null);
  404. }
  405. public Object eval(String engineName, String script, ScriptContext context) throws ScriptException
  406. {
  407. ScriptEngine engine = getEngineByName(engineName);
  408. if (engine == null)
  409. {
  410. throw new ScriptException("No engine registered with name (" + engineName + ")");
  411. }
  412. return eval(engine, script, context);
  413. }
  414. public Object eval(ScriptEngine engine, String script) throws ScriptException
  415. {
  416. return eval(engine, script, null);
  417. }
  418. public void reportScriptFileError(File script, ScriptException e)
  419. {
  420. String dir = script.getParent();
  421. String name = script.getName() + ".error.log";
  422. if (dir != null)
  423. {
  424. final File file = new File(dir + "/" + name);
  425. try (FileOutputStream fos = new FileOutputStream(file))
  426. {
  427. String errorHeader = "Error on: " + file.getCanonicalPath() + Config.EOL + "Line: " + e.getLineNumber() + " - Column: " + e.getColumnNumber() + Config.EOL + Config.EOL;
  428. fos.write(errorHeader.getBytes());
  429. fos.write(e.getMessage().getBytes());
  430. _log.warning("Failed executing script: " + script.getAbsolutePath() + ". See " + file.getName() + " for details.");
  431. }
  432. catch (IOException ioe)
  433. {
  434. _log.log(Level.WARNING, "Failed executing script: " + script.getAbsolutePath() + Config.EOL + e.getMessage() + "Additionally failed when trying to write an error report on script directory. Reason: " + ioe.getMessage(), ioe);
  435. }
  436. }
  437. else
  438. {
  439. _log.log(Level.WARNING, "Failed executing script: " + script.getAbsolutePath() + Config.EOL + e.getMessage() + "Additionally failed when trying to write an error report on script directory.", e);
  440. }
  441. }
  442. public void registerScriptManager(ScriptManager<?> manager)
  443. {
  444. _scriptManagers.add(manager);
  445. }
  446. public void removeScriptManager(ScriptManager<?> manager)
  447. {
  448. _scriptManagers.remove(manager);
  449. }
  450. public List<ScriptManager<?>> getScriptManagers()
  451. {
  452. return _scriptManagers;
  453. }
  454. /**
  455. * @param currentLoadingScript The currentLoadingScript to set.
  456. */
  457. protected void setCurrentLoadingScript(File currentLoadingScript)
  458. {
  459. _currentLoadingScript = currentLoadingScript;
  460. }
  461. /**
  462. * @return Returns the currentLoadingScript.
  463. */
  464. protected File getCurrentLoadingScript()
  465. {
  466. return _currentLoadingScript;
  467. }
  468. private static class SingletonHolder
  469. {
  470. protected static final L2ScriptEngineManager _instance = new L2ScriptEngineManager();
  471. }
  472. }