L2ScriptEngineManager.java 16 KB

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