Class ContextFactory
- Direct Known Subclasses:
LoboContextFactory
Context instances. A
ContextFactory can also notify listeners about context creation and release.
When the Rhino runtime needs to create new Context instance during execution of Context.enter() or Context, it will call makeContext() of the current global
ContextFactory. See getGlobal() and initGlobal(ContextFactory).
It is also possible to use explicit ContextFactory instances for Context creation. This is
useful to have a set of independent Rhino runtime instances under single JVM. See call(ContextAction).
The following example demonstrates Context customization to terminate scripts running more then 10 seconds and to provide better compatibility with JavaScript code using MSIE-specific features.
import org.mozilla.javascript.*;
class MyFactory extends ContextFactory
{
// Custom Context to store execution time.
private static class MyContext extends Context
{
long startTime;
}
static {
// Initialize GlobalFactory with custom factory
ContextFactory.initGlobal(new MyFactory());
}
// Override makeContext()
protected Context makeContext()
{
MyContext cx = new MyContext();
// Make Rhino runtime to call observeInstructionCount
// each 10000 bytecode instructions
cx.setInstructionObserverThreshold(10000);
return cx;
}
// Override hasFeature(Context, int)
public boolean hasFeature(Context cx, int featureIndex)
{
// Turn on maximum compatibility with MSIE scripts
switch (featureIndex) {
case Context.FEATURE_NON_ECMA_GET_YEAR:
return true;
case Context.FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME:
return true;
case Context.FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER:
return true;
case Context.FEATURE_PARENT_PROTO_PROPERTIES:
return false;
}
return super.hasFeature(cx, featureIndex);
}
// Override observeInstructionCount(Context, int)
protected void observeInstructionCount(Context cx, int instructionCount)
{
MyContext mcx = (MyContext)cx;
long currentTime = System.currentTimeMillis();
if (currentTime - mcx.startTime > 10*1000) {
// More then 10 seconds from Context creation time:
// it is time to stop the script.
// Throw Error instance to ensure that script will never
// get control back through catch or finally.
throw new Error();
}
}
// Override doTopCall(Callable, Context, Scriptable, Scriptable, Object[])
protected Object doTopCall(Callable callable,
Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
MyContext mcx = (MyContext)cx;
mcx.startTime = System.currentTimeMillis();
return super.doTopCall(callable, cx, scope, thisObj, args);
}
}
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfacestatic interfaceListener ofContextcreation and release events. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionfinal voidaddListener(ContextFactory.Listener listener) final <T> Tcall(ContextAction<T> action) CallContextAction.run(Context cx)using theContextinstance associated with the current thread.protected final voidprotected GeneratedClassLoadercreateClassLoader(ClassLoader parent) Create class loader for generated classes.protected ObjectdoTopCall(Callable callable, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) Execute top call to script or function.final Contextenter()Deprecated.Get a context associated with the current thread, creating one if need be.final ContextenterContext(Context cx) Get a Context associated with the current thread, using the given Context if need be.final voidexit()Deprecated.UseContext.exit()instead.final ClassLoaderGet ClassLoader to use when searching for Java classes.protected XMLLib.FactoryProvides a defaultXMLLib.Factoryto be used by theContextinstances produced by this factory.static ContextFactoryGet global ContextFactory.static ContextFactory.GlobalSetterstatic booleanCheck if global factory was set.protected booleanhasFeature(Context cx, int featureIndex) Implementation ofContext.hasFeature(int featureIndex).final voidSet explicit class loader to use when searching for Java classes.static voidinitGlobal(ContextFactory factory) Set global ContextFactory.final booleanisSealed()Checks if this is a sealed ContextFactory.protected ContextCreate newContextinstance to be associated with the current thread.protected voidobserveInstructionCount(Context cx, int instructionCount) Implementation ofContext.observeInstructionCount(int instructionCount).protected voidprotected voidfinal voidremoveListener(ContextFactory.Listener listener) final voidseal()Seal this ContextFactory so any attempt to modify it like to add or remove its listeners will throw an exception.
-
Constructor Details
-
ContextFactory
public ContextFactory()
-
-
Method Details
-
getGlobal
Get global ContextFactory.- See Also:
-
hasExplicitGlobal
public static boolean hasExplicitGlobal()Check if global factory was set. Return true to indicate thatinitGlobal(ContextFactory)was already called and false to indicate that the global factory was not explicitly set.- See Also:
-
initGlobal
Set global ContextFactory. The method can only be called once.- See Also:
-
getGlobalSetter
-
makeContext
Create newContextinstance to be associated with the current thread. This is a callback method used by Rhino to createContextinstance when it is necessary to associate one with the current execution thread.makeContext()is allowed to callContext.seal(Object)on the result to preventContextchanges by hostile scripts or applets. -
hasFeature
Implementation ofContext.hasFeature(int featureIndex). This can be used to customizeContextwithout introducing additional subclasses. -
getE4xImplementationFactory
Provides a defaultXMLLib.Factoryto be used by theContextinstances produced by this factory. SeeContext.getE4xImplementationFactory()for details.May return null, in which case E4X functionality is not supported in Rhino.
The default implementation now prefers the DOM3 E4X implementation.
-
createClassLoader
Create class loader for generated classes. This method creates an instance of the default implementation ofGeneratedClassLoader. Rhino uses this interface to load generated JVM classes when noSecurityControlleris installed. Application can override the method to provide custom class loading. -
getApplicationClassLoader
Get ClassLoader to use when searching for Java classes. Unless it was explicitly initialized withinitApplicationClassLoader(ClassLoader)the method returns null to indicate that Thread.getContextClassLoader() should be used. -
initApplicationClassLoader
Set explicit class loader to use when searching for Java classes.- See Also:
-
doTopCall
protected Object doTopCall(Callable callable, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) Execute top call to script or function. When the runtime is about to execute a script or function that will create the first stack frame with scriptable code, it calls this method to perform the real call. In this way execution of any script happens inside this function. -
observeInstructionCount
Implementation ofContext.observeInstructionCount(int instructionCount). This can be used to customizeContextwithout introducing additional subclasses. -
onContextCreated
-
onContextReleased
-
addListener
-
removeListener
-
isSealed
public final boolean isSealed()Checks if this is a sealed ContextFactory.- See Also:
-
seal
public final void seal()Seal this ContextFactory so any attempt to modify it like to add or remove its listeners will throw an exception.- See Also:
-
checkNotSealed
protected final void checkNotSealed() -
call
CallContextAction.run(Context cx)using theContextinstance associated with the current thread. If no Context is associated with the thread, thenmakeContext()will be called to construct new Context instance. The instance will be temporary associated with the thread during call toContextAction.run(Context).- See Also:
-
enterContext
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
enterContext()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 toenterContext()must have a matching call toContext.exit().Context cx = contextFactory.enterContext(); try { ... cx.evaluateString(...); } finally { Context.exit(); }Instead of usingenterContext(),exit()pair consider usingcall(ContextAction)which guarantees proper association of Context instances with the current thread. With this method the above example becomes:ContextFactory.call(new ContextAction() { public Object run(Context cx) { ... cx.evaluateString(...); return null; } });- Returns:
- a Context associated with the current thread
- See Also:
-
enter
Deprecated.useenterContext()instead- Returns:
- a Context associated with the current thread
-
exit
Deprecated.UseContext.exit()instead. -
enterContext
Get a Context associated with the current thread, using the given Context if need be.The same as
enterContext()except thatcxis associated with the current thread and returned if the current thread has no associated context andcxis 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
- Throws:
IllegalStateException- ifcxis already associated with a different thread- See Also:
-
enterContext()instead