List of usage examples for javax.script ScriptEngine setBindings
public void setBindings(Bindings bindings, int scope);
From source file:org.apache.nifi.processors.script.ExecuteScript.java
/** * Evaluates the given script body (or file) using the current session, context, and flowfile. The script * evaluation expects a FlowFile to be returned, in which case it will route the FlowFile to success. If a script * error occurs, the original FlowFile will be routed to failure. If the script succeeds but does not return a * FlowFile, the original FlowFile will be routed to no-flowfile * * @param context the current process context * @param sessionFactory provides access to a {@link ProcessSessionFactory}, which * can be used for accessing FlowFiles, etc. * @throws ProcessException if the scripted processor's onTrigger() method throws an exception *//*from www .ja va 2 s .c o m*/ @Override public void onTrigger(ProcessContext context, ProcessSessionFactory sessionFactory) throws ProcessException { synchronized (scriptingComponentHelper.isInitialized) { if (!scriptingComponentHelper.isInitialized.get()) { scriptingComponentHelper.createResources(); } } ScriptEngine scriptEngine = scriptingComponentHelper.engineQ.poll(); ComponentLog log = getLogger(); if (scriptEngine == null) { // No engine available so nothing more to do here return; } ProcessSession session = sessionFactory.createSession(); try { try { Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE); if (bindings == null) { bindings = new SimpleBindings(); } bindings.put("session", session); bindings.put("context", context); bindings.put("log", log); bindings.put("REL_SUCCESS", REL_SUCCESS); bindings.put("REL_FAILURE", REL_FAILURE); // Find the user-added properties and set them on the script for (Map.Entry<PropertyDescriptor, String> property : context.getProperties().entrySet()) { if (property.getKey().isDynamic()) { // Add the dynamic property bound to its full PropertyValue to the script engine if (property.getValue() != null) { bindings.put(property.getKey().getName(), context.getProperty(property.getKey())); } } } scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); // Execute any engine-specific configuration before the script is evaluated ScriptEngineConfigurator configurator = scriptingComponentHelper.scriptEngineConfiguratorMap .get(scriptingComponentHelper.getScriptEngineName().toLowerCase()); // Evaluate the script with the configurator (if it exists) or the engine if (configurator != null) { configurator.eval(scriptEngine, scriptToRun, scriptingComponentHelper.getModules()); } else { scriptEngine.eval(scriptToRun); } // Commit this session for the user. This plus the outermost catch statement mimics the behavior // of AbstractProcessor. This class doesn't extend AbstractProcessor in order to share a base // class with InvokeScriptedProcessor session.commit(); } catch (ScriptException e) { throw new ProcessException(e); } } catch (final Throwable t) { // Mimic AbstractProcessor behavior here getLogger().error("{} failed to process due to {}; rolling back session", new Object[] { this, t }); session.rollback(true); throw t; } finally { scriptingComponentHelper.engineQ.offer(scriptEngine); } }
From source file:org.apache.nifi.reporting.script.ScriptedReportingTask.java
@Override public void onTrigger(final ReportingContext context) { synchronized (scriptingComponentHelper.isInitialized) { if (!scriptingComponentHelper.isInitialized.get()) { scriptingComponentHelper.createResources(); }/* ww w . j a va 2 s .c om*/ } ScriptEngine scriptEngine = scriptingComponentHelper.engineQ.poll(); ComponentLog log = getLogger(); if (scriptEngine == null) { // No engine available so nothing more to do here return; } try { try { Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE); if (bindings == null) { bindings = new SimpleBindings(); } bindings.put("context", context); bindings.put("log", log); bindings.put("vmMetrics", vmMetrics); // Find the user-added properties and set them on the script for (Map.Entry<PropertyDescriptor, String> property : context.getProperties().entrySet()) { if (property.getKey().isDynamic()) { // Add the dynamic property bound to its full PropertyValue to the script engine if (property.getValue() != null) { bindings.put(property.getKey().getName(), context.getProperty(property.getKey())); } } } scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); // Execute any engine-specific configuration before the script is evaluated ScriptEngineConfigurator configurator = scriptingComponentHelper.scriptEngineConfiguratorMap .get(scriptingComponentHelper.getScriptEngineName().toLowerCase()); // Evaluate the script with the configurator (if it exists) or the engine if (configurator != null) { configurator.eval(scriptEngine, scriptToRun, scriptingComponentHelper.getModules()); } else { scriptEngine.eval(scriptToRun); } } catch (ScriptException e) { throw new ProcessException(e); } } catch (final Throwable t) { // Mimic AbstractProcessor behavior here getLogger().error("{} failed to process due to {}; rolling back session", new Object[] { this, t }); throw t; } finally { scriptingComponentHelper.engineQ.offer(scriptEngine); } }
From source file:org.apache.nifi.scripting.ScriptFactory.java
private void updateEngine() throws IOException, ScriptException { final String extension = getExtension(scriptFileName); // if engine is thread safe, it's being reused...if it's a JrubyEngine it File scriptFile = new File(this.scriptFileName); ScriptEngine scriptEngine = engineFactory.getNewEngine(scriptFile, extension); scriptText = getScriptText(scriptFile, extension); Map<String, Object> localThreadVariables = new HashMap<>(); String loggerVariableKey = getVariableName("GLOBAL", "logger", extension); localThreadVariables.put(loggerVariableKey, logger); String propertiesVariableKey = getVariableName("INSTANCE", "properties", extension); localThreadVariables.put(propertiesVariableKey, new HashMap<String, String>()); localThreadVariables.put(ScriptEngine.FILENAME, scriptFileName); if (scriptEngine instanceof Compilable) { Bindings bindings = new SimpleBindings(localThreadVariables); scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); compiledScript = ((Compilable) scriptEngine).compile(scriptText); }/*from ww w . ja v a 2 s. c o m*/ logger.debug("Updating Engine!!"); }
From source file:org.jahia.services.render.scripting.bundle.BundleScriptEngineManager.java
private ScriptEngine getEngine(String key, Map<String, ScriptEngineFactory> factoriesForKeyType, KeyType keyType) {/*w w w . j a v a 2 s .c o m*/ final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); Map<String, ScriptEngine> stringScriptEngineMap = engineCache.get(contextClassLoader); if (stringScriptEngineMap == null) { stringScriptEngineMap = new ConcurrentHashMap<>(); engineCache.put(contextClassLoader, stringScriptEngineMap); } ScriptEngine scriptEngine = stringScriptEngineMap.get(key); if (scriptEngine == null) { final ScriptEngineFactory scriptEngineFactory = factoriesForKeyType.get(key); if (scriptEngineFactory != null) { // perform configuration of the factory if needed if (scriptEngineFactory instanceof BundleScriptEngineFactory) { BundleScriptEngineFactory factory = (BundleScriptEngineFactory) scriptEngineFactory; factory.configurePreScriptEngineCreation(); } scriptEngine = scriptEngineFactory.getScriptEngine(); scriptEngine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); } else { switch (keyType) { case EXTENSION: scriptEngine = super.getEngineByExtension(key); break; case MIME_TYPE: scriptEngine = super.getEngineByMimeType(key); break; case NAME: scriptEngine = super.getEngineByName(key); break; default: scriptEngine = null; } } if (scriptEngine != null) { stringScriptEngineMap.put(key, scriptEngine); } } return scriptEngine; }
From source file:org.ms123.common.utils.UtilsServiceImpl.java
public Object executeScript(String scriptName, String namespace, String user, Map params) throws Exception { System.out.println("UtilsServiceImpl.executeScript:" + params); String storeId = (String) params.get("storeId"); StoreDesc sdesc = StoreDesc.get(storeId); namespace = sdesc.getNamespace();//from ww w. j a va2s . c o m System.out.println("UtilsServiceImpl.namespace:" + sdesc + "/" + namespace); ScriptEngine se = m_scriptEngineService.getEngineByName("groovy"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); se.getContext().setWriter(pw); Bindings b = se.createBindings(); b.putAll(params); b.put("jdo", m_dataLayer); b.put("ws", lookupServiceByName("org.ms123.common.workflow.api.WorkflowService")); b.put("ss", lookupServiceByName("org.ms123.common.setting.api.SettingService")); b.put("et", lookupServiceByName("org.ms123.common.entity.api.EntityService")); b.put("storeDesc", sdesc); b.put("home", System.getProperty("simpl4.dir")); b.put("log", m_logger); b.put("user", user); b.put("namespace", namespace); se.setBindings(b, ScriptContext.ENGINE_SCOPE); b.put("se", se); Object r = ""; FileReader fr = getScriptFile(namespace, scriptName); r = se.eval(fr); System.out.println("r:" + r); pw.close(); m_logger.info("executeScript:" + sw); System.out.println("executeScript:" + sw); return null; }
From source file:org.omegat.gui.scripting.ScriptRunner.java
/** * Execute a script with a given engine and bindings. * /*from w w w. ja v a 2s . c om*/ * @param script * The script in string form * @param engine * The engine * @param additionalBindings * A map of bindings that will be included along with other * bindings * @return The evaluation result * @throws ScriptException */ public static Object executeScript(String script, ScriptEngine engine, Map<String, Object> additionalBindings) throws ScriptException { // logResult(StaticUtils.format(OStrings.getString("SCW_SELECTED_LANGUAGE"), // engine.getFactory().getEngineName())); Bindings bindings = engine.createBindings(); 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_CORE, Core.class); if (additionalBindings != null) { bindings.putAll(additionalBindings); } engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE); Object result = engine.eval(script); if (engine instanceof Invocable) { invokeGuiScript((Invocable) engine); } return result; }
From source file:org.paxml.test.SelfTest.java
public void testSyntax() throws Exception { ScriptEngine runtime = new ScriptEngineManager().getEngineByName("javascript"); Bindings bindings = runtime.getBindings(ScriptContext.ENGINE_SCOPE); bindings.put("util", "xx"); runtime.setBindings(new SimpleBindings() { }, ScriptContext.ENGINE_SCOPE); }
From source file:org.rhq.bindings.ScriptEngineFactory.java
/** * Injects the values provided in the bindings into the {@link ScriptContext#ENGINE_SCOPE engine scope} * of the provided script engine./*www. j a va 2 s . c om*/ * * @param engine the engine * @param bindings the bindings * @param deleteExistingBindings true if the existing bindings should be replaced by the provided ones, false * if the provided bindings should be added to the existing ones (possibly overwriting bindings with the same name). */ public static void injectStandardBindings(ScriptEngine engine, StandardBindings bindings, boolean deleteExistingBindings) { bindings.preInject(engine); Bindings engineBindings = deleteExistingBindings ? engine.createBindings() : engine.getBindings(ScriptContext.ENGINE_SCOPE); for (Map.Entry<String, Object> entry : bindings.entrySet()) { engineBindings.put(entry.getKey(), entry.getValue()); } engine.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE); bindings.postInject(engine); }
From source file:org.rhq.bindings.ScriptEngineFactory.java
/** * Remove the specified bindings from the engine. * /*from w w w . j a va 2 s . c o m*/ * @param engine the engine * @param keySet the binding keys to be removed */ public static void removeBindings(ScriptEngine engine, Set<String> keySet) { Bindings engineBindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); for (String key : keySet) { engineBindings.remove(key); } engine.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE); }
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; }