Example usage for javax.script ScriptContext setAttribute

List of usage examples for javax.script ScriptContext setAttribute

Introduction

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

Prototype

public void setAttribute(String name, Object value, int scope);

Source Link

Document

Sets the value of an attribute in a given scope.

Usage

From source file:com.l2jfree.gameserver.scripting.L2ScriptEngineManager.java

public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

    if (VERBOSE_LOADING) {
        _log.info("Loading Script: " + file.getAbsolutePath());
    }/*from   w w  w . j  a  va2 s  .  c  om*/

    if (PURGE_ERROR_LOG) {
        String name = file.getAbsolutePath() + ".error.log";
        File errorLog = new File(name);
        if (errorLog.isFile()) {
            errorLog.delete();
        }
    }

    if (engine instanceof Compilable && ATTEMPT_COMPILATION) {
        ScriptContext context = new SimpleScriptContext();
        context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'),
                ScriptContext.ENGINE_SCOPE);
        context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE);

        setCurrentLoadingScript(file);
        ScriptContext ctx = engine.getContext();
        try {
            engine.setContext(context);
            if (USE_COMPILED_CACHE) {
                CompiledScript cs = _cache.loadCompiledScript(engine, file);
                cs.eval(context);
            } else {
                Compilable eng = (Compilable) engine;
                CompiledScript cs = eng.compile(reader);
                cs.eval(context);
            }
        } finally {
            engine.setContext(ctx);
            setCurrentLoadingScript(null);
            context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
            context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
            context.removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE);
        }
    } else {
        ScriptContext context = new SimpleScriptContext();
        context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'),
                ScriptContext.ENGINE_SCOPE);
        context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE);
        setCurrentLoadingScript(file);
        try {
            engine.eval(reader, context);
        } finally {
            setCurrentLoadingScript(null);
            engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
            engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
            engine.getContext().removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE);
        }

    }
}

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 ww w  .ja  v  a  2 s.  co  m*/
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.//from w  w  w  .  j  a v  a 2  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.camel.builder.script.ScriptBuilder.java

protected ScriptEngine createScriptEngine() {
    ScriptEngineManager manager = new ScriptEngineManager();
    try {/*from  w  w w . j a v  a  2s .  co m*/
        engine = manager.getEngineByName(scriptEngineName);
    } catch (NoClassDefFoundError ex) {
        LOG.error("Cannot load the scriptEngine for " + scriptEngineName + ", the exception is " + ex
                + ", please ensure correct JARs is provided on classpath.");
    }
    if (engine == null) {
        throw new IllegalArgumentException("No script engine could be created for: " + getScriptEngineName());
    }
    if (isPython()) {
        ScriptContext context = engine.getContext();
        context.setAttribute("com.sun.script.jython.comp.mode", "eval", ScriptContext.ENGINE_SCOPE);
    }
    return engine;
}

From source file:org.apache.camel.builder.script.ScriptBuilder.java

protected void populateBindings(ScriptEngine engine, Exchange exchange) {
    ScriptContext context = engine.getContext();
    int scope = ScriptContext.ENGINE_SCOPE;
    context.setAttribute("context", exchange.getContext(), scope);
    context.setAttribute("exchange", exchange, scope);
    context.setAttribute("request", exchange.getIn(), scope);
    if (exchange.hasOut()) {
        context.setAttribute("response", exchange.getOut(), scope);
    }//from   w  w w. j  a  v a 2 s  .c o m
}

From source file:org.apache.sling.scripting.sightly.js.impl.JsEnvironment.java

public void runResource(Resource scriptResource, Bindings globalBindings, Bindings arguments,
        UnaryCallback callback) {//from  w w  w . j a v  a  2  s  .c o m
    ScriptContext scriptContext = new SimpleScriptContext();
    CommonJsModule module = new CommonJsModule();
    Bindings scriptBindings = buildBindings(scriptResource, globalBindings, arguments, module);
    scriptContext.setBindings(scriptBindings, ScriptContext.ENGINE_SCOPE);
    scriptContext.setAttribute(ScriptEngine.FILENAME, scriptResource.getPath(), ScriptContext.ENGINE_SCOPE);
    runScript(scriptResource, scriptContext, callback, module);
}

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//  w  w  w.  j a  v  a2s  .co  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:org.rhq.enterprise.server.plugins.alertScriptlang.ScriptLangSender.java

@Override
public SenderResult send(Alert alert) {

    String scriptName = alertParameters.getSimpleValue("name", null);
    if (scriptName == null) {
        return new SenderResult(ResultState.FAILURE, "No script given");
    }/*from  w w w .  j  a v a  2 s  .co  m*/
    String language = alertParameters.getSimpleValue("language", "jruby");

    ScriptEngine engine = pluginComponent.getEngineByLanguage(language);
    //        ScriptEngineManager manager = new ScriptEngineManager(serverPluginEnvironment.getPluginClassLoader());
    //        engine = manager.getEngineByName(language);

    if (engine == null) {
        return new SenderResult(ResultState.FAILURE,
                "Script engine with name [" + language + "] does not exist");
    }

    File file = new File(pluginComponent.baseDir + scriptName);
    if (!file.exists() || !file.canRead()) {
        return new SenderResult(ResultState.FAILURE, "Script [" + scriptName
                + "] does not exist or is not readable at [" + file.getAbsolutePath() + "]");
    }

    Object result;
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));

        Map<String, String> preferencesMap = new HashMap<String, String>();
        for (String key : preferences.getSimpleProperties().keySet())
            preferencesMap.put(key, preferences.getSimple(key).getStringValue());

        Map<String, String> parameterMap = new HashMap<String, String>();
        for (String key : alertParameters.getSimpleProperties().keySet())
            parameterMap.put(key, alertParameters.getSimple(key).getStringValue());

        ScriptContext sc = engine.getContext();
        sc.setAttribute("alertPreferences", preferencesMap, ScriptContext.ENGINE_SCOPE);
        sc.setAttribute("alertParameters", parameterMap, ScriptContext.ENGINE_SCOPE);
        engine.eval(br);

        AlertManagerLocal alertManager = LookupUtil.getAlertManager();

        Object[] args = new Object[3];
        args[0] = alert;
        args[1] = alertManager.prettyPrintAlertURL(alert);
        args[2] = alertManager.prettyPrintAlertConditions(alert, false);
        result = ((Invocable) engine).invokeFunction("sendAlert", args);

        if (result == null) {
            return new SenderResult(ResultState.FAILURE,
                    "Script ]" + scriptName + "] returned null, so success is unknown");
        }
        if (result instanceof SenderResult)
            return (SenderResult) result;

        return new SenderResult(ResultState.SUCCESS, "Sending via script resulted in " + result.toString());
    } catch (Exception e) {
        e.printStackTrace();
        return new SenderResult(ResultState.FAILURE,
                "Sending via [" + scriptName + "] failed: " + e.getMessage());
    }
}

From source file:org.xwiki.rendering.internal.macro.ctsreport.CTSDataMacro.java

@Override
public List<Block> execute(Object unusedParameters, String content, MacroTransformationContext context)
        throws MacroExecutionException {
    // We consider the content as containing wiki syntax so we parse it and render it with the Plain text parser.
    XDOM xdom = this.contentParser.parse(content, context, true, false);
    DefaultWikiPrinter printer = new DefaultWikiPrinter();
    this.plainTextRenderer.render(xdom, printer);
    String parsedContent = printer.toString();

    // Parse the results
    TestParser parser = new TestParser();
    List<Result> results = new ArrayList<Result>();
    for (String resultLine : parsedContent.split("[\\r\\n]+")) {
        results.add(parser.parse(resultLine));
    }/*from w  w w .  j  a  va 2 s . co m*/

    // Bind 2 variables in the Script Context so that they can be used by Script macros
    ScriptContext scriptContext = getScriptContext();
    if (scriptContext != null) {
        ResultExtractor extractor = new ResultExtractor();
        Set<String> testNames = extractor.extractByTestName(results);
        scriptContext.setAttribute("ctsTestNames", testNames, ScriptContext.ENGINE_SCOPE);
        Map<String, Pair<Set<Test>, Set<Test>>> tests = extractor.extractBySyntax(results);
        extractor.normalize(testNames, tests);
        scriptContext.setAttribute("ctsTests", tests, ScriptContext.ENGINE_SCOPE);
    } else {
        this.logger.warn("Script Context not found in the Execution Context. CTS Data variable not bound!");
    }

    return Collections.emptyList();
}