Example usage for javax.script ScriptEngineManager ScriptEngineManager

List of usage examples for javax.script ScriptEngineManager ScriptEngineManager

Introduction

In this page you can find the example usage for javax.script ScriptEngineManager ScriptEngineManager.

Prototype

public ScriptEngineManager() 

Source Link

Document

The effect of calling this constructor is the same as calling ScriptEngineManager(Thread.currentThread().getContextClassLoader()).

Usage

From source file:mrf.Graficar.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    ArrayList<Integer> Datosx = new ArrayList<Integer>();
    ArrayList<Double> Datosy = new ArrayList<Double>();
    int in = Integer.parseInt(jTextField2.getText());
    int sup = Integer.parseInt(jTextField3.getText());
    try {/*  ww  w.j  a v a 2  s .  co  m*/
        XYSeries series = new XYSeries("");
        int inferior = in, superior = sup;
        while (inferior <= superior) {
            Datosx.add(inferior);
            engine.put("X", inferior);
            String a = jTextField1.getText();
            Object operation = engine.eval(a);
            Datosy.add(Double.parseDouble("" + operation));
            jTextArea1.append("Parejas ordenadas " + inferior + ":" + operation + "\n");
            series.add(inferior, Double.parseDouble("" + operation));
            inferior++;
        }

        XYSeriesCollection dataset = new XYSeriesCollection();
        dataset.addSeries(series);

        JFreeChart chart = ChartFactory.createXYLineChart("Grafica del polinomio ingresado", // Ttulo
                "Eje x", // Etiqueta Coordenada X
                "Eje y", // Etiqueta Coordenada Y
                dataset, // Datos
                PlotOrientation.VERTICAL, true, // Muestra la leyenda de los productos (Producto A)              
                false, false);

        // Mostramos la grafica en pantalla
        ChartFrame frame = new ChartFrame("GRAFICA POLINOMIO", chart);
        frame.pack();
        frame.setVisible(true);

    } catch (ScriptException e) {
        e.printStackTrace();
    }

}

From source file:nl.geodienstencentrum.maven.plugin.sass.AbstractSassMojo.java

/**
 * Execute the Sass Compilation Ruby Script.
 *
 * @param sassScript//  w w  w  .  j  av a2  s  .co m
 *            the sass script
 * @throws MojoExecutionException
 *             the mojo execution exception
 * @throws MojoFailureException
 *             the mojo failure exception
 */
protected void executeSassScript(final String sassScript) throws MojoExecutionException, MojoFailureException {
    if (this.skip) {
        return;
    }

    final Log log = this.getLog();
    System.setProperty("org.jruby.embed.localcontext.scope", "threadsafe");

    log.debug("Execute Sass Ruby script:\n\n" + sassScript + "\n\n");
    final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    final ScriptEngine jruby = scriptEngineManager.getEngineByName("jruby");
    try {
        final CompilerCallback compilerCallback = new CompilerCallback(log);
        jruby.getBindings(ScriptContext.ENGINE_SCOPE).put("compiler_callback", compilerCallback);
        jruby.eval(sassScript);
        if (this.failOnError && compilerCallback.hadError()) {
            throw new MojoFailureException("Sass compilation encountered errors (see above for details).");
        }
    } catch (final ScriptException e) {
        throw new MojoExecutionException("Failed to execute Sass ruby script:\n" + sassScript, e);
    }
    log.debug("\n");
}

From source file:io.vertx.lang.js.JSVerticleFactory.java

private synchronized void init() {
    if (engine == null) {
        ScriptEngineManager mgr = new ScriptEngineManager();
        engine = mgr.getEngineByName("nashorn");
        if (engine == null) {
            throw new IllegalStateException(
                    "Cannot find Nashorn JavaScript engine - maybe you are not running with Java 8 or later?");
        }/*from   w  w w. j  ava  2  s  . c  o m*/

        URL url = getClass().getClassLoader().getResource(JVM_NPM);
        if (url == null) {
            throw new IllegalStateException("Cannot find " + JVM_NPM + " on classpath");
        }
        try (Scanner scanner = new Scanner(url.openStream(), "UTF-8").useDelimiter("\\A")) {
            String jvmNpm = scanner.next();
            String jvmNpmPath = ClasspathFileResolver.resolveFilename(JVM_NPM);
            jvmNpm += "\n//# sourceURL=" + jvmNpmPath;
            engine.eval(jvmNpm);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }

        try {
            futureJSClass = (ScriptObjectMirror) engine.eval("require('vertx-js/future');");
            // Put the globals in
            engine.put("__jvertx", vertx);
            String globs = "var Vertx = require('vertx-js/vertx'); var vertx = new Vertx(__jvertx);"
                    + "var console = require('vertx-js/util/console');"
                    + "var setTimeout = function(callback,delay) { return vertx.setTimer(delay, callback); };"
                    + "var clearTimeout = function(id) { vertx.cancelTimer(id); };"
                    + "var setInterval = function(callback, delay) { return vertx.setPeriodic(delay, callback); };"
                    + "var clearInterval = clearTimeout;" + "var parent = this;" + "var global = this;";
            if (ADD_NODEJS_PROCESS_ENV) {
                globs += "var process = {}; process.env=java.lang.System.getenv();";
            }
            engine.eval(globs);
        } catch (ScriptException e) {
            throw new IllegalStateException("Failed to eval: " + e.getMessage(), e);
        }
    }
}

From source file:io.github.jeddict.jcode.util.FileUtil.java

/**
 * Used core method for getting {@code ScriptEngine} from {@code
 * org.netbeans.modules.templates.ScriptingCreateFromTemplateHandler}.
 *///from  ww w.jav a2  s . co m
private static ScriptEngine getScriptEngine() {
    if (manager == null) {
        synchronized (FileUtil.class) {
            if (manager == null) {
                manager = new ScriptEngineManager();
            }
        }
    }
    return manager.getEngineByName("freemarker");
}

From source file:org.zaproxy.zap.extension.zest.ExtensionZest.java

@Override
public void hook(ExtensionHook extensionHook) {
    super.hook(extensionHook);

    extensionHook.addOptionsParamSet(getParam());

    if (getView() != null) {
        extensionHook.addProxyListener(this);
        extensionHook.addSessionListener(new ViewSessionChangedListener());

        extensionHook.getHookView().addStatusPanel(this.getZestResultsPanel());
        extensionHook.getHookView().addOptionPanel(getOptionsPanel());

        this.dialogManager = new ZestDialogManager(this, this.getExtScript().getScriptUI());
        new ZestMenuManager(this, extensionHook);

        View.getSingleton().addMainToolbarButton(getRecordButton());
        View.getSingleton().addMainToolbarSeparator(getToolbarSeparator());

        if (getExtScript().getScriptUI() != null) {
            ZestTreeTransferHandler th = new ZestTreeTransferHandler(this);
            getExtScript().getScriptUI().addScriptTreeTransferHandler(ZestElementWrapper.class, th);
        }/* w  ww. j a v a  2  s .com*/
    }

    List<Path> defaultTemplates = getDefaultTemplates();

    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine se = mgr.getEngineByName(ZestScriptEngineFactory.NAME);
    if (se != null) {
        // Looks like this only works if the Zest lib is in the top level
        // lib directory
        this.zestEngineFactory = (ZestScriptEngineFactory) se.getFactory();
    } else {
        // Needed for when the Zest lib is in an add-on (usual case)
        this.zestEngineFactory = new ZestScriptEngineFactory();
        se = zestEngineFactory.getScriptEngine();
    }
    zestEngineWrapper = new ZestEngineWrapper(se, defaultTemplates);
    this.getExtScript().registerScriptEngineWrapper(zestEngineWrapper);

    this.getExtScript().addListener(this);

    if (this.getExtScript().getScriptUI() != null) {
        ZestTreeCellRenderer renderer = new ZestTreeCellRenderer();
        this.getExtScript().getScriptUI().addRenderer(ZestElementWrapper.class, renderer);
        this.getExtScript().getScriptUI().addRenderer(ZestScriptWrapper.class, renderer);
        this.getExtScript().getScriptUI().disableScriptDialog(ZestScriptWrapper.class);
    }
}

From source file:fr.ens.transcriptome.corsen.calc.CorsenHistoryResults.java

/**
 * Set the custom expression//w w w . j av  a  2  s  . c o m
 * @param expression The expression to set
 * @return true if the expression is correct
 */
public boolean setCustomExpression(final String expression) {

    this.script = null;

    if (expression == null || "".equals(expression.trim()))
        return true;

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");

    Compilable compilable = (Compilable) engine;

    try {

        final CompiledScript script = compilable.compile(expression);
        this.script = script;

    } catch (ScriptException e) {

        return false;
    }

    return true;
}

From source file:org.xwiki.rendering.macro.script.AbstractJSR223ScriptMacro.java

/**
 * @param engineName the script engine name (eg "groovy", etc)
 * @return the Script engine to use to evaluate the script
 * @throws MacroExecutionException in case of an error in parsing the jars parameter
 *///from   w  w w .  j  a  v  a  2 s  .  c  o  m
private ScriptEngine getScriptEngine(String engineName) throws MacroExecutionException {
    // Look for a script engine in the Execution Context since we want the same engine to be used
    // for all evals during the same execution lifetime.
    // We must use the same engine because that engine may create an internal ClassLoader in which
    // it loads new classes defined in the script and if we create a new engine then defined classes
    // will be lost.
    // However we also need to be able to execute several script Macros during a single execution request
    // and for example the second macro could have jar parameters. In order to support this use case
    // we ensure in AbstractScriptMacro to reuse the same thread context ClassLoader during the whole
    // request execution.
    ExecutionContext executionContext = this.execution.getContext();
    Map<String, ScriptEngine> scriptEngines = (Map<String, ScriptEngine>) executionContext
            .getProperty(EXECUTION_CONTEXT_ENGINE_KEY);
    if (scriptEngines == null) {
        scriptEngines = new HashMap<String, ScriptEngine>();
        executionContext.setProperty(EXECUTION_CONTEXT_ENGINE_KEY, scriptEngines);
    }
    ScriptEngine engine = scriptEngines.get(engineName);

    if (engine == null) {
        ScriptEngineManager sem = new ScriptEngineManager();
        engine = sem.getEngineByName(engineName);
        scriptEngines.put(engineName, engine);
    }

    return engine;
}

From source file:org.pentaho.js.require.RequireJsGenerator.java

private void requirejsFromJs(String moduleName, String moduleVersion, String jsScript)
        throws IOException, ScriptException, NoSuchMethodException, ParseException {
    moduleInfo = new ModuleInfo(moduleName, moduleVersion);

    Pattern pat = Pattern.compile("webjars!(.*).js");
    Matcher m = pat.matcher(jsScript);

    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, m.group(1));
    }/*from w ww .j a v  a 2  s.  c  o m*/
    m.appendTail(sb);

    jsScript = sb.toString();

    pat = Pattern.compile("webjars\\.path\\(['\"]{1}(.*)['\"]{1}, (['\"]{0,1}[^\\)]+['\"]{0,1})\\)");
    m = pat.matcher(jsScript);
    while (m.find()) {
        m.appendReplacement(sb, m.group(2));
    }
    m.appendTail(sb);

    jsScript = sb.toString();

    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    String script = IOUtils
            .toString(getClass().getResourceAsStream("/org/pentaho/js/require/require-js-aggregator.js"));
    script = script.replace("{{EXTERNAL_CONFIG}}", jsScript);

    engine.eval(script);

    requireConfig = (Map<String, Object>) parser
            .parse(((Invocable) engine).invokeFunction("processConfig", "").toString());
}

From source file:org.labkey.nashorn.NashornController.java

private Pair<ScriptEngine, ScriptContext> getNashorn(boolean useSession) throws Exception {
    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine engine;//from w  ww  . j a  v a2 s. co  m
    ScriptContext context;

    Callable<ScriptEngine> createContext = new Callable<ScriptEngine>() {
        @Override
        @NotNull
        public ScriptEngine call() throws Exception {
            NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
            ScriptEngine engine = factory.getScriptEngine(new String[] { "--global-per-engine" });
            return engine;
        }
    };

    if (useSession) {
        HttpServletRequest req = getViewContext().getRequest();
        engine = SessionHelper.getAttribute(req, this.getClass().getName() + "#scriptEngine", createContext);
    } else {
        engine = createContext.call();
    }

    Bindings engineScope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    engineScope.put("LABKEY", new org.labkey.nashorn.env.LABKEY(getViewContext()));

    Bindings globalScope = engine.getBindings(ScriptContext.GLOBAL_SCOPE);
    // null==engine.getBindings(ScriptContext.GLOBAL_SCOPE), because of --global-per-engine
    // some docs mention enginScope.get("nashorn.global"), but that is also null
    if (null == globalScope)
        globalScope = (Bindings) engineScope.get("nashorn.global");
    if (null == globalScope)
        globalScope = engineScope;
    globalScope.put("console", new Console());

    return new Pair<>(engine, engine.getContext());
}

From source file:com.cubeia.ProtocolGeneratorMojo.java

private void generateCode(String lang, File protocolFile, File outputBaseDirectory, String packageName,
        boolean generateVisitors, String version, boolean failOnBadPacketOrder, String javascript_package_name)
        throws MojoExecutionException, MojoFailureException {

    if (append_language_to_output_base_dir) {
        outputBaseDirectory = appendLangToBaseDir(lang, outputBaseDirectory);
        getLog().info("Appended language '" + lang + "' to base dir, new base dir: " + outputBaseDirectory);
    }/*from  w w w . ja  v  a 2 s  .c om*/

    ScriptEngineManager factory = new ScriptEngineManager();

    // Create a JRuby engine.
    ScriptEngine engine = factory.getEngineByName("jruby");

    // Evaluate JRuby code from string.
    InputStream scriptIn = getClass().getResourceAsStream(GENERATOR_WRAPPER_SCRIPT);
    if (scriptIn == null) {
        new MojoExecutionException(
                "unable to find code generator script resource: " + GENERATOR_WRAPPER_SCRIPT);
    }

    Object[] args = new Object[] { protocolFile.getPath(), lang, outputBaseDirectory.getPath(), packageName,
            generateVisitors ? "true" : null, version, failOnBadPacketOrder ? "true" : null,
            javascript_package_name };

    InputStreamReader scriptReader = new InputStreamReader(scriptIn);

    try {
        engine.eval(scriptReader);
        Invocable invocableEngine = (Invocable) engine;
        invocableEngine.invokeFunction("generate_code", args);
    } catch (ScriptException e) {
        throw new MojoFailureException("code generation error: " + e.toString());
    } catch (NoSuchMethodException e) {
        throw new MojoExecutionException("error calling code generator script: " + e.getMessage());
    }
}