Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/javax/script/ScriptEngineManager.java
38829 views
/*1* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.script;26import java.util.*;27import java.security.*;28import java.util.ServiceLoader;29import java.util.ServiceConfigurationError;3031/**32* The <code>ScriptEngineManager</code> implements a discovery and instantiation33* mechanism for <code>ScriptEngine</code> classes and also maintains a34* collection of key/value pairs storing state shared by all engines created35* by the Manager. This class uses the <a href="../../../technotes/guides/jar/jar.html#Service%20Provider">service provider</a> mechanism to enumerate all the36* implementations of <code>ScriptEngineFactory</code>. <br><br>37* The <code>ScriptEngineManager</code> provides a method to return a list of all these factories38* as well as utility methods which look up factories on the basis of language name, file extension39* and mime type.40* <p>41* The <code>Bindings</code> of key/value pairs, referred to as the "Global Scope" maintained42* by the manager is available to all instances of <code>ScriptEngine</code> created43* by the <code>ScriptEngineManager</code>. The values in the <code>Bindings</code> are44* generally exposed in all scripts.45*46* @author Mike Grogan47* @author A. Sundararajan48* @since 1.649*/50public class ScriptEngineManager {51private static final boolean DEBUG = false;52/**53* The effect of calling this constructor is the same as calling54* <code>ScriptEngineManager(Thread.currentThread().getContextClassLoader())</code>.55*56* @see java.lang.Thread#getContextClassLoader57*/58public ScriptEngineManager() {59ClassLoader ctxtLoader = Thread.currentThread().getContextClassLoader();60init(ctxtLoader);61}6263/**64* This constructor loads the implementations of65* <code>ScriptEngineFactory</code> visible to the given66* <code>ClassLoader</code> using the <a href="../../../technotes/guides/jar/jar.html#Service%20Provider">service provider</a> mechanism.<br><br>67* If loader is <code>null</code>, the script engine factories that are68* bundled with the platform and that are in the usual extension69* directories (installed extensions) are loaded. <br><br>70*71* @param loader ClassLoader used to discover script engine factories.72*/73public ScriptEngineManager(ClassLoader loader) {74init(loader);75}7677private void init(final ClassLoader loader) {78globalScope = new SimpleBindings();79engineSpis = new HashSet<ScriptEngineFactory>();80nameAssociations = new HashMap<String, ScriptEngineFactory>();81extensionAssociations = new HashMap<String, ScriptEngineFactory>();82mimeTypeAssociations = new HashMap<String, ScriptEngineFactory>();83initEngines(loader);84}8586private ServiceLoader<ScriptEngineFactory> getServiceLoader(final ClassLoader loader) {87if (loader != null) {88return ServiceLoader.load(ScriptEngineFactory.class, loader);89} else {90return ServiceLoader.loadInstalled(ScriptEngineFactory.class);91}92}9394private void initEngines(final ClassLoader loader) {95Iterator<ScriptEngineFactory> itr = null;96try {97ServiceLoader<ScriptEngineFactory> sl = AccessController.doPrivileged(98new PrivilegedAction<ServiceLoader<ScriptEngineFactory>>() {99@Override100public ServiceLoader<ScriptEngineFactory> run() {101return getServiceLoader(loader);102}103});104105itr = sl.iterator();106} catch (ServiceConfigurationError err) {107System.err.println("Can't find ScriptEngineFactory providers: " +108err.getMessage());109if (DEBUG) {110err.printStackTrace();111}112// do not throw any exception here. user may want to113// manage his/her own factories using this manager114// by explicit registratation (by registerXXX) methods.115return;116}117118try {119while (itr.hasNext()) {120try {121ScriptEngineFactory fact = itr.next();122engineSpis.add(fact);123} catch (ServiceConfigurationError err) {124System.err.println("ScriptEngineManager providers.next(): "125+ err.getMessage());126if (DEBUG) {127err.printStackTrace();128}129// one factory failed, but check other factories...130continue;131}132}133} catch (ServiceConfigurationError err) {134System.err.println("ScriptEngineManager providers.hasNext(): "135+ err.getMessage());136if (DEBUG) {137err.printStackTrace();138}139// do not throw any exception here. user may want to140// manage his/her own factories using this manager141// by explicit registratation (by registerXXX) methods.142return;143}144}145146/**147* <code>setBindings</code> stores the specified <code>Bindings</code>148* in the <code>globalScope</code> field. ScriptEngineManager sets this149* <code>Bindings</code> as global bindings for <code>ScriptEngine</code>150* objects created by it.151*152* @param bindings The specified <code>Bindings</code>153* @throws IllegalArgumentException if bindings is null.154*/155public void setBindings(Bindings bindings) {156if (bindings == null) {157throw new IllegalArgumentException("Global scope cannot be null.");158}159160globalScope = bindings;161}162163/**164* <code>getBindings</code> returns the value of the <code>globalScope</code> field.165* ScriptEngineManager sets this <code>Bindings</code> as global bindings for166* <code>ScriptEngine</code> objects created by it.167*168* @return The globalScope field.169*/170public Bindings getBindings() {171return globalScope;172}173174/**175* Sets the specified key/value pair in the Global Scope.176* @param key Key to set177* @param value Value to set.178* @throws NullPointerException if key is null.179* @throws IllegalArgumentException if key is empty string.180*/181public void put(String key, Object value) {182globalScope.put(key, value);183}184185/**186* Gets the value for the specified key in the Global Scope187* @param key The key whose value is to be returned.188* @return The value for the specified key.189*/190public Object get(String key) {191return globalScope.get(key);192}193194/**195* Looks up and creates a <code>ScriptEngine</code> for a given name.196* The algorithm first searches for a <code>ScriptEngineFactory</code> that has been197* registered as a handler for the specified name using the <code>registerEngineName</code>198* method.199* <br><br> If one is not found, it searches the set of <code>ScriptEngineFactory</code> instances200* stored by the constructor for one with the specified name. If a <code>ScriptEngineFactory</code>201* is found by either method, it is used to create instance of <code>ScriptEngine</code>.202* @param shortName The short name of the <code>ScriptEngine</code> implementation.203* returned by the <code>getNames</code> method of its <code>ScriptEngineFactory</code>.204* @return A <code>ScriptEngine</code> created by the factory located in the search. Returns null205* if no such factory was found. The <code>ScriptEngineManager</code> sets its own <code>globalScope</code>206* <code>Bindings</code> as the <code>GLOBAL_SCOPE</code> <code>Bindings</code> of the newly207* created <code>ScriptEngine</code>.208* @throws NullPointerException if shortName is null.209*/210public ScriptEngine getEngineByName(String shortName) {211if (shortName == null) throw new NullPointerException();212//look for registered name first213Object obj;214if (null != (obj = nameAssociations.get(shortName))) {215ScriptEngineFactory spi = (ScriptEngineFactory)obj;216try {217ScriptEngine engine = spi.getScriptEngine();218engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);219return engine;220} catch (Exception exp) {221if (DEBUG) exp.printStackTrace();222}223}224225for (ScriptEngineFactory spi : engineSpis) {226List<String> names = null;227try {228names = spi.getNames();229} catch (Exception exp) {230if (DEBUG) exp.printStackTrace();231}232233if (names != null) {234for (String name : names) {235if (shortName.equals(name)) {236try {237ScriptEngine engine = spi.getScriptEngine();238engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);239return engine;240} catch (Exception exp) {241if (DEBUG) exp.printStackTrace();242}243}244}245}246}247248return null;249}250251/**252* Look up and create a <code>ScriptEngine</code> for a given extension. The algorithm253* used by <code>getEngineByName</code> is used except that the search starts254* by looking for a <code>ScriptEngineFactory</code> registered to handle the255* given extension using <code>registerEngineExtension</code>.256* @param extension The given extension257* @return The engine to handle scripts with this extension. Returns <code>null</code>258* if not found.259* @throws NullPointerException if extension is null.260*/261public ScriptEngine getEngineByExtension(String extension) {262if (extension == null) throw new NullPointerException();263//look for registered extension first264Object obj;265if (null != (obj = extensionAssociations.get(extension))) {266ScriptEngineFactory spi = (ScriptEngineFactory)obj;267try {268ScriptEngine engine = spi.getScriptEngine();269engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);270return engine;271} catch (Exception exp) {272if (DEBUG) exp.printStackTrace();273}274}275276for (ScriptEngineFactory spi : engineSpis) {277List<String> exts = null;278try {279exts = spi.getExtensions();280} catch (Exception exp) {281if (DEBUG) exp.printStackTrace();282}283if (exts == null) continue;284for (String ext : exts) {285if (extension.equals(ext)) {286try {287ScriptEngine engine = spi.getScriptEngine();288engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);289return engine;290} catch (Exception exp) {291if (DEBUG) exp.printStackTrace();292}293}294}295}296return null;297}298299/**300* Look up and create a <code>ScriptEngine</code> for a given mime type. The algorithm301* used by <code>getEngineByName</code> is used except that the search starts302* by looking for a <code>ScriptEngineFactory</code> registered to handle the303* given mime type using <code>registerEngineMimeType</code>.304* @param mimeType The given mime type305* @return The engine to handle scripts with this mime type. Returns <code>null</code>306* if not found.307* @throws NullPointerException if mimeType is null.308*/309public ScriptEngine getEngineByMimeType(String mimeType) {310if (mimeType == null) throw new NullPointerException();311//look for registered types first312Object obj;313if (null != (obj = mimeTypeAssociations.get(mimeType))) {314ScriptEngineFactory spi = (ScriptEngineFactory)obj;315try {316ScriptEngine engine = spi.getScriptEngine();317engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);318return engine;319} catch (Exception exp) {320if (DEBUG) exp.printStackTrace();321}322}323324for (ScriptEngineFactory spi : engineSpis) {325List<String> types = null;326try {327types = spi.getMimeTypes();328} catch (Exception exp) {329if (DEBUG) exp.printStackTrace();330}331if (types == null) continue;332for (String type : types) {333if (mimeType.equals(type)) {334try {335ScriptEngine engine = spi.getScriptEngine();336engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);337return engine;338} catch (Exception exp) {339if (DEBUG) exp.printStackTrace();340}341}342}343}344return null;345}346347/**348* Returns a list whose elements are instances of all the <code>ScriptEngineFactory</code> classes349* found by the discovery mechanism.350* @return List of all discovered <code>ScriptEngineFactory</code>s.351*/352public List<ScriptEngineFactory> getEngineFactories() {353List<ScriptEngineFactory> res = new ArrayList<ScriptEngineFactory>(engineSpis.size());354for (ScriptEngineFactory spi : engineSpis) {355res.add(spi);356}357return Collections.unmodifiableList(res);358}359360/**361* Registers a <code>ScriptEngineFactory</code> to handle a language362* name. Overrides any such association found using the Discovery mechanism.363* @param name The name to be associated with the <code>ScriptEngineFactory</code>.364* @param factory The class to associate with the given name.365* @throws NullPointerException if any of the parameters is null.366*/367public void registerEngineName(String name, ScriptEngineFactory factory) {368if (name == null || factory == null) throw new NullPointerException();369nameAssociations.put(name, factory);370}371372/**373* Registers a <code>ScriptEngineFactory</code> to handle a mime type.374* Overrides any such association found using the Discovery mechanism.375*376* @param type The mime type to be associated with the377* <code>ScriptEngineFactory</code>.378*379* @param factory The class to associate with the given mime type.380* @throws NullPointerException if any of the parameters is null.381*/382public void registerEngineMimeType(String type, ScriptEngineFactory factory) {383if (type == null || factory == null) throw new NullPointerException();384mimeTypeAssociations.put(type, factory);385}386387/**388* Registers a <code>ScriptEngineFactory</code> to handle an extension.389* Overrides any such association found using the Discovery mechanism.390*391* @param extension The extension type to be associated with the392* <code>ScriptEngineFactory</code>.393* @param factory The class to associate with the given extension.394* @throws NullPointerException if any of the parameters is null.395*/396public void registerEngineExtension(String extension, ScriptEngineFactory factory) {397if (extension == null || factory == null) throw new NullPointerException();398extensionAssociations.put(extension, factory);399}400401/** Set of script engine factories discovered. */402private HashSet<ScriptEngineFactory> engineSpis;403404/** Map of engine name to script engine factory. */405private HashMap<String, ScriptEngineFactory> nameAssociations;406407/** Map of script file extension to script engine factory. */408private HashMap<String, ScriptEngineFactory> extensionAssociations;409410/** Map of script script MIME type to script engine factory. */411private HashMap<String, ScriptEngineFactory> mimeTypeAssociations;412413/** Global bindings associated with script engines created by this manager. */414private Bindings globalScope;415}416417418