org.mozilla.javascript

Class Context

public class Context extends 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 call or enter methods.

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 Object[]emptyArgs
Convinient value to use as zero-length array of objects.
static StringerrorReporterProperty
static intFEATURE_DYNAMIC_SCOPE
Control if dynamic scope should be used for name access.
static intFEATURE_E4X
Control if support for E4X(ECMAScript for XML) extension is available.
static intFEATURE_MEMBER_EXPR_AS_FUNCTION_NAME
Control if member expression as function name extension is available.
static intFEATURE_NON_ECMA_GET_YEAR
Controls behaviour of Date.prototype.getYear().
static intFEATURE_PARENT_PROTO_PROPRTIES
Control if properties __proto__ and __parent__ are treated specially.
static intFEATURE_RESERVED_KEYWORD_AS_IDENTIFIER
Control if reserved keywords are treated as identifiers.
static intFEATURE_STRICT_EVAL
Control if strict eval mode is enabled.
static intFEATURE_STRICT_VARS
Control if strict variable mode is enabled.
static intFEATURE_TO_STRING_AS_SOURCE
Control if toString() should returns the same result as toSource() when applied to objects and arrays.
static StringlanguageVersionProperty
static intVERSION_1_0
JavaScript 1.0
static intVERSION_1_1
JavaScript 1.1
static intVERSION_1_2
JavaScript 1.2
static intVERSION_1_3
JavaScript 1.3
static intVERSION_1_4
JavaScript 1.4
static intVERSION_1_5
JavaScript 1.5
static intVERSION_1_6
JavaScript 1.5
static intVERSION_DEFAULT
The default version.
static intVERSION_UNKNOWN
The unknown version.
Constructor Summary
Context()
Create a new Context.
Method Summary
voidaddActivationName(String name)
Add a name to the list of names forcing the creation of real activation objects for functions.
static voidaddContextListener(ContextListener listener)
voidaddPropertyChangeListener(PropertyChangeListener l)
Register an object to receive notifications when a bound property has changed
static Objectcall(ContextAction action)
Call ContextAction using the Context instance associated with the current thread.
static Objectcall(ContextFactory factory, Callable callable, Scriptable scope, Scriptable thisObj, Object[] args)
Call (Context cx, Scriptable scope, Scriptable thisObj, Object[] args) using the Context instance associated with the current thread.
static voidcheckLanguageVersion(int version)
static voidcheckOptimizationLevel(int optimizationLevel)
FunctioncompileFunction(Scriptable scope, String source, String sourceName, int lineno, Object securityDomain)
Compile a JavaScript function.
ScriptcompileReader(Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain)
ScriptcompileReader(Reader in, String sourceName, int lineno, Object securityDomain)
Compiles the source in the given reader.
ScriptcompileString(String source, String sourceName, int lineno, Object securityDomain)
Compiles the source in the given string.
StringcompressReader(Scriptable scope, Script script, String source, String sourceName, int lineno, Object securityDomain)
StringcompressScript(Script script, int indent, String source, int lineno)
Compress the script.
GeneratedClassLoadercreateClassLoader(ClassLoader parent)
Create class loader for generated classes.
StringdecompileFunction(Function fun, int indent)
Decompile a JavaScript Function.
StringdecompileFunctionBody(Function fun, int indent)
Decompile the body of a JavaScript Function.
StringdecompileReader(Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain)
StringdecompileScript(Script script, int indent)
Decompile the script.
static Contextenter()
Get a context associated with the current thread, creating one if need be.
static Contextenter(Context cx)
Get a Context associated with the current thread, using the given Context if need be.
ObjectevaluateReader(Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain)
Evaluate a reader as JavaScript source.
ObjectevaluateString(Scriptable scope, String source, String sourceName, int lineno, Object securityDomain)
Evaluate a JavaScript source string.
static voidexit()
Exit a block of code requiring a Context.
ClassLoadergetApplicationClassLoader()
static ContextgetCurrentContext()
Get the current Context.
static DebuggableScriptgetDebuggableView(Script script)
Return DebuggableScript instance if any associated with the script.
DebuggergetDebugger()
Return the current debugger.
ObjectgetDebuggerContextData()
Return the debugger context data associated with current context.
Object[]getElements(Scriptable object)
Get the elements of a JavaScript array.
ErrorReportergetErrorReporter()
Get the current error reporter.
ContextFactorygetFactory()
Return ContextFactory instance used to create this Context or the result of getGlobal if no factory was used for Context creation.
StringgetImplementationVersion()
Get the implementation version.
intgetInstructionObserverThreshold()
Get/Set threshold of executed instructions counter that triggers call to observeInstructionCount().
intgetLanguageVersion()
Get the current language version.
LocalegetLocale()
Get the current locale.
intgetMaximumInterpreterStackDepth()
Returns the maximum stack depth (in terms of number of call frames) allowed in a single invocation of interpreter.
intgetOptimizationLevel()
Get the current optimization level.
ObjectgetThreadLocal(Object key)
Get a value corresponding to a key.
static ObjectgetUndefinedValue()
Get the singleton object that represents the JavaScript Undefined value.
WrapFactorygetWrapFactory()
Return the current WrapFactory, or null if none is defined.
booleanhasCompileFunctionsWithDynamicScope()
booleanhasFeature(int featureIndex)
Controls certain aspects of script semantics.
ScriptableObjectinitStandardObjects()
Initialize the standard objects.
ScriptableinitStandardObjects(ScriptableObject scope)
Initialize the standard objects.
ScriptableObjectinitStandardObjects(ScriptableObject scope, boolean sealed)
Initialize the standard objects.
booleanisActivationNeeded(String name)
Check whether the name is in the list of names of objects forcing the creation of activation objects.
booleanisGeneratingDebug()
Tell whether debug information is being generated.
booleanisGeneratingDebugChanged()
booleanisGeneratingSource()
Tell whether source information is being generated.
booleanisSealed()
Checks if this is a sealed Context.
static booleanisValidLanguageVersion(int version)
static booleanisValidOptimizationLevel(int optimizationLevel)
static ObjectjavaToJS(Object value, Scriptable scope)
Convenient method to convert java value to its closest representation in JavaScript.
static ObjectjsToJava(Object value, Class desiredType)
Convert a JavaScript value into the desired type.
ScriptablenewArray(Scriptable scope, int length)
Create an array with a specified initial length.
ScriptablenewArray(Scriptable scope, Object[] elements)
Create an array with a set of initial elements.
ScriptablenewObject(Scriptable scope)
Create a new JavaScript object.
ScriptablenewObject(Scriptable scope, String constructorName)
Create a new JavaScript object by executing the named constructor.
ScriptablenewObject(Scriptable scope, String constructorName, Object[] args)
Creates a new JavaScript object by executing the named constructor.
protected voidobserveInstructionCount(int instructionCount)
Allow application to monitor counter of executed script instructions in Context subclasses.
voidputThreadLocal(Object key, Object value)
Put a value that can later be retrieved using a given key.
voidremoveActivationName(String name)
Remove a name from the list of names forcing the creation of real activation objects for functions.
static voidremoveContextListener(ContextListener listener)
voidremovePropertyChangeListener(PropertyChangeListener l)
Remove an object from the list of objects registered to receive notification of changes to a bounded property
voidremoveThreadLocal(Object key)
Remove values from thread-local storage.
static voidreportError(String message, String sourceName, int lineno, String lineSource, int lineOffset)
Report an error using the error reporter for the current thread.
static voidreportError(String message)
Report an error using the error reporter for the current thread.
static EvaluatorExceptionreportRuntimeError(String message, String sourceName, int lineno, String lineSource, int lineOffset)
Report a runtime error using the error reporter for the current thread.
static EvaluatorExceptionreportRuntimeError(String message)
Report a runtime error using the error reporter for the current thread.
static voidreportWarning(String message, String sourceName, int lineno, String lineSource, int lineOffset)
Report a warning using the error reporter for the current thread.
static voidreportWarning(String message)
Report a warning using the error reporter for the current thread.
voidseal(Object sealKey)
Seal this Context object so any attempt to modify any of its properties including calling enter and exit methods will throw an exception.
voidsetApplicationClassLoader(ClassLoader loader)
static voidsetCachingEnabled(boolean cachingEnabled)
voidsetClassShutter(ClassShutter shutter)
Set the LiveConnect access filter for this context.
voidsetCompileFunctionsWithDynamicScope(boolean flag)
voidsetDebugger(Debugger debugger, Object contextData)
Set the associated debugger.
ErrorReportersetErrorReporter(ErrorReporter reporter)
Change the current error reporter.
voidsetGeneratingDebug(boolean generatingDebug)
Specify whether or not debug information should be generated.
voidsetGeneratingSource(boolean generatingSource)
Specify whether or not source information should be generated.
voidsetInstructionObserverThreshold(int threshold)
voidsetLanguageVersion(int version)
Set the language version.
LocalesetLocale(Locale loc)
Set the current locale.
voidsetMaximumInterpreterStackDepth(int max)
Sets the maximum stack depth (in terms of number of call frames) allowed in a single invocation of interpreter.
voidsetOptimizationLevel(int optimizationLevel)
Set the current optimization level.
voidsetSecurityController(SecurityController controller)
Set the security controller for this context.
voidsetWrapFactory(WrapFactory wrapFactory)
Set a WrapFactory for this Context.
booleanstringIsCompilableUnit(String source)
Check whether a string is ready to be compiled.
static RuntimeExceptionthrowAsScriptRuntimeEx(Throwable e)
Rethrow the exception wrapping it as the script runtime exception.
static booleantoBoolean(Object value)
Convert the value to a JavaScript boolean value.
static doubletoNumber(Object value)
Convert the value to a JavaScript Number value.
static ScriptabletoObject(Object value, Scriptable scope)
Convert the value to an JavaScript object value.
static ScriptabletoObject(Object value, Scriptable scope, Class staticType)
static StringtoString(Object value)
Convert the value to a JavaScript String value.
static ObjecttoType(Object value, Class desiredType)
voidunseal(Object sealKey)
Unseal previously sealed Context object.

Field Detail

emptyArgs

public static final Object[] emptyArgs
Convinient value to use as zero-length array of objects.

errorReporterProperty

public static final String errorReporterProperty

FEATURE_DYNAMIC_SCOPE

public static final int FEATURE_DYNAMIC_SCOPE
Control if dynamic scope should be used for name access. If hasFeature(FEATURE_DYNAMIC_SCOPE) returns true, then the name lookup during name resolution will use the top scope of the script or function which is at the top of JS execution stack instead of the top scope of the script or function from the current stack frame if the top scope of the top stack frame contains the top scope of the current stack frame on its prototype chain.

This is useful to define shared scope containing functions that can be called from scripts and functions using private scopes.

By default Context returns false.

Since: 1.6 Release 1

FEATURE_E4X

public static final int FEATURE_E4X
Control if support for E4X(ECMAScript for XML) extension is available. If hasFeature(FEATURE_E4X) returns true, the XML syntax is available.

By default Context returns true if the current JS version is set to VERSION_DEFAULT or is greater then VERSION_1_6.

Since: 1.6 Release 1

FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME

public static final int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME
Control if member expression as function name extension is available. If hasFeature(FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME) returns true, allow function memberExpression(args) { body } to be syntax sugar for memberExpression = function(args) { body }, when memberExpression is not a simple identifier. See ECMAScript-262, section 11.2 for definition of memberExpression. By default Context returns false.

FEATURE_NON_ECMA_GET_YEAR

public static final int FEATURE_NON_ECMA_GET_YEAR
Controls behaviour of Date.prototype.getYear(). If hasFeature(FEATURE_NON_ECMA_GET_YEAR) returns true, Date.prototype.getYear subtructs 1900 only if 1900 <= date < 2000. The default behavior of Context is always to subtruct 1900 as rquired by ECMAScript B.2.4.

FEATURE_PARENT_PROTO_PROPRTIES

public static final int FEATURE_PARENT_PROTO_PROPRTIES
Control if properties __proto__ and __parent__ are treated specially. If hasFeature(FEATURE_PARENT_PROTO_PROPRTIES) returns true, treat __parent__ and __proto__ as special properties.

The properties allow to query and set scope and prototype chains for the objects. The special meaning of the properties is available only when they are used as the right hand side of the dot operator. For example, while x.__proto__ = y changes the prototype chain of the object x to point to y, x["__proto__"] = y simply assigns a new value to the property __proto__ in x even when the feature is on. By default Context returns true.

FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER

public static final int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER
Control if reserved keywords are treated as identifiers. 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. By default Context returns false.

FEATURE_STRICT_EVAL

public static final int FEATURE_STRICT_EVAL
Control if strict eval mode is enabled. When the feature is on Rhino reports runtime errors if non-string argument is passed to the eval function. When the feature is off eval simply return non-string argument as is without performing any evaluation as required by ECMA 262.

By default Context returns false.

Since: 1.6 Release 1

FEATURE_STRICT_VARS

public static final int FEATURE_STRICT_VARS
Control if strict variable mode is enabled. When the feature is on Rhino reports runtime errors if assignment to a global variable that does not exist is executed. When the feature is off such assignments creates new variable in the global scope as required by ECMA 262.

By default Context returns false.

Since: 1.6 Release 1

FEATURE_TO_STRING_AS_SOURCE

public static final int FEATURE_TO_STRING_AS_SOURCE
Control if toString() should returns the same result as toSource() when applied to objects and arrays. If hasFeature(FEATURE_TO_STRING_AS_SOURCE) returns true, calling toString() on JS objects gives the same result as calling toSource(). That is it returns JS source with code to create an object with all enumeratable fields of the original object instead of printing [object result of getClassName].

By default Context returns true only if the current JS version is set to VERSION_1_2.

languageVersionProperty

public static final String languageVersionProperty

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

VERSION_1_6

public static final int VERSION_1_6
JavaScript 1.5

VERSION_DEFAULT

public static final int VERSION_DEFAULT
The default version.

VERSION_UNKNOWN

public static final int VERSION_UNKNOWN
The unknown version.

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 call

Method Detail

addActivationName

public void addActivationName(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

addContextListener

public static void addContextListener(ContextListener listener)

Deprecated:

See Also: addListener getGlobal

addPropertyChangeListener

public final void addPropertyChangeListener(PropertyChangeListener l)
Register an object to receive notifications when a bound property has changed

Parameters: l the listener

See Also: java.beans.PropertyChangeEvent Context

call

public static Object call(ContextAction action)
Call ContextAction using the Context instance associated with the current thread. If no Context is associated with the thread, then ContextFactory.getGlobal().makeContext() will be called to construct new Context instance. The instance will be temporary associated with the thread during call to run.

Returns: The result of run.

call

public static Object call(ContextFactory factory, Callable callable, Scriptable scope, Scriptable thisObj, Object[] args)
Call (Context cx, Scriptable scope, Scriptable thisObj, Object[] args) using the Context instance associated with the current thread. If no Context is associated with the thread, then makeContext will be called to construct new Context instance. The instance will be temporary associated with the thread during call to run.

It is allowed to use null for factory argument in which case the factory associated with the scope will be used to create new context instances.

See Also: call

checkLanguageVersion

public static void checkLanguageVersion(int version)

checkOptimizationLevel

public static void checkOptimizationLevel(int optimizationLevel)

compileFunction

public final Function compileFunction(Scriptable scope, String source, String sourceName, int lineno, 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

compileReader

public final Script compileReader(Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain)

Deprecated:

See Also: Context

compileReader

public final Script compileReader(Reader in, String sourceName, int lineno, Object securityDomain)
Compiles the source in the given reader.

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

Parameters: 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: IOException if an IOException was generated by the Reader

See Also: Script

compileString

public final Script compileString(String source, String sourceName, int lineno, Object securityDomain)
Compiles the source in the given string.

Returns a script that may later be executed.

Parameters: source the source string 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

See Also: Script

compressReader

public final String compressReader(Scriptable scope, Script script, String source, String sourceName, int lineno, Object securityDomain)

compressScript

public final String compressScript(Script script, int indent, String source, int lineno)
Compress the script.

Compressed script is returned.

Parameters: script the script object indent the number of spaces to indent the result

Returns: a string representing the script source

createClassLoader

public GeneratedClassLoader createClassLoader(ClassLoader parent)
Create class loader for generated classes. The method calls createClassLoader using the result of getFactory.

decompileFunction

public final 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 final 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.

decompileReader

public final String decompileReader(Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain)

decompileScript

public final String decompileScript(Script script, int indent)
Decompile the script.

The canonical source of the script is returned.

Parameters: script the script to decompile indent the number of spaces to indent the result

Returns: a string representing the script source

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();
      }
 
Instead of using enter(), exit() pair consider using call which guarantees proper association of Context instances with the current thread and is faster. With this method the above example becomes:
      Context.call(new ContextAction() {
          public Object run(Context cx) {
              ...
              cx.evaluateString(...);
              return null;
          }
      });
 

Returns: a Context associated with the current thread

See Also: getCurrentContext exit call

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

See Also: enter call call

evaluateReader

public final Object evaluateReader(Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain)
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: IOException if an IOException was generated by the Reader

evaluateString

public final Object evaluateString(Scriptable scope, String source, String sourceName, int lineno, Object securityDomain)
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

See Also: SecurityController

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 call call

getApplicationClassLoader

public final ClassLoader getApplicationClassLoader()

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

getDebuggableView

public static DebuggableScript getDebuggableView(Script script)
Return DebuggableScript instance if any associated with the script. If callable supports DebuggableScript implementation, the method returns it. Otherwise null is returned.

getDebugger

public final Debugger getDebugger()
Return the current debugger.

Returns: the debugger, or null if none is attached.

getDebuggerContextData

public final Object getDebuggerContextData()
Return the debugger context data associated with current context.

Returns: the debugger data, or null if debugger is not attached

getElements

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

If the object defines a length property convertible to double number, then the number is converted Uint32 value as defined in Ecma 9.6 and Java array of that size is allocated. The array is 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

getErrorReporter

public final ErrorReporter getErrorReporter()
Get the current error reporter.

See Also: ErrorReporter

getFactory

public final ContextFactory getFactory()
Return ContextFactory instance used to create this Context or the result of getGlobal if no factory was used for Context creation.

getImplementationVersion

public final 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.

getInstructionObserverThreshold

public final 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.

getLanguageVersion

public final 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.

getLocale

public final Locale getLocale()
Get the current locale. Returns the default locale if none has been set.

See Also: java.util.Locale

getMaximumInterpreterStackDepth

public final int getMaximumInterpreterStackDepth()
Returns the maximum stack depth (in terms of number of call frames) allowed in a single invocation of interpreter. If the set depth would be exceeded, the interpreter will throw an EvaluatorException in the script. Defaults to Integer.MAX_VALUE. The setting only has effect for interpreted functions (those compiled with optimization level set to -1). As the interpreter doesn't use the Java stack but rather manages its own stack in the heap memory, a runaway recursion in interpreted code would eventually consume all available memory and cause OutOfMemoryError instead of a StackOverflowError limited to only a single thread. This setting helps prevent such situations.

Returns: The current maximum interpreter stack depth.

getOptimizationLevel

public final int getOptimizationLevel()
Get the current optimization level.

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

Since: 1.3

getThreadLocal

public final Object getThreadLocal(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.

getUndefinedValue

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

getWrapFactory

public final WrapFactory getWrapFactory()
Return the current WrapFactory, or null if none is defined.

Since: 1.5 Release 4

See Also: WrapFactory

hasCompileFunctionsWithDynamicScope

public final boolean hasCompileFunctionsWithDynamicScope()

Deprecated:

See Also: FEATURE_DYNAMIC_SCOPE Context

hasFeature

public boolean hasFeature(int featureIndex)
Controls certain aspects of script semantics. Should be overwritten to alter default behavior.

The default implementation calls ContextFactory that allows to customize Context behavior without introducing Context subclasses. ContextFactory documentation gives an example of hasFeature implementation.

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 FEATURE_PARENT_PROTO_PROPRTIES FEATURE_E4X FEATURE_DYNAMIC_SCOPE FEATURE_STRICT_VARS FEATURE_STRICT_EVAL

initStandardObjects

public final ScriptableObject initStandardObjects()
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.

Returns: the initialized scope

initStandardObjects

public final 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. The method returns the value of the scope argument if it is not null or newly allocated scope object which is an instance ScriptableObject.

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, changed, 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. The method returns the value of the scope argument if it is not null or newly allocated scope object.

Since: 1.4R3

isActivationNeeded

public final boolean isActivationNeeded(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.

isGeneratingDebug

public final boolean isGeneratingDebug()
Tell whether debug information is being generated.

Since: 1.3

isGeneratingDebugChanged

public final boolean isGeneratingDebugChanged()

isGeneratingSource

public final boolean isGeneratingSource()
Tell whether source information is being generated.

Since: 1.3

isSealed

public final boolean isSealed()
Checks if this is a sealed Context. A sealed Context instance does not allow to modify any of its properties and will throw an exception on any such attempt.

See Also: Context

isValidLanguageVersion

public static boolean isValidLanguageVersion(int version)

isValidOptimizationLevel

public static boolean isValidOptimizationLevel(int optimizationLevel)

javaToJS

public static Object javaToJS(Object value, Scriptable scope)
Convenient method to convert java value to its closest representation in JavaScript.

If value is an instance of String, Number, Boolean, Function or Scriptable, it is returned as it and will be treated as the corresponding JavaScript type of string, number, boolean, function and object.

Note that for Number instances during any arithmetic operation in JavaScript the engine will always use the result of Number.doubleValue() resulting in a precision loss if the number can not fit into double.

If value is an instance of Character, it will be converted to string of length 1 and its JavaScript type will be string.

The rest of values will be wrapped as LiveConnect objects by calling WrapFactory as in:

    Context cx = Context.getCurrentContext();
    return cx.getWrapFactory().wrap(cx, scope, value, null);
 

Parameters: value any Java object scope top scope object

Returns: value suitable to pass to any API that takes JavaScript values.

jsToJava

public static Object jsToJava(Object value, Class desiredType)
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 desiredType 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: EvaluatorException if the conversion cannot be performed

newArray

public final 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 final Scriptable newArray(Scriptable scope, 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 and type of array should be exactly Object[], not SomeObjectSubclass[].

Returns: the new array object.

newObject

public final Scriptable newObject(Scriptable scope)
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

newObject

public final Scriptable newObject(Scriptable scope, String constructorName)
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

newObject

public final Scriptable newObject(Scriptable scope, String constructorName, Object[] args)
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

observeInstructionCount

protected void observeInstructionCount(int instructionCount)
Allow application to monitor counter of executed script instructions in Context subclasses. Run-time calls this when instruction counting is enabled and the counter reaches limit set by setInstructionObserverThreshold(). The method is useful to observe long running scripts and if necessary to terminate them.

The instruction counting support is available only for interpreted scripts generated when the optimization level is set to -1.

The default implementation calls ContextFactory that allows to customize Context behavior without introducing Context subclasses.

Parameters: instructionCount amount of script instruction executed since last call to observeInstructionCount

Throws: Error to terminate the script

See Also: Context

putThreadLocal

public final void putThreadLocal(Object key, 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

removeActivationName

public void removeActivationName(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

removeContextListener

public static void removeContextListener(ContextListener listener)

Deprecated:

See Also: removeListener getGlobal

removePropertyChangeListener

public final void removePropertyChangeListener(PropertyChangeListener l)
Remove an object from the list of objects registered to receive notification of changes to a bounded property

Parameters: l the listener

See Also: java.beans.PropertyChangeEvent Context

removeThreadLocal

public final void removeThreadLocal(Object key)
Remove values from thread-local storage.

Parameters: key the key for the entry to remove.

Since: 1.5 release 2

reportError

public static void reportError(String message, String sourceName, int lineno, 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(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 EvaluatorException reportRuntimeError(String message, String sourceName, int lineno, 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 EvaluatorException reportRuntimeError(String message)
Report a runtime error using the error reporter for the current thread.

Parameters: message the error message to report

See Also: ErrorReporter

reportWarning

public static void reportWarning(String message, String sourceName, int lineno, 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(String message)
Report a warning using the error reporter for the current thread.

Parameters: message the warning message to report

See Also: ErrorReporter

seal

public final void seal(Object sealKey)
Seal this Context object so any attempt to modify any of its properties including calling enter and exit methods will throw an exception.

If sealKey is not null, calling Context with the same key unseals the object. If sealKey is null, unsealing is no longer possible.

See Also: isSealed unseal

setApplicationClassLoader

public final void setApplicationClassLoader(ClassLoader loader)

setCachingEnabled

public static void setCachingEnabled(boolean cachingEnabled)

Deprecated:

See Also: get ClassCache

setClassShutter

public final 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: SecurityException if there is already a ClassShutter object for this Context

setCompileFunctionsWithDynamicScope

public final void setCompileFunctionsWithDynamicScope(boolean flag)

Deprecated:

See Also: FEATURE_DYNAMIC_SCOPE Context

setDebugger

public final void setDebugger(Debugger debugger, 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.

setErrorReporter

public final ErrorReporter setErrorReporter(ErrorReporter reporter)
Change the current error reporter.

Returns: the previous error reporter

See Also: ErrorReporter

setGeneratingDebug

public final 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

setGeneratingSource

public final 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

setInstructionObserverThreshold

public final void setInstructionObserverThreshold(int threshold)

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.

setLocale

public final Locale setLocale(Locale loc)
Set the current locale.

See Also: java.util.Locale

setMaximumInterpreterStackDepth

public final void setMaximumInterpreterStackDepth(int max)
Sets the maximum stack depth (in terms of number of call frames) allowed in a single invocation of interpreter. If the set depth would be exceeded, the interpreter will throw an EvaluatorException in the script. Defaults to Integer.MAX_VALUE. The setting only has effect for interpreted functions (those compiled with optimization level set to -1). As the interpreter doesn't use the Java stack but rather manages its own stack in the heap memory, a runaway recursion in interpreted code would eventually consume all available memory and cause OutOfMemoryError instead of a StackOverflowError limited to only a single thread. This setting helps prevent such situations.

Parameters: max the new maximum interpreter stack depth

Throws: IllegalStateException if this context's optimization level is not -1 IllegalArgumentException if the new depth is not at least 1

setOptimizationLevel

public final 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

setSecurityController

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

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

Parameters: controller a SecurityController object

Throws: SecurityException if there is already a SecurityController object for this Context or globally installed.

See Also: SecurityController hasGlobal

setWrapFactory

public final 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

stringIsCompilableUnit

public final boolean stringIsCompilableUnit(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

throwAsScriptRuntimeEx

public static RuntimeException throwAsScriptRuntimeEx(Throwable e)
Rethrow the exception wrapping it as the script runtime exception. Unless the exception is instance of EcmaError or EvaluatorException it will be wrapped as WrappedException, a subclass of EvaluatorException. The resulting exception object always contains source name and line number of script that triggered exception.

This method always throws an exception, its return value is provided only for convenience to allow a usage like:

 throw Context.throwAsScriptRuntimeEx(ex);
 
to indicate that code after the method is unreachable.

Throws: EvaluatorException EcmaError

toBoolean

public static boolean toBoolean(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(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

toObject

public static Scriptable toObject(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(Object value, Scriptable scope, Class staticType)

Deprecated:

See Also: Context

toString

public static String toString(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

toType

public static Object toType(Object value, Class desiredType)

Deprecated:

Throws: IllegalArgumentException if the conversion cannot be performed. Note that Context throws EvaluatorException instead.

See Also: Context

unseal

public final void unseal(Object sealKey)
Unseal previously sealed Context object. The sealKey argument should not be null and should match sealKey suplied with the last call to seal or an exception will be thrown.

See Also: isSealed Context