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

public static void addToGlobalJythonScope(String name, Object value) {
    Bindings globalContext = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    globalContext.put(name, value);/*from  ww w. java 2 s. c om*/
}

From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java

Object eval(final Class scriptClass, final ScriptContext context) throws ScriptException {
    final Binding binding = new Binding(context.getBindings(ScriptContext.ENGINE_SCOPE)) {
        @Override/*from  w w w . j  a v  a 2s.c o  m*/
        public Object getVariable(String name) {
            synchronized (context) {
                int scope = context.getAttributesScope(name);
                if (scope != -1) {
                    return context.getAttribute(name, scope);
                }
                // Redirect script output to context writer, if out var is not already provided
                if ("out".equals(name)) {
                    final Writer writer = context.getWriter();
                    if (writer != null) {
                        return (writer instanceof PrintWriter) ? (PrintWriter) writer
                                : new PrintWriter(writer, true);
                    }
                }
                // Provide access to engine context, if context var is not already provided
                if ("context".equals(name)) {
                    return context;
                }
            }
            throw new MissingPropertyException(name, getClass());
        }

        @Override
        public void setVariable(String name, Object value) {
            synchronized (context) {
                int scope = context.getAttributesScope(name);
                if (scope == -1) {
                    scope = ScriptContext.ENGINE_SCOPE;
                }
                context.setAttribute(name, value, scope);
            }
        }
    };

    try {
        // if this class is not an instance of Script, it's a full-blown class then simply return that class
        if (!Script.class.isAssignableFrom(scriptClass)) {
            return scriptClass;
        } else {
            final Script scriptObject = InvokerHelper.createScript(scriptClass, binding);
            for (Method m : scriptClass.getMethods()) {
                final String name = m.getName();
                globalClosures.put(name, new MethodClosure(scriptObject, name));
            }

            final MetaClass oldMetaClass = scriptObject.getMetaClass();
            scriptObject.setMetaClass(new DelegatingMetaClass(oldMetaClass) {
                @Override
                public Object invokeMethod(final Object object, final String name, final Object args) {
                    if (args == null) {
                        return invokeMethod(object, name, MetaClassHelper.EMPTY_ARRAY);
                    } else if (args instanceof Tuple) {
                        return invokeMethod(object, name, ((Tuple) args).toArray());
                    } else if (args instanceof Object[]) {
                        return invokeMethod(object, name, (Object[]) args);
                    } else {
                        return invokeMethod(object, name, new Object[] { args });
                    }
                }

                @Override
                public Object invokeMethod(final Object object, final String name, final Object args[]) {
                    try {
                        return super.invokeMethod(object, name, args);
                    } catch (MissingMethodException mme) {
                        return callGlobal(name, args, context);
                    }
                }

                @Override
                public Object invokeStaticMethod(final Object object, final String name, final Object args[]) {
                    try {
                        return super.invokeStaticMethod(object, name, args);
                    } catch (MissingMethodException mme) {
                        return callGlobal(name, args, context);
                    }
                }
            });

            final Object o = scriptObject.run();

            // if interpreter mode is enable then local vars of the script are promoted to engine scope bindings.
            if (interpreterModeEnabled) {
                final Map<String, Object> localVars = (Map<String, Object>) context
                        .getAttribute(COLLECTED_BOUND_VARS_MAP_VARNAME);
                if (localVars != null) {
                    localVars.entrySet().forEach(e -> {
                        // closures need to be cached for later use
                        if (e.getValue() instanceof Closure)
                            globalClosures.put(e.getKey(), (Closure) e.getValue());

                        context.setAttribute(e.getKey(), e.getValue(), ScriptContext.ENGINE_SCOPE);
                    });

                    // get rid of the temporary collected vars
                    context.removeAttribute(COLLECTED_BOUND_VARS_MAP_VARNAME, ScriptContext.ENGINE_SCOPE);
                    localVars.clear();
                }
            }

            return o;
        }
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}

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

protected Object executeScriptFromResource(final URL resource) throws ScriptException {
    this.initialisationStateLock.readLock().lock();
    try {/*  w w w  .  java  2  s  .c o  m*/
        LOGGER.debug("Executing script from resource {}", resource);
        try (Reader reader = new URLReader(resource)) {
            this.engine.getContext().setAttribute(ScriptEngine.FILENAME, resource.toString(),
                    ScriptContext.ENGINE_SCOPE);
            return this.engine.eval(reader);
        } catch (final IOException e) {
            throw new ScriptException(e);
        } finally {
            LOGGER.trace("Execution of script from resource {} completed", resource);
        }
    } finally {
        this.initialisationStateLock.readLock().unlock();
    }
}

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

/**
 * Verifies if the creation inside the specified spaceReference is allowed by the current template provider. If the
 * creation is not allowed, an exception will be set on the context.
 *
 * @return {@code true} if the creation is allowed, {@code false} otherwise
 *//*from   w  ww  .  ja  va  2 s.c om*/
public boolean isTemplateProviderAllowedToCreateInCurrentSpace() {
    // Check that the chosen space is allowed with the given template, if not:
    // - Cancel the redirect
    // - Set an error on the context, to be read by the create.vm
    if (templateProvider != null) {
        // Check using the template provider's creation restrictions.
        if (!isTemplateProviderAllowedInSpace(templateProvider, spaceReference,
                TP_CREATION_RESTRICTIONS_PROPERTY)) {
            // put an exception on the context, for create.vm to know to display an error
            Object[] args = { templateProvider.getStringValue(TEMPLATE), spaceReference, name };
            XWikiException exception = new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                    XWikiException.ERROR_XWIKI_APP_TEMPLATE_NOT_AVAILABLE,
                    "Template {0} cannot be used in space {1} when creating page {2}", null, args);

            ScriptContext scontext = getCurrentScriptContext();
            scontext.setAttribute(EXCEPTION, exception, ScriptContext.ENGINE_SCOPE);
            scontext.setAttribute("createAllowedSpaces",
                    getTemplateProviderRestrictions(templateProvider, TP_CREATION_RESTRICTIONS_PROPERTY),
                    ScriptContext.ENGINE_SCOPE);

            return false;
        }
    }

    // For all other cases, creation is allowed.
    return true;
}

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

/**
 * @param newDocument the new document to check if it already exists
 * @return true if the document already exists (i.e. is not usable) and set an exception in the velocity context;
 *         false otherwise.//w w  w .  j  a v a2 s.co m
 */
public boolean isDocumentAlreadyExisting(XWikiDocument newDocument) {
    // if the document exists don't create it, put the exception on the context so that the template gets it and
    // re-requests the page and space, else create the document and redirect to edit
    if (!isEmptyDocument(newDocument)) {
        ScriptContext scontext = getCurrentScriptContext();

        // Expose to the template reference of the document that already exist so that it can propose to view or
        // edit it.
        scontext.setAttribute("existingDocumentReference", newDocument.getDocumentReference(),
                ScriptContext.ENGINE_SCOPE);

        // Throw an exception.
        Object[] args = { newDocument.getDocumentReference() };
        XWikiException documentAlreadyExists = new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY,
                "Cannot create document {0} because it already has content", null, args);
        scontext.setAttribute(EXCEPTION, documentAlreadyExists, ScriptContext.ENGINE_SCOPE);

        return true;
    }

    return false;
}

From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java

private void registerBindingTypes(final ScriptContext context) {
    if (typeCheckingEnabled) {
        final Map<String, ClassNode> variableTypes = new HashMap<>();
        clearVarTypes();/* w ww.ja v  a 2s. c om*/

        // use null for the classtype if the binding value itself is null - not fully sure if that is
        // a sound way to deal with that.  didn't see a class type for null - maybe it should just be
        // unknown and be "Object".  at least null is properly being accounted for now.
        context.getBindings(ScriptContext.GLOBAL_SCOPE)
                .forEach((k, v) -> variableTypes.put(k, null == v ? null : ClassHelper.make(v.getClass())));
        context.getBindings(ScriptContext.ENGINE_SCOPE)
                .forEach((k, v) -> variableTypes.put(k, null == v ? null : ClassHelper.make(v.getClass())));

        COMPILE_OPTIONS.get().put(COMPILE_OPTIONS_VAR_TYPES, variableTypes);
    }
}

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

@Override
public boolean execute(TestData data, TestResult result, final boolean debug) {
    // Interpret the file
    testData = data;/*from  w  ww  .ja v a  2  s .c o m*/
    testResult = result;

    if (debug) {
        testScriptBreakPointEventHandler.addTestScriptBreakpointListener(scriptBreakpoint);
    }

    try {
        Bindings bindings = engine.createBindings();
        engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

        engine.eval("import sys as __sys");
        engine.eval("if not globals().has_key('__initModules'):\n" + "  __initModules = __sys.modules.keys()\n"
                + "else:\n" + "  for m in __sys.modules.keys():\n" + "    if m not in __initModules:\n"
                + "      del __sys.modules[m]", globalBindings);

        // add all global bindinds
        bindings.putAll(globalBindings);

        if (testSuite != null) {
            // add pythonlib subdirectories of test script directory up to test suites directory, to python path
            List<String> additionalPythonPath = getAdditionalPythonPath();
            String pythonPathScript = "";
            for (String pythonlib : additionalPythonPath) {
                pythonPathScript += "__sys.path.append(r'" + pythonlib + "')\n";
            }
            engine.eval(pythonPathScript);
        }

        // reset doStep count / step id / step name stacks
        engine.eval("doStep.countStack = [0]\n" + "doStep.stepIdStack = []\n" + "doStep.stepNameStack = []\n");

        // add testAPI, testData and scriptBreakpoint to bindings
        bindings.put("this", this);
        engine.eval("testAPI = __TestAPIWrapper(this)");
        bindings.remove("__TestAPIWrapper");
        bindings.remove("this");
        bindings.put("testData", scriptTestData);
        bindings.put("DoubleWithPrecision", DoubleWithPrecision.class);
        bindings.put("QTasteException", QTasteException.class);
        bindings.put("QTasteDataException", QTasteDataException.class);
        bindings.put("QTasteTestFailException", QTasteTestFailException.class);
        bindings.put("__scriptBreakpoint", scriptBreakpoint);
        globalBindings.put("testScript", this);

        // create QTaste module with testAPI, testData, DoubleWithPrecision, doStep, doSteps, doSubStep, logger and Status
        engine.eval("class __QTaste_Module:\n" + "    def __init__(self):\n"
                + "        self.importTestScript= importTestScript\n"
                + "        self.isInTestScriptImport= isInTestScriptImport\n"
                + "        self.testAPI= testAPI\n" + "        self.testData = testData\n"
                + "        self.DoubleWithPrecision = DoubleWithPrecision\n" + "        self.doStep = doStep\n"
                + "        self.doSteps = doSteps\n" + "        self.doSubStep = doStep\n"
                + "        self.doSubSteps = doSteps\n" + "        self.logger = logger\n"
                + "        self.Status = Status\n" + "        self.QTasteException = QTasteException\n"
                + "        self.QTasteDataException = QTasteDataException\n"
                + "        self.QTasteTestFailException = QTasteTestFailException\n"
                + "__sys.modules['qtaste'] = __QTaste_Module()");

        // remove testAPI, testData, DoubleWithPrecision, doStep, doSteps, logger and Status from bindinds
        bindings.remove("__QTaste_Module");
        bindings.remove("importTestScript");
        bindings.remove("isCalledFromMainTestScript");
        bindings.remove("testAPI");
        bindings.remove("testData");
        bindings.remove("DoubleWithPrecision");
        bindings.remove("doStep");
        bindings.remove("doSteps");
        bindings.remove("logger");
        bindings.remove("Status");
        bindings.remove("QTasteException");
        bindings.remove("QTasteDataException");
        bindings.remove("QTasteTestFailException");

        // Check if test was aborted by user before execute testscript.py
        if (TestEngine.isAbortedByUser()) {
            return false;
        }

        if (!debug) {
            engine.eval("execfile(r'" + fileName + "', globals())");
        } else {
            // execute in debugger
            engine.eval(scriptDebuggerClassCode);
            engine.eval("__debugger = __ScriptDebugger()");
            bindings.remove("__bdb");
            bindings.remove("__ScriptDebugger");
            for (Breakpoint b : breakPointEventHandler.getBreakpoints()) {
                engine.eval("__debugger.set_break(r'" + b.getFileName() + "', " + b.getLineIndex() + ")");
            }
            engine.eval("__debugger.runcall(execfile, r'" + fileName + "', globals())");
        }
    } catch (ScriptException e) {
        handleScriptException(e, result);
    } finally {
        if (debug) {
            testScriptBreakPointEventHandler.removeTestScriptBreakpointListener(scriptBreakpoint);
        }
    }
    return true;
}

From source file:org.jahia.ajax.gwt.helper.UIConfigHelper.java

/**
 * Get resources//  w w w.  j  a va2 s  .  c o m
 *
 * @param key
 * @param locale
 * @param site
 * @param jahiaUser
 * @return
 */
private String getResources(String key, Locale locale, JCRSiteNode site, JahiaUser jahiaUser) {
    if (key == null || key.length() == 0) {
        return key;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Resources key: " + key);
    }
    String baseName = null;
    String value = null;
    if (key.contains("@")) {
        baseName = StringUtils.substringAfter(key, "@");
        key = StringUtils.substringBefore(key, "@");
    }

    value = Messages.get(baseName, site != null ? site.getTemplatePackage() : null, key, locale, null);
    if (value == null || value.length() == 0) {
        value = Messages.getInternal(key, locale);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Resources value: " + value);
    }
    if (value.contains("${")) {
        try {
            ScriptEngine scriptEngine = scriptEngineUtils.getEngineByName("velocity");
            ScriptContext scriptContext = new SimpleScriptContext();
            final Bindings bindings = new SimpleBindings();
            bindings.put("currentSite", site);
            bindings.put("currentUser", jahiaUser);
            bindings.put("currentLocale", locale);
            bindings.put("PrincipalViewHelper", PrincipalViewHelper.class);
            scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
            scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE),
                    ScriptContext.GLOBAL_SCOPE);
            scriptContext.setWriter(new StringWriter());
            scriptContext.setErrorWriter(new StringWriter());
            scriptEngine.eval(value, scriptContext);
            //String error = scriptContext.getErrorWriter().toString();
            return scriptContext.getWriter().toString().trim();
        } catch (ScriptException e) {
            logger.error("Error while executing script [" + value + "]", e);
        }
    }
    return value;
}