List of usage examples for javax.script ScriptContext ENGINE_SCOPE
int ENGINE_SCOPE
To view the source code for javax.script ScriptContext ENGINE_SCOPE.
Click Source Link
ScriptEngine
and a set of attributes is maintained for each engine. From source file:org.apache.accumulo.core.util.shell.commands.ScriptCommand.java
public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception { boolean invoke = false; ScriptEngineManager mgr = new ScriptEngineManager(); if (cl.hasOption(list.getOpt())) { listJSREngineInfo(mgr, shellState); } else if (cl.hasOption(file.getOpt()) || cl.hasOption(script.getOpt())) { String engineName = DEFAULT_ENGINE; if (cl.hasOption(engine.getOpt())) { engineName = cl.getOptionValue(engine.getOpt()); }/*from w w w. j av a 2 s . c om*/ ScriptEngine engine = mgr.getEngineByName(engineName); if (null == engine) { shellState.printException(new Exception(engineName + " not found")); return 1; } if (cl.hasOption(object.getOpt()) || cl.hasOption(function.getOpt())) { if (!(engine instanceof Invocable)) { shellState.printException( new Exception(engineName + " does not support invoking functions or methods")); return 1; } invoke = true; } ScriptContext ctx = new SimpleScriptContext(); // Put the following objects into the context so that they // are available to the scripts // TODO: What else should go in here? Bindings b = engine.getBindings(ScriptContext.ENGINE_SCOPE); b.put("connection", shellState.getConnector()); List<Object> argValues = new ArrayList<Object>(); if (cl.hasOption(args.getOpt())) { String[] argList = cl.getOptionValue(args.getOpt()).split(","); for (String arg : argList) { String[] parts = arg.split("="); if (parts.length == 0) { continue; } else if (parts.length == 1) { b.put(parts[0], null); argValues.add(null); } else if (parts.length == 2) { b.put(parts[0], parts[1]); argValues.add(parts[1]); } } } ctx.setBindings(b, ScriptContext.ENGINE_SCOPE); Object[] argArray = argValues.toArray(new Object[argValues.size()]); Writer writer = null; if (cl.hasOption(out.getOpt())) { File f = new File(cl.getOptionValue(out.getOpt())); writer = new FileWriter(f); ctx.setWriter(writer); } if (cl.hasOption(file.getOpt())) { File f = new File(cl.getOptionValue(file.getOpt())); if (!f.exists()) { if (null != writer) { writer.close(); } shellState.printException(new Exception(f.getAbsolutePath() + " not found")); return 1; } Reader reader = new FileReader(f); try { engine.eval(reader, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { reader.close(); if (null != writer) { writer.close(); } } } else if (cl.hasOption(script.getOpt())) { String inlineScript = cl.getOptionValue(script.getOpt()); try { if (engine instanceof Compilable) { Compilable compiledEng = (Compilable) engine; CompiledScript script = compiledEng.compile(inlineScript); script.eval(ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } else { engine.eval(inlineScript, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { if (null != writer) { writer.close(); } } } if (null != writer) { writer.close(); } } else { printHelp(shellState); } return 0; }
From source file:cc.arduino.net.CustomProxySelector.java
private Proxy pacProxy(String pac, URI uri) throws IOException, ScriptException, NoSuchMethodException { setAuthenticator(preferences.get(Constants.PREF_PROXY_AUTO_USERNAME), preferences.get(Constants.PREF_PROXY_AUTO_PASSWORD)); URLConnection urlConnection = new URL(pac).openConnection(); urlConnection.connect();//from ww w. ja v a2 s . c o m if (urlConnection instanceof HttpURLConnection) { int responseCode = ((HttpURLConnection) urlConnection).getResponseCode(); if (responseCode != 200) { throw new IOException("Unable to fetch PAC file at " + pac + ". Response code is " + responseCode); } } String pacScript = new String(IOUtils.toByteArray(urlConnection.getInputStream()), Charset.forName("ASCII")); ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn"); nashorn.getBindings(ScriptContext.ENGINE_SCOPE).put("pac", new PACSupportMethods()); Stream.of("isPlainHostName(host)", "dnsDomainIs(host, domain)", "localHostOrDomainIs(host, hostdom)", "isResolvable(host)", "isInNet(host, pattern, mask)", "dnsResolve(host)", "myIpAddress()", "dnsDomainLevels(host)", "shExpMatch(str, shexp)").forEach((fn) -> { try { nashorn.eval("function " + fn + " { return pac." + fn + "; }"); } catch (ScriptException e) { throw new RuntimeException(e); } }); nashorn.eval(pacScript); String proxyConfigs = callFindProxyForURL(uri, nashorn); return makeProxyFrom(proxyConfigs); }
From source file:tk.tomby.tedit.services.ScriptingManager.java
/** * DOCUMENT ME!// ww w.ja v a2 s.c o m * * @param lang DOCUMENT ME! * @param script DOCUMENT ME! * @param buffer DOCUMENT ME! */ public static Object exec(String lang, InputStream stream, IBuffer buffer) { Object result = null; BufferedReader reader = null; try { ScriptEngine engine = manager.getEngineByName(lang); reader = new BufferedReader(new InputStreamReader(stream)); if (buffer != null) { Bindings bindings = engine.createBindings(); bindings.put("buffer", new BufferDecorator(buffer)); engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); } result = engine.eval(reader); } catch (ScriptException e) { log.error("error in script excution", e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { log.warn("error closing reader", e); } } } return result; }
From source file:org.jahia.modules.docrules.EmailDocumentRule.java
private String evaluate(String subject, JCRNodeWrapper document) { if (subject.contains("${")) { try {// w w w .j a v a2s . com ScriptEngine byName = ScriptEngineUtils.getInstance().getEngineByName("velocity"); ScriptContext scriptContext = byName.getContext(); final Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE); bindings.put("document", document); scriptContext.setWriter(new StringWriter()); scriptContext.setErrorWriter(new StringWriter()); byName.eval(subject, bindings); return scriptContext.getWriter().toString().trim(); } catch (ScriptException e) { logger.error("Error while evaluating value [" + subject + "]", e); } } return null; }
From source file:org.siphon.common.js.JsTypeUtil.java
public JsTypeUtil(ScriptEngine jsEngine) { this.engine = (NashornScriptEngine) jsEngine; try {/*ww w.j av a 2 s . co m*/ Bindings b = engine.getContext().getBindings(ScriptContext.ENGINE_SCOPE); this.arrayConstructor = (ScriptObjectMirror) b.get("Array"); this.objectConstructor = (ScriptObjectMirror) b.get("Object"); this.newDate = this.engine.compile("new Date()"); this.global = JsEngineUtil.getGlobal(jsEngine); } catch (Exception e) { e.printStackTrace(); // logger.error("", e); } }
From source file:tk.elevenk.restfulrobot.testcase.TestCase.java
/** * Runs all actions in the test case//from w ww. j a v a2 s .c o m * * @return * @throws Exception */ public void runTest(ScriptEngine _engine) { // check that the test is not already running if (!running) { // prepare bindings before running test this.bindings = _engine.getBindings(ScriptContext.ENGINE_SCOPE); // create empty response and request for bindings this.buildRequest(null); this.bindings.put("Response", this.response); // run the script runtime = System.nanoTime(); this.runScript(scriptFileName); runtime = System.nanoTime() - runtime; } }
From source file:services.plugins.system.notification1.EventNotificationPluginRunner.java
/** * Initialize a new script engine based on the plugin configuration * @throws PluginException /*ww w .ja v a 2 s. c o m*/ */ private synchronized void initScriptEngine() throws PluginException { if (log.isDebugEnabled()) { log.debug("Activating the script engine..."); } this.supportedDataTypes = new ArrayList<DataType>(); this.scriptEngine = getScriptService().getEngine(getPluginContext().getPluginConfigurationName()); this.scriptEngine.getContext().setAttribute("scriptUtils", new HookScriptUtils(getCustomAttributeManagerService(), getPluginContext(), getWsClient()), ScriptContext.ENGINE_SCOPE); Pair<Boolean, byte[]> hookScriptConfiguration = getPluginContext().getConfiguration(getPluginContext() .getPluginDescriptor().getConfigurationBlockDescriptors().get(HOOKSCRIPT_CONFIGURATION_NAME), true); if (!hookScriptConfiguration.getLeft()) { try { //Evaluate the script this.scriptEngine.eval(new String(hookScriptConfiguration.getRight())); } catch (ScriptException e) { if (log.isDebugEnabled()) { log.debug("Invalid hook script", e); } throw new PluginException("Invalid hook script", e); } //Get the registered data types Invocable invocable = (Invocable) this.scriptEngine; try { List<String> supportedDataTypeNames = new ArrayList<String>(); invocable.invokeFunction("register", supportedDataTypeNames); for (String supportedDataTypeName : supportedDataTypeNames) { DataType dataType = DataType.getDataType(supportedDataTypeName); if (dataType == null) { throw new PluginException( "Invalid data type " + supportedDataTypeName + " in the \"register\" method"); } this.supportedDataTypes.add(dataType); } } catch (NoSuchMethodException e) { throw new PluginException("No method \"register\" in this hook script", e); } catch (ScriptException e) { throw new PluginException("No method \"register\" in this hook script or invalid method", e); } } else { throw new PluginException( "WARNING: the current script might not be compatible with the version of the plugin" + ", please edit it and save it before attempting a new start"); } if (log.isDebugEnabled()) { log.debug("...script engine activated"); } }
From source file:org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsGraphBuilderFactory.java
public ScriptEngine createEngine(AuthenticationContext authenticationContext) { ScriptEngine engine = factory.getScriptEngine("--no-java"); Bindings bindings = engine.createBindings(); engine.setBindings(bindings, ScriptContext.GLOBAL_SCOPE); engine.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE); SelectAcrFromFunction selectAcrFromFunction = new SelectAcrFromFunction(); // todo move to functions registry bindings.put(FrameworkConstants.JSAttributes.JS_FUNC_SELECT_ACR_FROM, (SelectOneFunction) selectAcrFromFunction::evaluate); JsLogger jsLogger = new JsLogger(); bindings.put(FrameworkConstants.JSAttributes.JS_LOG, jsLogger); return engine; }
From source file:org.jahia.services.content.nodetypes.initializers.ScriptChoiceListInitializerImpl.java
public List<ChoiceListValue> getChoiceListValues(ExtendedPropertyDefinition epd, String param, List<ChoiceListValue> values, Locale locale, Map<String, Object> context) { if (param != null) { final String extension = Patterns.DOT.split(param)[1]; ScriptEngine byName;/*from w ww . ja v a 2 s . c o m*/ try { byName = scriptEngineUtils.scriptEngine(extension); } catch (ScriptException e) { logger.error(e.getMessage(), e); byName = null; } if (byName != null) { final Set<JahiaTemplatesPackage> forModule = ServicesRegistry.getInstance() .getJahiaTemplateManagerService().getModulesWithViewsForComponent( JCRContentUtils.replaceColon(epd.getDeclaringNodeType().getName())); final Bindings bindings = byName.getBindings(ScriptContext.ENGINE_SCOPE); bindings.put("values", values); for (JahiaTemplatesPackage template : forModule) { final Resource scriptPath = template .getResource(File.separator + "scripts" + File.separator + param); if (scriptPath != null && scriptPath.exists()) { Reader scriptContent = null; try { scriptContent = new InputStreamReader(scriptPath.getInputStream()); return (List<ChoiceListValue>) byName.eval(scriptContent, bindings); } catch (ScriptException e) { logger.error("Error while executing script " + scriptPath, e); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { if (scriptContent != null) { IOUtils.closeQuietly(scriptContent); } } } } } } return Collections.emptyList(); }
From source file:org.nuxeo.ecm.webengine.scripting.Scripting.java
protected Object _runScript(ScriptFile script, Map<String, Object> args) throws Exception { SimpleBindings bindings = new SimpleBindings(); if (args != null) { bindings.putAll(args);// ww w .ja v a 2s .co m } String ext = script.getExtension(); // check for a script engine ScriptEngine engine = getEngineManager().getEngineByExtension(ext); if (engine != null) { ScriptContext ctx = new SimpleScriptContext(); ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE); CompiledScript comp = getCompiledScript(engine, script.getFile()); // use cache for compiled scripts if (comp != null) { return comp.eval(ctx); } // compilation not supported - eval it on the fly try { Reader reader = new FileReader(script.getFile()); try { // TODO use __result__ to pass return value for engine that doesn't returns like jython Object result = engine.eval(reader, ctx); if (result == null) { result = bindings.get("__result__"); } return result; } finally { reader.close(); } } catch (IOException e) { throw new ScriptException(e); } } return null; }