1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
/* * @(#)ScriptEngineManager.java 1.6 06/04/21 17:44:33 * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTAIL. Use is subject to license terms. */ package javax.script; import java.util.*; import java.net.URL; import java.io.*; import java.security.*; import sun.misc.Service; import sun.misc.ServiceConfigurationError; import sun.reflect.Reflection; import sun.security.util.SecurityConstants; /** * The <code>ScriptEngineManager</code> implements a discovery and instantiation * mechanism for <code>ScriptEngine</code> classes and also maintains a * collection of key/value pairs storing state shared by all engines created * by the Manager. This class uses the <a href="../../../technotes/guides/jar/jar.html#Service%20Provider">service provider</a> mechanism to enumerate all the * implementations of <code>ScriptEngineFactory</code>. <br><br> * The <code>ScriptEngineManager</code> provides a method to return an array of all these factories * as well as utility methods which look up factories on the basis of language name, file extension * and mime type. * <p> * The <code>Bindings</code> of key/value pairs, referred to as the "Global Scope" maintained * by the manager is available to all instances of <code>ScriptEngine</code> created * by the <code>ScriptEngineManager</code>. The values in the <code>Bindings</code> are * generally exposed in all scripts. * * @author Mike Grogan * @author A. Sundararajan * @since 1.6 */ public class ScriptEngineManager { private static final boolean DEBUG = false; /** * If the thread context ClassLoader can be accessed by the caller, * then the effect of calling this constructor is the same as calling * <code>ScriptEngineManager(Thread.currentThread().getContextClassLoader())</code>. * Otherwise, the effect is the same as calling <code>ScriptEngineManager(null)</code>. * * @see java.lang.Thread#getContextClassLoader */ public ScriptEngineManager() { ClassLoader ctxtLoader = Thread.currentThread().getContextClassLoader(); if (canCallerAccessLoader(ctxtLoader)) { if (DEBUG) System.out.println("using " + ctxtLoader); init(ctxtLoader); } else { if (DEBUG) System.out.println("using bootstrap loader"); init(null); } } /** * This constructor loads the implementations of * <code>ScriptEngineFactory</code> visible to the given * <code>ClassLoader</code> using the <a href="../../../technotes/guides/jar/jar.html#Service%20Provider">service provider</a> mechanism.<br><br> * If loader is <code>null</code>, the script engine factories that are * bundled with the platform and that are in the usual extension * directories (installed extensions) are loaded. <br><br> * * @param loader ClassLoader used to discover script engine factories. */ public ScriptEngineManager(ClassLoader loader) { init(loader); } private void init(final ClassLoader loader) { globalScope = new SimpleBindings(); engineSpis = new HashSet<ScriptEngineFactory>(); nameAssociations = new HashMap<String, ScriptEngineFactory>(); extensionAssociations = new HashMap<String, ScriptEngineFactory>(); mimeTypeAssociations = new HashMap<String, ScriptEngineFactory>(); AccessController.doPrivileged(new PrivilegedAction() { public Object run() { initEngines(loader); return null; } }); } private void initEngines(final ClassLoader loader) { Iterator itr = null; try { if (loader != null) { itr = Service.providers(ScriptEngineFactory.class, loader); } else { itr = Service.installedProviders(ScriptEngineFactory.class); } } catch (ServiceConfigurationError err) { System.err.println("Can't find ScriptEngineFactory providers: " + err.getMessage()); if (DEBUG) { err.printStackTrace(); } // do not throw any exception here. user may want to // manage his/her own factories using this manager // by explicit registratation (by registerXXX) methods. return; } try { while (itr.hasNext()) { try { ScriptEngineFactory fact = (ScriptEngineFactory) itr.next(); engineSpis.add(fact); } catch (ServiceConfigurationError err) { System.err.println("ScriptEngineManager providers.next(): " + err.getMessage()); if (DEBUG) { err.printStackTrace(); } // one factory failed, but check other factories... continue; } } } catch (ServiceConfigurationError err) { System.err.println("ScriptEngineManager providers.hasNext(): " + err.getMessage()); if (DEBUG) { err.printStackTrace(); } // do not throw any exception here. user may want to // manage his/her own factories using this manager // by explicit registratation (by registerXXX) methods. return; } } /** * <code>setBindings</code> stores the specified <code>Bindings</code> * in the <code>globalScope</code> field. ScriptEngineManager sets this * <code>Bindings</code> as global bindings for <code>ScriptEngine</code> * objects created by it. * * @param bindings The specified <code>Bindings</code> * @throws IllegalArgumentException if bindings is null. */ public void setBindings(Bindings bindings) { if (bindings == null) { throw new IllegalArgumentException("Global scope cannot be null."); } globalScope = bindings; } /** * <code>getBindings</code> returns the value of the <code>globalScope</code> field. * ScriptEngineManager sets this <code>Bindings</code> as global bindings for * <code>ScriptEngine</code> objects created by it. * * @return The globalScope field. */ public Bindings getBindings() { return globalScope; } /** * Sets the specified key/value pair in the Global Scope. * @param key Key to set * @param value Value to set. * @throws NullPointerException if key is null. * @throws IllegalArgumentException if key is empty string. */ public void put(String key, Object value) { globalScope.put(key, value); } /** * Gets the value for the specified key in the Global Scope * @param key The key whose value is to be returned. * @return The value for the specified key. */ public Object get(String key) { return globalScope.get(key); } /** * Looks up and creates a <code>ScriptEngine</code> for a given name. * The algorithm first searches for a <code>ScriptEngineFactory</code> that has been * registered as a handler for the specified name using the <code>registerEngineName</code> * method. * <br><br> If one is not found, it searches the array of <code>ScriptEngineFactory</code> instances * stored by the constructor for one with the specified name. If a <code>ScriptEngineFactory</code> * is found by either method, it is used to create instance of <code>ScriptEngine</code>. * @param shortName The short name of the <code>ScriptEngine</code> implementation. * returned by the <code>getNames</code> method of its <code>ScriptEngineFactory</code>. * @return A <code>ScriptEngine</code> created by the factory located in the search. Returns null * if no such factory was found. The <code>ScriptEngineManager</code> sets its own <code>globalScope</code> * <code>Bindings</code> as the <code>GLOBAL_SCOPE</code> <code>Bindings</code> of the newly * created <code>ScriptEngine</code>. * @throws NullPointerException if shortName is null. */ public ScriptEngine getEngineByName(String shortName) { if (shortName == null) throw new NullPointerException(); //look for registered name first Object obj; if (null != (obj = nameAssociations.get(shortName))) { ScriptEngineFactory spi = (ScriptEngineFactory)obj; try { ScriptEngine engine = spi.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } } for (ScriptEngineFactory spi : engineSpis) { List<String> names = null; try { names = spi.getNames(); } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } if (names != null) { for (String name : names) { if (shortName.equals(name)) { try { ScriptEngine engine = spi.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } } } } } return null; } /** * Look up and create a <code>ScriptEngine</code> for a given extension. The algorithm * used by <code>getEngineByName</code> is used except that the search starts * by looking for a <code>ScriptEngineFactory</code> registered to handle the * given extension using <code>registerEngineExtension</code>. * @param extension The given extension * @return The engine to handle scripts with this extension. Returns <code>null</code> * if not found. * @throws NullPointerException if extension is null. */ public ScriptEngine getEngineByExtension(String extension) { if (extension == null) throw new NullPointerException(); //look for registered extension first Object obj; if (null != (obj = extensionAssociations.get(extension))) { ScriptEngineFactory spi = (ScriptEngineFactory)obj; try { ScriptEngine engine = spi.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } } for (ScriptEngineFactory spi : engineSpis) { List<String> exts = null; try { exts = spi.getExtensions(); } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } if (exts == null) continue; for (String ext : exts) { if (extension.equals(ext)) { try { ScriptEngine engine = spi.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } } } } return null; } /** * Look up and create a <code>ScriptEngine</code> for a given mime type. The algorithm * used by <code>getEngineByName</code> is used except that the search starts * by looking for a <code>ScriptEngineFactory</code> registered to handle the * given mime type using <code>registerEngineMimeType</code>. * @param mimeType The given mime type * @return The engine to handle scripts with this mime type. Returns <code>null</code> * if not found. * @throws NullPointerException if mimeType is null. */ public ScriptEngine getEngineByMimeType(String mimeType) { if (mimeType == null) throw new NullPointerException(); //look for registered types first Object obj; if (null != (obj = mimeTypeAssociations.get(mimeType))) { ScriptEngineFactory spi = (ScriptEngineFactory)obj; try { ScriptEngine engine = spi.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } } for (ScriptEngineFactory spi : engineSpis) { List<String> types = null; try { types = spi.getMimeTypes(); } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } if (types == null) continue; for (String type : types) { if (mimeType.equals(type)) { try { ScriptEngine engine = spi.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } } } } return null; } /** * Returns an array whose elements are instances of all the <code>ScriptEngineFactory</code> classes * found by the discovery mechanism. * @return List of all discovered <code>ScriptEngineFactory</code>s. */ public List<ScriptEngineFactory> getEngineFactories() { List<ScriptEngineFactory> res = new ArrayList<ScriptEngineFactory>(engineSpis.size()); for (ScriptEngineFactory spi : engineSpis) { res.add(spi); } return Collections.unmodifiableList(res); } /** * Registers a <code>ScriptEngineFactory</code> to handle a language * name. Overrides any such association found using the Discovery mechanism. * @param name The name to be associated with the <code>ScriptEngineFactory</code>. * @param factory The class to associate with the given name. * @throws NullPointerException if any of the parameters is null. */ public void registerEngineName(String name, ScriptEngineFactory factory) { if (name == null || factory == null) throw new NullPointerException(); nameAssociations.put(name, factory); } /** * Registers a <code>ScriptEngineFactory</code> to handle a mime type. * Overrides any such association found using the Discovery mechanism. * * @param type The mime type to be associated with the * <code>ScriptEngineFactory</code>. * * @param factory The class to associate with the given mime type. * @throws NullPointerException if any of the parameters is null. */ public void registerEngineMimeType(String type, ScriptEngineFactory factory) { if (type == null || factory == null) throw new NullPointerException(); mimeTypeAssociations.put(type, factory); } /** * Registers a <code>ScriptEngineFactory</code> to handle an extension. * Overrides any such association found using the Discovery mechanism. * * @param extension The extension type to be associated with the * <code>ScriptEngineFactory</code>. * @param factory The class to associate with the given extension. * @throws NullPointerException if any of the parameters is null. */ public void registerEngineExtension(String extension, ScriptEngineFactory factory) { if (extension == null || factory == null) throw new NullPointerException(); extensionAssociations.put(extension, factory); } /** Set of script engine factories discovered. */ private HashSet<ScriptEngineFactory> engineSpis; /** Map of engine name to script engine factory. */ private HashMap<String, ScriptEngineFactory> nameAssociations; /** Map of script file extension to script engine factory. */ private HashMap<String, ScriptEngineFactory> extensionAssociations; /** Map of script script MIME type to script engine factory. */ private HashMap<String, ScriptEngineFactory> mimeTypeAssociations; /** Global bindings associated with script engines created by this manager. */ private Bindings globalScope; private boolean canCallerAccessLoader(ClassLoader loader) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { ClassLoader callerLoader = getCallerClassLoader(); if (callerLoader != null) { if (loader != callerLoader || !isAncestor(loader, callerLoader)) { try { sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION); } catch (SecurityException exp) { if (DEBUG) exp.printStackTrace(); return false; } } // else fallthru.. } // else fallthru.. } // else fallthru.. return true; } // Note that this code is same as ClassLoader.getCallerClassLoader(). // But, that method is package private and hence we can't call here. private ClassLoader getCallerClassLoader() { Class caller = Reflection.getCallerClass(3); if (caller == null) { return null; } return caller.getClassLoader(); } // is cl1 ancestor of cl2? private boolean isAncestor(ClassLoader cl1, ClassLoader cl2) { do { cl2 = cl2.getParent(); if (cl1 == cl2) return true; } while (cl2 != null); return false; } }