コード例 #1
0
  @Test
  public void testEngine() {
    ScriptEngineManager m = new ScriptEngineManager();

    Assert.assertNotNull(m.getEngineByExtension("rb"));
    Assert.assertNotNull(m.getEngineByName("ruby"));
  }
コード例 #2
0
ファイル: ScriptingWindow.java プロジェクト: ryancar/OmegaT
  public static Object executeScriptFileHeadless(
      ScriptItem scriptItem, boolean forceFromFile, Map<String, Object> additionalBindings) {
    ScriptEngineManager manager = new ScriptEngineManager(ScriptingWindow.class.getClassLoader());
    ScriptEngine scriptEngine =
        manager.getEngineByExtension(getFileExtension(scriptItem.getName()));

    if (scriptEngine == null) {
      scriptEngine = manager.getEngineByName(DEFAULT_SCRIPT);
    }

    SimpleBindings bindings = new SimpleBindings();
    bindings.put(VAR_PROJECT, Core.getProject());
    bindings.put(VAR_EDITOR, Core.getEditor());
    bindings.put(VAR_GLOSSARY, Core.getGlossary());
    bindings.put(VAR_MAINWINDOW, Core.getMainWindow());
    bindings.put(VAR_RESOURCES, scriptItem.getResourceBundle());

    if (additionalBindings != null) {
      bindings.putAll(additionalBindings);
    }

    Object eval = null;
    try {
      eval = scriptEngine.eval(scriptItem.getText(), bindings);
      if (eval != null) {
        Log.logRB("SCW_SCRIPT_RESULT");
        Log.log(eval.toString());
      }
    } catch (Throwable e) {
      Log.logErrorRB(e, "SCW_SCRIPT_ERROR");
    }

    return eval;
  }
コード例 #3
0
  private ScriptEngine createEngine(
      String scriptName, String templateName, boolean runInit, Object it, AbstractBuild<?, ?> build)
      throws FileNotFoundException, IOException {
    String extension = scriptName.substring(scriptName.lastIndexOf('.') + 1);

    ScriptEngine engine = scriptEngineManager.getEngineByExtension(extension);
    if (engine != null) {
      ScriptContext context = engine.getContext();
      context.setAttribute("it", it, ScriptContext.GLOBAL_SCOPE);
      context.setAttribute("build", build, ScriptContext.GLOBAL_SCOPE);
      context.setAttribute("project", build.getParent(), ScriptContext.GLOBAL_SCOPE);
      context.setAttribute(
          "rooturl", ExtendedEmailPublisher.DESCRIPTOR.getHudsonUrl(), ScriptContext.GLOBAL_SCOPE);
      context.setAttribute("host", this, ScriptContext.GLOBAL_SCOPE);
      context.setAttribute("template", templateName, ScriptContext.GLOBAL_SCOPE);

      if (runInit) {
        InputStream initFile = null;
        try {
          initFile = getFileInputStream(extension + "/init." + extension);
          if (initFile != null) {
            engine.eval(new InputStreamReader(initFile));
          }
        } catch (ScriptException e) {
          LOGGER.log(Level.SEVERE, "ScriptException on init file: " + e.toString());
        } catch (Exception e) {
          LOGGER.log(Level.SEVERE, "Exception on init file: " + e.toString());
        } finally {
          IOUtils.closeQuietly(initFile);
        }
      }
    }
    return engine;
  }
コード例 #4
0
 protected ScriptEngine createScriptEngineByExtension(final String extension) {
   assert ScriptLanguage.getByExtension(extension) != null;
   assert supportsScriptLanguageExtension(extension);
   final ScriptEngine result = engineManager.getEngineByExtension(extension);
   if (result == null) {
     final ScriptLanguage language = ScriptLanguage.getByExtension(extension);
     throw new NoEngineException(language);
   }
   return result;
 }
コード例 #5
0
  /**
   * {@inheritDoc}
   *
   * @see schemacrawler.tools.integration.TemplatedSchemaRenderer#render(java.lang.String,
   *     schemacrawler.schema.Schema, java.io.Writer)
   */
  @Override
  protected void render(
      final Connection connection,
      final String scriptFileName,
      final Database database,
      final Writer writer)
      throws ExecutionException {
    if (sf.util.Utility.isBlank(scriptFileName)) {
      throw new ExecutionException("No script file provided");
    }
    final Reader reader;
    final File scriptFile = new File(scriptFileName);
    if (scriptFile.exists() && scriptFile.canRead()) {
      try {
        reader = new FileReader(scriptFile);
      } catch (final FileNotFoundException e) {
        throw new ExecutionException("Cannot load script, " + scriptFile.getAbsolutePath());
      }
    } else {
      final InputStream inputStream =
          ScriptRenderer.class.getResourceAsStream("/" + scriptFileName);
      if (inputStream != null) {
        reader = new InputStreamReader(inputStream);
      } else {
        throw new ExecutionException("Cannot load script, " + scriptFileName);
      }
    }

    try {
      // Create a new instance of the engine
      final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
      ScriptEngine scriptEngine =
          scriptEngineManager.getEngineByExtension(FileUtility.getFileExtension(scriptFile));
      if (scriptEngine == null) {
        scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
      }
      if (scriptEngine == null) {
        throw new ExecutionException("Script engine not found");
      }

      // Set up the context
      scriptEngine.getContext().setWriter(writer);
      scriptEngine.put("database", database);
      scriptEngine.put("connection", connection);

      // Evaluate the script
      scriptEngine.eval(reader);
    } catch (final ScriptException e) {
      throw new ExecutionException("Could not evaluate script", e);
    }
  }
コード例 #6
0
ファイル: Script.java プロジェクト: ptrvif/openhab
 public void loadScript(File file)
     throws FileNotFoundException, ScriptException, NoSuchMethodException {
   logger.info("Loading Script " + file.getName());
   String extension = getFileExtension(file);
   ScriptEngineManager factory = new ScriptEngineManager();
   engine = factory.getEngineByExtension(extension);
   if (engine != null) {
     logger.info("EngineName: " + engine.getFactory().getEngineName());
     initializeSciptGlobals();
     engine.eval(new FileReader(file));
     Invocable inv = (Invocable) engine;
     RuleSet ruleSet = (RuleSet) inv.invokeFunction("getRules");
     rules.addAll(ruleSet.getRules());
   }
 }
コード例 #7
0
    /**
     * Executes a script file without displaying it in the dialog.
     *
     * @param scriptFile The file to execute.
     */
    private void executeScriptFile(final File scriptFile) {
      final List<Pair<String, Object>> bindings = toPairList(m_bindings);

      final ScriptEngineManager manager = new ScriptEngineManager();

      final ScriptEngine engine =
          manager.getEngineByExtension(FileUtils.getFileExtension(scriptFile));

      final IScriptConsole console = new ConsoleWriter(new StringWriter());

      engine.getContext().setWriter(console.getWriter());

      bindings.add(new Pair<String, Object>("SCRIPT_CONSOLE", console));

      final ScriptThread thread = new ScriptThread(engine, scriptFile, bindings);

      CProgressDialog.showEndless(
          getOwner(), String.format("Executing '%s'", scriptFile.getAbsolutePath()), thread);

      if (thread.getException() != null) {
        CUtilityFunctions.logException(thread.getException());

        final String message = "E00108: " + "Script file could not be executed";
        final String description =
            CUtilityFunctions.createDescription(
                String.format(
                    "The script file '%s' could not be executed.", scriptFile.getAbsolutePath()),
                new String[] {
                  "The script file is in use by another program and can not be read.",
                  "You do not have sufficient rights to read the file",
                  "The script contains a bug that caused an exception."
                },
                new String[] {"BinNavi can not read the script file."});

        NaviErrorDialog.show(CScriptingDialog.this, message, description, thread.getException());
      }

      final IScriptPanel panel = (IScriptPanel) scriptTab.getSelectedComponent();

      panel.setOutput(console.getOutput());

      toFront();
    }
コード例 #8
0
  public Gauge getGauge(InputStream stream) {
    GeneralPath path = new GeneralPath();
    GaugeFactoryAPI api = new GaugeFactoryAPI();

    InputStreamReader reader = new InputStreamReader(stream);

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByExtension("js");
    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.put("path", path);
    bindings.put("self", api);
    try {
      engine.eval(reader, bindings);
    } catch (Exception e) {
      e.printStackTrace();
    }

    Gauge gauge = new Gauge(path, api.color);
    return gauge;
  }
コード例 #9
0
ファイル: ScriptMediator.java プロジェクト: rcamus/platform
  protected void initScriptEngine() {
    if (log.isDebugEnabled()) {
      log.debug("Initializing script mediator for language : " + language);
    }

    ScriptEngineManager manager = new ScriptEngineManager();
    manager.registerEngineExtension("js", new RhinoScriptEngineFactory());
    manager.registerEngineExtension("groovy", new GroovyScriptEngineFactory());
    manager.registerEngineExtension("rb", new JRubyScriptEngineFactory());
    this.scriptEngine = manager.getEngineByExtension(language);
    if (scriptEngine == null) {
      handleException("No script engine found for language: " + language);
    }
    xmlHelper = XMLHelper.getArgHelper(scriptEngine);

    this.multiThreadedEngine = scriptEngine.getFactory().getParameter("THREADING") != null;
    log.debug(
        "Script mediator for language : "
            + language
            + " supports multithreading? : "
            + multiThreadedEngine);
  }
コード例 #10
0
ファイル: JSLayerImporter.java プロジェクト: bandj/Ardor3D
  /**
   * Populate a manager with layer information.
   *
   * @param layersFile the script file to read from.
   * @param manager the manager to add layer information to.
   * @param input the input store object, holding things like AnimationClips that the layers might
   *     need for construction.
   * @return an output store object
   * @throws IOException if there is a problem accessing the contents of the layersFile.
   * @throws ScriptException if the script given has syntax/parse errors.
   */
  public static OutputStore addLayers(
      final ResourceSource layersFile, final AnimationManager manager, final InputStore input)
      throws IOException, ScriptException {
    final OutputStore output = new OutputStore();
    final ScriptEngineManager mgr = new ScriptEngineManager();
    final ScriptEngine jsEngine = mgr.getEngineByExtension("js");

    jsEngine.put("MANAGER", manager);
    jsEngine.put("INPUTSTORE", input);
    jsEngine.put("OUTPUTSTORE", output);

    // load our helper functions first...
    jsEngine.eval(
        new InputStreamReader(
            ResourceLocatorTool.getClassPathResourceAsStream(
                JSLayerImporter.class,
                "com/ardor3d/extension/animation/skeletal/state/loader/functions.js")));

    // Add our user data...
    jsEngine.eval(new InputStreamReader(layersFile.openStream()));

    // return our output store, which may have useful items such as attachment points, etc.
    return output;
  }
コード例 #11
0
 protected boolean supportsScriptLanguageExtension(final String extension) {
   final ScriptEngine engine = engineManager.getEngineByExtension(extension);
   final boolean result = engine != null;
   return result;
 }