Example usage for javax.script ScriptContext ENGINE_SCOPE

List of usage examples for javax.script ScriptContext ENGINE_SCOPE

Introduction

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

Prototype

int ENGINE_SCOPE

To view the source code for javax.script ScriptContext ENGINE_SCOPE.

Click Source Link

Document

EngineScope attributes are visible during the lifetime of a single ScriptEngine and a set of attributes is maintained for each engine.

Usage

From source file:com.qspin.qtaste.testsuite.impl.JythonTestScript.java

private static void initializeEmbeddedJython() {
    TestBedConfiguration testbedConfig = TestBedConfiguration.getInstance();
    if (testbedConfig != null) {
        platform = testbedConfig.getList("testapi_implementation.import");
    } else {// ww w  .  j a v  a  2 s  . c o m
        platform = null;
    }

    // to force loading of components if not loaded
    ComponentsLoader.getInstance();

    // dynamically create VerbsTestAPI class with verbs methods
    TestAPI testAPI = TestAPIImpl.getInstance();
    Collection<String> registeredComponents = testAPI.getRegisteredComponents();

    // install line buffered auto-flush writers for stdout/sterr
    engine.getContext().setWriter(new LineBufferedPrintWriter(System.out));
    engine.getContext().setErrorWriter(new LineBufferedPrintWriter(System.err));

    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    if (bindings != null) {
        bindings.clear();
    }

    globalBindings = engine.createBindings();
    globalBindings.put(ScriptEngine.FILENAME, "embedded_jython");
    globalBindings.put("logger", scriptLogger);
    globalBindings.put("Status", ScriptTestResultStatus.class);
    try {
        // Declare __TestAPIWrapper class, of which the testAPI variable will be an instance
        String code = "import sys as __sys\n" + "from sets import Set as __Set\n"
                + "from com.qspin.qtaste.testsuite import QTasteException, QTasteTestFailException, QTasteDataException\n"
                + "import com.qspin.qtaste.testsuite.impl.JythonTestScript.ScriptTestResultStatus as Status\n"
                + "class ComponentNotPresentException(Exception):\n" + "    pass\n"
                + "class StepsException(Exception):\n" + "    pass\n" + "class __TestAPIWrapper:\n"
                + "    def __init__(self, testScript):\n" + "        self.testScript = testScript\n"
                + "    def __invoke(self, method, args):\n"
                + "        self.testScript.logInvoke(method.im_self, method.__name__, str(args)[1:-1-(len(args)==1)])\n"
                + "        try:\n" + "            return method(*args)\n" + "        except TypeError, e:\n"
                + "            raise QTasteDataException('Invalid argument(s): ' + str(e))\n"
                + "    def stopTest(self, status, message):\n" + "        if status == Status.FAIL:\n"
                + "            raise QTasteTestFailException(message)\n"
                + "        elif status == Status.NOT_AVAILABLE:\n"
                + "            raise QTasteDataException(message)\n" + "        else:\n"
                + "            raise SyntaxError('Invalid status argument')\n";

        // add get<Component>() methods to the __TestAPIWrapper class
        for (String component : registeredComponents) {
            code += "    def get" + component + "(self, **kw):\n"
                    + "        component = self.testScript.getComponent('" + component + "', kw)\n"
                    + "        return __TestAPIWrapper." + component + "Wrapper(self, component)\n";
        }
        engine.eval(code, globalBindings);

        for (String component : registeredComponents) {
            // declare the <Component>Wrapper class, of which the objects returned
            // by get<Component>() methods will be instances
            code = "class __TestAPIWrapper_" + component + "Wrapper:\n"
                    + "    def __init__(self, testAPI, component):\n" + "        self.testAPI = testAPI\n"
                    + "        self.component = component\n" + "    def __nonzero__(self):\n"
                    + "        return self.component\n" + "    def __getattr__(self, attr):\n" + // only called when self.attr doesn't exist
                    "        raise AttributeError('Component " + component
                    + " has no \\'' + attr + '\\' verb')\n" + "    def __checkPresent(self):\n"
                    + "        if not self.component:\n"
                    + "            raise ComponentNotPresentException('Component " + component
                    + " is not present in testbed')\n";

            // add verbs methods to the ComponentWrapper class
            Collection<String> verbs = testAPI.getRegisteredVerbs(component);
            for (String verb : verbs) {
                code += "    def " + verb + "(self, *args):\n" + "        self.__checkPresent()\n"
                        + "        return self.testAPI._TestAPIWrapper__invoke(self.component." + verb
                        + ", args)\n";
            }
            code += "__TestAPIWrapper." + component + "Wrapper = __TestAPIWrapper_" + component + "Wrapper\n";
            code += "del __TestAPIWrapper_" + component + "Wrapper\n";
            engine.eval(code, globalBindings);
        }
    } catch (ScriptException e) {
        logger.fatal("Couldn't create __TestAPIWrapper Python class", e);
        TestEngine.shutdown();
        System.exit(1);
    }

    try {
        String code = "import os as __os\n"
                + "from com.qspin.qtaste.testsuite.impl import JythonTestScript as __JythonTestScript\n"
                + "__isInTestScriptImport = 0\n" + "def isInTestScriptImport():\n"
                + "    return __isInTestScriptImport != 0\n" + "def importTestScript(testCasePath):\n"
                + "    global __isInTestScriptImport\n" + "    wasInTestScriptImport = __isInTestScriptImport\n"
                + "    __isInTestScriptImport = __isInTestScriptImport + 1\n" + "    try:\n"
                + "        import sys as __sys\n" + "        testCaseName = __os.path.basename(testCasePath)\n"
                + "        basePath = __os.path.dirname(__sys._getframe(1).f_code.co_filename) + __os.sep + '..'\n"
                + "        testCasePath = __os.path.realpath(__os.path.join(basePath, testCasePath))\n"
                + "        __sys.path.insert(0, testCasePath)\n" + "        try:\n"
                + "            if 'TestScript' in __sys.modules:\n"
                + "                del __sys.modules['TestScript']\n" + "            try:\n"
                + "                import TestScript\n" + "            except ImportError:\n"
                + "                raise ImportError('No test script found in ' + testCasePath)\n"
                + "            if wasInTestScriptImport:\n" + "                # test script is imported\n"
                + "                __sys._getframe(1).f_globals[testCaseName] = TestScript\n"
                + "            else:\n" + "                # test script is not imported\n"
                + "                __JythonTestScript.addToGlobalJythonScope(testCaseName, TestScript)\n"
                + "            del __sys.modules['TestScript']\n" + "            del TestScript\n"
                + "        finally:\n" + "            __sys.path.pop(0)\n" + "    finally:\n"
                + "        __isInTestScriptImport = __isInTestScriptImport - 1\n";
        engine.eval(code, globalBindings);
    } catch (ScriptException e) {
        logger.fatal("Couldn't create importTestScript or isInTestScriptImport Python function", e);
        TestEngine.shutdown();
        System.exit(1);
    }

    try {
        String code = "import time as __time, sys as __sys\n"
                + "from java.lang import ThreadDeath as __ThreadDeath\n"
                + "from java.lang.reflect import UndeclaredThrowableException as __UndeclaredThrowableException\n"
                + "from com.qspin.qtaste.testsuite import QTasteTestFailException\n"
                + "import com.qspin.qtaste.reporter.testresults.TestResult.Status as __TestResultStatus\n"
                + "def doStep(idOrFunc, func=None):\n" + "    if __isInTestScriptImport:\n"
                + "        # test script is imported, so don't execute step\n" + "        return\n"
                + "    doStep.countStack = getattr(doStep, 'countStack', [0])\n"
                + "    doStep.stepIdStack = getattr(doStep, 'stepIdStack', [])\n"
                + "    doStep.stepNameStack = getattr(doStep, 'stepNameStack', [])\n"
                + "    doStep.countStack[-1] = doStep.countStack[-1] + 1\n" + "    if func is None:\n"
                + "        # idOrFunc is the step function no id is given\n"
                + "        id = str(doStep.countStack[-1])\n" + "        func = idOrFunc\n" + "    else:\n"
                + "        # idOrFunc is the step id, args[0] is the step function\n"
                + "        id = str(idOrFunc)\n" + "    doStep.stepIdStack.append(id)\n"
                + "    doStep.stepNameStack.append(func.func_name)\n" + "    doStep.countStack.append(0)\n"
                + "    doStep.stepId = stepId = '.'.join(doStep.stepIdStack)\n"
                + "    stepName = '.'.join(doStep.stepNameStack)\n" + "    stepDoc = func.func_doc\n"
                + "    __JythonTestScript.getLogger().info('Begin of step %s (%s)' % (stepId, stepName))\n"
                + "    status = __TestResultStatus.SUCCESS\n" + "    begin_time = __time.clock()\n"
                + "    try:\n"
                + "        testScript.addStepResult(stepId, __TestResultStatus.RUNNING, stepName, stepDoc, 0)\n"
                + "        func()\n"
                + "    except (QTasteTestFailException, __ThreadDeath, __UndeclaredThrowableException):\n"
                + "        status = __TestResultStatus.FAIL\n" + "        raise\n" + "    except:\n"
                + "        status = __TestResultStatus.NOT_AVAILABLE\n" + "        raise\n" + "    finally:\n"
                + "        end_time = __time.clock()\n" + "        elapsed_time = end_time - begin_time\n"
                + "        __JythonTestScript.getLogger().info('End of step %s (%s) - status: %s - elapsed time: %.3f seconds' "
                + "% (stepId, stepName, status, elapsed_time))\n"
                + "        testScript.addStepResult(stepId, status, stepName, stepDoc, elapsed_time)\n"
                + "        doStep.countStack.pop()\n" + "        doStep.stepIdStack.pop()\n"
                + "        doStep.stepNameStack.pop()\n";
        engine.eval(code, globalBindings);
    } catch (ScriptException e) {
        logger.fatal("Couldn't create doStep Python function", e);
        TestEngine.shutdown();
        System.exit(1);
    }

    try {
        String code = "import sys as __sys\n" + "def __findStepIndex(table, id):\n"
                + "   for index in range(len(table)):\n" + "       stepId = str(table[index][0])\n"
                + "       if stepId == id:\n" + "           return index\n"
                + "   raise StepsException('Step %s does not exist in steps table' % id)\n"
                + "def doSteps(table, selector = None):\n" + "    if __isInTestScriptImport:\n"
                + "        # test script is imported, so don't execute steps\n" + "        return\n"
                + "    # check that steps id are correct identifiers\n" + "    import re\n"
                + "    idPattern = re.compile(r'^\\w+$')\n" + "    for index in range(len(table)):\n"
                + "       stepId = str(table[index][0])\n" + "       if not idPattern.match(stepId):\n"
                + "           raise StepsException('Step id %s is not a valid identifier' % stepId)\n"
                + "    if selector is None:\n" + "        for (stepId, stepName) in table:\n"
                + "            doStep(stepId, stepName)\n" + "    else:\n"
                + "        match = re.match(r'^\\[\\s*(\\w*)(?:\\s*-\\s*(\\w*))?\\s*\\]$', selector)\n"
                + "        if match:\n" + "            startId = match.group(1)\n"
                + "            endId = match.group(match.lastindex)\n" + "        else:\n"
                + "            raise StepsException(arg + ' is not a valid format of selector, should be [id], [id1-id2], "
                + "[id1-] or [-id2]')\n" + "        if startId == '':\n" + "            startIndex = 0\n"
                + "        else:" + "            startIndex = __findStepIndex(table, startId)\n"
                + "        if endId == '':\n" + "            endIndex = len(table)-1\n" + "        else:"
                + "            endIndex = __findStepIndex(table, endId)\n"
                + "        if endIndex < startIndex:\n"
                + "            raise StepsException('Step %s should occur after step %s in steps table' % (startId, endId))\n"
                + "        for (stepId, stepName) in table[startIndex:endIndex+1]:\n"
                + "            doStep(stepId, stepName)\n";
        engine.eval(code, globalBindings);
    } catch (ScriptException e) {
        logger.fatal("Couldn't create doSteps Python function", e);
        TestEngine.shutdown();
        System.exit(1);
    }

    // set code to declare __ScriptDebugger class
    // note: it doesn't work if it is evaluated in the global bindings
    scriptDebuggerClassCode = "import bdb as __bdb\n" + "class __ScriptDebugger(__bdb.Bdb):\n"
            + "  def user_line(self, frame):\n" + "    if self.run:\n" + "      self.run = 0\n"
            + "      self.set_continue()\n" + "    else:\n" + "      # arrived at breakpoint\n"
            + "      lineNumber = frame.f_lineno\n" + "      fileName = frame.f_code.co_filename\n"
            + "      action = __scriptBreakpoint.breakScript(fileName, lineNumber, frame.f_locals)\n"
            + "      if action == 0:\n"
            + "        testAPI.stopTest(Status.NOT_AVAILABLE, 'Script has been stopped by user')\n"
            + "      elif action == 1:\n" + "        self.set_next(frame)\n" + "      elif action == 3:\n"
            + "        self.set_step()\n" + "      elif action == 2:\n" + "        self.set_continue()\n";
}

From source file:org.rhq.bindings.ScriptEngineFactory.java

/**
 * Remove the specified bindings from the engine.
 * /*from w w w  .j a va  2s  .com*/
 * @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.netbeans.jcode.core.util.FileUtil.java

public static String expandTemplate(String template, Map<String, Object> values) {
    StringWriter writer = new StringWriter();
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    if (values != null) {
        bind.putAll(values);//from w w w  . j a va  2s  . c o m
    }
    bind.put(ENCODING_PROPERTY_NAME, Charset.defaultCharset().name());
    eng.getContext().setWriter(writer);
    Reader is = new StringReader(template);
    try {
        eng.eval(is);
    } catch (ScriptException ex) {
        Exceptions.printStackTrace(ex);
    }

    return writer.toString();

}

From source file:com.lucidtechnics.blackboard.util.Jsr223ScriptingUtil.java

public Object executeScript(String[] _scriptResources) {
    ScriptContext scriptContext = getScriptEngine().getContext();

    Object result = null;// w ww  . j a v a2  s .com

    int i = 0;

    try {
        for (String key : getBindingsMap().keySet()) {
            scriptContext.setAttribute(key, getBindingsMap().get(key), ScriptContext.ENGINE_SCOPE);
        }

        for (i = 0; i < _scriptResources.length; i++) {
            CompiledScript script = compileScript(_scriptResources[i]);

            if (script != null) {
                result = script.eval(scriptContext);
            } else {
                result = getScriptEngine().eval(new InputStreamReader(findScript(_scriptResources[i])),
                        scriptContext);
            }
        }
    } catch (Throwable t) {
        throw new RuntimeException(
                "Unable to execute script: " + _scriptResources[i] + " for this reason: " + t.toString(), t);
    }

    return result;
}

From source file:tk.elevenk.restfulrobot.testcase.TestCase.java

/**
 * Runs the given test script file/*w  w w . j a va2s. co  m*/
 * 
 * @param fileName
 */
public void runScript(String fileName) {

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
    engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

    if (!fileName.endsWith(".js")) {
        fileName = fileName.concat(".js");
    }

    FileReader scriptFile = null;
    // attempt to open the script file
    try {
        scriptFile = new FileReader(new File(RestfulRobot.SCRIPTS_PATH + fileName));
    } catch (FileNotFoundException e) {
        logger.error(ExceptionUtils.getStackTrace(e));
        result.setDetails(e.getMessage());
        result.setResultType(TestResult.TYPE_ERROR);
    }

    // run the script
    try {
        logger.info("Running script " + fileName);
        engine.eval(scriptFile);
    } catch (ScriptException e) {
        logger.error(ExceptionUtils.getStackTrace(e));
        result.setDetails(e.getMessage());
        result.setResultType(TestResult.TYPE_ERROR);
    }

    // pull data from script
    try {
        this.testCaseID = (String) engine.get("testCaseID");
        this.testCategory = (String) engine.get("testCategory");
        this.testPlan = (String) engine.get("testPlan");
        this.testProject = (String) engine.get("testProject");
        this.testType = (String) engine.get("testType");
        this.testName = (String) engine.get("testName");
    } catch (Exception e) {
        // TODO make this try each parameter
    }

    logger.info("Finished running script");
}

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

public static String expandTemplate(String inputTemplatePath, Map<String, Object> values) {
    InputStream contentStream = loadResource(inputTemplatePath);
    StringWriter writer = new StringWriter();
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    if (values != null) {
        bind.putAll(values);//from   w  w w .  ja v a 2s .  com
    }
    bind.put(ENCODING_PROPERTY_NAME, Charset.defaultCharset().name());
    eng.getContext().setWriter(writer);
    Reader is = new InputStreamReader(contentStream);
    try {
        eng.eval(is);
    } catch (ScriptException ex) {
        Exceptions.printStackTrace(ex);
    }

    return writer.toString();
}

From source file:com.xpn.xwiki.web.SaveAction.java

/**
 * Saves the current document, updated according to the parameters sent in the request.
 *
 * @param context The current request {@link XWikiContext context}.
 * @return <code>true</code> if there was an error and the response needs to render an error page,
 *         <code>false</code> if the document was correctly saved.
 * @throws XWikiException If an error occured: cannot communicate with the storage module, or cannot update the
 *             document because the request contains invalid parameters.
 *//*  ww w .  ja va  2  s  .co m*/
public boolean save(XWikiContext context) throws XWikiException {
    XWiki xwiki = context.getWiki();
    XWikiRequest request = context.getRequest();
    XWikiDocument doc = context.getDoc();
    EditForm form = (EditForm) context.getForm();

    // Check save session
    int sectionNumber = 0;
    if (request.getParameter("section") != null && xwiki.hasSectionEdit(context)) {
        sectionNumber = Integer.parseInt(request.getParameter("section"));
    }

    // We need to clone this document first, since a cached storage would return the same object for the
    // following requests, so concurrent request might get a partially modified object, or worse, if an error
    // occurs during the save, the cached object will not reflect the actual document at all.
    doc = doc.clone();

    String language = form.getLanguage();
    // FIXME Which one should be used: doc.getDefaultLanguage or
    // form.getDefaultLanguage()?
    // String defaultLanguage = ((EditForm) form).getDefaultLanguage();
    XWikiDocument tdoc;

    if (doc.isNew() || (language == null) || (language.equals("")) || (language.equals("default"))
            || (language.equals(doc.getDefaultLanguage()))) {
        // Saving the default document translation.
        // Need to save parent and defaultLanguage if they have changed
        tdoc = doc;
    } else {
        tdoc = doc.getTranslatedDocument(language, context);
        if ((tdoc == doc) && xwiki.isMultiLingual(context)) {
            // Saving a new document translation.
            tdoc = new XWikiDocument(doc.getDocumentReference());
            tdoc.setLanguage(language);
            tdoc.setStore(doc.getStore());
        } else if (tdoc != doc) {
            // Saving an existing document translation (but not the default one).
            // Same as above, clone the object retrieved from the store cache.
            tdoc = tdoc.clone();
        }
    }

    if (doc.isNew()) {
        doc.setLocale(Locale.ROOT);
        if (doc.getDefaultLocale() == Locale.ROOT) {
            doc.setDefaultLocale(
                    LocaleUtils.toLocale(context.getWiki().getLanguagePreference(context), Locale.ROOT));
        }
    }

    try {
        tdoc.readFromTemplate(form.getTemplate(), context);
    } catch (XWikiException e) {
        if (e.getCode() == XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY) {
            context.put("exception", e);
            return true;
        }
    }

    if (sectionNumber != 0) {
        XWikiDocument sectionDoc = tdoc.clone();
        sectionDoc.readFromForm(form, context);
        String sectionContent = sectionDoc.getContent() + "\n";
        String content = tdoc.updateDocumentSection(sectionNumber, sectionContent);
        tdoc.setContent(content);
        tdoc.setComment(sectionDoc.getComment());
        tdoc.setMinorEdit(sectionDoc.isMinorEdit());
    } else {
        tdoc.readFromForm(form, context);
    }

    // TODO: handle Author
    String username = context.getUser();
    tdoc.setAuthor(username);
    if (tdoc.isNew()) {
        tdoc.setCreator(username);
    }

    // Make sure we have at least the meta data dirty status
    tdoc.setMetaDataDirty(true);

    // Validate the document if we have xvalidate=1 in the request
    if ("1".equals(request.getParameter("xvalidate"))) {
        boolean validationResult = tdoc.validate(context);
        // If the validation fails we should show the "Inline form" edit mode
        if (validationResult == false) {
            // Set display context to 'edit'
            context.put("display", "edit");
            // Set the action used by the "Inline form" edit mode as the context action. See #render(XWikiContext).
            context.setAction(tdoc.getDefaultEditMode(context));
            // Set the document in the context
            context.put("doc", doc);
            context.put("cdoc", tdoc);
            context.put("tdoc", tdoc);
            // Force the "Inline form" edit mode.
            getCurrentScriptContext().setAttribute("editor", "inline", ScriptContext.ENGINE_SCOPE);

            return true;
        }
    }

    // Remove the redirect object if the save request doesn't update it. This allows users to easily overwrite
    // redirect place-holders that are created when we move pages around.
    if (tdoc.getXObject(REDIRECT_CLASS) != null
            && request.getParameter("XWiki.RedirectClass_0_location") == null) {
        tdoc.removeXObjects(REDIRECT_CLASS);
    }

    // We get the comment to be used from the document
    // It was read using readFromForm
    xwiki.saveDocument(tdoc, tdoc.getComment(), tdoc.isMinorEdit(), context);

    Job createJob = startCreateJob(tdoc.getDocumentReference(), form);
    if (createJob != null) {
        if (isAsync(request)) {
            if (Utils.isAjaxRequest(context)) {
                // Redirect to the job status URL of the job we have just launched.
                sendRedirect(context.getResponse(), String.format("%s/rest/jobstatus/%s?media=json",
                        context.getRequest().getContextPath(), serializeJobId(createJob.getRequest().getId())));
            }

            // else redirect normally and the operation will eventually finish in the background.
            // Note: It is preferred that async mode is called in an AJAX request that can display the progress.
        } else {
            // Sync mode, default, wait for the work to finish.
            try {
                createJob.join();
            } catch (InterruptedException e) {
                throw new XWikiException(String.format(
                        "Interrupted while waiting for template [%s] to be processed when creating the document [%s]",
                        form.getTemplate(), tdoc.getDocumentReference()), e);
            }
        }
    } else {
        // Nothing more to do, just unlock the document.
        XWikiLock lock = tdoc.getLock(context);
        if (lock != null) {
            tdoc.removeLock(context);
        }
    }

    return false;
}

From source file:org.fit.cssbox.scriptbox.demo.tester.ConsoleInjector.java

@Override
public boolean inject(ScriptContext context) {
    Console console = new Console(textPane);
    Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.put("console", console);

    return true;//w  ww  . j a  va 2 s.  co  m
}

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();
        }//w w w .j a  va  2s.  com
    }
    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.jaffa.rules.util.ScriptEnginePool.java

/**
 * Clears the script engine of all previous state except, if it is a BeanShell interpreter,
 * the engine is left//w  w  w  .j  a  v a 2  s  .c  o  m
 *
 * @param scriptEngine ScriptEngine to clear
 */
private void clearEngine(String language, ScriptEngine scriptEngine) {
    // Clear everything except the BeanShell engine ("bsh" in the binding)
    // This will clear all imported class, methods, and variables
    List<String> itemsToRemove = new ArrayList<String>();
    for (Map.Entry<String, Object> bindingEntry : scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE)
            .entrySet()) {
        if (language.equalsIgnoreCase(BEANSHELL)
                && bindingEntry.getKey().equalsIgnoreCase(BEANSHELL_ENGINE_NAME)) {
            continue;
        }
        itemsToRemove.add(bindingEntry.getKey());
    }
    for (String value : itemsToRemove) {
        scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE).remove(value);
    }

    // Clear entire global scope
    scriptEngine.getBindings(ScriptContext.GLOBAL_SCOPE).clear();
}