or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.mdjava-integration.mdjavascript-objects.mdscript-execution.mdsecurity-debugging.md
tile.json

tessl/maven-org-mozilla--rhino

JavaScript engine implementation that enables JavaScript execution within Java applications with full ECMAScript support and Java-JavaScript interoperability.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/org.mozilla/rhino@1.8.x

To install, run

npx @tessl/cli install tessl/maven-org-mozilla--rhino@1.8.0

index.mddocs/

Mozilla Rhino JavaScript Engine

Mozilla Rhino is a Java implementation of JavaScript that enables embedding JavaScript execution capabilities within Java applications. It provides full ECMAScript compliance with extensive Java-JavaScript interoperability, making it ideal for server-side scripting, application extensibility, and Java-based JavaScript evaluation.

Package Information

  • Package Name: org.mozilla:rhino
  • Package Type: maven
  • Language: Java
  • Installation: <dependency><groupId>org.mozilla</groupId><artifactId>rhino</artifactId><version>1.8.0</version></dependency>

Core Imports

import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Script;

Basic Usage

import org.mozilla.javascript.*;

public class RhinoExample {
    public static void main(String[] args) {
        // Create and enter a Context
        Context cx = Context.enter();
        try {
            // Initialize the standard objects (Object, Function, etc.)
            Scriptable scope = cx.initStandardObjects();
            
            // Evaluate a JavaScript expression
            Object result = cx.evaluateString(scope, "1 + 2", "<cmd>", 1, null);
            System.out.println("Result: " + Context.toString(result)); // "3"
            
            // Execute a more complex script
            String script = """
                function factorial(n) {
                    return n <= 1 ? 1 : n * factorial(n - 1);
                }
                factorial(5);
                """;
            Object factorial = cx.evaluateString(scope, script, "factorial.js", 1, null);
            System.out.println("Factorial: " + Context.toString(factorial)); // "120"
            
        } finally {
            // Exit from the Context
            Context.exit();
        }
    }
}

Architecture

Mozilla Rhino is built around several key components:

  • Context Management: Context and ContextFactory classes manage JavaScript execution environments with thread safety and configuration
  • Scriptable Interface: Core abstraction for all JavaScript objects, providing property access and prototype chain management
  • Native Objects: Complete implementations of JavaScript built-in objects (Array, Object, Function, Promise, etc.)
  • Java Integration: Seamless bidirectional communication between Java and JavaScript with automatic type conversion
  • Compilation System: Advanced parsing, compilation, and optimization capabilities with AST access
  • Security Framework: Fine-grained access control for sandboxed execution environments

Capabilities

Context and Script Execution

Core JavaScript execution engine with context management, script compilation, and evaluation capabilities. Supports both interpreted and compiled execution modes.

// Context management
public static Context enter();
public static void exit();
public static Context getCurrentContext();
public void close(); // Implements Closeable

// Script compilation and execution
public Object evaluateString(Scriptable scope, String source, String sourceName, int lineno, Object securityDomain);
public Object evaluateReader(Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain) throws IOException;
public Script compileString(String source, String sourceName, int lineno, Object securityDomain);
public Script compileReader(Reader in, String sourceName, int lineno, Object securityDomain) throws IOException;
public Function compileFunction(Scriptable scope, String source, String sourceName, int lineno, Object securityDomain);
public Object exec(Context cx, Scriptable scope); // Script interface

// Scope initialization
public ScriptableObject initStandardObjects();
public Scriptable initStandardObjects(ScriptableObject scope);
public ScriptableObject initStandardObjects(ScriptableObject scope, boolean sealed);
public ScriptableObject initSafeStandardObjects();

// Object creation
public Scriptable newObject(Scriptable scope);
public Scriptable newObject(Scriptable scope, String constructorName);
public Scriptable newObject(Scriptable scope, String constructorName, Object[] args);
public Scriptable newArray(Scriptable scope, int length);
public Scriptable newArray(Scriptable scope, Object[] elements);

// Decompilation
public String decompileScript(Script script, int indent);
public String decompileFunction(Function fun, int indent);
public String decompileFunctionBody(Function fun, int indent);

Script Execution

JavaScript Objects and Natives

Complete JavaScript object system with all ECMAScript built-in objects, including ES6+ features like Promises, Symbols, Maps, and Sets.

// Scriptable interface - core JavaScript object contract
public interface Scriptable {
    Object get(String name, Scriptable start);
    void put(String name, Scriptable start, Object value);
    boolean has(String name, Scriptable start);
    void delete(String name);
    Scriptable getPrototype();
    void setPrototype(Scriptable prototype);
    String getClassName();
    Object[] getIds();
}

// Native object creation (moved to Context section above)
// See Context API above for object creation methods

JavaScript Objects

Java-JavaScript Integration

Seamless interoperability between Java and JavaScript with automatic type conversion, Java class access, and adapter objects.

// Type conversion utilities
public static Object javaToJS(Object value, Scriptable scope);
public static Object javaToJS(Object value, Scriptable scope, Context cx);
public static Object jsToJava(Object value, Class<?> desiredType);
public static boolean toBoolean(Object value);
public static double toNumber(Object value);
public static String toString(Object value);
public static Scriptable toObject(Object value, Scriptable scope);

// Java object wrapping
public class WrapFactory {
    public Object wrap(Context cx, Scriptable scope, Object obj, Class<?> staticType);
    public Scriptable wrapAsJavaObject(Context cx, Scriptable scope, Object javaObject, Class<?> staticType);
}

Java Integration

Security and Debugging

Comprehensive security framework with access control, sandboxing, and debugging support for production environments.

// Security control
public interface ClassShutter {
    boolean visibleToScripts(String fullClassName);
}

public class SecurityController {
    public static SecurityController global();
    public static void initGlobal(SecurityController controller);
}

// Debugging support
public interface Debugger {
    void handleCompilationDone(Context cx, DebuggableScript fnOrScript, String source);
    DebugFrame getFrame(Context cx, DebuggableScript fnOrScript);
}

Security and Debugging

Command Line Tools and Shell

Interactive JavaScript shell and command-line tools for script execution, compilation, and debugging.

// Interactive shell main class
public class org.mozilla.javascript.tools.shell.Main {
    /**
     * Main entry point for Rhino shell
     * @param args Command line arguments
     */
    public static void main(String[] args);
    
    /**
     * Execute JavaScript code in shell context
     * @param cx JavaScript context
     * @param args Arguments to process
     */
    public static void exec(String[] args);
}

// Enhanced global object with I/O capabilities
public class org.mozilla.javascript.tools.shell.Global extends ImporterTopLevel {
    /**
     * Initialize global object with standard functions plus I/O extensions
     * @param cx Context for initialization
     */
    public static Global initQuitAction(Context cx, Global global, boolean printAndQuit);
    
    // Built-in shell functions available in global scope
    public static void print(Context cx, Scriptable thisObj, Object[] args, Function funObj);
    public static void quit(Context cx, Scriptable thisObj, Object[] args, Function funObj);
    public static Object readFile(String path, String characterCoding) throws IOException;
    public static Object readUrl(String url, String characterCoding) throws IOException;
    public static String readline() throws IOException;
    public static void write(String string);
    public static void writeFile(String filename, String text, String characterCoding) throws IOException;
}

// Enhanced error reporting for command-line tools
public class org.mozilla.javascript.tools.ToolErrorReporter implements ErrorReporter {
    /**
     * Create error reporter for command-line tools
     * @param reportWarnings Whether to report warnings
     */
    public ToolErrorReporter(boolean reportWarnings);
    
    /**
     * Create error reporter with custom output stream
     * @param reportWarnings Whether to report warnings
     * @param out Output stream for errors
     */
    public ToolErrorReporter(boolean reportWarnings, PrintStream out);
}

Maven Dependency for Tools:

<dependency>
    <groupId>org.mozilla</groupId>
    <artifactId>rhino-tools</artifactId>
    <version>1.8.0</version>
</dependency>

Usage Examples:

// Using shell Global object programmatically
Context cx = Context.enter();
try {
    Global global = new Global();
    global.init(cx);
    
    // Global object includes print, quit, readFile, etc.
    Object result = cx.evaluateString(global, 
        "print('Hello from Rhino!'); readFile('script.js');", 
        "shell", 1, null);
} finally {
    Context.exit();
}

// Custom error reporting
ToolErrorReporter errorReporter = new ToolErrorReporter(true, System.err);
cx.setErrorReporter(errorReporter);

Version and Language Support

// Language version constants
public static final int VERSION_UNKNOWN = -1;
public static final int VERSION_DEFAULT = 0;
public static final int VERSION_1_0 = 100;
public static final int VERSION_1_1 = 110;
public static final int VERSION_1_2 = 120;
public static final int VERSION_1_3 = 130;
public static final int VERSION_1_4 = 140;
public static final int VERSION_1_5 = 150;
public static final int VERSION_1_6 = 160;
public static final int VERSION_1_7 = 170;
public static final int VERSION_1_8 = 180;
public static final int VERSION_ES6 = 200;    // Default
public static final int VERSION_ECMASCRIPT = 250;  // Latest features

// Version configuration
public int getLanguageVersion();
public void setLanguageVersion(int version);
public static boolean isValidLanguageVersion(int version);
public static void checkLanguageVersion(int version);

Feature Configuration

// Feature flags for controlling JavaScript behavior
public static final int FEATURE_NON_ECMA_GET_YEAR = 1;
public static final int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME = 2;
public static final int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER = 3;
public static final int FEATURE_TO_STRING_AS_SOURCE = 4;
public static final int FEATURE_PARENT_PROTO_PROPERTIES = 5;
public static final int FEATURE_E4X = 6;  // E4X XML support
public static final int FEATURE_DYNAMIC_SCOPE = 7;
public static final int FEATURE_STRICT_VARS = 8;
public static final int FEATURE_STRICT_EVAL = 9;
public static final int FEATURE_LOCATION_INFORMATION_IN_ERROR = 10;
public static final int FEATURE_STRICT_MODE = 11;
public static final int FEATURE_WARNING_AS_ERROR = 12;
public static final int FEATURE_ENHANCED_JAVA_ACCESS = 13;
public static final int FEATURE_V8_EXTENSIONS = 14;
public static final int FEATURE_OLD_UNDEF_NULL_THIS = 15;
public static final int FEATURE_ENUMERATE_IDS_FIRST = 16;
public static final int FEATURE_THREAD_SAFE_OBJECTS = 17;
public static final int FEATURE_INTEGER_WITHOUT_DECIMAL_PLACE = 18;
public static final int FEATURE_LITTLE_ENDIAN = 19;
public static final int FEATURE_ENABLE_XML_SECURE_PARSING = 20;
public static final int FEATURE_ENABLE_JAVA_MAP_ACCESS = 21;
public static final int FEATURE_INTL_402 = 22;  // Internationalization API

// Feature testing and configuration
public boolean hasFeature(int featureIndex);

Core Interfaces

Script and Function Interfaces

Essential interfaces for compiled scripts and callable functions that form the foundation of Rhino's execution model.

// Script interface - all compiled scripts implement this
public interface Script {
    /**
     * Execute the script relative to a scope
     * @param cx the Context associated with the current thread
     * @param scope the scope to execute relative to
     * @return the result of executing the script
     */
    Object exec(Context cx, Scriptable scope);
}

// Function interface - all JavaScript functions implement this
public interface Function extends Scriptable, Callable, Constructable {
    /**
     * Call the function
     * @param cx the current Context for this thread
     * @param scope the scope to execute the function relative to
     * @param thisObj the JavaScript 'this' object
     * @param args the array of arguments
     * @return the result of the call
     */
    Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args);
    
    /**
     * Call the function as a constructor
     * @param cx the current Context for this thread
     * @param scope an enclosing scope of the caller
     * @param args the array of arguments
     * @return the allocated object
     */
    Scriptable construct(Context cx, Scriptable scope, Object[] args);
}

// Callable interface - generic callable object
public interface Callable {
    /**
     * Perform the call
     * @param cx the current Context for this thread
     * @param scope the scope to use to resolve properties
     * @param thisObj the JavaScript 'this' object
     * @param args the array of arguments
     * @return the result of the call
     */
    Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args);
}

// Constructable interface - objects that can be constructed
public interface Constructable {
    /**
     * Call the function as a constructor
     * @param cx the current Context for this thread
     * @param scope an enclosing scope of the caller
     * @param args the array of arguments
     * @return the allocated object
     */
    Scriptable construct(Context cx, Scriptable scope, Object[] args);
}

Error Handling

// Exception hierarchy
public abstract class RhinoException extends RuntimeException {
    public String sourceName();
    public int lineNumber();
    public String lineSource();
    public int columnNumber();
}

public class EvaluatorException extends RhinoException;  // Compilation errors
public class EcmaError extends RhinoException;          // JavaScript errors  
public class JavaScriptException extends RhinoException; // Thrown values
public class WrappedException extends EvaluatorException; // Java exceptions
public class ContinuationPending extends RuntimeException; // Continuation support

// Error reporting
public interface ErrorReporter {
    void warning(String message, String sourceName, int line, String lineSource, int lineOffset);
    void error(String message, String sourceName, int line, String lineSource, int lineOffset);
    EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset);
}

Thread Safety and Context Factory

// Context factory for thread-safe Context creation
public class ContextFactory {
    public static ContextFactory getGlobal();
    public Context enterContext();
    public <T> T call(ContextAction<T> action);
}

// Context action for safe Context usage
public interface ContextAction<T> {
    T run(Context cx);
}