org.mozilla.javascript
Class Context

java.lang.Object
  |
  +--org.mozilla.javascript.Context

public class Context
extends java.lang.Object

This class represents the runtime context of an executing script. Before executing a script, an instance of Context must be created and associated with the thread that will be executing the script. The Context will be used to store information about the executing of the script such as the call stack. Contexts are associated with the current thread using the enter() method.

The behavior of the execution engine may be altered through methods such as setErrorReporter.

Different forms of script execution are supported. Scripts may be evaluated from the source directly, or first compiled and then later executed. Interactive execution is also supported.

Some aspects of script execution, such as type conversions and object creation, may be accessed directly through methods of Context.

Author:
Norris Boyd, Brendan Eich
See Also:
Scriptable

Field Summary
static java.lang.String errorReporterProperty
           
static int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME
          if hasFeature(FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME) returns true, allow 'function (...) { ...
static int FEATURE_NON_ECMA_GET_YEAR
          if hasFeature(FEATURE_NON_ECMA_GET_YEAR) returns true, Date.prototype.getYear subtructs 1900 only if 1900 <= date < 2000 in deviation with Ecma B.2.4
static int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER
          if hasFeature(RESERVED_KEYWORD_AS_IDENTIFIER) returns true, treat future reserved keyword (see Ecma-262, section 7.5.3) as ordinary identifiers but warn about this usage
static int FEATURE_TO_STRING_AS_SOURCE
          if hasFeature(FEATURE_TO_STRING_AS_SOURCE) returns true, calling toString on JS objects gives JS source with code to create an object with all enumeratable fields of the original object instead of printing "[object ]".
static java.lang.String languageVersionProperty
           
static int VERSION_1_0
          JavaScript 1.0
static int VERSION_1_1
          JavaScript 1.1
static int VERSION_1_2
          JavaScript 1.2
static int VERSION_1_3
          JavaScript 1.3
static int VERSION_1_4
          JavaScript 1.4
static int VERSION_1_5
          JavaScript 1.5
static int VERSION_DEFAULT
          The default version.
static int VERSION_UNKNOWN
          The unknown version.
 
Constructor Summary
Context()
          Create a new Context.
Context(SecuritySupport x)
          Deprecated. The SecuritySupport class is deprecated. See its documentation for the upgrade path.
 
Method Summary
 void addActivationName(java.lang.String name)
          Add a name to the list of names forcing the creation of real activation objects for functions.
static void addContextListener(ContextListener listener)
          Add a Context listener.
 void addPropertyChangeListener(java.beans.PropertyChangeListener listener)
          Register an object to receive notifications when a bound property has changed
 Function compileFunction(Scriptable scope, java.lang.String source, java.lang.String sourceName, int lineno, java.lang.Object securityDomain)
          Compile a JavaScript function.
 Script compileReader(Scriptable scope, java.io.Reader in, java.lang.String sourceName, int lineno, java.lang.Object securityDomain)
          Compiles the source in the given reader.
 org.mozilla.javascript.GeneratedClassLoader createClassLoader(java.lang.ClassLoader parent)
           
 java.lang.String decompileFunction(Function fun, int indent)
          Decompile a JavaScript Function.
 java.lang.String decompileFunctionBody(Function fun, int indent)
          Decompile the body of a JavaScript Function.
 java.lang.String decompileScript(Script script, Scriptable scope, int indent)
          Decompile the script.
static Context enter()
          Get a context associated with the current thread, creating one if need be.
static Context enter(Context cx)
          Get a Context associated with the current thread, using the given Context if need be.
 java.lang.Object evaluateReader(Scriptable scope, java.io.Reader in, java.lang.String sourceName, int lineno, java.lang.Object securityDomain)
          Evaluate a reader as JavaScript source.
 java.lang.Object evaluateString(Scriptable scope, java.lang.String source, java.lang.String sourceName, int lineno, java.lang.Object securityDomain)
          Evaluate a JavaScript source string.
static void exit()
          Exit a block of code requiring a Context.
 java.lang.String getClassName()
          Deprecated. Use ClassNameHelper.get(cx).getClassName() instead.
 ClassOutput getClassOutput()
          Deprecated. Use ClassNameHelper.get(cx).getClassOutput() instead.
 org.mozilla.javascript.ClassRepository getClassRepository()
          Deprecated. Use ClassNameHelper.get(cx).getClassRepository() instead.
static Context getCurrentContext()
          Get the current Context.
 org.mozilla.javascript.debug.Debugger getDebugger()
          Return the current debugger.
 java.lang.Object getDebuggerContextData()
          Return the debugger context data associated with current context.
 java.lang.Object[] getElements(Scriptable object)
          Get the elements of a JavaScript array.
 ErrorReporter getErrorReporter()
          Get the current error reporter.
 java.lang.String getImplementationVersion()
          Get the implementation version.
 int getInstructionObserverThreshold()
          Get/Set threshold of executed instructions counter that triggers call to observeInstructionCount().
 int getLanguageVersion()
          Get the current language version.
 java.util.Locale getLocale()
          Get the current locale.
 int getOptimizationLevel()
          Get the current optimization level.
 java.lang.String getTargetClassFileName()
          Deprecated. Use ClassNameHelper.get(cx).getTargetClassFileName() instead.
 java.lang.String getTargetPackage()
          Deprecated. Use ClassNameHelper.get(cx).getTargetPackage() instead.
 java.lang.Object getThreadLocal(java.lang.Object key)
          Get a value corresponding to a key.
static java.lang.Object getUndefinedValue()
          Get the singleton object that represents the JavaScript Undefined value.
 WrapFactory getWrapFactory()
          Return the current WrapHandler, or null if none is defined.
 WrapHandler getWrapHandler()
          Deprecated. As of Rhino 1.5 Release 4, use WrapFactory and getWrapFactory()
 boolean hasCompileFunctionsWithDynamicScope()
          Return whether functions are compiled by this context using dynamic scope.
 boolean hasFeature(int featureIndex)
          Controls certain aspects of script semantics.
 Scriptable initStandardObjects(ScriptableObject scope)
          Initialize the standard objects.
 ScriptableObject initStandardObjects(ScriptableObject scope, boolean sealed)
          Initialize the standard objects.
 boolean isActivationNeeded(java.lang.String name)
          Check whether the name is in the list of names of objects forcing the creation of activation objects.
 boolean isGeneratingDebug()
          Tell whether debug information is being generated.
 boolean isGeneratingDebugChanged()
           
 boolean isGeneratingSource()
          Tell whether source information is being generated.
 Scriptable newArray(Scriptable scope, int length)
          Create an array with a specified initial length.
 Scriptable newArray(Scriptable scope, java.lang.Object[] elements)
          Create an array with a set of initial elements.
 Scriptable newObject(Scriptable scope)
          Create a new JavaScript object.
 Scriptable newObject(Scriptable scope, java.lang.String constructorName)
          Create a new JavaScript object by executing the named constructor.
 Scriptable newObject(Scriptable scope, java.lang.String constructorName, java.lang.Object[] args)
          Creates a new JavaScript object by executing the named constructor.
 void putThreadLocal(java.lang.Object key, java.lang.Object value)
          Put a value that can later be retrieved using a given key.
 void removeActivationName(java.lang.String name)
          Remove a name from the list of names forcing the creation of real activation objects for functions.
static void removeContextListener(ContextListener listener)
          Remove a Context listener.
 void removePropertyChangeListener(java.beans.PropertyChangeListener listener)
          Remove an object from the list of objects registered to receive notification of changes to a bounded property
 void removeThreadLocal(java.lang.Object key)
          Remove values from thread-local storage.
static void reportError(java.lang.String message)
          Report an error using the error reporter for the current thread.
static void reportError(java.lang.String message, java.lang.String sourceName, int lineno, java.lang.String lineSource, int lineOffset)
          Report an error using the error reporter for the current thread.
static org.mozilla.javascript.EvaluatorException reportRuntimeError(java.lang.String message)
          Report a runtime error using the error reporter for the current thread.
static org.mozilla.javascript.EvaluatorException reportRuntimeError(java.lang.String message, java.lang.String sourceName, int lineno, java.lang.String lineSource, int lineOffset)
          Report a runtime error using the error reporter for the current thread.
static void reportWarning(java.lang.String message)
          Report a warning using the error reporter for the current thread.
static void reportWarning(java.lang.String message, java.lang.String sourceName, int lineno, java.lang.String lineSource, int lineOffset)
          Report a warning using the error reporter for the current thread.
static void setCachingEnabled(boolean cachingEnabled)
          Set whether to cache some values statically.
 void setClassName(java.lang.String className)
          Deprecated. Use ClassNameHelper.get(cx).setClassName(className) instead.
 void setClassOutput(ClassOutput classOutput)
          Deprecated. Use ClassNameHelper.get(cx).setClassOutput(classOutput) instead.
 void setClassRepository(org.mozilla.javascript.ClassRepository classRepository)
          Deprecated. Use ClassNameHelper.get(cx).setClassRepository(classRepository) instead.
 void setClassShutter(ClassShutter shutter)
          Set the LiveConnect access filter for this context.
 void setCompileFunctionsWithDynamicScope(boolean flag)
          Set whether functions compiled by this context should use dynamic scope.
 void setDebugger(org.mozilla.javascript.debug.Debugger debugger, java.lang.Object contextData)
          Set the associated debugger.
 ErrorReporter setErrorReporter(ErrorReporter reporter)
          Change the current error reporter.
 void setGeneratingDebug(boolean generatingDebug)
          Specify whether or not debug information should be generated.
 void setGeneratingSource(boolean generatingSource)
          Specify whether or not source information should be generated.
 void setInstructionObserverThreshold(int threshold)
           
 void setLanguageVersion(int version)
          Set the language version.
 java.util.Locale setLocale(java.util.Locale loc)
          Set the current locale.
 void setOptimizationLevel(int optimizationLevel)
          Set the current optimization level.
 void setSecurityController(SecurityController controller)
          Set the security controller for this context.
 void setSecuritySupport(SecuritySupport x)
          Deprecated. The SecuritySupport class is deprecated. See its documentation for the upgrade path.
 void setTargetClassFileName(java.lang.String classFileName)
          Deprecated. Use ClassNameHelper.get(cx).setTargetClassFileName(classFileName) instead.
 void setTargetExtends(java.lang.Class extendsClass)
          Deprecated. Use ClassNameHelper.get(cx).setTargetExtends(extendsClass) instead.
 void setTargetImplements(java.lang.Class[] implementsClasses)
          Deprecated. Use ClassNameHelper.get(cx).setTargetImplements(implementsClasses) instead.
 void setTargetPackage(java.lang.String targetPackage)
          Deprecated. Use ClassNameHelper.get(cx).setTargetPackage(targetPackage) instead.
 void setWrapFactory(WrapFactory wrapFactory)
          Set a WrapFactory for this Context.
 void setWrapHandler(WrapHandler wrapHandler)
          Deprecated. As of Rhino 1.5 Release 4, use WrapFactory and setWrapFactory(WrapFactory)
 boolean stringIsCompilableUnit(java.lang.String source)
          Check whether a string is ready to be compiled.
static boolean toBoolean(java.lang.Object value)
          Convert the value to a JavaScript boolean value.
static double toNumber(java.lang.Object value)
          Convert the value to a JavaScript Number value.
static Scriptable toObject(java.lang.Object value, Scriptable scope)
          Convert the value to an JavaScript object value.
static Scriptable toObject(java.lang.Object value, Scriptable scope, java.lang.Class staticType)
          Convert the value to an JavaScript object value.
static java.lang.String toString(java.lang.Object value)
          Convert the value to a JavaScript String value.
static java.lang.Object toType(java.lang.Object value, java.lang.Class desiredType)
          Convert a JavaScript value into the desired type.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

languageVersionProperty

public static final java.lang.String languageVersionProperty

errorReporterProperty

public static final java.lang.String errorReporterProperty

VERSION_UNKNOWN

public static final int VERSION_UNKNOWN
The unknown version.

VERSION_DEFAULT

public static final int VERSION_DEFAULT
The default version.

VERSION_1_0

public static final int VERSION_1_0
JavaScript 1.0

VERSION_1_1

public static final int VERSION_1_1
JavaScript 1.1

VERSION_1_2

public static final int VERSION_1_2
JavaScript 1.2

VERSION_1_3

public static final int VERSION_1_3
JavaScript 1.3

VERSION_1_4

public static final int VERSION_1_4
JavaScript 1.4

VERSION_1_5

public static final int VERSION_1_5
JavaScript 1.5

FEATURE_NON_ECMA_GET_YEAR

public static final int FEATURE_NON_ECMA_GET_YEAR
if hasFeature(FEATURE_NON_ECMA_GET_YEAR) returns true, Date.prototype.getYear subtructs 1900 only if 1900 <= date < 2000 in deviation with Ecma B.2.4

FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME

public static final int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME
if hasFeature(FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME) returns true, allow 'function (...) { ... }' to be syntax sugar for ' = function(...) { ... }', when is not simply identifier. See Ecma-262, section 11.2 for definition of

FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER

public static final int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER
if hasFeature(RESERVED_KEYWORD_AS_IDENTIFIER) returns true, treat future reserved keyword (see Ecma-262, section 7.5.3) as ordinary identifiers but warn about this usage

FEATURE_TO_STRING_AS_SOURCE

public static final int FEATURE_TO_STRING_AS_SOURCE
if hasFeature(FEATURE_TO_STRING_AS_SOURCE) returns true, calling toString on JS objects gives JS source with code to create an object with all enumeratable fields of the original object instead of printing "[object ]". By default hasFeature(int) returns true only if the current JS version is set to VERSION_1_2.
Constructor Detail

Context

public Context()
Create a new Context. Note that the Context must be associated with a thread before it can be used to execute a script.
See Also:
enter()

Context

public Context(SecuritySupport x)
Deprecated. The SecuritySupport class is deprecated. See its documentation for the upgrade path.

Method Detail

enter

public static Context enter()
Get a context associated with the current thread, creating one if need be. The Context stores the execution state of the JavaScript engine, so it is required that the context be entered before execution may begin. Once a thread has entered a Context, then getCurrentContext() may be called to find the context that is associated with the current thread.

Calling enter() will return either the Context currently associated with the thread, or will create a new context and associate it with the current thread. Each call to enter() must have a matching call to exit(). For example,

      Context cx = Context.enter();
      try {
          ...
          cx.evaluateString(...);
      }
      finally { Context.exit(); }
 
Returns:
a Context associated with the current thread
See Also:
getCurrentContext(), exit()

enter

public static Context enter(Context cx)
Get a Context associated with the current thread, using the given Context if need be.

The same as enter() except that cx is associated with the current thread and returned if the current thread has no associated context and cx is not associated with any other thread.

Parameters:
cx - a Context to associate with the thread if possible
Returns:
a Context associated with the current thread

exit

public static void exit()
Exit a block of code requiring a Context. Calling exit() will remove the association between the current thread and a Context if the prior call to enter() on this thread newly associated a Context with this thread. Once the current thread no longer has an associated Context, it cannot be used to execute JavaScript until it is again associated with a Context.
See Also:
enter()

addContextListener

public static void addContextListener(ContextListener listener)
Add a Context listener.

removeContextListener

public static void removeContextListener(ContextListener listener)
Remove a Context listener.
Parameters:
listener - the listener to remove.

getCurrentContext

public static Context getCurrentContext()
Get the current Context. The current Context is per-thread; this method looks up the Context associated with the current thread.

Returns:
the Context associated with the current thread, or null if no context is associated with the current thread.
See Also:
enter(), exit()

getLanguageVersion

public int getLanguageVersion()
Get the current language version.

The language version number affects JavaScript semantics as detailed in the overview documentation.

Returns:
an integer that is one of VERSION_1_0, VERSION_1_1, etc.

setLanguageVersion

public void setLanguageVersion(int version)
Set the language version.

Setting the language version will affect functions and scripts compiled subsequently. See the overview documentation for version-specific behavior.

Parameters:
version - the version as specified by VERSION_1_0, VERSION_1_1, etc.

getImplementationVersion

public java.lang.String getImplementationVersion()
Get the implementation version.

The implementation version is of the form

    "name langVer release relNum date"
 
where name is the name of the product, langVer is the language version, relNum is the release number, and date is the release date for that specific release in the form "yyyy mm dd".
Returns:
a string that encodes the product, language version, release number, and date.

getErrorReporter

public ErrorReporter getErrorReporter()
Get the current error reporter.
See Also:
ErrorReporter

setErrorReporter

public ErrorReporter setErrorReporter(ErrorReporter reporter)
Change the current error reporter.
Returns:
the previous error reporter
See Also:
ErrorReporter

getLocale

public java.util.Locale getLocale()
Get the current locale. Returns the default locale if none has been set.
See Also:
Locale

setLocale

public java.util.Locale setLocale(java.util.Locale loc)
Set the current locale.
See Also:
Locale

addPropertyChangeListener

public void addPropertyChangeListener(java.beans.PropertyChangeListener listener)
Register an object to receive notifications when a bound property has changed
Parameters:
listener - the listener
See Also:
PropertyChangeEvent, removePropertyChangeListener(java.beans.PropertyChangeListener)

removePropertyChangeListener

public void removePropertyChangeListener(java.beans.PropertyChangeListener listener)
Remove an object from the list of objects registered to receive notification of changes to a bounded property
Parameters:
listener - the listener
See Also:
PropertyChangeEvent, addPropertyChangeListener(java.beans.PropertyChangeListener)

reportWarning

public static void reportWarning(java.lang.String message,
                                 java.lang.String sourceName,
                                 int lineno,
                                 java.lang.String lineSource,
                                 int lineOffset)
Report a warning using the error reporter for the current thread.
Parameters:
message - the warning message to report
sourceName - a string describing the source, such as a filename
lineno - the starting line number
lineSource - the text of the line (may be null)
lineOffset - the offset into lineSource where problem was detected
See Also:
ErrorReporter

reportWarning

public static void reportWarning(java.lang.String message)
Report a warning using the error reporter for the current thread.
Parameters:
message - the warning message to report
See Also:
ErrorReporter

reportError

public static void reportError(java.lang.String message,
                               java.lang.String sourceName,
                               int lineno,
                               java.lang.String lineSource,
                               int lineOffset)
Report an error using the error reporter for the current thread.
Parameters:
message - the error message to report
sourceName - a string describing the source, such as a filename
lineno - the starting line number
lineSource - the text of the line (may be null)
lineOffset - the offset into lineSource where problem was detected
See Also:
ErrorReporter

reportError

public static void reportError(java.lang.String message)
Report an error using the error reporter for the current thread.
Parameters:
message - the error message to report
See Also:
ErrorReporter

reportRuntimeError

public static org.mozilla.javascript.EvaluatorException reportRuntimeError(java.lang.String message,
                                                                           java.lang.String sourceName,
                                                                           int lineno,
                                                                           java.lang.String lineSource,
                                                                           int lineOffset)
Report a runtime error using the error reporter for the current thread.
Parameters:
message - the error message to report
sourceName - a string describing the source, such as a filename
lineno - the starting line number
lineSource - the text of the line (may be null)
lineOffset - the offset into lineSource where problem was detected
Returns:
a runtime exception that will be thrown to terminate the execution of the script
See Also:
ErrorReporter

reportRuntimeError

public static org.mozilla.javascript.EvaluatorException reportRuntimeError(java.lang.String message)
Report a runtime error using the error reporter for the current thread.
Parameters:
message - the error message to report
See Also:
ErrorReporter

initStandardObjects

public Scriptable initStandardObjects(ScriptableObject scope)
Initialize the standard objects. Creates instances of the standard objects and their constructors (Object, String, Number, Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1.

This method must be called to initialize a scope before scripts can be evaluated in that scope.

This method does not affect the Context it is called upon.

Parameters:
scope - the scope to initialize, or null, in which case a new object will be created to serve as the scope
Returns:
the initialized scope

initStandardObjects

public ScriptableObject initStandardObjects(ScriptableObject scope,
                                            boolean sealed)
Initialize the standard objects. Creates instances of the standard objects and their constructors (Object, String, Number, Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1.

This method must be called to initialize a scope before scripts can be evaluated in that scope.

This method does not affect the Context it is called upon.

This form of the method also allows for creating "sealed" standard objects. An object that is sealed cannot have properties added or removed. This is useful to create a "superglobal" that can be shared among several top-level objects. Note that sealing is not allowed in the current ECMA/ISO language specification, but is likely for the next version.

Parameters:
scope - the scope to initialize, or null, in which case a new object will be created to serve as the scope
sealed - whether or not to create sealed standard objects that cannot be modified.
Returns:
the initialized scope
Since:
1.4R3

getUndefinedValue

public static java.lang.Object getUndefinedValue()
Get the singleton object that represents the JavaScript Undefined value.

evaluateString

public java.lang.Object evaluateString(Scriptable scope,
                                       java.lang.String source,
                                       java.lang.String sourceName,
                                       int lineno,
                                       java.lang.Object securityDomain)
                                throws JavaScriptException
Evaluate a JavaScript source string. The provided source name and line number are used for error messages and for producing debug information.
Parameters:
scope - the scope to execute in
source - the JavaScript source
sourceName - a string describing the source, such as a filename
lineno - the starting line number
securityDomain - an arbitrary object that specifies security information about the origin or owner of the script. For implementations that don't care about security, this value may be null.
Returns:
the result of evaluating the string
Throws:
JavaScriptException - if an uncaught JavaScript exception occurred while evaluating the source string
See Also:
SecuritySupport

evaluateReader

public java.lang.Object evaluateReader(Scriptable scope,
                                       java.io.Reader in,
                                       java.lang.String sourceName,
                                       int lineno,
                                       java.lang.Object securityDomain)
                                throws java.io.IOException,
                                       JavaScriptException
Evaluate a reader as JavaScript source. All characters of the reader are consumed.
Parameters:
scope - the scope to execute in
in - the Reader to get JavaScript source from
sourceName - a string describing the source, such as a filename
lineno - the starting line number
securityDomain - an arbitrary object that specifies security information about the origin or owner of the script. For implementations that don't care about security, this value may be null.
Returns:
the result of evaluating the source
Throws:
java.io.IOException - if an IOException was generated by the Reader
JavaScriptException - if an uncaught JavaScript exception occurred while evaluating the Reader

stringIsCompilableUnit

public boolean stringIsCompilableUnit(java.lang.String source)
Check whether a string is ready to be compiled.

stringIsCompilableUnit is intended to support interactive compilation of javascript. If compiling the string would result in an error that might be fixed by appending more source, this method returns false. In every other case, it returns true.

Interactive shells may accumulate source lines, using this method after each new line is appended to check whether the statement being entered is complete.

Parameters:
source - the source buffer to check
Returns:
whether the source is ready for compilation
Since:
1.4 Release 2

compileReader

public Script compileReader(Scriptable scope,
                            java.io.Reader in,
                            java.lang.String sourceName,
                            int lineno,
                            java.lang.Object securityDomain)
                     throws java.io.IOException
Compiles the source in the given reader.

Returns a script that may later be executed. Will consume all the source in the reader.

Parameters:
scope - if nonnull, will be the scope in which the script object is created. The script object will be a valid JavaScript object as if it were created using the JavaScript1.3 Script constructor
in - the input reader
sourceName - a string describing the source, such as a filename
lineno - the starting line number for reporting errors
securityDomain - an arbitrary object that specifies security information about the origin or owner of the script. For implementations that don't care about security, this value may be null.
Returns:
a script that may later be executed
Throws:
java.io.IOException - if an IOException was generated by the Reader
See Also:
Script.exec(org.mozilla.javascript.Context, org.mozilla.javascript.Scriptable)

compileFunction

public Function compileFunction(Scriptable scope,
                                java.lang.String source,
                                java.lang.String sourceName,
                                int lineno,
                                java.lang.Object securityDomain)
Compile a JavaScript function.

The function source must be a function definition as defined by ECMA (e.g., "function f(a) { return a; }").

Parameters:
scope - the scope to compile relative to
source - the function definition source
sourceName - a string describing the source, such as a filename
lineno - the starting line number
securityDomain - an arbitrary object that specifies security information about the origin or owner of the script. For implementations that don't care about security, this value may be null.
Returns:
a Function that may later be called
See Also:
Function

decompileScript

public java.lang.String decompileScript(Script script,
                                        Scriptable scope,
                                        int indent)
Decompile the script.

The canonical source of the script is returned.

Parameters:
script - the script to decompile
scope - the scope under which to decompile
indent - the number of spaces to indent the result
Returns:
a string representing the script source

decompileFunction

public java.lang.String decompileFunction(Function fun,
                                          int indent)
Decompile a JavaScript Function.

Decompiles a previously compiled JavaScript function object to canonical source.

Returns function body of '[native code]' if no decompilation information is available.

Parameters:
fun - the JavaScript function to decompile
indent - the number of spaces to indent the result
Returns:
a string representing the function source

decompileFunctionBody

public java.lang.String decompileFunctionBody(Function fun,
                                              int indent)
Decompile the body of a JavaScript Function.

Decompiles the body a previously compiled JavaScript Function object to canonical source, omitting the function header and trailing brace. Returns '[native code]' if no decompilation information is available.

Parameters:
fun - the JavaScript function to decompile
indent - the number of spaces to indent the result
Returns:
a string representing the function body source.

newObject

public Scriptable newObject(Scriptable scope)
                     throws PropertyException,
                            NotAFunctionException,
                            JavaScriptException
Create a new JavaScript object. Equivalent to evaluating "new Object()".
Parameters:
scope - the scope to search for the constructor and to evaluate against
Returns:
the new object
Throws:
PropertyException - if "Object" cannot be found in the scope
NotAFunctionException - if the "Object" found in the scope is not a function
JavaScriptException - if an uncaught JavaScript exception occurred while creating the object

newObject

public Scriptable newObject(Scriptable scope,
                            java.lang.String constructorName)
                     throws PropertyException,
                            NotAFunctionException,
                            JavaScriptException
Create a new JavaScript object by executing the named constructor. The call newObject(scope, "Foo") is equivalent to evaluating "new Foo()".
Parameters:
scope - the scope to search for the constructor and to evaluate against
constructorName - the name of the constructor to call
Returns:
the new object
Throws:
PropertyException - if a property with the constructor name cannot be found in the scope
NotAFunctionException - if the property found in the scope is not a function
JavaScriptException - if an uncaught JavaScript exception occurred while creating the object

newObject

public Scriptable newObject(Scriptable scope,
                            java.lang.String constructorName,
                            java.lang.Object[] args)
                     throws PropertyException,
                            NotAFunctionException,
                            JavaScriptException
Creates a new JavaScript object by executing the named constructor. Searches scope for the named constructor, calls it with the given arguments, and returns the result.

The code

 Object[] args = { "a", "b" };
 newObject(scope, "Foo", args)
is equivalent to evaluating "new Foo('a', 'b')", assuming that the Foo constructor has been defined in scope.
Parameters:
scope - The scope to search for the constructor and to evaluate against
constructorName - the name of the constructor to call
args - the array of arguments for the constructor
Returns:
the new object
Throws:
PropertyException - if a property with the constructor name cannot be found in the scope
NotAFunctionException - if the property found in the scope is not a function
JavaScriptException - if an uncaught JavaScript exception occurs while creating the object

newArray

public Scriptable newArray(Scriptable scope,
                           int length)
Create an array with a specified initial length.

Parameters:
scope - the scope to create the object in
length - the initial length (JavaScript arrays may have additional properties added dynamically).
Returns:
the new array object

newArray

public Scriptable newArray(Scriptable scope,
                           java.lang.Object[] elements)
Create an array with a set of initial elements.

Parameters:
scope - the scope to create the object in
elements - the initial elements. Each object in this array must be an acceptable JavaScript type.
Returns:
the new array object

getElements

public java.lang.Object[] getElements(Scriptable object)
Get the elements of a JavaScript array.

If the object defines a length property which can be converted to a number a Java array with length given by ScriptRuntime#toUint32(double) is created and initialized with the values obtained by calling get() on object for each value of i in [0,length-1]. If there is not a defined value for a property the Undefined value is used to initialize the corresponding element in the array. The Java array is then returned. If the object doesn't define a length property or it is not a number, empty array is returned.

Parameters:
object - the JavaScript array or array-like object
Returns:
a Java array of objects
Since:
1.4 release 2

toBoolean

public static boolean toBoolean(java.lang.Object value)
Convert the value to a JavaScript boolean value.

See ECMA 9.2.

Parameters:
value - a JavaScript value
Returns:
the corresponding boolean value converted using the ECMA rules

toNumber

public static double toNumber(java.lang.Object value)
Convert the value to a JavaScript Number value.

Returns a Java double for the JavaScript Number.

See ECMA 9.3.

Parameters:
value - a JavaScript value
Returns:
the corresponding double value converted using the ECMA rules

toString

public static java.lang.String toString(java.lang.Object value)
Convert the value to a JavaScript String value.

See ECMA 9.8.

Parameters:
value - a JavaScript value
Returns:
the corresponding String value converted using the ECMA rules

toObject

public static Scriptable toObject(java.lang.Object value,
                                  Scriptable scope)
Convert the value to an JavaScript object value.

Note that a scope must be provided to look up the constructors for Number, Boolean, and String.

See ECMA 9.9.

Additionally, arbitrary Java objects and classes will be wrapped in a Scriptable object with its Java fields and methods reflected as JavaScript properties of the object.

Parameters:
value - any Java object
scope - global scope containing constructors for Number, Boolean, and String
Returns:
new JavaScript object

toObject

public static Scriptable toObject(java.lang.Object value,
                                  Scriptable scope,
                                  java.lang.Class staticType)
Convert the value to an JavaScript object value.

Note that a scope must be provided to look up the constructors for Number, Boolean, and String.

See ECMA 9.9.

Additionally, arbitrary Java objects and classes will be wrapped in a Scriptable object with its Java fields and methods reflected as JavaScript properties of the object. If the "staticType" parameter is provided, it will be used as the static type of the Java value to create.

Parameters:
value - any Java object
scope - global scope containing constructors for Number, Boolean, and String
staticType - the static type of the Java value to create
Returns:
new JavaScript object

toType

public static java.lang.Object toType(java.lang.Object value,
                                      java.lang.Class desiredType)
                               throws java.lang.IllegalArgumentException
Convert a JavaScript value into the desired type. Uses the semantics defined with LiveConnect3 and throws an Illegal argument exception if the conversion cannot be performed.
Parameters:
value - the JavaScript value to convert
desired - type the Java type to convert to. Primitive Java types are represented using the TYPE fields in the corresponding wrapper class in java.lang.
Returns:
the converted value
Throws:
java.lang.IllegalArgumentException - if the conversion cannot be performed

isGeneratingDebug

public boolean isGeneratingDebug()
Tell whether debug information is being generated.
Since:
1.3

setGeneratingDebug

public void setGeneratingDebug(boolean generatingDebug)
Specify whether or not debug information should be generated.

Setting the generation of debug information on will set the optimization level to zero.

Since:
1.3

isGeneratingSource

public boolean isGeneratingSource()
Tell whether source information is being generated.
Since:
1.3

setGeneratingSource

public void setGeneratingSource(boolean generatingSource)
Specify whether or not source information should be generated.

Without source information, evaluating the "toString" method on JavaScript functions produces only "[native code]" for the body of the function. Note that code generated without source is not fully ECMA conformant.

Since:
1.3

getOptimizationLevel

public int getOptimizationLevel()
Get the current optimization level.

The optimization level is expressed as an integer between -1 and 9.

Since:
1.3

setOptimizationLevel

public void setOptimizationLevel(int optimizationLevel)
Set the current optimization level.

The optimization level is expected to be an integer between -1 and 9. Any negative values will be interpreted as -1, and any values greater than 9 will be interpreted as 9. An optimization level of -1 indicates that interpretive mode will always be used. Levels 0 through 9 indicate that class files may be generated. Higher optimization levels trade off compile time performance for runtime performance. The optimizer level can't be set greater than -1 if the optimizer package doesn't exist at run time.

Parameters:
optimizationLevel - an integer indicating the level of optimization to perform
Since:
1.3

getClassName

public java.lang.String getClassName()
Deprecated. Use ClassNameHelper.get(cx).getClassName() instead.

See Also:
ClassNameHelper#getClassName

setClassName

public void setClassName(java.lang.String className)
Deprecated. Use ClassNameHelper.get(cx).setClassName(className) instead.

See Also:
ClassNameHelper#setClassName

getTargetClassFileName

public java.lang.String getTargetClassFileName()
Deprecated. Use ClassNameHelper.get(cx).getTargetClassFileName() instead.

See Also:
ClassNameHelper#getTargetClassFileName

setTargetClassFileName

public void setTargetClassFileName(java.lang.String classFileName)
Deprecated. Use ClassNameHelper.get(cx).setTargetClassFileName(classFileName) instead.

See Also:
ClassNameHelper#setTargetClassFileName

getTargetPackage

public java.lang.String getTargetPackage()
Deprecated. Use ClassNameHelper.get(cx).getTargetPackage() instead.

See Also:
ClassNameHelper#getTargetPackage

setTargetPackage

public void setTargetPackage(java.lang.String targetPackage)
Deprecated. Use ClassNameHelper.get(cx).setTargetPackage(targetPackage) instead.

See Also:
ClassNameHelper#setTargetPackage

getClassRepository

public org.mozilla.javascript.ClassRepository getClassRepository()
Deprecated. Use ClassNameHelper.get(cx).getClassRepository() instead.

See Also:
ClassNameHelper#getClassRepository

setClassRepository

public void setClassRepository(org.mozilla.javascript.ClassRepository classRepository)
Deprecated. Use ClassNameHelper.get(cx).setClassRepository(classRepository) instead.

See Also:
ClassNameHelper#setClassRepository

getClassOutput

public ClassOutput getClassOutput()
Deprecated. Use ClassNameHelper.get(cx).getClassOutput() instead.

See Also:
ClassNameHelper#getClassOutput

setClassOutput

public void setClassOutput(ClassOutput classOutput)
Deprecated. Use ClassNameHelper.get(cx).setClassOutput(classOutput) instead.

See Also:
ClassNameHelper#setClassOutput

setSecurityController

public void setSecurityController(SecurityController controller)
Set the security controller for this context.

SecurityController may only be set if it is currently null. Otherwise a SecurityException is thrown.

Parameters:
controller - a SecurityController object
Throws:
java.lang.SecurityException - if there is already a SecurityController object for this Context

setSecuritySupport

public void setSecuritySupport(SecuritySupport x)
Deprecated. The SecuritySupport class is deprecated. See its documentation for the upgrade path.


setClassShutter

public void setClassShutter(ClassShutter shutter)
Set the LiveConnect access filter for this context.

ClassShutter may only be set if it is currently null. Otherwise a SecurityException is thrown.

Parameters:
shutter - a ClassShutter object
Throws:
java.lang.SecurityException - if there is already a ClassShutter object for this Context

setTargetExtends

public void setTargetExtends(java.lang.Class extendsClass)
Deprecated. Use ClassNameHelper.get(cx).setTargetExtends(extendsClass) instead.

See Also:
ClassNameHelper#setTargetExtends

setTargetImplements

public void setTargetImplements(java.lang.Class[] implementsClasses)
Deprecated. Use ClassNameHelper.get(cx).setTargetImplements(implementsClasses) instead.

See Also:
ClassNameHelper#setTargetImplements

getThreadLocal

public final java.lang.Object getThreadLocal(java.lang.Object key)
Get a value corresponding to a key.

Since the Context is associated with a thread it can be used to maintain values that can be later retrieved using the current thread.

Note that the values are maintained with the Context, so if the Context is disassociated from the thread the values cannot be retreived. Also, if private data is to be maintained in this manner the key should be a java.lang.Object whose reference is not divulged to untrusted code.

Parameters:
key - the key used to lookup the value
Returns:
a value previously stored using putThreadLocal.

putThreadLocal

public void putThreadLocal(java.lang.Object key,
                           java.lang.Object value)
Put a value that can later be retrieved using a given key.

Parameters:
key - the key used to index the value
value - the value to save

removeThreadLocal

public void removeThreadLocal(java.lang.Object key)
Remove values from thread-local storage.
Parameters:
key - the key for the entry to remove.
Since:
1.5 release 2

hasCompileFunctionsWithDynamicScope

public final boolean hasCompileFunctionsWithDynamicScope()
Return whether functions are compiled by this context using dynamic scope.

If functions are compiled with dynamic scope, then they execute in the scope of their caller, rather than in their parent scope. This is useful for sharing functions across multiple scopes.

Since:
1.5 Release 1

setCompileFunctionsWithDynamicScope

public void setCompileFunctionsWithDynamicScope(boolean flag)
Set whether functions compiled by this context should use dynamic scope.

Parameters:
flag - if true, compile functions with dynamic scope
Since:
1.5 Release 1

setCachingEnabled

public static void setCachingEnabled(boolean cachingEnabled)
Set whether to cache some values statically.

By default, the engine will cache some values statically (reflected Java classes, for instance). This can speed execution dramatically, but increases the memory footprint. Also, with caching enabled, references may be held to objects past the lifetime of any real usage.

If caching is enabled and this method is called with a false argument, the caches will be emptied. So one strategy could be to clear the caches at times appropriate to the application.

Caching is enabled by default.

Parameters:
cachingEnabled - if true, caching is enabled
Since:
1.5 Release 1

setWrapHandler

public void setWrapHandler(WrapHandler wrapHandler)
Deprecated. As of Rhino 1.5 Release 4, use WrapFactory and setWrapFactory(WrapFactory)


getWrapHandler

public WrapHandler getWrapHandler()
Deprecated. As of Rhino 1.5 Release 4, use WrapFactory and getWrapFactory()


setWrapFactory

public void setWrapFactory(WrapFactory wrapFactory)
Set a WrapFactory for this Context.

The WrapFactory allows custom object wrapping behavior for Java object manipulated with JavaScript.

Since:
1.5 Release 4
See Also:
WrapFactory

getWrapFactory

public final WrapFactory getWrapFactory()
Return the current WrapHandler, or null if none is defined.
Since:
1.5 Release 4
See Also:
WrapHandler

getDebugger

public final org.mozilla.javascript.debug.Debugger getDebugger()
Return the current debugger.
Returns:
the debugger, or null if none is attached.

getDebuggerContextData

public final java.lang.Object getDebuggerContextData()
Return the debugger context data associated with current context.
Returns:
the debugger data, or null if debugger is not attached

setDebugger

public void setDebugger(org.mozilla.javascript.debug.Debugger debugger,
                        java.lang.Object contextData)
Set the associated debugger.
Parameters:
debugger - the debugger to be used on callbacks from the engine.
contextData - arbitrary object that debugger can use to store per Context data.

hasFeature

public boolean hasFeature(int featureIndex)
Controls certain aspects of script semantics. Should be overwritten to alter default behavior.
Parameters:
featureIndex - feature index to check
Returns:
true if the featureIndex feature is turned on
See Also:
FEATURE_NON_ECMA_GET_YEAR, FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME, FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER, FEATURE_TO_STRING_AS_SOURCE

getInstructionObserverThreshold

public int getInstructionObserverThreshold()
Get/Set threshold of executed instructions counter that triggers call to observeInstructionCount(). When the threshold is zero, instruction counting is disabled, otherwise each time the run-time executes at least the threshold value of script instructions, observeInstructionCount() will be called.

setInstructionObserverThreshold

public void setInstructionObserverThreshold(int threshold)

createClassLoader

public org.mozilla.javascript.GeneratedClassLoader createClassLoader(java.lang.ClassLoader parent)

isGeneratingDebugChanged

public boolean isGeneratingDebugChanged()

addActivationName

public void addActivationName(java.lang.String name)
Add a name to the list of names forcing the creation of real activation objects for functions.
Parameters:
name - the name of the object to add to the list

isActivationNeeded

public boolean isActivationNeeded(java.lang.String name)
Check whether the name is in the list of names of objects forcing the creation of activation objects.
Parameters:
name - the name of the object to test
Returns:
true if an function activation object is needed.

removeActivationName

public void removeActivationName(java.lang.String name)
Remove a name from the list of names forcing the creation of real activation objects for functions.
Parameters:
name - the name of the object to remove from the list