L2ScriptEngineManager.java 15 KB

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