Example usage for javax.script ScriptEngine FILENAME

List of usage examples for javax.script ScriptEngine FILENAME

Introduction

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

Prototype

String FILENAME

To view the source code for javax.script ScriptEngine FILENAME.

Click Source Link

Document

Reserved key for a named value that is the name of the file being executed.

Usage

From source file:ch.admin.hermes.etl.load.HermesETLApplication.java

/**
 * Hauptprogramm//  w w w.j  a  v a2s  .  co m
 * @param args Commandline Argumente
 */
public static void main(String[] args) {
    JFrame frame = null;
    try {
        // Crawler fuer Zugriff auf HERMES 5 Online Loesung initialiseren */
        crawler = new HermesOnlineCrawler();

        // CommandLine Argumente aufbereiten
        parseCommandLine(args);

        // Methoden Export (Variante Zuehlke) extrahieren
        System.out.println("load library " + model);
        ModelExtract root = new ModelExtract();
        root.extract(model);

        frame = createProgressDialog();
        // wird das XML Model von HERMES Online geholt - URL der Templates korrigieren
        if (scenario != null) {
            List<Workproduct> workproducts = (List<Workproduct>) root.getObjects().get("workproducts");
            for (Workproduct wp : workproducts)
                for (Template t : wp.getTemplate()) {
                    // Template beinhaltet kompletten URL - keine Aenderung
                    if (t.getUrl().toLowerCase().startsWith("http")
                            || t.getUrl().toLowerCase().startsWith("file"))
                        continue;
                    // Model wird ab Website geholte
                    if (model.startsWith("http"))
                        t.setUrl(crawler.getTemplateURL(scenario, t.getUrl()));
                    // Model ist lokal - Path aus model und relativem Path Template zusammenstellen
                    else {
                        File m = new File(model);
                        t.setUrl(m.getParentFile() + "/" + t.getUrl());
                    }
                }
        }

        // JavaScript - fuer Import in Fremdsystem
        if (script.endsWith(".js")) {
            final JavaScriptEngine js = new JavaScriptEngine();
            js.setObjects(root.getObjects());
            js.put("progress", progress);
            js.eval("function log( x ) { println( x ); progress.setString( x ); }");
            progress.setString("call main() in " + script);
            js.put(ScriptEngine.FILENAME, script);
            js.call(new InputStreamReader(new FileInputStream(script)), "main",
                    new Object[] { site, user, passwd });
        }
        // FreeMarker - fuer Umwandlungen nach HTML
        else if (script.endsWith(".ftl")) {
            FileOutputStream out = new FileOutputStream(
                    new File(script.substring(0, script.length() - 3) + "html "));
            int i = script.indexOf("templates");
            if (i >= 0)
                script = script.substring(i + "templates".length());
            MethodTransform transform = new MethodTransform();
            transform.transform(root.getObjects(), script, out);
            out.close();
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.toString(), "Fehlerhafte Verarbeitung",
                JOptionPane.WARNING_MESSAGE);
        e.printStackTrace();
    }
    if (frame != null) {
        frame.setVisible(false);
        frame.dispose();
    }
    System.exit(0);
}

From source file:com.espertech.esper.epl.script.jsr223.JSR223Helper.java

public static CompiledScript verifyCompileScript(ExpressionScriptProvided script, String dialect)
        throws ExprValidationException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName(dialect);
    if (engine == null) {
        throw new ExprValidationException("Failed to obtain script engine for dialect '" + dialect
                + "' for script '" + script.getName() + "'");
    }//from   w  ww  . jav a2  s  . c  o m
    engine.put(ScriptEngine.FILENAME, script.getName());

    Compilable compilingEngine = (Compilable) engine;
    try {
        return compilingEngine.compile(script.getExpression());
    } catch (ScriptException ex) {
        String message = "Exception compiling script '" + script.getName() + "' of dialect '" + dialect + "': "
                + getScriptCompileMsg(ex);
        log.info(message, ex);
        throw new ExprValidationException(message, ex);
    }
}

From source file:org.red5.server.script.rhino.RhinoScriptUtils.java

/**
 * Create a new Rhino-scripted object from the given script source.
 * /*from   w  w  w .j  a  va2s.co m*/
 * @param scriptSource
 *            the script source text
 * @param interfaces
 *            the interfaces that the scripted Java object is supposed to
 *            implement
 * @param extendedClass
 * @return the scripted Java object
 * @throws ScriptCompilationException
 *             in case of Rhino parsing failure
 * @throws java.io.IOException
 */
@SuppressWarnings("rawtypes")
public static Object createRhinoObject(String scriptSource, Class[] interfaces, Class extendedClass)
        throws ScriptCompilationException, IOException, Exception {
    if (log.isDebugEnabled()) {
        log.debug("Script Engine Manager: " + mgr.getClass().getName());
    }
    ScriptEngine engine = mgr.getEngineByExtension("js");
    if (null == engine) {
        log.warn("Javascript is not supported in this build");
    }
    // set engine scope namespace
    Bindings nameSpace = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    // add the logger to the script
    nameSpace.put("log", log);
    // compile the wrapper script
    CompiledScript wrapper = ((Compilable) engine).compile(jsWrapper);
    nameSpace.put("Wrapper", wrapper);

    // get the function name ie. class name / ctor
    String funcName = RhinoScriptUtils.getFunctionName(scriptSource);
    if (log.isDebugEnabled()) {
        log.debug("New script: " + funcName);
    }
    // set the 'filename'
    nameSpace.put(ScriptEngine.FILENAME, funcName);

    if (null != interfaces) {
        nameSpace.put("interfaces", interfaces);
    }

    if (null != extendedClass) {
        if (log.isDebugEnabled()) {
            log.debug("Extended: " + extendedClass.getName());
        }
        nameSpace.put("supa", extendedClass.newInstance());
    }
    //
    // compile the script
    CompiledScript script = ((Compilable) engine).compile(scriptSource);
    // eval the script with the associated namespace
    Object o = null;
    try {
        o = script.eval();
    } catch (Exception e) {
        log.error("Problem evaluating script", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Result of script call: " + o);
    }
    // script didnt return anything we can use so try the wrapper
    if (null == o) {
        wrapper.eval();
    } else {
        wrapper.eval();
        o = ((Invocable) engine).invokeFunction("Wrapper", new Object[] { engine.get(funcName) });
        if (log.isDebugEnabled()) {
            log.debug("Result of invokeFunction: " + o);
        }
    }
    return Proxy.newProxyInstance(ClassUtils.getDefaultClassLoader(), interfaces,
            new RhinoObjectInvocationHandler(engine, o));
}

From source file:org.callimachusproject.fluid.consumers.HttpJavaScriptResponseWriter.java

public HttpJavaScriptResponseWriter() throws ScriptException {
    String systemId = getSystemId("SCRIPT");
    ScriptEngineManager man = new ScriptEngineManager();
    ScriptEngine engine = man.getEngineByName("rhino");
    engine.put(ScriptEngine.FILENAME, systemId);
    engine.eval(SCRIPT);//from w ww .  ja v a2 s  .  c o  m
    this.engine = (Invocable) engine;
    this.delegate = new HttpMessageWriter();
}

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 {//www  . jav 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: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  . java2  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.galeoconsulting.leonardinius.rest.service.ScriptRunner.java

private ScriptEngine createScriptEngine(String scriptLanguage, Script script) {
    ScriptEngine engine = engineByLanguage(scriptLanguage);
    if (engine == null) {
        throw new IllegalStateException(
                String.format("Language '%s' script engine could not be found", scriptLanguage));
    }//from  w  w w . j av  a 2 s. co  m
    updateBindings(engine, ScriptContext.ENGINE_SCOPE, new HashMap<String, Object>() {
        {
            put("log", LOG);
            put("selfScriptRunner", ScriptRunner.this);
        }
    });

    engine.getContext().setAttribute(ScriptEngine.FILENAME, scriptName(script.getFilename()),
            ScriptContext.ENGINE_SCOPE);
    engine.getContext().setAttribute(ScriptEngine.ARGV, getArgvs(script.getArgv()), ScriptContext.ENGINE_SCOPE);

    return engine;
}

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 .  ja  v  a2s . 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:de.axelfaust.alfresco.nashorn.repo.processor.NashornScriptProcessor.java

protected Object executeScriptFromResource(final URL resource) throws ScriptException {
    this.initialisationStateLock.readLock().lock();
    try {/*w  w w . j  a va2 s .  co  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:org.apache.nifi.scripting.ScriptFactory.java

private Script getScriptInstance(final Map<String, String> properties) throws ScriptException {

    Map<String, Object> localThreadVariables = new HashMap<>();
    final String extension = getExtension(scriptFileName);
    String loggerVariableKey = getVariableName("GLOBAL", "logger", extension);
    localThreadVariables.put(loggerVariableKey, logger);
    String propertiesVariableKey = getVariableName("INSTANCE", "properties", extension);
    localThreadVariables.put(propertiesVariableKey, properties);
    localThreadVariables.put(ScriptEngine.FILENAME, scriptFileName);
    final Bindings bindings = new SimpleBindings(localThreadVariables);
    final ScriptEngine scriptEngine = engineFactory.getEngine(extension);
    Script instance;/* ww w . j a  v  a 2 s.  c  o m*/
    if (compiledScript == null) {
        instance = (Script) scriptEngine.eval(scriptText, bindings);
        if (instance == null) { // which it will be for python and also for local variables in javascript
            instance = (Script) scriptEngine.eval("instance", bindings);
        }
    } else {
        instance = (Script) compiledScript.eval(bindings);
        if (instance == null) { // which it will be for python and also for local variables in javascript
            instance = (Script) compiledScript.getEngine().eval("instance", bindings);
        }
    }
    instance.setEngine(scriptEngine);
    return instance;
}