Example usage for javax.script Bindings clear

List of usage examples for javax.script Bindings clear

Introduction

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

Prototype

void clear();

Source Link

Document

Removes all of the mappings from this map (optional operation).

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 {// w w w  .  ja  v a 2s.  c om
        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:be.solidx.hot.test.TestScriptExecutors.java

@SuppressWarnings("rawtypes")
private Collection<Long> multiThreadedTest(final Script script, final int max,
        final ScriptExecutor scriptExecutor) throws InterruptedException {
    final int iterations = 100;
    ExecutorService executor = Executors.newFixedThreadPool(8);
    final ConcurrentHashMap<String, Long> results = new ConcurrentHashMap<String, Long>();
    final ConcurrentHashMap<String, Long> avgs = new ConcurrentHashMap<String, Long>();
    long benchStart = System.currentTimeMillis();
    for (int i = 0; i < iterations; i++) {
        Runnable runnable = new Runnable() {
            @SuppressWarnings("unchecked")
            @Override//from   w ww.jav  a2 s .  co  m
            public void run() {
                try {
                    long res = 0;
                    Map<String, Object> parameters = new HashMap<String, Object>();
                    parameters.put("i", new Integer(max));
                    parameters.put("n", new Integer(0));

                    //long starting = System.currentTimeMillis();
                    Object object = scriptExecutor.execute(script, parameters);
                    if (object instanceof Bindings) {
                        Bindings bindings = (Bindings) object;
                        res = (Integer) bindings.get("result");
                        bindings.clear();
                    } else if (object instanceof Double) {
                        res = Math.round((Double) object);
                    } else if (object instanceof Long) {
                        res = (long) object;
                    } else
                        res = new Long((Integer) object);
                    long end = System.currentTimeMillis() - avgs.get(this.toString());
                    results.put(UUID.randomUUID().getLeastSignificantBits() + "", res);
                    avgs.put(this.toString(), end);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        avgs.put(runnable.toString(), System.currentTimeMillis());
        executor.submit(runnable);
    }

    while (results.size() < iterations) {
        Thread.sleep(50);
    }
    //Thread.sleep(20000);
    double sum = 0;
    for (Long value : avgs.values()) {
        sum += value;
    }
    System.out.println((sum / (double) iterations) + "");
    System.out.println("==== Time needed for all requests: " + (System.currentTimeMillis() - benchStart));
    results.remove("avg");
    executor = null;
    return results.values();
}

From source file:de.axelfaust.alfresco.nashorn.repo.processor.NashornScriptProcessor.java

protected void initScriptContext() throws ScriptException {
    final Bindings oldEngineBindings = this.engine.getBindings(ScriptContext.ENGINE_SCOPE);
    final AMDModulePreloader oldPreloader = this.amdPreloader;
    final AMDScriptRunner oldAMDRunner = this.amdRunner;

    LOGGER.debug("Initializing new script context");

    inEngineContextInitialization.set(Boolean.TRUE);
    try (NashornScriptModel model = NashornScriptModel.openModel()) {
        // create new (unpolluted) engine bindings
        final Bindings engineBindings = this.engine.createBindings();
        this.engine.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE);

        final Bindings globalBindings = new SimpleBindings();
        this.engine.setBindings(globalBindings, ScriptContext.GLOBAL_SCOPE);

        // only available during initialisation
        globalBindings.put("applicationContext", this.applicationContext);

        LOGGER.debug("Executing bootstrap scripts");
        URL resource;//  w  w w.j a  v a  2 s .c om

        // 1) simple logger facade for SLF4J
        LOGGER.debug("Bootstrapping simple logger");
        resource = NashornScriptProcessor.class.getResource(SCRIPT_SIMPLE_LOGGER);
        this.executeScriptFromResource(resource);

        // 2) AMD loader and noSuchProperty to be used for all scripts apart from bootstrap
        LOGGER.debug("Setting up AMD");
        resource = NashornScriptProcessor.class.getResource(SCRIPT_AMD);
        this.executeScriptFromResource(resource);

        resource = NashornScriptProcessor.class.getResource(SCRIPT_NO_SUCH_PROPERTY);
        this.executeScriptFromResource(resource);

        final Object define = this.engine.get("define");
        this.amdPreloader = ((Invocable) this.engine).getInterface(define, AMDModulePreloader.class);

        // 3) the nashorn loader plugin so we can control access to globals
        LOGGER.debug("Setting up nashorn AMD loader");
        this.preloadAMDModule("loaderMetaLoader", "nashorn", "nashorn");

        // 4) remove Nashorn globals
        LOGGER.debug("Removing disallowed Nashorn globals \"{}\" and \"{}\"",
                NASHORN_GLOBAL_PROPERTIES_TO_ALWAYS_REMOVE, this.nashornGlobalPropertiesToRemove);
        for (final String property : NASHORN_GLOBAL_PROPERTIES_TO_ALWAYS_REMOVE) {
            engineBindings.remove(property);
        }

        if (this.nashornGlobalPropertiesToRemove != null) {
            for (final String property : this.nashornGlobalPropertiesToRemove.split(",")) {
                engineBindings.remove(property.trim());
            }
        }

        // 5) Java extensions (must be picked up by modules before #9)
        globalBindings.put("processorExtensions", this.processorExtensions);

        // 6) AMD config
        LOGGER.debug("Applying AMD config \"{}\"", this.amdConfig);
        resource = this.amdConfig.getURL();
        this.executeScriptFromResource(resource);

        // 7) configured JavaScript base modules
        LOGGER.debug("Bootstrapping base modules");
        this.initScriptContextBaseModules(this.amdPreloader);

        // 8) configured JavaScript extension modules
        LOGGER.debug("Bootstrapping extension modules");
        this.initScriptContextExtensions(this.amdPreloader);

        // 9) remove any init data that shouldn't be publicly available
        globalBindings.clear();

        // 10) obtain the runner interface
        LOGGER.debug("Preparing AMD script runner");
        resource = NashornScriptProcessor.class.getResource(SCRIPE_AMD_SCRIPT_RUNNER);
        final Object scriptRunnerObj = this.executeScriptFromResource(resource);
        this.amdRunner = ((Invocable) this.engine).getInterface(scriptRunnerObj, AMDScriptRunner.class);

        LOGGER.info("New script context initialized");
    } catch (final Throwable t) {
        LOGGER.warn("Initialization of script context failed", t);

        // reset
        this.engine.setBindings(oldEngineBindings, ScriptContext.ENGINE_SCOPE);
        this.engine.getBindings(ScriptContext.GLOBAL_SCOPE).clear();
        this.amdPreloader = oldPreloader;
        this.amdRunner = oldAMDRunner;

        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else if (t instanceof ScriptException) {
            throw (ScriptException) t;
        } else {
            throw new org.alfresco.scripts.ScriptException(
                    "Unknown error initializing script context - reset to previous state", t);
        }
    } finally {
        inEngineContextInitialization.remove();
    }
}