L2ScriptEngineManager.java 15 KB

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