L2ScriptEngineManager.java 16 KB

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