Class Context.Builder
- Enclosing class:
Context
-
Method Summary
Modifier and TypeMethodDescriptionallowAllAccess(boolean enabled) Sets the default value for all privileges.allowCreateProcess(boolean enabled) Iftrue, allows guest language to execute external processes.allowCreateThread(boolean enabled) Iftrue, allows guest languages to create new threads.allowEnvironmentAccess(EnvironmentAccess accessPolicy) Allow environment access using the provided policy.allowExperimentalOptions(boolean enabled) Allow experimental options to be used for language options.allowHostAccess(boolean enabled) Deprecated.allowHostAccess(HostAccess config) Configures which public constructors, methods or fields of public classes are accessible by guest applications.allowHostClassLoading(boolean enabled) If host class loading is enabled, then the guest language is allowed to load new host classes via jar or class files.allowHostClassLookup(Predicate<String> classFilter) Sets a filter that specifies the Java host classes that can be looked up by the guest application.allowInnerContextOptions(boolean enabled) Allows this context to spawn inner contexts that may change option values set for the outer context.allowIO(boolean enabled) Deprecated.Configures guest language access to host IO.allowNativeAccess(boolean enabled) Allows guest languages to access the native interface.allowPolyglotAccess(PolyglotAccess accessPolicy) Allow polyglot access using the provided policy.allowValueSharing(boolean enabled) Enables or disables sharing of anyvaluebetween contexts.apply(Consumer<Context.Builder> action) Applies the provided Consumer to this Builder instance.Sets the guest language application arguments for a languagecontext.build()Creates a new context instance from the configuration provided in the builder.currentWorkingDirectory(Path workingDirectory) Sets the current working directory used by the guest application to resolve relative paths.Explicitly sets the underlying engine to use.environment(String name, String value) Sets an environment variable.environment(Map<String, String> env) Shortcut for setting multipleenvironment variablesusing a map.err(OutputStream err) Sets the error output stream to be used for the context.extendHostAccess(HostAccess defaultInitialValue, Consumer<HostAccess.Builder> setup) Extends the existing host access configuration that determines, which public constructors, methods or fields of public classes are accessible by guest applications.extendIO(IOAccess defaultInitialValue, Consumer<IOAccess.Builder> setup) Extends the existing guest language access to host IO configuration.fileSystem(FileSystem fileSystem) Deprecated.If a file system was previously set useallowIO(IOAccess.newBuilder().fileSystem(fileSystem).build()).hostClassFilter(Predicate<String> classFilter) Deprecated.useallowHostClassLookup(Predicate)instead.hostClassLoader(ClassLoader classLoader) Sets a host class loader.in(InputStream in) Sets the input stream to be used for the context.logHandler(OutputStream logOut) Installs a new loggingHandlerusing givenOutputStream.logHandler(Handler logHandler) Installs a new loggingHandler.Sets an option for thiscontext.Shortcut for setting multipleoptionsusing a map.out(OutputStream out) Sets the standard output stream to be used for the context.processHandler(ProcessHandler handler) Installs aProcessHandlerresponsible for external process creation.resourceLimits(ResourceLimits limits) Assigns resource limit configuration to a context.sandbox(SandboxPolicy policy) Sets a code sandbox policy to a context.serverTransport(MessageTransport serverTransport) Take over the transport of messages communication with a server peer.Sets the default time zone to be used for this context.useSystemExit(boolean enabled) Specifies whetherSystem.exit(int)may be used to improve efficiency of stack unwinding for context exit requested by the guest application.
-
Method Details
-
apply
Applies the provided Consumer to this Builder instance.This method allows encapsulating complex Builder configuration logic into separate methods while maintaining the fluent API of
Context.Builder.Example
private void configureEnv(Builder builder) { return builder.environment("DEBUG", appConfiguration.isDebugMode()) .environment("APP_NAME", appConfiguration.getApplicationName()) .environment("JAVA_VER", System.getProperty("java.version"))@ } public Context createContext() { return Context.newBuilder() .apply(this::configureEnv) .allowNativeAccess(true) .build(); }- Parameters:
action- The Consumer that configures this Builder instance; it is not supposed to finalize the Builder usingbuild().- Since:
- 25.0
-
engine
Explicitly sets the underlying engine to use. By default, every context has its own isolated engine. If multiple contexts are created from one engine, then they may share/cache certain system resources like ASTs or optimized code by specifying a single underlying engine. SeeEnginefor more details about system resource sharing.- Since:
- 19.0
-
out
Sets the standard output stream to be used for the context. If not set, then the standard output stream configured for theengineor standard error stream is used.- Since:
- 19.0
-
err
Sets the error output stream to be used for the context. If not set, then either the error stream configured for theengineor standard error stream is used.- Since:
- 19.0
-
in
Sets the input stream to be used for the context. If not set, then either the input stream configured for theengineor standard in stream is used.- Since:
- 19.0
-
allowHostAccess
Deprecated.useallowHostAccess(HostAccess)orallowHostClassLookup(Predicate)instead.Allows guest languages to access the host language by loading new classes. Default isfalse. Ifall accessis set totrue, then host access is enabled if not disallowed explicitly.- Since:
- 19.0
-
allowHostAccess
Configures which public constructors, methods or fields of public classes are accessible by guest applications. By default ifallowAllAccess(boolean)isfalsetheHostAccess.EXPLICITpolicy will be used, otherwiseHostAccess.ALL.Repeated calls of this method on the same
Context.Builderinstance override the previously setHostAccessconfiguration. UseextendHostAccess(HostAccess, Consumer)for composableHostAccessconfiguration.- Since:
- 19.0
- See Also:
-
extendHostAccess
public Context.Builder extendHostAccess(HostAccess defaultInitialValue, Consumer<HostAccess.Builder> setup) Extends the existing host access configuration that determines, which public constructors, methods or fields of public classes are accessible by guest applications.This method allows composing code that configures
HostAccess.The provided
setupis applied to aHostAccess.Builderinstance, which is initialized with the currentHostAccessconfiguration. If noHostAccessconfiguration exists, thedefaultInitialValueis used to initialize the builder.Example usage
public static final class MyArrayWrapper { private final Value v; private MyArrayWrapper(Value v) { this.v = v; } // ... public static void addMapping(Context.Builder builder) { builder.extendHostAccess(HostAccess.NONE, b -> b.targetTypeMapping(Value.class, MyArrayWrapper.class, Value::hasArrayElements, MyArrayWrapper::new)); } } // ... public Context createContext() { return Context.newBuilder(). .allowHostAccess(HostAccess.ALL) .apply(MyArrayWrapper::addMapping) // ... .build(); }In this example the call toextendHostAccessinMyArrayWrapper::addMappingdoes not override theHostAccess.ALLconfigured before. UsingallowHostAccess(HostAccess)in this situation would override the previous configuration.- Parameters:
defaultInitialValue- - the initial value to use if noHostAccessis configured.setup- - Consumer that receives aHostAccess.Builderpreconfigured with the currentHostAccessconfiguration.- Returns:
- the
Context.Builder - Since:
- 25.0
- See Also:
-
allowNativeAccess
Allows guest languages to access the native interface.- Since:
- 19.0
-
allowCreateThread
Iftrue, allows guest languages to create new threads. Default isfalse. Ifall accessis set totrue, then the creation of threads is enabled if not allowed explicitly. Threads created by guest languages are closed, when the context isclosed.- Since:
- 19.0
-
allowAllAccess
Sets the default value for all privileges. If not explicitly specified, then all access isfalse. If all access is enabled then certain privileges may still be disabled by configuring it explicitly using the builder (either before or after the call toallowAllAccess()). Allowing all access should only be set if the guest application is fully trusted.If
true, grants the context the same access privileges as the host virtual machine. If the host VM runs without asecurity managerenabled, then enabling all access gives the guest languages full control over the host process. Otherwise, Javasecurity manageris in control of restricting the privileges of the polyglot context. If new privilege restrictions are added to the polyglot API, then they will default to full access.Grants full access to the following privileges by default:
- The
creationand use of new threads. - The access to public
host classes. - The loading of new
host classesby adding entries to the class path. - Exporting new members into the polyglot
bindings. - Unrestricted
IO operationson host system. - Passing
experimental options. - The
creationand use of new sub-processes. - The
accessto process environment variables. - The
changingof options for of inner contexts spawned by the language.
- Parameters:
enabled-truefor all access by default.- Since:
- 19.0
- The
-
allowHostClassLoading
If host class loading is enabled, then the guest language is allowed to load new host classes via jar or class files. Ifall accessis set totrue, then the host class loading is enabled if it is not disallowed explicitly. For host class loading to be useful,IOoperationshost class lookup, and thehost access policyneeds to be configured as well.- Since:
- 19.0
- See Also:
-
allowHostClassLookup
Sets a filter that specifies the Java host classes that can be looked up by the guest application. If set tonullthen no class lookup is allowed and relevant language builtins are not available (e.g.Java.typein JavaScript). If theclassFilterparameter is set to a filter predicate, then language builtins are available and classes can be looked up if the filter predicate returnstruefor the fully qualified class name. If the filter returnsfalse, then the class cannot be looked up and as a result throws a guest language error when accessed. By default and ifall accessisfalse, host class lookup is disabled. By default and ifall accessistrue, then all classes may be looked up by the guest application.In order to access class members looked up by the guest application a
host access policyneeds to be set orall accessneeds to be set totrue.To load new classes the context uses the
hostClassLoaderif specified or thecontext class loaderthat will be captured when the context isbuilt. If an explicitenginewas specified, then the context class loader at enginebuild-timewill be used instead. When the Java module system is available (>= JDK 9) then only classes are accessible that are exported to the unnamed module of the captured class loader.Example usage with JavaScript:
public class MyClass { @HostAccess.Export public int accessibleMethod() { return 42; } public static void main(String[] args) { try (Context context = Context.newBuilder() // .allowHostClassLookup(c -> c.equals("myPackage.MyClass")) // .build()) { int result = context.eval("js", "" + "var MyClass = Java.type('myPackage.MyClass');" + "new MyClass().accessibleMethod()").asInt(); assert result == 42; } } }In this example:
- We create a new context with the
permissionto look up the classmyPackage.MyClassin the guest language application. - We evaluate a JavaScript code snippet that accesses the Java class
myPackage.MyClassusing theJava.typebuiltin provided by the JavaScript language implementation. Other classes can only be looked up if the provided class filter returnstruefor their name. - We create a new instance of the Java class
MyClassby using the JavaScriptnewkeyword. - We call the method
accessibleMethodwhich returns42. The method is accessible to the guest language because because the enclosing class and the declared method are public, as well as annotated with the@HostAccess.Exportannotation. Which Java members of classes are accessible can be configured using thehost access policy.
- Parameters:
classFilter- a predicate that returnstrueorfalsefor a qualified Java class name ornullto disable host class lookup.- Since:
- 19.0
- See Also:
- We create a new context with the
-
allowExperimentalOptions
Allow experimental options to be used for language options. Do not use experimental options in production environments. If set tofalse(the default), then passing an experimental option results in anIllegalArgumentExceptionwhen the context is built.Alternatively
Engine.Builder.allowExperimentalOptions(boolean)may be used when constructing the context using anexplicit engine.- Since:
- 19.0
-
allowPolyglotAccess
Allow polyglot access using the provided policy. Ifall accessistruethen the default polyglot access policy isPolyglotAccess.ALL, otherwisePolyglotAccess.NONE. The provided access policy must not benull.- Since:
- 19.0
-
allowValueSharing
Enables or disables sharing of anyvaluebetween contexts. Value sharing is enabled by default and is not affected byallowAllAccess(boolean).If this option is set to
true(default) then any value that is associated with one context will be automatically migrated when passed to another context. Primitive,hostandproxyvalues can be migrated without limitation. When guest language values are migrated, they capture and remember their original context. Guest language objects need to be accessed when their respective context isentered, therefore before any access their original context is entered and subsequently left. Entering the original context may fail, for example when the context of a original context value only allows single threaded access to values or if it wasclosedin the mean time.If this option is set to
falsethen any value passed from one context to another will fail with an error indicating that sharing is disallowed. Turning sharing off can be useful when strict safety is required and it would be considered an error if a value of one context is passed to another.Values of a guest language that are passed from one context to another are restricted to using the interoperability protocol only. In practice this often leads to slight changes and incompatibilities in behavior. For example, the prototype of a JavaScript object passed from one context to another is not writable, as the interoperability protocol does not allow such an operation (yet). A typical use-case is passing big immutable data structures that are infrequently accessed from one context to another, without copying them. In practice, passing values from one context to another should be avoided if possible, as their access is slower and their language compatibility reduced. This feature was introduced in 21.3. Older versions fail when guest values are passed from one context to another.
- Since:
- 21.3
-
allowInnerContextOptions
Allows this context to spawn inner contexts that may change option values set for the outer context. If this privilege is set tofalsethen inner contexts are only allowed to use the same option values as its outer context. If this privilege is set totruethen the context may modify option values for inner contexts it creates. This privilege should not be enabled for security sensitive use-cases. The default value for this privilege is inherited fromallowAllAccess(boolean).Inner contexts are spawned by language implementations to implement language embeddings of their own. For example, some languages provide dedicated APIs to spawn language virtual machines. Such APIs are often implemented using the inner context mechanism.
- Since:
- 22.3
- See Also:
-
hostClassFilter
Deprecated.useallowHostClassLookup(Predicate)instead.Sets a class filter that allows to limit the classes that are allowed to be loaded by guest languages. If the filter returnstrue, then the class is accessible, otherwise it is not accessible and throws a guest language error when accessed. In order to have an effect,allowHostAccess(org.graalvm.polyglot.HostAccess)orallowAllAccess(boolean)needs to be set totrue.- Parameters:
classFilter- a predicate that returnstrueorfalsefor a java qualified class name.- Since:
- 19.0
-
option
Sets an option for thiscontext. By default, any options for theengine,languageorinstrumentcan be set for a context. If anexplicit engineis set for the context, then only language options can be set. Instrument and engine options can be set exclusively on the explicit engine instance. If a language option is set for the context and the engine, then the option of the context is going to take precedence.If one of the set option keys or values is invalid, then an
IllegalArgumentExceptionis thrown when the context isbuilt. The given key and value must not benull.- Since:
- 19.0
- See Also:
-
options
Shortcut for setting multipleoptionsusing a map. All values of the provided map must be non-null.- Parameters:
options- a map options.- Since:
- 19.0
- See Also:
-
arguments
Sets the guest language application arguments for a languagecontext. Application arguments are typically made available to guest language implementations. It depends on the language if and how they are accessible within theevaluatedguest language scripts. Passing no arguments to a language is equivalent to providing an empty arguments array.- Parameters:
language- the language id of the primary language.args- an array of arguments passed to the guest language program.- Throws:
IllegalArgumentException- if an invalid language id was specified.- Since:
- 19.0
-
allowIO
Configures guest language access to host IO. Default isIOAccess.NONE. Ifall accessis set totrue, thenIOAccess.ALLis used unless explicitly set. This method can be used to virtualize file system access in the guest language by using anIOAccesswith a custom filesystem.Repeated calls of this method on the same
Context.Builderinstance override the previously setIOAccessconfiguration. UseextendIO(IOAccess, Consumer)for composableIOAccessconfiguration.- Parameters:
ioAccess- the IO configuration- Returns:
- the
Context.Builder - Since:
- 23.0
- See Also:
-
extendIO
Extends the existing guest language access to host IO configuration. This method allows composing code that configuresIOAccess.The provided
setupis applied to aIOAccess.Builderinstance, which is initialized with the currentIOAccessconfiguration. If noIOAccessconfiguration exists, thedefaultInitialValueis used to initialize the builder.Example usage
private void addFileSystem(IOAccess.Builder builder) { builder.fileSystem(new MyCustomFileSystem()); } public Context createContext() { return Context.newBuilder().extendIOAccess(IOAccess.NONE, this::addFileSystem) // ... .extendIOAccess(IOAccess.NONE, b -> b.allowHostSocketAccess(true)) // ... .build(); }In this example the call toextendIOAccessdoes not override theFileSystemconfigured inaddFileSystem. UsingallowIO(IOAccess)in this situation would override the configuredFileSystem.- Parameters:
defaultInitialValue- - the initial value to use if noIOAccessis configured.setup- - Consumer that receives aIOAccess.Builderpreconfigured with the currentIOAccessconfiguration.- Returns:
- the
Context.Builder - Since:
- 25.0
- See Also:
-
allowIO
Deprecated.Iftrue, allows guest language to perform unrestricted IO operations on host system. Default isfalse. Ifall accessis set totrue, then IO is enabled if not allowed explicitly.- Parameters:
enabled-trueto enable Input/Output- Returns:
- the
Context.Builder - Since:
- 19.0
-
fileSystem
Deprecated.If a file system was previously set useallowIO(IOAccess.newBuilder().fileSystem(fileSystem).build()).Installs a newFileSystem.- Parameters:
fileSystem- the file system to be installed- Returns:
- the
Context.Builder - Since:
- 19.0
-
serverTransport
Take over the transport of messages communication with a server peer. Provide an implementation ofMessageTransportto virtualize a transport of messages to a server endpoint.MessageTransport.open(java.net.URI, org.graalvm.polyglot.io.MessageEndpoint)corresponds to accept of a server socket.- Parameters:
serverTransport- an implementation of message transport interceptor- Since:
- 19.0
- See Also:
-
logHandler
Installs a new loggingHandler. The logger'sLevelconfiguration is done using theContext's options. The level option key has the following format:log.languageId.loggerName.levelorlog.instrumentId.loggerName.level. The value is either the name of a pre-definedLevelconstant or a numericLevelvalue. If not explicitly set in options, the level is inherited from the parent logger.Examples of setting log level options:
builder.option("log.level","FINE");sets theFINE levelto allTruffleLoggers.
builder.option("log.js.level","FINE");sets theFINE levelto JavaScriptTruffleLoggers.
builder.option("log.js.com.oracle.truffle.js.parser.JavaScriptLanguage.level","FINE");sets theFINE leveltoTruffleLoggerfor theJavaScriptLanguageclass.
If the
logHandleris not set onEnginenor onContext, the log messages are printed toContext's error output stream.- Parameters:
logHandler- theHandlerto use for logging in builtContext. The passedlogHandleris closed when the context isclosed.- Returns:
- the
Context.Builder - Since:
- 19.0
-
timeZone
Sets the default time zone to be used for this context. If not set, or explicitly set tonullthen thesystem defaultzone will be used.- Returns:
- the
Context.Builder - Since:
- 19.2.0
- See Also:
-
logHandler
Installs a new loggingHandlerusing givenOutputStream. The logger'sLevelconfiguration is done using theContext's options. The level option key has the following format:log.languageId.loggerName.levelorlog.instrumentId.loggerName.level. The value is either the name of pre-definedLevelconstant or a numericLevelvalue. If not explicitly set in options the level is inherited from the parent logger.Examples of setting log level options:
builder.option("log.level","FINE");sets theFINE levelto allTruffleLoggers.
builder.option("log.js.level","FINE");sets theFINE levelto JavaScriptTruffleLoggers.
builder.option("log.js.com.oracle.truffle.js.parser.JavaScriptLanguage.level","FINE");sets theFINE leveltoTruffleLoggerfor theJavaScriptLanguageclass.
If the
logHandleris not set onEnginenor onContextthe log messages are printed toContext's standard output stream.- Parameters:
logOut- theOutputStreamto use for logging in builtContext. The passedlogOutstream is closed when the context isclosed.- Returns:
- the
Context.Builder - Since:
- 19.0
-
allowCreateProcess
Iftrue, allows guest language to execute external processes. Default isfalse. Ifall accessis set totrue, then process creation is enabled if not denied explicitly.- Parameters:
enabled-trueto enable external process creation- Since:
- 19.1.0
-
processHandler
Installs aProcessHandlerresponsible for external process creation.- Parameters:
handler- the handler to be installed- Since:
- 19.1.0
-
resourceLimits
Assigns resource limit configuration to a context. By default no resource limits are assigned. The limits will be enabled for all contexts created using this builder. Assigning a limit may have performance impact of all contexts that run with the same engine.- Since:
- 19.3.0
- See Also:
-
sandbox
Sets a code sandbox policy to a context. By default, the context's sandbox policy isSandboxPolicy.TRUSTED, there are no restrictions to the context configuration.- Since:
- 23.0
- See Also:
-
allowEnvironmentAccess
Allow environment access using the provided policy. Ifall accessistruethen the default environment access policy isEnvironmentAccess.INHERIT, otherwiseEnvironmentAccess.NONE. The provided access policy must not benull.- Parameters:
accessPolicy- theenvironment access policy- Since:
- 19.1.0
-
environment
Sets an environment variable.- Parameters:
name- the environment variable namevalue- the environment variable value- Since:
- 19.1.0
-
environment
Shortcut for setting multipleenvironment variablesusing a map. All values of the provided map must be non-null.- Parameters:
env- environment variables- Since:
- 19.1.0
- See Also:
-
currentWorkingDirectory
Sets the current working directory used by the guest application to resolve relative paths. When the Context is built, the given directory is set as the current working directory on the Context's file system using theFileSystem.setCurrentWorkingDirectorymethod.- Parameters:
workingDirectory- the new current working directory- Throws:
NullPointerException- whenworkingDirectoryisnullIllegalArgumentException- whenworkingDirectoryis a relative path- Since:
- 20.0.0
-
hostClassLoader
Sets a host class loader. If set the givenclassLoaderis used to load host classes and it's also set as acontext ClassLoaderduring code execution. Otherwise the ClassLoader that was captured when the context wasbuiltis used to to load host classes and thecontext ClassLoaderis not set during code execution. Setting the hostClassLoader has a negative effect on enter and leave performance.- Parameters:
classLoader- the host class loader- Since:
- 20.1.0
-
useSystemExit
Specifies whetherSystem.exit(int)may be used to improve efficiency of stack unwinding for context exit requested by the guest application.- Since:
- 22.0
- See Also:
-
build
Creates a new context instance from the configuration provided in the builder. The same context builder can be used to create multiple context instances.- Since:
- 19.0
-
allowHostAccess(HostAccess)orallowHostClassLookup(Predicate)instead.