Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ScriptEngineWrapper.java 5.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. /*
  2. * Copyright (c) 2006-2015 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.addons.scriptplugin;
  23. import com.google.common.base.Preconditions;
  24. import java.io.File;
  25. import java.io.FileReader;
  26. import java.io.IOException;
  27. import javax.script.Invocable;
  28. import javax.script.ScriptEngine;
  29. import javax.script.ScriptEngineManager;
  30. import javax.script.ScriptException;
  31. import org.slf4j.Logger;
  32. import org.slf4j.LoggerFactory;
  33. import static com.dmdirc.util.LogUtils.USER_ERROR;
  34. /**
  35. * Class to create script engines!
  36. */
  37. public class ScriptEngineWrapper {
  38. private static final Logger LOG = LoggerFactory.getLogger(ScriptEngineWrapper.class);
  39. /** The Script Engine this wrapper wraps */
  40. private ScriptEngine engine;
  41. /** The File this script is from */
  42. private final File file;
  43. /** Script-Local JS Helper */
  44. private final JavaScriptHelper localHelper = new JavaScriptHelper();
  45. /** Manager to get script engines. */
  46. private final ScriptEngineManager scriptEngineManager;
  47. /**
  48. * Create a new ScriptEngineWrapper
  49. *
  50. * @param scriptEngineManager Manager to get script engines
  51. * @param filename Filename of script
  52. *
  53. * @throws ScriptException If there was an error during creation
  54. */
  55. protected ScriptEngineWrapper(final ScriptEngineManager scriptEngineManager,
  56. final String filename) throws ScriptException {
  57. Preconditions.checkNotNull(filename, "File cannot be null");
  58. this.scriptEngineManager = scriptEngineManager;
  59. file = new File(filename);
  60. engine = createEngine();
  61. callFunction("onLoad");
  62. }
  63. /**
  64. * Get a reference to the ScriptEngine.
  65. *
  66. * @return a reference to the ScriptEngine
  67. */
  68. protected ScriptEngine getScriptEngine() {
  69. return engine;
  70. }
  71. /**
  72. * Get a reference to the JavaScriptHelper
  73. *
  74. * @return a reference to the JavaScriptHelper
  75. */
  76. protected JavaScriptHelper getJavaScriptHelper() {
  77. return localHelper;
  78. }
  79. /**
  80. * Get the file for this script
  81. *
  82. * @return The file for this script
  83. */
  84. protected File getFile() {
  85. return file;
  86. }
  87. /**
  88. * Create a new engine for this script
  89. *
  90. * @return Created script engine
  91. *
  92. * @throws ScriptException If there was an error during creation
  93. */
  94. protected ScriptEngine createEngine() throws ScriptException {
  95. final ScriptEngine result = scriptEngineManager.getEngineByName("JavaScript");
  96. try (FileReader fr = new FileReader(file)) {
  97. result.eval(fr);
  98. } catch (IOException ex) {
  99. throw new ScriptException(ex);
  100. }
  101. result.put("localHelper", localHelper);
  102. result.put("thisEngine", this);
  103. return result;
  104. }
  105. /**
  106. * Call a function in this script.
  107. *
  108. * @param functionName Name of function
  109. * @param args Arguments for function
  110. */
  111. protected void callFunction(final String functionName, final Object... args) {
  112. try {
  113. // Call Function
  114. final Invocable invEngine = (Invocable) engine;
  115. invEngine.invokeFunction(functionName, args);
  116. } catch (NoSuchMethodException nsme) {
  117. // There is no "methodExists" function, so we catch NoSuchMethodException
  118. // and do nothing rather that add an error every time a method is called
  119. // that doesn't exist (such as the action_* methods)
  120. } catch (ScriptException e) {
  121. LOG.info(USER_ERROR, "Error calling '{}' in '{}': {}",
  122. functionName, file.getPath(), e.getMessage(), e);
  123. }
  124. }
  125. /**
  126. * Try to reload this script.
  127. *
  128. * @return True if script was reloaded
  129. */
  130. protected boolean reload() {
  131. // Tell the current engine that its about to be obliterated.
  132. callFunction("onPreRehash");
  133. try {
  134. // Try making a new engine
  135. engine = createEngine();
  136. // Tell it that it has been rehashed
  137. callFunction("onRehashSucess");
  138. } catch (ScriptException e) {
  139. LOG.info(USER_ERROR, "Reloading '{}' failed: {}", file.getPath(), e.getMessage(), e);
  140. // Tell it that its rehash failed
  141. callFunction("onRehashFailed", e);
  142. return false;
  143. }
  144. return true;
  145. }
  146. }