L2ScriptEngineManager.java 18 KB

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