Class Context.Builder

java.lang.Object
org.graalvm.polyglot.Context.Builder
Enclosing class:
Context

public final class Context.Builder extends Object
Builder class to construct Context instances. A builder instance is not thread-safe and must not be used from multiple threads at the same time.
Since:
19.0
See Also:
  • Method Details

    • engine

      public Context.Builder engine(Engine 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. See Engine for more details about system resource sharing.
      Since:
      19.0
    • out

      public Context.Builder out(OutputStream out)
      Sets the standard output stream to be used for the context. If not set, then the standard output stream configured for the engine or standard error stream is used.
      Since:
      19.0
    • err

      public Context.Builder err(OutputStream err)
      Sets the error output stream to be used for the context. If not set, then either the error stream configured for the engine or standard error stream is used.
      Since:
      19.0
    • in

      public Context.Builder in(InputStream in)
      Sets the input stream to be used for the context. If not set, then either the input stream configured for the engine or standard in stream is used.
      Since:
      19.0
    • allowHostAccess

      @Deprecated(since="19.0") public Context.Builder allowHostAccess(boolean enabled)
      Allows guest languages to access the host language by loading new classes. Default is false. If all access is set to true, then host access is enabled if not disallowed explicitly.
      Since:
      19.0
    • allowHostAccess

      public Context.Builder allowHostAccess(HostAccess config)
      Configures which public constructors, methods or fields of public classes are accessible by guest applications. By default if allowAllAccess(boolean) is false the HostAccess.EXPLICIT policy will be used, otherwise HostAccess.ALL.
      Since:
      19.0
      See Also:
    • allowNativeAccess

      public Context.Builder allowNativeAccess(boolean enabled)
      Allows guest languages to access the native interface.
      Since:
      19.0
    • allowCreateThread

      public Context.Builder allowCreateThread(boolean enabled)
      If true, allows guest languages to create new threads. Default is false. If all access is set to true, then the creation of threads is enabled if not allowed explicitly. Threads created by guest languages are closed, when the context is closed.
      Since:
      19.0
    • allowAllAccess

      public Context.Builder allowAllAccess(boolean enabled)
      Sets the default value for all privileges. If not explicitly specified, then all access is false. 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 to allowAllAccess()). 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 a security manager enabled, then enabling all access gives the guest languages full control over the host process. Otherwise, Java security manager is 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:

      Parameters:
      enabled - true for all access by default.
      Since:
      19.0
    • allowHostClassLoading

      public Context.Builder 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. If all access is set to true, then the host class loading is enabled if it is not disallowed explicitly. For host class loading to be useful, IO operations host class lookup, and the host access policy needs to be configured as well.
      Since:
      19.0
      See Also:
    • allowHostClassLookup

      public Context.Builder allowHostClassLookup(Predicate<String> classFilter)
      Sets a filter that specifies the Java host classes that can be looked up by the guest application. If set to null then no class lookup is allowed and relevant language builtins are not available (e.g. Java.type in JavaScript). If the classFilter parameter is set to a filter predicate, then language builtins are available and classes can be looked up if the filter predicate returns true for the fully qualified class name. If the filter returns false, then the class cannot be looked up and as a result throws a guest language error when accessed. By default and if all access is false, host class lookup is disabled. By default and if all access is true, 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 policy needs to be set or all access needs to be set to true.

      To load new classes the context uses the hostClassLoader if specified or the context class loader that will be captured when the context is built. If an explicit engine was specified, then the context class loader at engine build-time will 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 permission to look up the class myPackage.MyClass in the guest language application.
      • We evaluate a JavaScript code snippet that accesses the Java class myPackage.MyClass using the Java.type builtin provided by the JavaScript language implementation. Other classes can only be looked up if the provided class filter returns true for their name.
      • We create a new instance of the Java class MyClass by using the JavaScript new keyword.
      • We call the method accessibleMethod which returns 42. 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.Export annotation. Which Java members of classes are accessible can be configured using the host access policy.
      Parameters:
      classFilter - a predicate that returns true or false for a qualified Java class name or null to disable host class lookup.
      Since:
      19.0
      See Also:
    • allowExperimentalOptions

      public Context.Builder allowExperimentalOptions(boolean enabled)
      Allow experimental options to be used for language options. Do not use experimental options in production environments. If set to false (the default), then passing an experimental option results in an IllegalArgumentException when the context is built.

      Alternatively Engine.Builder.allowExperimentalOptions(boolean) may be used when constructing the context using an explicit engine.

      Since:
      19.0
    • allowPolyglotAccess

      public Context.Builder allowPolyglotAccess(PolyglotAccess accessPolicy)
      Allow polyglot access using the provided policy. If all access is true then the default polyglot access policy is PolyglotAccess.ALL, otherwise PolyglotAccess.NONE. The provided access policy must not be null.
      Since:
      19.0
    • allowValueSharing

      public Context.Builder allowValueSharing(boolean enabled)
      Enables or disables sharing of any value between contexts. Value sharing is enabled by default and is not affected by allowAllAccess(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, host and proxy values 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 is entered, 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 was closed in the mean time.

      If this option is set to false then 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

      public Context.Builder allowInnerContextOptions(boolean enabled)
      Allows this context to spawn inner contexts that may change option values set for the outer context. If this privilege is set to false then inner contexts are only allowed to use the same option values as its outer context. If this privilege is set to true then 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 from allowAllAccess(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(since="19.0") public Context.Builder hostClassFilter(Predicate<String> classFilter)
      Deprecated.
      Sets a class filter that allows to limit the classes that are allowed to be loaded by guest languages. If the filter returns true, 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) or allowAllAccess(boolean) needs to be set to true.
      Parameters:
      classFilter - a predicate that returns true or false for a java qualified class name.
      Since:
      19.0
    • option

      public Context.Builder option(String key, String value)
      Sets an option for this context. By default, any options for the engine, language or instrument can be set for a context. If an explicit engine is 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 IllegalArgumentException is thrown when the context is built. The given key and value must not be null.

      Since:
      19.0
      See Also:
    • options

      public Context.Builder options(Map<String,String> options)
      Shortcut for setting multiple options using a map. All values of the provided map must be non-null.
      Parameters:
      options - a map options.
      Since:
      19.0
      See Also:
    • arguments

      public Context.Builder arguments(String language, String[] args)
      Sets the guest language application arguments for a language context. Application arguments are typically made available to guest language implementations. It depends on the language if and how they are accessible within the evaluated guest 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

      public Context.Builder allowIO(IOAccess ioAccess)
      Configures guest language access to host IO. Default is IOAccess.NONE. If all access is set to true, then IOAccess.ALL is used unless explicitly set. This method can be used to virtualize file system access in the guest language by using an IOAccess with a custom filesystem.
      Parameters:
      ioAccess - the IO configuration
      Returns:
      the Context.Builder
      Since:
      23.0
      See Also:
    • allowIO

      @Deprecated(since="23.0") public Context.Builder allowIO(boolean enabled)
      Deprecated.
      If the value was previously true pass IOAccess.ALL, otherwise pass IOAccess.NONE.
      If true, allows guest language to perform unrestricted IO operations on host system. Default is false. If all access is set to true, then IO is enabled if not allowed explicitly.
      Parameters:
      enabled - true to enable Input/Output
      Returns:
      the Context.Builder
      Since:
      19.0
    • fileSystem

      @Deprecated(since="23.0") public Context.Builder fileSystem(FileSystem fileSystem)
      Deprecated.
      If a file system was previously set use allowIO(IOAccess.newBuilder().fileSystem(fileSystem).build()).
      Installs a new FileSystem.
      Parameters:
      fileSystem - the file system to be installed
      Returns:
      the Context.Builder
      Since:
      19.0
    • serverTransport

      public Context.Builder serverTransport(MessageTransport serverTransport)
      Take over the transport of messages communication with a server peer. Provide an implementation of MessageTransport to 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

      public Context.Builder logHandler(Handler logHandler)
      Installs a new logging Handler. The logger's Level configuration is done using the Context's options. The level option key has the following format: log.languageId.loggerName.level or log.instrumentId.loggerName.level. The value is either the name of a pre-defined Level constant or a numeric Level value. 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 the FINE level to all TruffleLoggers.
      builder.option("log.js.level","FINE"); sets the FINE level to JavaScript TruffleLoggers.
      builder.option("log.js.com.oracle.truffle.js.parser.JavaScriptLanguage.level","FINE"); sets the FINE level to TruffleLogger for the JavaScriptLanguage class.

      If the logHandler is not set on Engine nor on Context, the log messages are printed to Context's error output stream.

      Parameters:
      logHandler - the Handler to use for logging in built Context. The passed logHandler is closed when the context is closed.
      Returns:
      the Context.Builder
      Since:
      19.0
    • timeZone

      public Context.Builder timeZone(ZoneId zone)
      Sets the default time zone to be used for this context. If not set, or explicitly set to null then the system default zone will be used.
      Returns:
      the Context.Builder
      Since:
      19.2.0
      See Also:
    • logHandler

      public Context.Builder logHandler(OutputStream logOut)
      Installs a new logging Handler using given OutputStream. The logger's Level configuration is done using the Context's options. The level option key has the following format: log.languageId.loggerName.level or log.instrumentId.loggerName.level. The value is either the name of pre-defined Level constant or a numeric Level value. 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 the FINE level to all TruffleLoggers.
      builder.option("log.js.level","FINE"); sets the FINE level to JavaScript TruffleLoggers.
      builder.option("log.js.com.oracle.truffle.js.parser.JavaScriptLanguage.level","FINE"); sets the FINE level to TruffleLogger for the JavaScriptLanguage class.

      If the logHandler is not set on Engine nor on Context the log messages are printed to Context's standard output stream.

      Parameters:
      logOut - the OutputStream to use for logging in built Context. The passed logOut stream is closed when the context is closed.
      Returns:
      the Context.Builder
      Since:
      19.0
    • allowCreateProcess

      public Context.Builder allowCreateProcess(boolean enabled)
      If true, allows guest language to execute external processes. Default is false. If all access is set to true, then process creation is enabled if not denied explicitly.
      Parameters:
      enabled - true to enable external process creation
      Since:
      19.1.0
    • processHandler

      public Context.Builder processHandler(ProcessHandler handler)
      Installs a ProcessHandler responsible for external process creation.
      Parameters:
      handler - the handler to be installed
      Since:
      19.1.0
    • resourceLimits

      public Context.Builder resourceLimits(ResourceLimits limits)
      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

      public Context.Builder sandbox(SandboxPolicy policy)
      Sets a code sandbox policy to a context. By default, the context's sandbox policy is SandboxPolicy.TRUSTED, there are no restrictions to the context configuration.
      Since:
      23.0
      See Also:
    • allowEnvironmentAccess

      public Context.Builder allowEnvironmentAccess(EnvironmentAccess accessPolicy)
      Allow environment access using the provided policy. If all access is true then the default environment access policy is EnvironmentAccess.INHERIT, otherwise EnvironmentAccess.NONE. The provided access policy must not be null.
      Parameters:
      accessPolicy - the environment access policy
      Since:
      19.1.0
    • environment

      public Context.Builder environment(String name, String value)
      Sets an environment variable.
      Parameters:
      name - the environment variable name
      value - the environment variable value
      Since:
      19.1.0
    • environment

      public Context.Builder environment(Map<String,String> env)
      Shortcut for setting multiple environment variables using a map. All values of the provided map must be non-null.
      Parameters:
      env - environment variables
      Since:
      19.1.0
      See Also:
    • currentWorkingDirectory

      public Context.Builder currentWorkingDirectory(Path workingDirectory)
      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 the FileSystem.setCurrentWorkingDirectory method.
      Parameters:
      workingDirectory - the new current working directory
      Throws:
      NullPointerException - when workingDirectory is null
      IllegalArgumentException - when workingDirectory is a relative path
      Since:
      20.0.0
    • hostClassLoader

      public Context.Builder hostClassLoader(ClassLoader classLoader)
      Sets a host class loader. If set the given classLoader is used to load host classes and it's also set as a context ClassLoader during code execution. Otherwise the ClassLoader that was captured when the context was built is used to to load host classes and the context ClassLoader is 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

      public Context.Builder useSystemExit(boolean enabled)
      Specifies whether System.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

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