List of usage examples for javax.script ScriptEngine eval
public Object eval(Reader reader, Bindings n) throws ScriptException;
eval(String, Bindings)
except that the source of the script is provided as a Reader
. From source file:org.jahia.ajax.gwt.helper.UIConfigHelper.java
/** * Get resources/*from w ww .j a v a 2s. 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; }
From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java
public static void LoadScriptFromTab(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList, Object FunctionContext) { try {//from w w w. j a v a 2s . c o m for (int i = 0; i < ArgList.length; i++) { // don't worry about "undefined" arguments String strToLoad = (String) ArgList[i]; String strScript = actualObject.get(strToLoad).toString(); actualContext.eval(strScript, actualObject); } } catch (Exception e) { // System.out.println(e.toString()); } }
From source file:org.jahia.services.render.scripting.JSR223Script.java
/** * Execute the script and return the result as a string * * @param resource resource to display/*from ww w .j a v a 2 s. c om*/ * @param context * @return the rendered resource * @throws org.jahia.services.render.RenderException */ public String execute(Resource resource, RenderContext context) throws RenderException { ScriptEngine scriptEngine = null; ClassLoader tccl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(view.getModule().getChainedClassLoader()); try { scriptEngine = ScriptEngineUtils.getInstance().scriptEngine(view.getFileExtension()); if (scriptEngine != null) { ScriptContext scriptContext = new SimpleScriptContext(); final Bindings bindings = new SimpleBindings(); Enumeration<?> attrNamesEnum = context.getRequest().getAttributeNames(); while (attrNamesEnum.hasMoreElements()) { String currentAttributeName = (String) attrNamesEnum.nextElement(); if (!"".equals(currentAttributeName)) { bindings.put(currentAttributeName, context.getRequest().getAttribute(currentAttributeName)); } } bindings.put("params", context.getRequest().getParameterMap()); Reader scriptContent = null; try { InputStream scriptInputStream = getViewInputStream(); if (scriptInputStream != null) { scriptContent = new InputStreamReader(scriptInputStream); scriptContext.setWriter(new StringWriter()); scriptContext.setErrorWriter(new StringWriter()); // The following binding is necessary for Javascript, which doesn't offer a console by default. bindings.put("out", new PrintWriter(scriptContext.getWriter())); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE), ScriptContext.GLOBAL_SCOPE); scriptEngine.eval(scriptContent, scriptContext); StringWriter writer = (StringWriter) scriptContext.getWriter(); return writer.toString().trim(); } else { throw new RenderException( "Error while retrieving input stream for the resource " + view.getPath()); } } catch (ScriptException e) { throw new RenderException("Error while executing script " + view.getPath(), e); } catch (IOException e) { throw new RenderException( "Error while retrieving input stream for the resource " + view.getPath(), e); } finally { if (scriptContent != null) { IOUtils.closeQuietly(scriptContent); } } } } catch (ScriptException e) { logger.error(e.getMessage(), e); } finally { Thread.currentThread().setContextClassLoader(tccl); } return null; }
From source file:org.apache.jmeter.util.JSR223TestElement.java
/** * This method will run inline script or file script with special behaviour for file script: * - If ScriptEngine implements Compilable script will be compiled and cached * - If not if will be run// ww w. j av a2s. c o m * @param scriptEngine ScriptEngine * @param bindings {@link Bindings} might be null * @return Object returned by script * @throws IOException when reading the script fails * @throws ScriptException when compiling or evaluation of the script fails */ protected Object processFileOrScript(ScriptEngine scriptEngine, Bindings bindings) throws IOException, ScriptException { if (bindings == null) { bindings = scriptEngine.createBindings(); } populateBindings(bindings); File scriptFile = new File(getFilename()); // Hack: bsh-2.0b5.jar BshScriptEngine implements Compilable but throws "java.lang.Error: unimplemented" boolean supportsCompilable = scriptEngine instanceof Compilable && !(scriptEngine.getClass().getName().equals("bsh.engine.BshScriptEngine")); // $NON-NLS-1$ if (!StringUtils.isEmpty(getFilename())) { if (scriptFile.exists() && scriptFile.canRead()) { BufferedReader fileReader = null; try { if (supportsCompilable) { String cacheKey = getScriptLanguage() + "#" + // $NON-NLS-1$ scriptFile.getAbsolutePath() + "#" + // $NON-NLS-1$ scriptFile.lastModified(); CompiledScript compiledScript = compiledScriptsCache.get(cacheKey); if (compiledScript == null) { synchronized (compiledScriptsCache) { compiledScript = compiledScriptsCache.get(cacheKey); if (compiledScript == null) { // TODO Charset ? fileReader = new BufferedReader(new FileReader(scriptFile), (int) scriptFile.length()); compiledScript = ((Compilable) scriptEngine).compile(fileReader); compiledScriptsCache.put(cacheKey, compiledScript); } } } return compiledScript.eval(bindings); } else { // TODO Charset ? fileReader = new BufferedReader(new FileReader(scriptFile), (int) scriptFile.length()); return scriptEngine.eval(fileReader, bindings); } } finally { IOUtils.closeQuietly(fileReader); } } else { throw new ScriptException("Script file '" + scriptFile.getAbsolutePath() + "' does not exist or is unreadable for element:" + getName()); } } else if (!StringUtils.isEmpty(getScript())) { if (supportsCompilable && !StringUtils.isEmpty(cacheKey)) { computeScriptMD5(); CompiledScript compiledScript = compiledScriptsCache.get(this.scriptMd5); if (compiledScript == null) { synchronized (compiledScriptsCache) { compiledScript = compiledScriptsCache.get(this.scriptMd5); if (compiledScript == null) { compiledScript = ((Compilable) scriptEngine).compile(getScript()); compiledScriptsCache.put(this.scriptMd5, compiledScript); } } } return compiledScript.eval(bindings); } else { return scriptEngine.eval(getScript(), bindings); } } else { throw new ScriptException("Both script file and script text are empty for element:" + getName()); } }
From source file:org.jahia.services.render.filter.StaticAssetsFilter.java
private void addResources(RenderContext renderContext, org.jahia.services.render.Resource resource, Source source, OutputDocument outputDocument, String targetTag, Map<String, Map<String, Map<String, String>>> assetsByType) throws IOException, ScriptException { renderContext.getRequest().setAttribute(STATIC_ASSETS, assetsByType); Element element = source.getFirstElement(targetTag); String templateContent = getResolvedTemplate(); if (element == null) { logger.warn("Trying to add resources to output but didn't find {} tag", targetTag); return;/*from ww w. java2s. c om*/ } if (templateContent != null) { final EndTag headEndTag = element.getEndTag(); ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(templateExtension); ScriptContext scriptContext = new AssetsScriptContext(); final Bindings bindings = scriptEngine.createBindings(); bindings.put("contextJsParameters", getContextJsParameters(assetsByType, renderContext)); if (aggregateAndCompress && resource.getWorkspace().equals("live")) { Map<String, Map<String, String>> cssAssets = assetsByType.get("css"); if (cssAssets != null) { assetsByType.put("css", aggregate(cssAssets, "css")); } Map<String, Map<String, String>> javascriptAssets = assetsByType.get("javascript"); if (javascriptAssets != null) { Map<String, Map<String, String>> scripts = new LinkedHashMap<String, Map<String, String>>( javascriptAssets); Map<String, Map<String, String>> newScripts = aggregate(javascriptAssets, "js"); assetsByType.put("javascript", newScripts); scripts.keySet().removeAll(newScripts.keySet()); assetsByType.put("aggregatedjavascript", scripts); } } else if (addLastModifiedDate) { addLastModified(assetsByType); } bindings.put(TARGET_TAG, targetTag); bindings.put("renderContext", renderContext); bindings.put("resource", resource); bindings.put("contextPath", renderContext.getRequest().getContextPath()); scriptContext.setBindings(bindings, ScriptContext.GLOBAL_SCOPE); // The following binding is necessary for Javascript, which doesn't offer a console by default. bindings.put("out", new PrintWriter(scriptContext.getWriter())); scriptEngine.eval(templateContent, scriptContext); StringWriter writer = (StringWriter) scriptContext.getWriter(); final String staticsAsset = writer.toString(); if (StringUtils.isNotBlank(staticsAsset)) { outputDocument.replace(headEndTag.getBegin(), headEndTag.getBegin() + 1, "\n" + AggregateCacheFilter.removeCacheTags(staticsAsset) + "\n<"); } } // workaround for ie9 in gxt/gwt // renderContext.isEditMode() means that gwt is loaded, for contribute, edit or studio if (isEnforceIECompatibilityMode(renderContext)) { int idx = element.getBegin() + element.toString().indexOf(">"); String str = ">\n<meta http-equiv=\"X-UA-Compatible\" content=\"" + SettingsBean.getInstance().getInternetExplorerCompatibility() + "\"/>"; outputDocument.replace(idx, idx + 1, str); } if ((renderContext.isPreviewMode()) && !Boolean.valueOf((String) renderContext.getRequest() .getAttribute("org.jahia.StaticAssetFilter.doNotModifyDocumentTitle"))) { for (Element title : element.getAllElements(HTMLElementName.TITLE)) { int idx = title.getBegin() + title.toString().indexOf(">"); String str = Messages.getInternal("label.preview", renderContext.getUILocale()); str = ">" + str + " - "; outputDocument.replace(idx, idx + 1, str); } } }
From source file:org.apache.accumulo.core.util.shell.commands.ScriptCommand.java
public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception { boolean invoke = false; ScriptEngineManager mgr = new ScriptEngineManager(); if (cl.hasOption(list.getOpt())) { listJSREngineInfo(mgr, shellState); } else if (cl.hasOption(file.getOpt()) || cl.hasOption(script.getOpt())) { String engineName = DEFAULT_ENGINE; if (cl.hasOption(engine.getOpt())) { engineName = cl.getOptionValue(engine.getOpt()); }//from ww w.j a v a 2s. co m ScriptEngine engine = mgr.getEngineByName(engineName); if (null == engine) { shellState.printException(new Exception(engineName + " not found")); return 1; } if (cl.hasOption(object.getOpt()) || cl.hasOption(function.getOpt())) { if (!(engine instanceof Invocable)) { shellState.printException( new Exception(engineName + " does not support invoking functions or methods")); return 1; } invoke = true; } ScriptContext ctx = new SimpleScriptContext(); // Put the following objects into the context so that they // are available to the scripts // TODO: What else should go in here? Bindings b = engine.getBindings(ScriptContext.ENGINE_SCOPE); b.put("connection", shellState.getConnector()); List<Object> argValues = new ArrayList<Object>(); if (cl.hasOption(args.getOpt())) { String[] argList = cl.getOptionValue(args.getOpt()).split(","); for (String arg : argList) { String[] parts = arg.split("="); if (parts.length == 0) { continue; } else if (parts.length == 1) { b.put(parts[0], null); argValues.add(null); } else if (parts.length == 2) { b.put(parts[0], parts[1]); argValues.add(parts[1]); } } } ctx.setBindings(b, ScriptContext.ENGINE_SCOPE); Object[] argArray = argValues.toArray(new Object[argValues.size()]); Writer writer = null; if (cl.hasOption(out.getOpt())) { File f = new File(cl.getOptionValue(out.getOpt())); writer = new FileWriter(f); ctx.setWriter(writer); } if (cl.hasOption(file.getOpt())) { File f = new File(cl.getOptionValue(file.getOpt())); if (!f.exists()) { if (null != writer) { writer.close(); } shellState.printException(new Exception(f.getAbsolutePath() + " not found")); return 1; } Reader reader = new FileReader(f); try { engine.eval(reader, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { reader.close(); if (null != writer) { writer.close(); } } } else if (cl.hasOption(script.getOpt())) { String inlineScript = cl.getOptionValue(script.getOpt()); try { if (engine instanceof Compilable) { Compilable compiledEng = (Compilable) engine; CompiledScript script = compiledEng.compile(inlineScript); script.eval(ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } else { engine.eval(inlineScript, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { if (null != writer) { writer.close(); } } } if (null != writer) { writer.close(); } } else { printHelp(shellState); } return 0; }
From source file:org.apache.accumulo.shell.commands.ScriptCommand.java
@Override public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception { boolean invoke = false; ScriptEngineManager mgr = new ScriptEngineManager(); if (cl.hasOption(list.getOpt())) { listJSREngineInfo(mgr, shellState); } else if (cl.hasOption(file.getOpt()) || cl.hasOption(script.getOpt())) { String engineName = DEFAULT_ENGINE; if (cl.hasOption(engine.getOpt())) { engineName = cl.getOptionValue(engine.getOpt()); }/* w w w.j a v a 2s .co m*/ ScriptEngine engine = mgr.getEngineByName(engineName); if (null == engine) { shellState.printException(new Exception(engineName + " not found")); return 1; } if (cl.hasOption(object.getOpt()) || cl.hasOption(function.getOpt())) { if (!(engine instanceof Invocable)) { shellState.printException( new Exception(engineName + " does not support invoking functions or methods")); return 1; } invoke = true; } ScriptContext ctx = new SimpleScriptContext(); // Put the following objects into the context so that they // are available to the scripts // TODO: What else should go in here? Bindings b = engine.getBindings(ScriptContext.ENGINE_SCOPE); b.put("connection", shellState.getConnector()); List<Object> argValues = new ArrayList<Object>(); if (cl.hasOption(args.getOpt())) { String[] argList = cl.getOptionValue(args.getOpt()).split(","); for (String arg : argList) { String[] parts = arg.split("="); if (parts.length == 0) { continue; } else if (parts.length == 1) { b.put(parts[0], null); argValues.add(null); } else if (parts.length == 2) { b.put(parts[0], parts[1]); argValues.add(parts[1]); } } } ctx.setBindings(b, ScriptContext.ENGINE_SCOPE); Object[] argArray = argValues.toArray(new Object[argValues.size()]); Writer writer = null; if (cl.hasOption(out.getOpt())) { File f = new File(cl.getOptionValue(out.getOpt())); writer = new FileWriter(f); ctx.setWriter(writer); } if (cl.hasOption(file.getOpt())) { File f = new File(cl.getOptionValue(file.getOpt())); if (!f.exists()) { if (null != writer) { writer.close(); } shellState.printException(new Exception(f.getAbsolutePath() + " not found")); return 1; } Reader reader = new FileReader(f); try { engine.eval(reader, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { reader.close(); if (null != writer) { writer.close(); } } } else if (cl.hasOption(script.getOpt())) { String inlineScript = cl.getOptionValue(script.getOpt()); try { if (engine instanceof Compilable) { Compilable compiledEng = (Compilable) engine; CompiledScript script = compiledEng.compile(inlineScript); script.eval(ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } else { engine.eval(inlineScript, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { if (null != writer) { writer.close(); } } } if (null != writer) { writer.close(); } } else { printHelp(shellState); } return 0; }
From source file:org.jahia.services.mail.MailServiceImpl.java
@Override public void sendMessageWithTemplate(String template, Map<String, Object> boundObjects, String toMail, String fromMail, String ccList, String bcclist, Locale locale, String templatePackageName) throws RepositoryException, ScriptException { // Resolve template : ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(StringUtils.substringAfterLast(template, ".")); ScriptContext scriptContext = new SimpleScriptContext(); //try if it is multilingual String suffix = StringUtils.substringAfterLast(template, "."); String languageMailConfTemplate = template.substring(0, template.length() - (suffix.length() + 1)) + "_" + locale.toString() + "." + suffix; JahiaTemplatesPackage templatePackage = templateManagerService.getTemplatePackage(templatePackageName); Resource templateRealPath = templatePackage.getResource(languageMailConfTemplate); if (templateRealPath == null) { templateRealPath = templatePackage.getResource(template); }/*from w ww . ja v a2 s .c o m*/ InputStream scriptInputStream = null; try { scriptInputStream = templateRealPath.getInputStream(); } catch (IOException e) { logger.error(e.getMessage(), e); } if (scriptInputStream != null) { ResourceBundle resourceBundle; if (templatePackageName == null) { String resourceBundleName = StringUtils.substringBeforeLast(Patterns.SLASH .matcher(StringUtils.substringAfter(Patterns.WEB_INF.matcher(template).replaceAll(""), "/")) .replaceAll("."), "."); resourceBundle = ResourceBundles.get(resourceBundleName, locale); } else { resourceBundle = ResourceBundles.get(ServicesRegistry.getInstance().getJahiaTemplateManagerService() .getTemplatePackage(templatePackageName), locale); } final Bindings bindings = new SimpleBindings(); bindings.put("bundle", resourceBundle); bindings.putAll(boundObjects); Reader scriptContent = null; // Subject String subject; try { String subjectTemplatePath = StringUtils.substringBeforeLast(template, ".") + ".subject." + StringUtils.substringAfterLast(template, "."); InputStream stream = templatePackage.getResource(subjectTemplatePath).getInputStream(); scriptContent = templateCharset != null ? new InputStreamReader(stream, templateCharset) : new InputStreamReader(stream); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE), ScriptContext.GLOBAL_SCOPE); scriptContext.setWriter(new StringWriter()); scriptEngine.eval(scriptContent, scriptContext); subject = scriptContext.getWriter().toString().trim(); } catch (Exception e) { logger.warn("Not able to render mail subject using " + StringUtils.substringBeforeLast(template, ".") + ".subject." + StringUtils.substringAfterLast(template, ".") + " template file - set org.jahia.services.mail.MailService in debug for more information"); if (logger.isDebugEnabled()) { logger.debug("generating the mail subject throw an exception : ", e); } subject = resourceBundle.getString( StringUtils.substringBeforeLast(StringUtils.substringAfterLast(template, "/"), ".") + ".subject"); } finally { IOUtils.closeQuietly(scriptContent); } try { try { scriptContent = templateCharset != null ? new InputStreamReader(scriptInputStream, templateCharset) : new InputStreamReader(scriptInputStream); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } scriptContext.setWriter(new StringWriter()); scriptContext.setErrorWriter(new StringWriter()); // The following binding is necessary for JavaScript, which // doesn't offer a console by default. bindings.put("out", new PrintWriter(scriptContext.getWriter())); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); scriptEngine.eval(scriptContent, scriptContext); StringWriter writer = (StringWriter) scriptContext.getWriter(); String body = writer.toString(); sendMessage(fromMail, toMail, ccList, bcclist, subject, null, body); } finally { IOUtils.closeQuietly(scriptContent); } } else { logger.warn("Cannot send mail, template [" + template + "] from module [" + templatePackageName + "] not found"); } }
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 ww. j a va 2s . c o m*/ 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()); }//from w w w.j a v a 2 s . c o m 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); } } }