Example usage for javax.script ScriptEngine setContext

List of usage examples for javax.script ScriptEngine setContext

Introduction

In this page you can find the example usage for javax.script ScriptEngine setContext.

Prototype

public void setContext(ScriptContext context);

Source Link

Document

Sets the default ScriptContext of the ScriptEngine whose Bindings, Reader and Writers are used for script executions when no ScriptContext is specified.

Usage

From source file:Main.java

public static void main(String[] args) throws ScriptException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    ScriptContext defaultCtx = engine.getContext();
    // Work with defaultCtx here

    // Create a new context
    ScriptContext ctx = new SimpleScriptContext();
    // Configure ctx here

    engine.setContext(ctx);
}

From source file:Main.java

public static void main(String[] args) throws ScriptException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    ScriptContext defaultCtx = engine.getContext();
    // Work with defaultCtx here

    // Create a new context
    ScriptContext ctx = new SimpleScriptContext();

    // Configure ctx here

    // Set ctx as the new default context for the engine
    engine.setContext(ctx);

    ctx.setBindings(manager.getBindings(), ScriptContext.GLOBAL_SCOPE);

    engine.setContext(ctx);//from ww  w  .j a  va  2  s  .c om
}

From source file:org.nuxeo.connect.connector.http.proxy.NashornProxyPacResolver.java

@Override
public String[] findPacProxies(String url) {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    ScriptContext context = new SimpleScriptContext();
    engine.setContext(context); // set as default context, for invokeFunctino
    SimpleBindings bindings = new SimpleBindings();
    context.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    try {/*from   w  ww. ja va 2 s  . c om*/
        // Register internet functions as Java upcalls
        engine.eval("var NashornProxyPacResolver = Java.type('" + getClass().getName() + "');"
                + "var dnsResolve = NashornProxyPacResolver.dnsResolve;"
                + "var myIpAddress = NashornProxyPacResolver.myIpAddress");
        // Register others pac methods
        engine.eval(getFileReader(PAC_FUNCTIONS_FILE));
        // Register remote pac function
        engine.eval(getRemotePacBodyReader());
        // Call and return pac resolution function
        String proxies = (String) ((Invocable) engine).invokeFunction(EXEC_PAC_FUNC, url, getHost(url));
        return proxies.split(";");
    } catch (IOException | ScriptException | NoSuchMethodException e) {
        log.warn(e, e);
    }
    return null;
}

From source file:com.aionemu.commons.scripting.AionScriptEngineManager.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());
    }// w  w w  . j  a  va  2s  . 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.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());
    }/*  ww  w. j a  v  a  2  s . com*/

    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:org.nuxeo.automation.scripting.internals.AutomationScriptingServiceImpl.java

@Override
public void run(String script, CoreSession session) throws ScriptException, OperationException {
    ScriptEngine engine = engines.get();
    engine.setContext(new SimpleScriptContext());
    engine.eval(getJSWrapper());//from  w ww  . jav a2  s  .co  m

    // Initialize Operation Context
    if (operationContext == null) {
        operationContext = operationContexts.get();
        operationContext.setCoreSession(session);
    }

    // Injecting Automation Mapper 'automation'
    AutomationMapper automationMapper = new AutomationMapper(session, operationContext);
    engine.put(AutomationScriptingConstants.AUTOMATION_MAPPER_KEY, automationMapper);

    // Inject operation context vars in 'Context'
    engine.put(AutomationScriptingConstants.AUTOMATION_CTX_KEY, automationMapper.ctx.getVars());
    // Session injection
    engine.put("Session", automationMapper.ctx.getCoreSession());
    // User injection
    PrincipalWrapper principalWrapper = new PrincipalWrapper(
            (NuxeoPrincipal) automationMapper.ctx.getPrincipal());
    engine.put("CurrentUser", principalWrapper);
    engine.put("currentUser", principalWrapper);
    // Env Properties injection
    engine.put("Env", Framework.getProperties());
    // DateWrapper injection
    engine.put("CurrentDate", new DateWrapper());
    // Workflow variables injection
    if (automationMapper.ctx.get(Constants.VAR_WORKFLOW) != null) {
        engine.put(Constants.VAR_WORKFLOW, automationMapper.ctx.get(Constants.VAR_WORKFLOW));
    }
    if (automationMapper.ctx.get(Constants.VAR_WORKFLOW_NODE) != null) {
        engine.put(Constants.VAR_WORKFLOW_NODE, automationMapper.ctx.get(Constants.VAR_WORKFLOW_NODE));
    }

    // Helpers injection
    ContextService contextService = Framework.getService(ContextService.class);
    Map<String, ContextHelper> helperFunctions = contextService.getHelperFunctions();
    for (String helperFunctionsId : helperFunctions.keySet()) {
        engine.put(helperFunctionsId, helperFunctions.get(helperFunctionsId));
    }
    engine.eval(script);
}

From source file:org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.DataFactoryScriptingSupport.java

public void initialize(final DataFactory dataFactory, final DataFactoryContext dataFactoryContext)
        throws ReportDataFactoryException {
    if (globalScriptContext != null) {
        return;//from   w ww.  j  ava  2  s  .  co  m
    }

    this.dataFactory = dataFactory;
    this.resourceManager = dataFactoryContext.getResourceManager();
    this.contextKey = dataFactoryContext.getContextKey();
    this.configuration = dataFactoryContext.getConfiguration();
    this.resourceBundleFactory = dataFactoryContext.getResourceBundleFactory();
    this.dataFactoryContext = dataFactoryContext;

    globalScriptContext = new SimpleScriptContext();
    globalScriptContext.setAttribute("dataFactory", dataFactory, ScriptContext.ENGINE_SCOPE);
    globalScriptContext.setAttribute("configuration", configuration, ScriptContext.ENGINE_SCOPE);
    globalScriptContext.setAttribute("resourceManager", resourceManager, ScriptContext.ENGINE_SCOPE);
    globalScriptContext.setAttribute("contextKey", contextKey, ScriptContext.ENGINE_SCOPE);
    globalScriptContext.setAttribute("resourceBundleFactory", resourceBundleFactory,
            ScriptContext.ENGINE_SCOPE);

    if (StringUtils.isEmpty(globalScriptLanguage)) {
        return;
    }

    globalScriptContext.setAttribute("scriptHelper",
            new ScriptHelper(globalScriptContext, globalScriptLanguage, resourceManager, contextKey),
            ScriptContext.ENGINE_SCOPE);

    final ScriptEngine maybeInvocableEngine = new ScriptEngineManager().getEngineByName(globalScriptLanguage);
    if (maybeInvocableEngine == null) {
        throw new ReportDataFactoryException(String.format(
                "DataFactoryScriptingSupport: Failed to locate scripting engine for language '%s'.",
                globalScriptLanguage));
    }
    if (maybeInvocableEngine instanceof Invocable == false) {
        return;
    }
    this.globalScriptEngine = (Invocable) maybeInvocableEngine;

    maybeInvocableEngine.setContext(globalScriptContext);
    try {
        maybeInvocableEngine.eval(globalScript);
    } catch (ScriptException e) {
        throw new ReportDataFactoryException(
                "DataFactoryScriptingSupport: Failed to execute datafactory init script.", e);
    }
}