2
0

L2ScriptEngineManager.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. 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. LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(list)));
  163. String line;
  164. while ((line = lnr.readLine()) != null)
  165. {
  166. if (Config.ALT_DEV_NO_HANDLERS && line.contains("MasterHandler.java"))
  167. {
  168. continue;
  169. }
  170. String[] parts = line.trim().split("#");
  171. if ((parts.length > 0) && !parts[0].startsWith("#") && (parts[0].length() > 0))
  172. {
  173. line = parts[0];
  174. if (line.endsWith("/**"))
  175. {
  176. line = line.substring(0, line.length() - 3);
  177. }
  178. else if (line.endsWith("/*"))
  179. {
  180. line = line.substring(0, line.length() - 2);
  181. }
  182. file = new File(SCRIPT_FOLDER, line);
  183. if (file.isDirectory() && parts[0].endsWith("/**"))
  184. {
  185. executeAllScriptsInDirectory(file, true, 32);
  186. }
  187. else if (file.isDirectory() && parts[0].endsWith("/*"))
  188. {
  189. executeAllScriptsInDirectory(file);
  190. }
  191. else if (file.isFile())
  192. {
  193. try
  194. {
  195. executeScript(file);
  196. }
  197. catch (ScriptException e)
  198. {
  199. reportScriptFileError(file, e);
  200. }
  201. }
  202. else
  203. {
  204. _log.warning("Failed loading: (" + file.getCanonicalPath() + ") @ " + list.getName() + ":" + lnr.getLineNumber() + " - Reason: doesnt exists or is not a file.");
  205. }
  206. }
  207. }
  208. lnr.close();
  209. }
  210. else
  211. {
  212. throw new IllegalArgumentException("Argument must be an file containing a list of scripts to be loaded");
  213. }
  214. }
  215. public void executeAllScriptsInDirectory(File dir)
  216. {
  217. executeAllScriptsInDirectory(dir, false, 0);
  218. }
  219. public void executeAllScriptsInDirectory(File dir, boolean recurseDown, int maxDepth)
  220. {
  221. executeAllScriptsInDirectory(dir, recurseDown, maxDepth, 0);
  222. }
  223. private void executeAllScriptsInDirectory(File dir, boolean recurseDown, int maxDepth, int currentDepth)
  224. {
  225. if (dir.isDirectory())
  226. {
  227. for (File file : dir.listFiles())
  228. {
  229. if (file.isDirectory() && recurseDown && (maxDepth > currentDepth))
  230. {
  231. if (VERBOSE_LOADING)
  232. {
  233. _log.info("Entering folder: " + file.getName());
  234. }
  235. executeAllScriptsInDirectory(file, recurseDown, maxDepth, currentDepth + 1);
  236. }
  237. else if (file.isFile())
  238. {
  239. try
  240. {
  241. String name = file.getName();
  242. int lastIndex = name.lastIndexOf('.');
  243. String extension;
  244. if (lastIndex != -1)
  245. {
  246. extension = name.substring(lastIndex + 1);
  247. ScriptEngine engine = getEngineByExtension(extension);
  248. if (engine != null)
  249. {
  250. executeScript(engine, file);
  251. }
  252. }
  253. }
  254. catch (FileNotFoundException e)
  255. {
  256. // should never happen
  257. _log.log(Level.WARNING, "", e);
  258. }
  259. catch (ScriptException e)
  260. {
  261. reportScriptFileError(file, e);
  262. // _log.log(Level.WARNING, "", e);
  263. }
  264. }
  265. }
  266. }
  267. else
  268. {
  269. throw new IllegalArgumentException("The argument directory either doesnt exists or is not an directory.");
  270. }
  271. }
  272. public void executeScript(File file) throws ScriptException, FileNotFoundException
  273. {
  274. String name = file.getName();
  275. int lastIndex = name.lastIndexOf('.');
  276. String extension;
  277. if (lastIndex != -1)
  278. {
  279. extension = name.substring(lastIndex + 1);
  280. }
  281. else
  282. {
  283. throw new ScriptException("Script file (" + name + ") doesnt has an extension that identifies the ScriptEngine to be used.");
  284. }
  285. ScriptEngine engine = getEngineByExtension(extension);
  286. if (engine == null)
  287. {
  288. throw new ScriptException("No engine registered for extension (" + extension + ")");
  289. }
  290. executeScript(engine, file);
  291. }
  292. public void executeScript(String engineName, File file) throws FileNotFoundException, ScriptException
  293. {
  294. ScriptEngine engine = getEngineByName(engineName);
  295. if (engine == null)
  296. {
  297. throw new ScriptException("No engine registered with name (" + engineName + ")");
  298. }
  299. executeScript(engine, file);
  300. }
  301. public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException
  302. {
  303. BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
  304. if (VERBOSE_LOADING)
  305. {
  306. _log.info("Loading Script: " + file.getAbsolutePath());
  307. }
  308. if (PURGE_ERROR_LOG)
  309. {
  310. String name = file.getAbsolutePath() + ".error.log";
  311. File errorLog = new File(name);
  312. if (errorLog.isFile())
  313. {
  314. errorLog.delete();
  315. }
  316. }
  317. if ((engine instanceof Compilable) && ATTEMPT_COMPILATION)
  318. {
  319. ScriptContext context = new SimpleScriptContext();
  320. context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE);
  321. context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
  322. context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
  323. context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
  324. context.setAttribute(JythonScriptEngine.JYTHON_ENGINE_INSTANCE, engine, ScriptContext.ENGINE_SCOPE);
  325. setCurrentLoadingScript(file);
  326. ScriptContext ctx = engine.getContext();
  327. try
  328. {
  329. engine.setContext(context);
  330. Compilable eng = (Compilable) engine;
  331. CompiledScript cs = eng.compile(reader);
  332. cs.eval(context);
  333. }
  334. finally
  335. {
  336. engine.setContext(ctx);
  337. setCurrentLoadingScript(null);
  338. context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
  339. context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
  340. }
  341. }
  342. else
  343. {
  344. ScriptContext context = new SimpleScriptContext();
  345. context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE);
  346. context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
  347. context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
  348. context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
  349. setCurrentLoadingScript(file);
  350. try
  351. {
  352. engine.eval(reader, context);
  353. }
  354. finally
  355. {
  356. setCurrentLoadingScript(null);
  357. engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
  358. engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
  359. }
  360. }
  361. }
  362. public static String getClassForFile(File script)
  363. {
  364. String path = script.getAbsolutePath();
  365. String scpPath = SCRIPT_FOLDER.getAbsolutePath();
  366. if (path.startsWith(scpPath))
  367. {
  368. int idx = path.lastIndexOf('.');
  369. return path.substring(scpPath.length() + 1, idx);
  370. }
  371. return null;
  372. }
  373. public ScriptContext getScriptContext(ScriptEngine engine)
  374. {
  375. return engine.getContext();
  376. }
  377. public ScriptContext getScriptContext(String engineName)
  378. {
  379. ScriptEngine engine = getEngineByName(engineName);
  380. if (engine == null)
  381. {
  382. throw new IllegalStateException("No engine registered with name (" + engineName + ")");
  383. }
  384. return getScriptContext(engine);
  385. }
  386. public Object eval(ScriptEngine engine, String script, ScriptContext context) throws ScriptException
  387. {
  388. if ((engine instanceof Compilable) && ATTEMPT_COMPILATION)
  389. {
  390. Compilable eng = (Compilable) engine;
  391. CompiledScript cs = eng.compile(script);
  392. return context != null ? cs.eval(context) : cs.eval();
  393. }
  394. return context != null ? engine.eval(script, context) : engine.eval(script);
  395. }
  396. public Object eval(String engineName, String script) throws ScriptException
  397. {
  398. return eval(engineName, script, null);
  399. }
  400. public Object eval(String engineName, String script, ScriptContext context) throws ScriptException
  401. {
  402. ScriptEngine engine = getEngineByName(engineName);
  403. if (engine == null)
  404. {
  405. throw new ScriptException("No engine registered with name (" + engineName + ")");
  406. }
  407. return eval(engine, script, context);
  408. }
  409. public Object eval(ScriptEngine engine, String script) throws ScriptException
  410. {
  411. return eval(engine, script, null);
  412. }
  413. public void reportScriptFileError(File script, ScriptException e)
  414. {
  415. String dir = script.getParent();
  416. String name = script.getName() + ".error.log";
  417. if (dir != null)
  418. {
  419. final File file = new File(dir + "/" + name);
  420. try (FileOutputStream fos = new FileOutputStream(file))
  421. {
  422. String errorHeader = "Error on: " + file.getCanonicalPath() + "\r\nLine: " + e.getLineNumber() + " - Column: " + e.getColumnNumber() + "\r\n\r\n";
  423. fos.write(errorHeader.getBytes());
  424. fos.write(e.getMessage().getBytes());
  425. _log.warning("Failed executing script: " + script.getAbsolutePath() + ". See " + file.getName() + " for details.");
  426. }
  427. catch (IOException ioe)
  428. {
  429. _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);
  430. }
  431. }
  432. else
  433. {
  434. _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);
  435. }
  436. }
  437. public void registerScriptManager(ScriptManager<?> manager)
  438. {
  439. _scriptManagers.add(manager);
  440. }
  441. public void removeScriptManager(ScriptManager<?> manager)
  442. {
  443. _scriptManagers.remove(manager);
  444. }
  445. public List<ScriptManager<?>> getScriptManagers()
  446. {
  447. return _scriptManagers;
  448. }
  449. /**
  450. * @param currentLoadingScript The currentLoadingScript to set.
  451. */
  452. protected void setCurrentLoadingScript(File currentLoadingScript)
  453. {
  454. _currentLoadingScript = currentLoadingScript;
  455. }
  456. /**
  457. * @return Returns the currentLoadingScript.
  458. */
  459. protected File getCurrentLoadingScript()
  460. {
  461. return _currentLoadingScript;
  462. }
  463. private static class SingletonHolder
  464. {
  465. protected static final L2ScriptEngineManager _instance = new L2ScriptEngineManager();
  466. }
  467. }