2
0

L2ScriptEngineManager.java 17 KB

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