Class RhinoEngine

  • All Implemented Interfaces:
    org.mozilla.javascript.tools.debugger.ScopeProvider

    public class RhinoEngine
    extends java.lang.Object
    implements org.mozilla.javascript.tools.debugger.ScopeProvider
    This class provides methods to create JavaScript objects from JavaScript files.
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static java.util.List<java.lang.Integer> VERSION  
    • Constructor Summary

      Constructors 
      Constructor Description
      RhinoEngine​(RingoConfig config, java.util.Map<java.lang.String,​java.lang.Object> globals)
      Create a RhinoEngine with the given configuration.
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void addModuleLoader​(java.lang.String extension, java.lang.Object value)  
      void addShutdownHook​(org.mozilla.javascript.Scriptable callback, boolean sync)
      Add a callback to be invoked on shutdown.
      void addToClasspath​(Trackable path)  
      java.lang.Object asJavaObject​(java.lang.Object object)
      Get a wrapper for an object that exposes it as Java object to JavaScript.
      java.lang.Object asJavaString​(java.lang.Object object)
      Get a wrapper for a string that exposes the java.lang.String methods to JavaScript This is useful for accessing strings as java.lang.String without the cost of creating a new instance.
      RhinoEngine createSandbox​(RingoConfig config, java.util.Map<java.lang.String,​java.lang.Object> globals)
      Create a sandboxed scripting engine with the same install directory as this and the given module paths, global properties, class shutter and sealing
      void defineHostClass​(java.lang.Class<org.mozilla.javascript.Scriptable> clazz)
      Define a Javascript host object implemented by the given class.
      protected void enterAsyncTask()  
      java.lang.Object evaluateExpression​(java.lang.String expr)
      Evaluate an expression from the command line.
      protected void exitAsyncTask()  
      Repository findRepository​(java.lang.String path, Repository localPath)
      Search for a repository in the local path, or the main repository path.
      Resource findResource​(java.lang.String path, ModuleLoader[] loaders, Repository localRoot)
      Search for a resource in a local path, or the main repository path.
      java.util.List<Resource> findResources​(java.lang.String path, boolean recursive)
      Get a list of all child resources for the given path relative to our script repository.
      java.lang.Object[] getArguments()
      Get the script arguments as object array suitable for use with Context.newArray().
      java.lang.String getCharset()  
      RingoClassLoader getClassLoader()  
      java.util.List<java.lang.String> getCommandLineArguments()
      Get the list of command line arguments
      RingoConfig getConfig()  
      RingoContextFactory getContextFactory()  
      RingoWorker getCurrentWorker​(org.mozilla.javascript.Scriptable obj)
      Get the worker associated with the current thread, or the given scope or function argument if provided.
      static RhinoEngine getEngine​(org.mozilla.javascript.Scriptable scope)
      Get the currently active RhinoEngine instance.
      java.util.List<ScriptError> getMainErrors()
      Get the list of errors encountered by the main worker.
      java.lang.String getMainModule()
      Get the name of the main script as module name, if any
      ModuleScope getMainModuleScope()
      Get the main scrip's module scope, if any
      RingoWorker getMainWorker()
      Get the main worker running the main script.
      ModuleLoader getModuleLoader​(Resource resource)  
      int getOptimizationLevel()
      Get the current Rhino optimization level
      Repository getParentRepository​(org.mozilla.javascript.Scriptable scope)
      Get the repository associated with the scope or one of its prototypes
      java.util.List<Repository> getRepositories()
      Get the engine's module search path as a list of repositories
      Repository getRingoHome()
      Get the our installation directory.
      org.mozilla.javascript.Scriptable getScope()
      Get the engine's global shared scope
      ReloadableScript getScript​(java.lang.String moduleName)
      Resolves a type name to a script file within our script directory and returns a Scriptable evaluated to the file.
      ReloadableScript getScript​(java.lang.String moduleName, Repository localPath)
      Resolves a type name to a script file within our script directory and returns a Scriptable evaluated to the file.
      org.mozilla.javascript.Scriptable getShellScope​(RingoWorker worker)
      Return a shell scope for interactive evaluation
      RingoWorker getWorker()
      Get a new RingoWorker.
      org.mozilla.javascript.WrapFactory getWrapFactory()
      Get the engine's WrapFactory.
      protected void initArguments​(java.lang.Object[] args)
      Initialize and normalize the global variables and arguments on a thread scope.
      java.lang.Object invoke​(java.lang.Object module, java.lang.String method, java.lang.Object... args)
      Invoke a javascript function.
      org.mozilla.javascript.Scriptable loadModule​(org.mozilla.javascript.Context cx, java.lang.String moduleName, org.mozilla.javascript.Scriptable loadingScope)
      Load a Javascript module into a module scope.
      protected Resource loadPackage​(java.lang.String moduleName, Repository localPath)
      Resolves a module id to a package resource.
      static java.lang.String normalizePath​(java.lang.String path)  
      void removeModuleLoader​(java.lang.String extension)  
      Trackable resolve​(java.lang.String path, Repository localRoot)
      Try to resolve path to a resource or repository relative to a local path, or the engine's repository path.
      java.lang.Object runScript​(java.lang.Object scriptResource, java.lang.String... scriptArgs)
      Invoke a script from the command line.
      protected RingoWorker setCurrentWorker​(RingoWorker worker)
      Associate a worker with the current thread and return the worker that was previously associated with it, or null.
      void setOptimizationLevel​(int level)
      Set Rhino optimization level
      void waitForAsyncTasks()
      Wait until all daemon threads running in this engine have terminated.
      static java.lang.Object wrapArgument​(java.lang.Object value, org.mozilla.javascript.Scriptable scope)
      Prepare a single property or argument value for use within rhino.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • VERSION

        public static final java.util.List<java.lang.Integer> VERSION
    • Constructor Detail

      • RhinoEngine

        public RhinoEngine​(RingoConfig config,
                           java.util.Map<java.lang.String,​java.lang.Object> globals)
                    throws java.lang.Exception
        Create a RhinoEngine with the given configuration. If globals is not null, its contents are added as properties on the global object.
        Parameters:
        config - the configuration used to initialize the engine.
        globals - an optional map of global properties
        Throws:
        java.lang.Exception - if the engine can't be created
    • Method Detail

      • defineHostClass

        public void defineHostClass​(java.lang.Class<org.mozilla.javascript.Scriptable> clazz)
                             throws java.lang.reflect.InvocationTargetException,
                                    java.lang.InstantiationException,
                                    java.lang.IllegalAccessException
        Define a Javascript host object implemented by the given class.
        Parameters:
        clazz - The Java class implementing the host object.
        Throws:
        java.lang.IllegalAccessException - if access is not available to a reflected class member
        java.lang.InstantiationException - if unable to instantiate the named class
        java.lang.reflect.InvocationTargetException - if an exception is thrown during execution of methods of the named class
      • runScript

        public java.lang.Object runScript​(java.lang.Object scriptResource,
                                          java.lang.String... scriptArgs)
                                   throws java.io.IOException,
                                          org.mozilla.javascript.JavaScriptException
        Invoke a script from the command line.
        Parameters:
        scriptResource - the script resource of path
        scriptArgs - an array of command line arguments
        Returns:
        the return value
        Throws:
        java.io.IOException - an I/O related error occurred
        org.mozilla.javascript.JavaScriptException - the script threw an error during compilation or execution
      • evaluateExpression

        public java.lang.Object evaluateExpression​(java.lang.String expr)
                                            throws java.io.IOException,
                                                   org.mozilla.javascript.JavaScriptException
        Evaluate an expression from the command line.
        Parameters:
        expr - the JavaScript expression to evaluate
        Returns:
        the return value
        Throws:
        java.io.IOException - an I/O related error occurred
        org.mozilla.javascript.JavaScriptException - the script threw an error during compilation or execution
      • invoke

        public java.lang.Object invoke​(java.lang.Object module,
                                       java.lang.String method,
                                       java.lang.Object... args)
                                throws java.io.IOException,
                                       java.lang.NoSuchMethodException
        Invoke a javascript function. This enters a JavaScript context, creates a new per-thread scope, calls the function, exits the context and returns the return value of the invocation.
        Parameters:
        module - the module name or object, or null for the main module
        method - the method name to call in the script
        args - the arguments to pass to the method
        Returns:
        the return value of the invocation
        Throws:
        java.lang.NoSuchMethodException - the method is not defined
        java.io.IOException - an I/O related error occurred
      • setCurrentWorker

        protected RingoWorker setCurrentWorker​(RingoWorker worker)
        Associate a worker with the current thread and return the worker that was previously associated with it, or null.
        Parameters:
        worker - the new worker associated with the current thread
        Returns:
        the worker previously associated with the current thread, or null
      • getCurrentWorker

        public RingoWorker getCurrentWorker​(org.mozilla.javascript.Scriptable obj)
        Get the worker associated with the current thread, or the given scope or function argument if provided. An IllegalStateException is thrown if no worker could be found or if different workers are associated with the current thread and the argument object.
        Parameters:
        obj - a scope or function object
        Returns:
        the current worker
        Throws:
        java.lang.IllegalStateException - if no worker could be found, or if different workers are associates with the current thread and the argument object
      • getMainWorker

        public RingoWorker getMainWorker()
        Get the main worker running the main script.
        Returns:
        the main worker
      • addShutdownHook

        public void addShutdownHook​(org.mozilla.javascript.Scriptable callback,
                                    boolean sync)
        Add a callback to be invoked on shutdown.
        Parameters:
        callback - a callback function wrapper
        sync - whether to invoke the callback synchronously (on the main shutdown thread) or asynchronously (on the worker's event loop thread)
      • getMainErrors

        public java.util.List<ScriptError> getMainErrors()
        Get the list of errors encountered by the main worker.
        Returns:
        a list of errors, may be null.
      • getShellScope

        public org.mozilla.javascript.Scriptable getShellScope​(RingoWorker worker)
                                                        throws java.io.IOException
        Return a shell scope for interactive evaluation
        Returns:
        a shell scope
        Throws:
        java.io.IOException - an I/O related exception occurred
      • getScope

        public org.mozilla.javascript.Scriptable getScope()
        Get the engine's global shared scope
        Specified by:
        getScope in interface org.mozilla.javascript.tools.debugger.ScopeProvider
        Returns:
        the global scope
      • initArguments

        protected void initArguments​(java.lang.Object[] args)
        Initialize and normalize the global variables and arguments on a thread scope.
        Parameters:
        args - the arguments
      • wrapArgument

        public static java.lang.Object wrapArgument​(java.lang.Object value,
                                                    org.mozilla.javascript.Scriptable scope)
        Prepare a single property or argument value for use within rhino.
        Parameters:
        value - the property or argument value
        scope - the scope
        Returns:
        the object wrapped and wired for rhino
      • getOptimizationLevel

        public int getOptimizationLevel()
        Get the current Rhino optimization level
        Returns:
        the current optimization level
      • setOptimizationLevel

        public void setOptimizationLevel​(int level)
        Set Rhino optimization level
        Parameters:
        level - the new optimization level
      • getScript

        public ReloadableScript getScript​(java.lang.String moduleName)
                                   throws org.mozilla.javascript.JavaScriptException,
                                          java.io.IOException
        Resolves a type name to a script file within our script directory and returns a Scriptable evaluated to the file.
        Parameters:
        moduleName - the name of the module to load
        Returns:
        The raw compiled script for the module
        Throws:
        org.mozilla.javascript.JavaScriptException - if an error occurred evaluating the script file
        java.io.IOException - if an error occurred reading the script file
      • getScript

        public ReloadableScript getScript​(java.lang.String moduleName,
                                          Repository localPath)
                                   throws org.mozilla.javascript.JavaScriptException,
                                          java.io.IOException
        Resolves a type name to a script file within our script directory and returns a Scriptable evaluated to the file.
        Parameters:
        moduleName - the name of the module to load
        localPath - the path of the resource issuing this call
        Returns:
        The raw compiled script for the module
        Throws:
        org.mozilla.javascript.JavaScriptException - if an error occurred evaluating the script file
        java.io.IOException - if an error occurred reading the script file
      • loadPackage

        protected Resource loadPackage​(java.lang.String moduleName,
                                       Repository localPath)
                                throws java.io.IOException
        Resolves a module id to a package resource. If module id consists of just one term and resolves to a package directory, the main module of the package is returned. If the module id consists of several terms and the first term resolves to a package directory, the remaining part of the module id is resolved against the "lib" directory of the package.
        Parameters:
        moduleName - the name of the package to load
        localPath - the path of the resource issuing this call
        Returns:
        the location of the package's main module
        Throws:
        java.io.IOException - an unrecoverable I/O exception occurred while reading the package
        See Also:
        NodeJS Modules
      • loadModule

        public org.mozilla.javascript.Scriptable loadModule​(org.mozilla.javascript.Context cx,
                                                            java.lang.String moduleName,
                                                            org.mozilla.javascript.Scriptable loadingScope)
                                                     throws java.io.IOException
        Load a Javascript module into a module scope. This checks if the module has already been loaded in the current context and if so returns the existing module scope.
        Parameters:
        cx - the current context
        moduleName - the module name
        loadingScope - the scope requesting the module
        Returns:
        the loaded module's scope
        Throws:
        java.io.IOException - indicates that in input/output related error occurred
      • getMainModule

        public java.lang.String getMainModule()
        Get the name of the main script as module name, if any
        Returns:
        the main module name, or null
      • getMainModuleScope

        public ModuleScope getMainModuleScope()
        Get the main scrip's module scope, if any
        Returns:
        the main module scope, or null
      • getArguments

        public java.lang.Object[] getArguments()
        Get the script arguments as object array suitable for use with Context.newArray().
        Returns:
        the script arguments
      • getCharset

        public java.lang.String getCharset()
      • getEngine

        public static RhinoEngine getEngine​(org.mozilla.javascript.Scriptable scope)
        Get the currently active RhinoEngine instance.
        Parameters:
        scope - the global scope or a top level module scope
        Returns:
        the current RhinoEngine
      • createSandbox

        public RhinoEngine createSandbox​(RingoConfig config,
                                         java.util.Map<java.lang.String,​java.lang.Object> globals)
                                  throws java.lang.Exception
        Create a sandboxed scripting engine with the same install directory as this and the given module paths, global properties, class shutter and sealing
        Parameters:
        config - the sandbox configuration
        globals - a map of predefined global properties, may be null
        Returns:
        a sandboxed RhinoEngine instance
        Throws:
        java.io.FileNotFoundException - if any part of the module paths does not exist
        java.lang.Exception
      • waitForAsyncTasks

        public void waitForAsyncTasks()
                               throws java.lang.InterruptedException
        Wait until all daemon threads running in this engine have terminated.
        Throws:
        java.lang.InterruptedException - if the current thread has been interrupted
      • enterAsyncTask

        protected void enterAsyncTask()
      • exitAsyncTask

        protected void exitAsyncTask()
      • getCommandLineArguments

        public java.util.List<java.lang.String> getCommandLineArguments()
        Get the list of command line arguments
        Returns:
        the command line arguments passed to this engine
      • getRepositories

        public java.util.List<Repository> getRepositories()
        Get the engine's module search path as a list of repositories
        Returns:
        the module repositories
      • getRingoHome

        public Repository getRingoHome()
        Get the our installation directory.
        Returns:
        the RingoJS installation directory
      • getParentRepository

        public Repository getParentRepository​(org.mozilla.javascript.Scriptable scope)
        Get the repository associated with the scope or one of its prototypes
        Parameters:
        scope - the scope to get the repository from
        Returns:
        the repository, or null
      • findResources

        public java.util.List<Resource> findResources​(java.lang.String path,
                                                      boolean recursive)
                                               throws java.io.IOException
        Get a list of all child resources for the given path relative to our script repository.
        Parameters:
        path - the repository path
        recursive - whether to include nested resources
        Returns:
        a list of all contained child resources
        Throws:
        java.io.IOException
      • resolve

        public Trackable resolve​(java.lang.String path,
                                 Repository localRoot)
                          throws java.io.IOException
        Try to resolve path to a resource or repository relative to a local path, or the engine's repository path.
        Parameters:
        path - the resource name
        localRoot - a repository to look first
        Returns:
        the resource or repository
        Throws:
        java.io.IOException - if an I/O error occurred
      • findResource

        public Resource findResource​(java.lang.String path,
                                     ModuleLoader[] loaders,
                                     Repository localRoot)
                              throws java.io.IOException
        Search for a resource in a local path, or the main repository path.
        Parameters:
        path - the resource name
        loaders - optional list of module loaders
        localRoot - a repository to look first
        Returns:
        the resource
        Throws:
        java.io.IOException - if an I/O error occurred
      • findRepository

        public Repository findRepository​(java.lang.String path,
                                         Repository localPath)
                                  throws java.io.IOException
        Search for a repository in the local path, or the main repository path.
        Parameters:
        path - the repository name
        localPath - a repository to look first
        Returns:
        the repository
        Throws:
        java.io.IOException - if an I/O error occurred
      • addModuleLoader

        public void addModuleLoader​(java.lang.String extension,
                                    java.lang.Object value)
      • removeModuleLoader

        public void removeModuleLoader​(java.lang.String extension)
      • normalizePath

        public static java.lang.String normalizePath​(java.lang.String path)
      • addToClasspath

        public void addToClasspath​(Trackable path)
                            throws java.net.MalformedURLException
        Throws:
        java.net.MalformedURLException
      • asJavaString

        public java.lang.Object asJavaString​(java.lang.Object object)
        Get a wrapper for a string that exposes the java.lang.String methods to JavaScript This is useful for accessing strings as java.lang.String without the cost of creating a new instance.
        Parameters:
        object - an object
        Returns:
        the object converted to a string and wrapped as native java object
      • asJavaObject

        public java.lang.Object asJavaObject​(java.lang.Object object)
        Get a wrapper for an object that exposes it as Java object to JavaScript.
        Parameters:
        object - an object
        Returns:
        the object wrapped as native java object
      • getWrapFactory

        public org.mozilla.javascript.WrapFactory getWrapFactory()
        Get the engine's WrapFactory.
        Returns:
        the engine's WrapFactory instance