@Override protected ScriptEngine makeEngine() { try { Class<?> c; c = this.getClass().getClassLoader().loadClass("com.sun.script.java.JavaScriptEngineFactory"); ScriptEngineFactory fact = (ScriptEngineFactory) c.newInstance(); ScriptEngine engine = fact.getScriptEngine(); engine .getContext() .setAttribute( "com.sun.script.java.parentLoader", Trampoline2.trampoline.getClassLoader(), ScriptContext.ENGINE_SCOPE); engine .getContext() .setAttribute( "parentLoader", Trampoline2.trampoline.getClassLoader(), ScriptContext.ENGINE_SCOPE); return engine; } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; }
/** * Execute the script and return the ScriptResult corresponding. This method can add an additional * user bindings if needed. * * @param aBindings the additional user bindings to add if needed. Can be null or empty. * @param outputSink where the script output is printed to. * @param errorSink where the script error stream is printed to. * @return a ScriptResult object. */ public ScriptResult<E> execute( Map<String, Object> aBindings, PrintStream outputSink, PrintStream errorSink) { ScriptEngine engine = createScriptEngine(); if (engine == null) return new ScriptResult<>( new Exception("No Script Engine Found for name or extension " + scriptEngineLookup)); // SCHEDULING-1532: redirect script output to a buffer (keep the latest DEFAULT_OUTPUT_MAX_SIZE) BoundedStringWriter outputBoundedWriter = new BoundedStringWriter(outputSink, DEFAULT_OUTPUT_MAX_SIZE); BoundedStringWriter errorBoundedWriter = new BoundedStringWriter(errorSink, DEFAULT_OUTPUT_MAX_SIZE); engine.getContext().setWriter(new PrintWriter(outputBoundedWriter)); engine.getContext().setErrorWriter(new PrintWriter(errorBoundedWriter)); Reader closedInput = new Reader() { @Override public int read(char[] cbuf, int off, int len) throws IOException { throw new IOException("closed"); } @Override public void close() throws IOException {} }; engine.getContext().setReader(closedInput); engine.getContext().setAttribute(ScriptEngine.FILENAME, scriptName, ScriptContext.ENGINE_SCOPE); try { Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); // add additional bindings if (aBindings != null) { for (Entry<String, Object> e : aBindings.entrySet()) { bindings.put(e.getKey(), e.getValue()); } } prepareBindings(bindings); Object evalResult = engine.eval(getReader()); engine.getContext().getErrorWriter().flush(); engine.getContext().getWriter().flush(); // Add output to the script result ScriptResult<E> result = this.getResult(evalResult, bindings); result.setOutput(outputBoundedWriter.toString()); return result; } catch (javax.script.ScriptException e) { // drop exception cause as it might not be serializable ScriptException scriptException = new ScriptException(e.getMessage()); scriptException.setStackTrace(e.getStackTrace()); return new ScriptResult<>(scriptException); } catch (Throwable t) { String stack = Throwables.getStackTraceAsString(t); if (t.getMessage() != null) { stack = t.getMessage() + System.lineSeparator() + stack; } return new ScriptResult<>(new Exception(stack)); } }
@Test public void testClearVariables() throws ScriptException { logger1.info("Clear Variables Test"); ScriptEngine instance = null; synchronized (this) { System.setProperty("org.jruby.embed.localcontext.scope", "singlethread"); System.setProperty("org.jruby.embed.localvariable.behavior", "global"); ScriptEngineManager manager = new ScriptEngineManager(); instance = manager.getEngineByName("jruby"); } instance.put("gvar", ":Gvar"); String result = (String) instance.eval("$gvar"); assertEquals(":Gvar", result); instance.getBindings(ScriptContext.ENGINE_SCOPE).remove("gvar"); instance .getContext() .setAttribute("org.jruby.embed.clear.variables", true, ScriptContext.ENGINE_SCOPE); instance.eval(""); instance .getContext() .setAttribute("org.jruby.embed.clear.variables", false, ScriptContext.ENGINE_SCOPE); result = (String) instance.eval("$gvar"); assertNull(result); instance = null; }
@Override protected void setUp() throws Exception { clearWorkDir(); FileWriter w = new FileWriter(new File(getWorkDir(), "template.txt")); w.write("<html><h1>${title}</h1></html>"); w.close(); parameters = new HashMap<String, String>(); parameters.put("title", "SOME_TITLE"); LocalFileSystem lfs = new LocalFileSystem(); lfs.setRootDirectory(getWorkDir()); fo = lfs.findResource("template.txt"); ScriptEngineManager mgr = new ScriptEngineManager(); eng = mgr.getEngineByName("freemarker"); assertNotNull("We do have such engine", eng); eng.getContext().setAttribute(FileObject.class.getName(), fo, ScriptContext.ENGINE_SCOPE); eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE).putAll(parameters); whereTo = new File[10000]; for (int i = 0; i < whereTo.length; i++) { whereTo[i] = new File(getWorkDir(), "outFile" + i + ".txt"); } }
private ScriptEngine createEngine( String scriptName, String templateName, boolean runInit, Object it, AbstractBuild<?, ?> build) throws FileNotFoundException, IOException { String extension = scriptName.substring(scriptName.lastIndexOf('.') + 1); ScriptEngine engine = scriptEngineManager.getEngineByExtension(extension); if (engine != null) { ScriptContext context = engine.getContext(); context.setAttribute("it", it, ScriptContext.GLOBAL_SCOPE); context.setAttribute("build", build, ScriptContext.GLOBAL_SCOPE); context.setAttribute("project", build.getParent(), ScriptContext.GLOBAL_SCOPE); context.setAttribute( "rooturl", ExtendedEmailPublisher.DESCRIPTOR.getHudsonUrl(), ScriptContext.GLOBAL_SCOPE); context.setAttribute("host", this, ScriptContext.GLOBAL_SCOPE); context.setAttribute("template", templateName, ScriptContext.GLOBAL_SCOPE); if (runInit) { InputStream initFile = null; try { initFile = getFileInputStream(extension + "/init." + extension); if (initFile != null) { engine.eval(new InputStreamReader(initFile)); } } catch (ScriptException e) { LOGGER.log(Level.SEVERE, "ScriptException on init file: " + e.toString()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Exception on init file: " + e.toString()); } finally { IOUtils.closeQuietly(initFile); } } } return engine; }
/* Utility functions for the binding classes */ protected static ScriptEngine createScriptEngine(String language) throws ScriptException { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(language); ScriptContext scriptContext = engine.getContext(); Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE); scriptContext.setBindings(new JSFBindings(bindings), ScriptContext.ENGINE_SCOPE); return engine; }
public void testSpeedThruIntegration() throws Exception { for (int i = 0; i < whereTo.length; i++) { Writer w = new BufferedWriter(new FileWriter(whereTo[i])); eng.getContext().setWriter(w); InputStreamReader is = new InputStreamReader(fo.getInputStream()); eng.eval(is); is.close(); w.close(); } }
/** Test of getContext method, of class Jsr223JRubyEngine. */ @Test public void testGetContext() { logger1.info("getContext"); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine instance = manager.getEngineByName("jruby"); ScriptContext result = instance.getContext(); assertNotNull(result); instance.getBindings(ScriptContext.ENGINE_SCOPE).clear(); instance = null; }
/** * {@inheritDoc} * * @see schemacrawler.tools.integration.TemplatedSchemaRenderer#render(java.lang.String, * schemacrawler.schema.Schema, java.io.Writer) */ @Override protected void render( final Connection connection, final String scriptFileName, final Database database, final Writer writer) throws ExecutionException { if (sf.util.Utility.isBlank(scriptFileName)) { throw new ExecutionException("No script file provided"); } final Reader reader; final File scriptFile = new File(scriptFileName); if (scriptFile.exists() && scriptFile.canRead()) { try { reader = new FileReader(scriptFile); } catch (final FileNotFoundException e) { throw new ExecutionException("Cannot load script, " + scriptFile.getAbsolutePath()); } } else { final InputStream inputStream = ScriptRenderer.class.getResourceAsStream("/" + scriptFileName); if (inputStream != null) { reader = new InputStreamReader(inputStream); } else { throw new ExecutionException("Cannot load script, " + scriptFileName); } } try { // Create a new instance of the engine final ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager.getEngineByExtension(FileUtility.getFileExtension(scriptFile)); if (scriptEngine == null) { scriptEngine = scriptEngineManager.getEngineByName("JavaScript"); } if (scriptEngine == null) { throw new ExecutionException("Script engine not found"); } // Set up the context scriptEngine.getContext().setWriter(writer); scriptEngine.put("database", database); scriptEngine.put("connection", connection); // Evaluate the script scriptEngine.eval(reader); } catch (final ScriptException e) { throw new ExecutionException("Could not evaluate script", e); } }
public void test() throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine e = manager.getEngineByName("php"); OutputStream out = new ByteArrayOutputStream(); Writer w = new OutputStreamWriter(out); e.getContext().setWriter(w); e.getContext().setErrorWriter(w); try { e.eval("<?php bleh();?>"); } catch (ScriptException ex) { if (out.toString().length() == 0) throw new Exception("test failed"); return; } fail("test failed"); }
@Override public Value eval(EvalContext ctx, Value[] args, Type resultType) { ScriptEngineManager m = new ScriptEngineManager(); ScriptEngine rubyEngine = m.getEngineByName("jruby"); if (rubyEngine == null) throw new RuntimeException("Did not find the ruby engine. Please verify your classpath"); ScriptContext context = rubyEngine.getContext(); context.setErrorWriter(new NullWriter()); context.setAttribute( "self", RubyHelper.useValueToRubyValue(args[0]), ScriptContext.ENGINE_SCOPE); for (int i = 0; i < parameter.size(); i++) { context.setAttribute( parameter.get(i).getName(), RubyHelper.useValueToRubyValue(args[i + 1]), ScriptContext.ENGINE_SCOPE); } try { Object result = rubyEngine.eval(operationBody, context); Value resultValue = RubyHelper.rubyValueToUseValue(result, resultType); // Wrong result type! if (!resultValue.type().isSubtypeOf(this.resultType)) { Log.warn( "Extension method `" + name + "' returned wrong type! Expected `" + this.resultType.toString() + "' got `" + resultValue.type().toString() + "'"); return UndefinedValue.instance; } else { return resultValue; } } catch (ScriptException e) { Log.error(e.getMessage()); } catch (EvalFailedException e) { Log.error(e.getMessage()); } return UndefinedValue.instance; }
private String evaluateExpression( Execution execution, String scriptToExecute, JCRSessionWrapper session) throws RepositoryException, ScriptException { ScriptContext scriptContext = scriptEngine.getContext(); if (bindings == null) { bindings = getBindings(execution, session); } scriptContext.setWriter(new StringWriter()); scriptContext.setErrorWriter(new StringWriter()); scriptEngine.eval(scriptToExecute, bindings); String error = scriptContext.getErrorWriter().toString(); if (error.length() > 0) { logger.error("Scripting error : " + error); } return scriptContext.getWriter().toString().trim(); }
public void testSourceProvider() throws Exception { PythonScriptEngineInitializer initializer = new PythonScriptEngineInitializer(); ScriptEngine engine = initializer.instantiate(Collections.<String>emptySet(), null); StringWriter wrt = new StringWriter(); engine.getContext().setWriter(wrt); initializer.installScriptSourceProvider(engine, new SourceProvider()); engine.eval( "import sys\nsys.path.append('__rhq__:test-unsupported/')\nsys.path.append('__rhq__:test/')\nimport test_module"); Assert.assertEquals( wrt.toString(), EXPECTED_OUTPUT + "\n", "Unexpected output from a custom module."); }
/** * Executes a script file without displaying it in the dialog. * * @param scriptFile The file to execute. */ private void executeScriptFile(final File scriptFile) { final List<Pair<String, Object>> bindings = toPairList(m_bindings); final ScriptEngineManager manager = new ScriptEngineManager(); final ScriptEngine engine = manager.getEngineByExtension(FileUtils.getFileExtension(scriptFile)); final IScriptConsole console = new ConsoleWriter(new StringWriter()); engine.getContext().setWriter(console.getWriter()); bindings.add(new Pair<String, Object>("SCRIPT_CONSOLE", console)); final ScriptThread thread = new ScriptThread(engine, scriptFile, bindings); CProgressDialog.showEndless( getOwner(), String.format("Executing '%s'", scriptFile.getAbsolutePath()), thread); if (thread.getException() != null) { CUtilityFunctions.logException(thread.getException()); final String message = "E00108: " + "Script file could not be executed"; final String description = CUtilityFunctions.createDescription( String.format( "The script file '%s' could not be executed.", scriptFile.getAbsolutePath()), new String[] { "The script file is in use by another program and can not be read.", "You do not have sufficient rights to read the file", "The script contains a bug that caused an exception." }, new String[] {"BinNavi can not read the script file."}); NaviErrorDialog.show(CScriptingDialog.this, message, description, thread.getException()); } final IScriptPanel panel = (IScriptPanel) scriptTab.getSelectedComponent(); panel.setOutput(console.getOutput()); toFront(); }
/** Test of setContext method, of class Jsr223JRubyEngine. */ @Test public void testSetContext() { logger1.info("setContext"); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine instance = manager.getEngineByName("jruby"); ScriptContext ctx = new SimpleScriptContext(); StringWriter sw = new StringWriter(); sw.write("Have a great summer!"); ctx.setWriter(sw); instance.setContext(ctx); ScriptContext result = instance.getContext(); Writer w = result.getWriter(); Object expResult = "Have a great summer!"; assertTrue(sw == result.getWriter()); assertEquals(expResult, (result.getWriter()).toString()); instance.getBindings(ScriptContext.ENGINE_SCOPE).clear(); instance = null; }
@Test public void testNashornWithCompile() throws Exception { ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine engine = engineManager.getEngineByName(AutomationScriptingConstants.NASHORN_ENGINE); assertNotNull(engine); Compilable compiler = (Compilable) engine; assertNotNull(compiler); InputStream stream = this.getClass().getResourceAsStream("/testScript" + ".js"); assertNotNull(stream); String js = IOUtils.toString(stream); CompiledScript compiled = compiler.compile(new StringReader(js)); engine.put("mapper", new Mapper()); compiled.eval(engine.getContext()); assertEquals( "1" + System.lineSeparator() + "str" + System.lineSeparator() + "[1, 2, {a=1, b=2}]" + System.lineSeparator() + "{a=1, b=2}" + System.lineSeparator() + "This is a string" + System.lineSeparator() + "This is a string" + System.lineSeparator() + "2" + System.lineSeparator() + "[A, B, C]" + System.lineSeparator() + "{a=salut, b=from java}" + System.lineSeparator() + "done" + System.lineSeparator(), outContent.toString()); }
/** Test of eval method, of class Jsr223JRubyEngine. */ @Test public void testEval_String() throws Exception { logger1.info("eval String"); ScriptEngine instance; synchronized (this) { System.setProperty("org.jruby.embed.localcontext.scope", "singlethread"); System.setProperty("org.jruby.embed.localvariable.behavior", "persistent"); ScriptEngineManager manager = new ScriptEngineManager(); instance = manager.getEngineByName("jruby"); } instance.getContext().setWriter(writer); instance.eval("p=9.0"); instance.eval("q = Math.sqrt p"); instance.eval("puts \"square root of #{p} is #{q}\""); Double expResult = 3.0; Double result = (Double) instance.get("q"); assertEquals(expResult, result, 0.01); instance.getBindings(ScriptContext.ENGINE_SCOPE).clear(); instance = null; }
/* * Test of ScriptEngine.ARGV, JRUBY-4090 */ @Test public void testARGV() throws ScriptException { logger1.info("ScriptEngine.ARGV"); ScriptEngine instance; synchronized (this) { System.setProperty("org.jruby.embed.localcontext.scope", "singlethread"); System.setProperty("org.jruby.embed.localvariable.behavior", "transient"); ScriptEngineManager manager = new ScriptEngineManager(); instance = manager.getEngineByName("jruby"); } instance.getContext().setErrorWriter(writer); String script = "" + // "ARGV << 'foo' \n" + "if ARGV.length == 0\n" + " raise 'Error No argv passed'\n" + "end"; instance.put(ScriptEngine.ARGV, new String[] {"one param"}); instance.eval(script); instance = null; }
public static void main(String[] args) throws ScriptException, FileNotFoundException { // 脚本引擎管理器 // ScriptEngineManager manager = new ScriptEngineManager(); /*List<ScriptEngineFactory> list = manager.getEngineFactories(); for(ScriptEngineFactory engine : list) { System.out.println(engine.getEngineName()); }*/ // 脚本引擎管理器 ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); // 向引擎中添加变量绑定 engine.eval("n=1728"); Object result = engine.eval("n+1"); // 1729.0 System.out.println(result); // 获取由脚本语句绑定的变量 engine.put("k", 100); result = engine.eval("k+1"); // 101 System.out.println(result); // 除了向引擎或全局作用域添加绑定外,还可以将绑定收集到一个类型为 Bindings 的对象中, // 然后将其传递给 eval 方法: Bindings scope = engine.createBindings(); scope.put("a", "hello, "); result = engine.eval("a+ 'world!'", scope); // hello, world! System.out.println(result); // 重定向输入和输出 // 任何用 js 的 print 和 println函数产生的输出都会发送到 writer StringWriter writer = new StringWriter(); engine.getContext().setWriter(new PrintWriter(new File("com/corejava/chapter10/output.txt"))); engine.eval("print('hello world, this msg is from java app')"); }
public boolean generateTarget(ProgressHandle ph, String target) { if (mapping.getServiceMapping(target) != null) { String msg = NbBundle.getMessage(ClientJavonTemplate.class, "MSG_Client"); // NOI18N ph.progress(msg); OutputLogger.getInstance().log(msg); mapping.setProperty("target", "client"); JavonMapping.Service service = mapping.getServiceMapping(target); FileObject outputDir = FileUtil.toFileObject( FileUtil.normalizeFile(new File(mapping.getClientMapping().getOutputDirectory()))); outputDir = outputDir.getFileObject(mapping.getClientMapping().getPackageName().replace('.', '/')); FileObject outputFile = outputDir.getFileObject(mapping.getClientMapping().getClassName(), "java"); if (outputFile == null) { OutputLogger.getInstance() .log( MessageFormat.format( NbBundle.getMessage(ClientJavonTemplate.class, "MSG_ClientJavonCreation"), mapping.getClientMapping().getClassName())); // NOI18N try { outputFile = outputDir.createData(mapping.getClientMapping().getClassName(), "java"); } catch (IOException e) { OutputLogger.getInstance() .log( LogLevel.ERROR, MessageFormat.format( NbBundle.getMessage(ClientJavonTemplate.class, "MSG_FailClientJavonCreation"), mapping.getClientMapping().getClassName())); // NOI18N } } OutputFileFormatter off = null; try { off = new OutputFileFormatter(outputFile); } catch (DataObjectNotFoundException e) { generationFailed(e, outputFile); return false; } catch (IOException e) { generationFailed(e, outputFile); return false; } ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine eng = mgr.getEngineByName("freemarker"); Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE); FileObject template = FileUtil.getConfigFile("Templates/Client/Client.java"); OutputLogger.getInstance() .log(NbBundle.getMessage(ClientJavonTemplate.class, "MSG_ConfigureBindings")); // NOI18N Set<ClassData> returnTypes = service.getReturnTypes(); Set<ClassData> parameterTypes = service.getParameterTypes(); bind.put("mapping", mapping); bind.put("registry", mapping.getRegistry()); bind.put("returnTypes", returnTypes); bind.put("parameterTypes", parameterTypes); bind.put("service", service); bind.put("utils", new Utils(mapping.getRegistry())); // Compute imports for JavaBeans Set<String> imports = new HashSet<String>(); for (ClassData cd : parameterTypes) { while (cd.isArray()) { cd = cd.getComponentType(); } if (cd.isPrimitive()) continue; if (cd.getPackage().equals("java.lang")) continue; if (cd.getFullyQualifiedName().equals("java.util.List")) continue; imports.add(cd.getFullyQualifiedName()); } for (ClassData cd : returnTypes) { while (cd.isArray()) { cd = cd.getComponentType(); } if (cd.isPrimitive()) continue; if (cd.getPackage().equals("java.lang")) continue; if (cd.getFullyQualifiedName().equals("java.util.List")) continue; imports.add(cd.getFullyQualifiedName()); } bind.put("imports", imports); OutputLogger.getInstance() .log( MessageFormat.format( NbBundle.getMessage(ClientBeanGeneratorTemplate.class, "MSG_GenerateJavonClient"), FileUtil.toFile(outputFile))); // NOI18N Writer w = null; Reader is = null; try { try { w = new StringWriter(); is = new InputStreamReader(template.getInputStream()); eng.getContext().setWriter(w); eng.getContext() .setAttribute(FileObject.class.getName(), template, ScriptContext.ENGINE_SCOPE); eng.getContext() .setAttribute( ScriptEngine.FILENAME, template.getNameExt(), ScriptContext.ENGINE_SCOPE); eng.eval(is); } catch (FileNotFoundException e) { OutputLogger.getInstance().log(e); ErrorManager.getDefault().notify(e); return false; } catch (ScriptException e) { OutputLogger.getInstance().log(e); ErrorManager.getDefault().notify(e); return false; } finally { if (w != null) { off.write(w.toString()); // System.err.println( "" + w.toString()); w.close(); } if (is != null) is.close(); off.close(); } } catch (IOException e) { generationFailed(e, FileUtil.toFile(outputFile)); return false; } OutputLogger.getInstance() .log( MessageFormat.format( NbBundle.getMessage(ClientJavonTemplate.class, "MSG_ClientGenerated"), FileUtil.toFile(outputFile))); } return true; }
public ScriptContext getScriptContext(ScriptEngine engine) { return engine.getContext(); }
public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); if (Config.SCRIPT_DEBUG) { _log.info("Loading Script: " + file.getAbsolutePath()); } if (Config.SCRIPT_ERROR_LOG) { String name = file.getAbsolutePath() + ".error.log"; File errorLog = new File(name); if (errorLog.isFile()) { errorLog.delete(); } } if (engine instanceof Compilable && Config.SCRIPT_ALLOW_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( JythonScriptEngine.JYTHON_ENGINE_INSTANCE, engine, ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); ScriptContext ctx = engine.getContext(); try { engine.setContext(context); if (Config.SCRIPT_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); } } 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); 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); } } }