1 /*
   2  * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package javax.script;
  27 import java.util.*;
  28 import java.security.*;
  29 import java.util.ServiceLoader;
  30 import java.util.ServiceConfigurationError;
  31 
  32 /**
  33  * The <code>ScriptEngineManager</code> implements a discovery and instantiation
  34  * mechanism for <code>ScriptEngine</code> classes and also maintains a
  35  * collection of key/value pairs storing state shared by all engines created
  36  * by the Manager. This class uses the service provider mechanism described in the
  37  * {@link java.util.ServiceLoader} class to enumerate all the
  38  * implementations of <code>ScriptEngineFactory</code>. <br><br>
  39  * The <code>ScriptEngineManager</code> provides a method to return a list of all these factories
  40  * as well as utility methods which look up factories on the basis of language name, file extension
  41  * and mime type.
  42  * <p>
  43  * The <code>Bindings</code> of key/value pairs, referred to as the "Global Scope"  maintained
  44  * by the manager is available to all instances of <code>ScriptEngine</code> created
  45  * by the <code>ScriptEngineManager</code>.  The values in the <code>Bindings</code> are
  46  * generally exposed in all scripts.
  47  *
  48  * @author Mike Grogan
  49  * @author A. Sundararajan
  50  * @since 1.6
  51  */
  52 public class ScriptEngineManager  {
  53     private static final boolean DEBUG = false;
  54     /**
  55      * The effect of calling this constructor is the same as calling
  56      * <code>ScriptEngineManager(Thread.currentThread().getContextClassLoader())</code>.
  57      *
  58      * @see java.lang.Thread#getContextClassLoader
  59      */
  60     public ScriptEngineManager() {
  61         ClassLoader ctxtLoader = Thread.currentThread().getContextClassLoader();
  62         init(ctxtLoader);
  63     }
  64 
  65     /**
  66      * This constructor loads the implementations of
  67      * <code>ScriptEngineFactory</code> visible to the given
  68      * <code>ClassLoader</code> using the service provider mechanism.<br><br>
  69      * If loader is <code>null</code>, the script engine factories that are
  70      * bundled with the platform are loaded. <br>
  71      *
  72      * @param loader ClassLoader used to discover script engine factories.
  73      */
  74     public ScriptEngineManager(ClassLoader loader) {
  75         init(loader);
  76     }
  77 
  78     private void init(final ClassLoader loader) {
  79         globalScope = new SimpleBindings();
  80         engineSpis = new ArrayList<ScriptEngineFactory>();
  81         nameAssociations = new HashMap<String, ScriptEngineFactory>();
  82         extensionAssociations = new HashMap<String, ScriptEngineFactory>();
  83         mimeTypeAssociations = new HashMap<String, ScriptEngineFactory>();
  84         initEngines(loader);
  85         sortEngines();
  86     }
  87 
  88     private void sortEngines() {
  89         Collections.sort(engineSpis, new Comparator<ScriptEngineFactory>() {
  90             @Override
  91             public int compare(ScriptEngineFactory lhs, ScriptEngineFactory rhs) {
  92                 return lhs.getEngineName().compareTo(rhs.getEngineName());
  93             }
  94         });
  95     }
  96 
  97     private ServiceLoader<ScriptEngineFactory> getServiceLoader(final ClassLoader loader) {
  98         if (loader != null) {
  99             return ServiceLoader.load(ScriptEngineFactory.class, loader);
 100         } else {
 101             return ServiceLoader.loadInstalled(ScriptEngineFactory.class);
 102         }
 103     }
 104 
 105     private void initEngines(final ClassLoader loader) {
 106         Iterator<ScriptEngineFactory> itr = null;
 107         try {
 108             ServiceLoader<ScriptEngineFactory> sl = AccessController.doPrivileged(
 109                 new PrivilegedAction<ServiceLoader<ScriptEngineFactory>>() {
 110                     @Override
 111                     public ServiceLoader<ScriptEngineFactory> run() {
 112                         return getServiceLoader(loader);
 113                     }
 114                 });
 115 
 116             itr = sl.iterator();
 117         } catch (ServiceConfigurationError err) {
 118             System.err.println("Can't find ScriptEngineFactory providers: " +
 119                           err.getMessage());
 120             if (DEBUG) {
 121                 err.printStackTrace();
 122             }
 123             // do not throw any exception here. user may want to
 124             // manage his/her own factories using this manager
 125             // by explicit registratation (by registerXXX) methods.
 126             return;
 127         }
 128 
 129         try {
 130             while (itr.hasNext()) {
 131                 try {
 132                     ScriptEngineFactory fact = itr.next();
 133                     engineSpis.add(fact);
 134                 } catch (ServiceConfigurationError err) {
 135                     System.err.println("ScriptEngineManager providers.next(): "
 136                                  + err.getMessage());
 137                     if (DEBUG) {
 138                         err.printStackTrace();
 139                     }
 140                     // one factory failed, but check other factories...
 141                     continue;
 142                 }
 143             }
 144         } catch (ServiceConfigurationError err) {
 145             System.err.println("ScriptEngineManager providers.hasNext(): "
 146                             + err.getMessage());
 147             if (DEBUG) {
 148                 err.printStackTrace();
 149             }
 150             // do not throw any exception here. user may want to
 151             // manage his/her own factories using this manager
 152             // by explicit registratation (by registerXXX) methods.
 153             return;
 154         }
 155     }
 156 
 157     /**
 158      * <code>setBindings</code> stores the specified <code>Bindings</code>
 159      * in the <code>globalScope</code> field. ScriptEngineManager sets this
 160      * <code>Bindings</code> as global bindings for <code>ScriptEngine</code>
 161      * objects created by it.
 162      *
 163      * @param bindings The specified <code>Bindings</code>
 164      * @throws IllegalArgumentException if bindings is null.
 165      */
 166     public void setBindings(Bindings bindings) {
 167         if (bindings == null) {
 168             throw new IllegalArgumentException("Global scope cannot be null.");
 169         }
 170 
 171         globalScope = bindings;
 172     }
 173 
 174     /**
 175      * <code>getBindings</code> returns the value of the <code>globalScope</code> field.
 176      * ScriptEngineManager sets this <code>Bindings</code> as global bindings for
 177      * <code>ScriptEngine</code> objects created by it.
 178      *
 179      * @return The globalScope field.
 180      */
 181     public Bindings getBindings() {
 182         return globalScope;
 183     }
 184 
 185     /**
 186      * Sets the specified key/value pair in the Global Scope.
 187      * @param key Key to set
 188      * @param value Value to set.
 189      * @throws NullPointerException if key is null.
 190      * @throws IllegalArgumentException if key is empty string.
 191      */
 192     public void put(String key, Object value) {
 193         globalScope.put(key, value);
 194     }
 195 
 196     /**
 197      * Gets the value for the specified key in the Global Scope
 198      * @param key The key whose value is to be returned.
 199      * @return The value for the specified key.
 200      */
 201     public Object get(String key) {
 202         return globalScope.get(key);
 203     }
 204 
 205     /**
 206      * Looks up and creates a <code>ScriptEngine</code> for a given  name.
 207      * The algorithm first searches for a <code>ScriptEngineFactory</code> that has been
 208      * registered as a handler for the specified name using the <code>registerEngineName</code>
 209      * method.
 210      * <br><br> If one is not found, it searches the set of <code>ScriptEngineFactory</code> instances
 211      * stored by the constructor for one with the specified name.  If a <code>ScriptEngineFactory</code>
 212      * is found by either method, it is used to create instance of <code>ScriptEngine</code>.
 213      * @param shortName The short name of the <code>ScriptEngine</code> implementation.
 214      * returned by the <code>getNames</code> method of its <code>ScriptEngineFactory</code>.
 215      * @return A <code>ScriptEngine</code> created by the factory located in the search.  Returns null
 216      * if no such factory was found.  The <code>ScriptEngineManager</code> sets its own <code>globalScope</code>
 217      * <code>Bindings</code> as the <code>GLOBAL_SCOPE</code> <code>Bindings</code> of the newly
 218      * created <code>ScriptEngine</code>.
 219      * @throws NullPointerException if shortName is null.
 220      */
 221     public ScriptEngine getEngineByName(String shortName) {
 222         if (shortName == null) throw new NullPointerException();
 223         //look for registered name first
 224         Object obj;
 225         if (null != (obj = nameAssociations.get(shortName))) {
 226             ScriptEngineFactory spi = (ScriptEngineFactory)obj;
 227             try {
 228                 ScriptEngine engine = spi.getScriptEngine();
 229                 engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);
 230                 return engine;
 231             } catch (Exception exp) {
 232                 if (DEBUG) exp.printStackTrace();
 233             }
 234         }
 235 
 236         for (ScriptEngineFactory spi : engineSpis) {
 237             List<String> names = null;
 238             try {
 239                 names = spi.getNames();
 240             } catch (Exception exp) {
 241                 if (DEBUG) exp.printStackTrace();
 242             }
 243 
 244             if (names != null) {
 245                 for (String name : names) {
 246                     if (shortName.equals(name)) {
 247                         try {
 248                             ScriptEngine engine = spi.getScriptEngine();
 249                             engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);
 250                             return engine;
 251                         } catch (Exception exp) {
 252                             if (DEBUG) exp.printStackTrace();
 253                         }
 254                     }
 255                 }
 256             }
 257         }
 258 
 259         return null;
 260     }
 261 
 262     /**
 263      * Look up and create a <code>ScriptEngine</code> for a given extension.  The algorithm
 264      * used by <code>getEngineByName</code> is used except that the search starts
 265      * by looking for a <code>ScriptEngineFactory</code> registered to handle the
 266      * given extension using <code>registerEngineExtension</code>.
 267      * @param extension The given extension
 268      * @return The engine to handle scripts with this extension.  Returns <code>null</code>
 269      * if not found.
 270      * @throws NullPointerException if extension is null.
 271      */
 272     public ScriptEngine getEngineByExtension(String extension) {
 273         if (extension == null) throw new NullPointerException();
 274         //look for registered extension first
 275         Object obj;
 276         if (null != (obj = extensionAssociations.get(extension))) {
 277             ScriptEngineFactory spi = (ScriptEngineFactory)obj;
 278             try {
 279                 ScriptEngine engine = spi.getScriptEngine();
 280                 engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);
 281                 return engine;
 282             } catch (Exception exp) {
 283                 if (DEBUG) exp.printStackTrace();
 284             }
 285         }
 286 
 287         for (ScriptEngineFactory spi : engineSpis) {
 288             List<String> exts = null;
 289             try {
 290                 exts = spi.getExtensions();
 291             } catch (Exception exp) {
 292                 if (DEBUG) exp.printStackTrace();
 293             }
 294             if (exts == null) continue;
 295             for (String ext : exts) {
 296                 if (extension.equals(ext)) {
 297                     try {
 298                         ScriptEngine engine = spi.getScriptEngine();
 299                         engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);
 300                         return engine;
 301                     } catch (Exception exp) {
 302                         if (DEBUG) exp.printStackTrace();
 303                     }
 304                 }
 305             }
 306         }
 307         return null;
 308     }
 309 
 310     /**
 311      * Look up and create a <code>ScriptEngine</code> for a given mime type.  The algorithm
 312      * used by <code>getEngineByName</code> is used except that the search starts
 313      * by looking for a <code>ScriptEngineFactory</code> registered to handle the
 314      * given mime type using <code>registerEngineMimeType</code>.
 315      * @param mimeType The given mime type
 316      * @return The engine to handle scripts with this mime type.  Returns <code>null</code>
 317      * if not found.
 318      * @throws NullPointerException if mimeType is null.
 319      */
 320     public ScriptEngine getEngineByMimeType(String mimeType) {
 321         if (mimeType == null) throw new NullPointerException();
 322         //look for registered types first
 323         Object obj;
 324         if (null != (obj = mimeTypeAssociations.get(mimeType))) {
 325             ScriptEngineFactory spi = (ScriptEngineFactory)obj;
 326             try {
 327                 ScriptEngine engine = spi.getScriptEngine();
 328                 engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);
 329                 return engine;
 330             } catch (Exception exp) {
 331                 if (DEBUG) exp.printStackTrace();
 332             }
 333         }
 334 
 335         for (ScriptEngineFactory spi : engineSpis) {
 336             List<String> types = null;
 337             try {
 338                 types = spi.getMimeTypes();
 339             } catch (Exception exp) {
 340                 if (DEBUG) exp.printStackTrace();
 341             }
 342             if (types == null) continue;
 343             for (String type : types) {
 344                 if (mimeType.equals(type)) {
 345                     try {
 346                         ScriptEngine engine = spi.getScriptEngine();
 347                         engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);
 348                         return engine;
 349                     } catch (Exception exp) {
 350                         if (DEBUG) exp.printStackTrace();
 351                     }
 352                 }
 353             }
 354         }
 355         return null;
 356     }
 357 
 358     /**
 359      * Returns a list whose elements are instances of all the <code>ScriptEngineFactory</code> classes
 360      * found by the discovery mechanism.
 361      * @return List of all discovered <code>ScriptEngineFactory</code>s.
 362      */
 363     public List<ScriptEngineFactory> getEngineFactories() {
 364         List<ScriptEngineFactory> res = new ArrayList<ScriptEngineFactory>(engineSpis.size());
 365         for (ScriptEngineFactory spi : engineSpis) {
 366             res.add(spi);
 367         }
 368         return Collections.unmodifiableList(res);
 369     }
 370 
 371     /**
 372      * Registers a <code>ScriptEngineFactory</code> to handle a language
 373      * name.  Overrides any such association found using the Discovery mechanism.
 374      * @param name The name to be associated with the <code>ScriptEngineFactory</code>.
 375      * @param factory The class to associate with the given name.
 376      * @throws NullPointerException if any of the parameters is null.
 377      */
 378     public void registerEngineName(String name, ScriptEngineFactory factory) {
 379         if (name == null || factory == null) throw new NullPointerException();
 380         nameAssociations.put(name, factory);
 381     }
 382 
 383     /**
 384      * Registers a <code>ScriptEngineFactory</code> to handle a mime type.
 385      * Overrides any such association found using the Discovery mechanism.
 386      *
 387      * @param type The mime type  to be associated with the
 388      * <code>ScriptEngineFactory</code>.
 389      *
 390      * @param factory The class to associate with the given mime type.
 391      * @throws NullPointerException if any of the parameters is null.
 392      */
 393     public void registerEngineMimeType(String type, ScriptEngineFactory factory) {
 394         if (type == null || factory == null) throw new NullPointerException();
 395         mimeTypeAssociations.put(type, factory);
 396     }
 397 
 398     /**
 399      * Registers a <code>ScriptEngineFactory</code> to handle an extension.
 400      * Overrides any such association found using the Discovery mechanism.
 401      *
 402      * @param extension The extension type  to be associated with the
 403      * <code>ScriptEngineFactory</code>.
 404      * @param factory The class to associate with the given extension.
 405      * @throws NullPointerException if any of the parameters is null.
 406      */
 407     public void registerEngineExtension(String extension, ScriptEngineFactory factory) {
 408         if (extension == null || factory == null) throw new NullPointerException();
 409         extensionAssociations.put(extension, factory);
 410     }
 411 
 412     /** Set of script engine factories discovered. */
 413     private List<ScriptEngineFactory> engineSpis;
 414 
 415     /** Map of engine name to script engine factory. */
 416     private HashMap<String, ScriptEngineFactory> nameAssociations;
 417 
 418     /** Map of script file extension to script engine factory. */
 419     private HashMap<String, ScriptEngineFactory> extensionAssociations;
 420 
 421     /** Map of script MIME type to script engine factory. */
 422     private HashMap<String, ScriptEngineFactory> mimeTypeAssociations;
 423 
 424     /** Global bindings associated with script engines created by this manager. */
 425     private Bindings globalScope;
 426 }