or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/maven-org-graalvm--polyglot

GraalVM Polyglot API - Language-agnostic API for embedding and interoperating between multiple languages

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/org.graalvm/polyglot@24.2.x

To install, run

npx @tessl/cli install tessl/maven-org-graalvm--polyglot@24.2.0

index.mddocs/

GraalVM Polyglot API

Language-agnostic API for embedding and interoperating between multiple programming languages including Python, JavaScript, Ruby, WebAssembly, and others on the GraalVM polyglot platform.

Package Information

Maven Coordinates: org.graalvm:polyglot:24.2.1
License: Universal Permissive License (UPL) 1.0
Platform: GraalVM Community Edition
Documentation: https://www.graalvm.org/latest/docs/

Core Imports

// Core polyglot API
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Engine;
import org.graalvm.polyglot.Value;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.PolyglotException;

// Access control and security
import org.graalvm.polyglot.HostAccess;
import org.graalvm.polyglot.SandboxPolicy;
import org.graalvm.polyglot.PolyglotAccess;
import org.graalvm.polyglot.EnvironmentAccess;

// Resource management
import org.graalvm.polyglot.ResourceLimits;
import org.graalvm.polyglot.ResourceLimitEvent;

// I/O operations
import org.graalvm.polyglot.io.IOAccess;
import org.graalvm.polyglot.io.FileSystem;

// Proxy objects for interoperability
import org.graalvm.polyglot.proxy.*;

// Monitoring and management
import org.graalvm.polyglot.management.ExecutionListener;
import org.graalvm.polyglot.management.ExecutionEvent;

Basic Usage

Simple Code Execution

// Basic JavaScript execution
try (Context context = Context.create("js")) {
    // Execute expressions
    Value result = context.eval("js", "2 + 3 * 4");
    int value = result.asInt(); // 14
    
    // Execute statements
    context.eval("js", "var x = 'Hello from JavaScript'");
    Value greeting = context.eval("js", "x");
    String message = greeting.asString(); // "Hello from JavaScript"
}

// Python execution  
try (Context context = Context.create("python")) {
    Value result = context.eval("python", "len('Hello World')");
    int length = result.asInt(); // 11
}

Data Exchange Between Java and Guest Languages

try (Context context = Context.create("js")) {
    Value bindings = context.getBindings("js");
    
    // Pass Java data to guest language
    bindings.putMember("java_number", 42);
    bindings.putMember("java_string", "Hello");
    bindings.putMember("java_array", new int[]{1, 2, 3, 4, 5});
    
    // Access from JavaScript
    context.eval("js", """
        var result = java_number * 2;
        var message = java_string + " World!";
        var array_sum = java_array.reduce((a, b) => a + b, 0);
        """);
    
    // Get results back to Java
    Value result = bindings.getMember("result");
    Value message = bindings.getMember("message");
    Value arraySum = bindings.getMember("array_sum");
    
    System.out.println(result.asInt());    // 84
    System.out.println(message.asString()); // "Hello World!"
    System.out.println(arraySum.asInt());   // 15
}

Capabilities

Guest Language Code Execution

Execute guest language code with full language support including modules, functions, classes, and standard library access.

// JavaScript execution
try (Context context = Context.create("js")) {
    // Define and call JavaScript functions
    context.eval("js", """
        function factorial(n) {
            if (n <= 1) return 1;
            return n * factorial(n - 1);
        }
        
        function fibonacci(n) {
            let a = 0, b = 1;
            for (let i = 0; i < n; i++) {
                [a, b] = [b, a + b];
            }
            return a;
        }
        """);
    
    Value bindings = context.getBindings("js");
    Value factorial = bindings.getMember("factorial");
    Value fibonacci = bindings.getMember("fibonacci");
    
    // Call JavaScript functions from Java
    int fact5 = factorial.execute(5).asInt(); // 120
    int fib10 = fibonacci.execute(10).asInt(); // 55
}

// Python execution example
try (Context context = Context.create("python")) {
    context.eval("python", "import math");
    Value result = context.eval("python", "math.sqrt(16)");
    double sqrtResult = result.asDouble(); // 4.0
}

Host Object Integration

Expose Java objects and methods to guest languages for seamless interoperability.

public class MathUtils {
    @HostAccess.Export
    public double sqrt(double value) {
        return Math.sqrt(value);
    }
    
    @HostAccess.Export
    public double pow(double base, double exponent) {
        return Math.pow(base, exponent);
    }
    
    @HostAccess.Export
    public final String PI = String.valueOf(Math.PI);
}

try (Context context = Context.newBuilder("python")
        .allowHostAccess(HostAccess.EXPLICIT)
        .build()) {
    
    // Make Java object available to Python
    context.getBindings("python").putMember("math_utils", new MathUtils());
    
    // Use Java methods in Python
    Value result = context.eval("python", """
        import math
        
        # Use Java methods
        sqrt_2 = math_utils.sqrt(2)
        power = math_utils.pow(2, 8)
        pi_value = float(math_utils.PI)
        
        # Combine with Python math
        result = sqrt_2 + power + pi_value
        result
        """);
    
    double finalResult = result.asDouble();
}

File System Operations

Configure file system access for Python code execution with security controls.

try (Context context = Context.newBuilder("python")
        .allowIO(IOAccess.newBuilder()
            .allowHostFileAccess(true)
            .build())
        .build()) {
    
    // Python code can access files
    context.eval("python", """
        with open('example.txt', 'w') as f:
            f.write('Hello from GraalVM Python!')
        
        with open('example.txt', 'r') as f:
            content = f.read()
        
        print(f"File content: {content}")
        """);
}

Multi-Language Polyglot Integration

Combine Python with other languages in the same context.

try (Context context = Context.newBuilder("python", "js")
        .allowPolyglotAccess(PolyglotAccess.ALL)
        .build()) {
    
    Value polyglotBindings = context.getPolyglotBindings();
    
    // Define JavaScript function
    context.eval("js", """
        var jsFunction = function(x, y) {
            return x * y + Math.random();
        };
        """);
    
    polyglotBindings.putMember("jsFunc", 
        context.getBindings("js").getMember("jsFunction"));
    
    // Use JavaScript function from Python
    Value result = context.eval("python", """
        import polyglot
        
        # Access JavaScript function
        js_func = polyglot.import_value("jsFunc")
        result = js_func(10, 20)
        result
        """);
    
    double value = result.asDouble();
}

Resource Management and Security

Control resource usage and implement security policies for safe Python execution.

// Configure resource limits
ResourceLimits limits = ResourceLimits.newBuilder()
    .statementLimit(100000, null) // Limit statements executed
    .onLimit(event -> {
        System.err.printf("Resource limit exceeded: %d/%d statements\n", 
            event.getConsumed(), event.getLimit());
    })
    .build();

try (Context context = Context.newBuilder("python")
        .sandbox(SandboxPolicy.CONSTRAINED)
        .allowHostAccess(HostAccess.CONSTRAINED)
        .allowIO(IOAccess.NONE) // No file system access
        .allowCreateThread(false) // No thread creation
        .allowNativeAccess(false) // No native code
        .resourceLimits(limits)
        .build()) {
    
    // Execute untrusted Python code safely
    Value result = context.eval("python", """
        # This code runs with security restrictions
        total = 0
        for i in range(1000):
            total += i * i
        total
        """);
    
    long safeResult = result.asLong();
}

Exception Handling and Error Management

Handle Python exceptions and errors in Java code with detailed information.

try (Context context = Context.create("python")) {
    try {
        // Execute Python code that may throw
        context.eval("python", """
            def divide(a, b):
                if b == 0:
                    raise ValueError("Cannot divide by zero")
                return a / b
            
            result = divide(10, 0)
            """);
    } catch (PolyglotException e) {
        if (e.isGuestException()) {
            System.err.println("Python exception: " + e.getMessage());
            
            // Get Python exception object
            Value guestException = e.getGuestObject();
            if (guestException != null && guestException.hasMember("__class__")) {
                Value exceptionType = guestException.getMember("__class__")
                    .getMember("__name__");
                System.err.println("Exception type: " + exceptionType.asString());
            }
            
            // Print stack trace
            if (e.getSourceLocation() != null) {
                System.err.println("Location: " + e.getSourceLocation());
            }
        }
    }
}

Advanced Python Module Usage

Work with Python modules, packages, and standard library functionality.

try (Context context = Context.create("python")) {
    // Import and use Python standard library
    context.eval("python", """
        import json
        import datetime
        import urllib.parse
        
        # JSON operations
        data = {"name": "GraalVM", "version": "24.2.1", "languages": ["Python", "Java", "JS"]}
        json_str = json.dumps(data, indent=2)
        parsed_data = json.loads(json_str)
        
        # Date operations
        now = datetime.datetime.now()
        formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
        
        # URL operations
        url = "https://example.com/api?name=GraalVM&version=24.2.1"
        parsed_url = urllib.parse.urlparse(url)
        query_params = urllib.parse.parse_qs(parsed_url.query)
        
        # Create result dictionary
        result = {
            "json_data": parsed_data,
            "timestamp": formatted_date,
            "url_host": parsed_url.netloc,
            "params": query_params
        }
        """);
    
    Value bindings = context.getBindings("python");
    Value result = bindings.getMember("result");
    
    // Access complex Python data structures
    Value jsonData = result.getMember("json_data");
    String projectName = jsonData.getMember("name").asString();
    Value languages = jsonData.getMember("languages");
    
    System.out.println("Project: " + projectName);
    System.out.println("Languages count: " + languages.getArraySize());
}

Custom Proxy Objects

Create Java proxy objects that can be used naturally from Python.

// Custom proxy for Python list-like behavior
public class JavaList implements ProxyArray {
    private final List<Object> list = new ArrayList<>();
    
    @Override
    public Object get(long index) {
        return list.get((int) index);
    }
    
    @Override
    public void set(long index, Value value) {
        Object javaValue = value.isHostObject() ? 
            value.asHostObject() : value.as(Object.class);
        
        if (index == list.size()) {
            list.add(javaValue);
        } else {
            list.set((int) index, javaValue);
        }
    }
    
    @Override
    public long getSize() {
        return list.size();
    }
    
    @Override
    public boolean remove(long index) {
        if (index >= 0 && index < list.size()) {
            list.remove((int) index);
            return true;
        }
        return false;
    }
}

// Custom proxy for Python callable behavior
public class JavaFunction implements ProxyExecutable {
    @Override
    public Object execute(Value... arguments) {
        // Convert arguments and execute Java logic
        double sum = 0;
        for (Value arg : arguments) {
            if (arg.isNumber()) {
                sum += arg.asDouble();
            }
        }
        return sum;
    }
}

try (Context context = Context.newBuilder("python")
        .allowHostAccess(HostAccess.ALL)
        .build()) {
    
    Value bindings = context.getBindings("python");
    
    // Provide custom proxy objects to Python
    bindings.putMember("java_list", new JavaList());
    bindings.putMember("java_func", new JavaFunction());
    
    context.eval("python", """
        # Use Java list like a Python list
        java_list.append(10)
        java_list.append(20)
        java_list.append(30)
        
        print(f"List size: {len(java_list)}")
        print(f"First item: {java_list[0]}")
        
        # Use Java function like Python function
        result = java_func(1, 2, 3, 4, 5)
        print(f"Sum result: {result}")
        """);
}

Performance Monitoring and Execution Tracking

Monitor Python execution with detailed event tracking and performance metrics.

try (Context context = Context.create("python")) {
    
    // Create execution listener for monitoring
    ExecutionListener listener = ExecutionListener.newBuilder()
        .statements(true)
        .expressions(true)
        .onEnter(event -> {
            if (event.isStatement()) {
                System.out.println("Executing statement at: " + 
                    event.getLocation());
            }
        })
        .onReturn(event -> {
            if (event.getReturnValue() != null) {
                System.out.println("Statement returned: " + 
                    event.getReturnValue());
            }
        })
        .attach(context)
        .install();
    
    try {
        // Execute Python code with monitoring
        context.eval("python", """
            def calculate_fibonacci(n):
                if n <= 1:
                    return n
                
                a, b = 0, 1
                for i in range(2, n + 1):
                    a, b = b, a + b
                
                return b
            
            result = calculate_fibonacci(10)
            print(f"Fibonacci(10) = {result}")
            """);
            
    } finally {
        listener.close();
    }
}

Core API Reference

Context Class

The Context class is the main entry point for executing guest languages in GraalVM.

// Static factory methods
Context create(String... permittedLanguages)           // Creates context with default config
Context.Builder newBuilder(String... permittedLanguages) // Creates builder for custom config
Context getCurrent()                                   // Returns currently entered context

// Evaluation methods
Value eval(Source source)                             // Evaluates a source object
Value eval(String languageId, CharSequence source)   // Evaluates code literal
Value parse(Source source)                           // Parses but doesn't evaluate source
Value parse(String languageId, CharSequence source) // Parses code literal

// Bindings and values
Value getPolyglotBindings()                          // Returns polyglot bindings
Value getBindings(String languageId)                 // Returns language-specific bindings
Value asValue(Object hostValue)                      // Converts host value to Value

// Context management
Engine getEngine()                                   // Gets underlying engine
boolean initialize(String languageId)               // Forces language initialization
void enter()                                        // Enters context on current thread
void leave()                                        // Leaves context on current thread
void close()                                        // Closes context and frees resources
void close(boolean cancelIfExecuting)               // Closes with cancellation option
void interrupt(Duration timeout)                    // Interrupts execution (non-destructive)
void safepoint()                                   // Polls safepoint events
void resetLimits()                                 // Resets resource limit accumulators

Engine Class

The Engine class manages language runtimes and provides execution environments.

// Static factory methods  
Engine create()                                      // Creates engine with default config
Engine create(String... permittedLanguages)         // Creates engine with permitted languages
Engine.Builder newBuilder()                         // Creates engine builder
Engine.Builder newBuilder(String... permittedLanguages) // Creates builder with languages
Path findHome()                                     // Finds GraalVM home folder
boolean copyResources(Path targetFolder, String... components) // Copies GraalVM resources

// Engine information
Map<String, Language> getLanguages()                // Gets installed languages
Map<String, Instrument> getInstruments()           // Gets installed instruments
OptionDescriptors getOptions()                      // Gets available engine options
String getVersion()                                 // Gets engine version
String getImplementationName()                      // Gets implementation name
Set<Source> getCachedSources()                     // Returns cached sources

// Engine lifecycle
void close()                                        // Closes engine and frees resources
void close(boolean cancelIfExecuting)               // Closes with cancellation option

Value Class

The Value class represents polyglot values with language-agnostic operations.

// Type checking methods
boolean isNull()                    // Tests if value is null
boolean isBoolean()                 // Tests if value is boolean
boolean isNumber()                  // Tests if value is number  
boolean isString()                  // Tests if value is string
boolean isDate()                    // Tests if value is date
boolean isTime()                    // Tests if value is time
boolean isTimeZone()                // Tests if value is timezone
boolean isInstant()                 // Tests if value is instant
boolean isDuration()                // Tests if value is duration
boolean isHostObject()              // Tests if value is host object
boolean isProxyObject()             // Tests if value is proxy object
boolean isNativePointer()           // Tests if value is native pointer
boolean isException()               // Tests if value is exception
boolean isMetaObject()              // Tests if value is metaobject
boolean isIterator()                // Tests if value is iterator
boolean hasMembers()                // Tests if value has members
boolean hasArrayElements()          // Tests if value has array elements
boolean hasBufferElements()         // Tests if value has buffer elements
boolean hasHashEntries()            // Tests if value has hash entries
boolean hasIterator()               // Tests if value has iterator
boolean canExecute()                // Tests if value can be executed
boolean canInstantiate()            // Tests if value can be instantiated
boolean canInvoke(String identifier) // Tests if member can be invoked

// Value conversion methods
boolean asBoolean()                 // Converts to boolean
byte asByte()                       // Converts to byte
short asShort()                     // Converts to short
int asInt()                         // Converts to int
long asLong()                       // Converts to long
float asFloat()                     // Converts to float
double asDouble()                   // Converts to double
BigInteger asBigInteger()           // Converts to BigInteger
String asString()                   // Converts to string
LocalDate asDate()                  // Converts to LocalDate
LocalTime asTime()                  // Converts to LocalTime
ZoneId asTimeZone()                 // Converts to ZoneId
Instant asInstant()                 // Converts to Instant
Duration asDuration()               // Converts to Duration
long asNativePointer()              // Converts to native pointer
<T> T asHostObject()                // Converts to host object
<T> T as(Class<T> targetType)       // Converts to target type

// Member access methods
Value getMember(String identifier)              // Gets member by identifier
boolean hasMember(String identifier)           // Tests if member exists
Set<String> getMemberKeys()                    // Gets all member keys
void putMember(String identifier, Object value) // Sets member value
boolean removeMember(String identifier)        // Removes member

// Array access methods
Value getArrayElement(long index)              // Gets array element
void setArrayElement(long index, Object value) // Sets array element
boolean removeArrayElement(long index)         // Removes array element
long getArraySize()                           // Gets array size

// Execution methods
Value execute(Object... arguments)                        // Executes with arguments
Value newInstance(Object... arguments)                    // Creates new instance
Value invoke(String identifier, Object... arguments)     // Invokes member

Language Class

The Language class represents an installed guest language.

String getId()                      // Gets language identifier
String getName()                    // Gets language name
String getImplementationName()      // Gets implementation name
String getVersion()                 // Gets language version
OptionDescriptors getOptions()      // Gets language options
Set<String> getMimeTypes()          // Gets supported MIME types
boolean isInteractive()             // Tests if supports interactive evaluation
String getDefaultMimeType()         // Gets default MIME type

Instrument Class

The Instrument class represents instruments that can monitor/alter execution.

String getId()                      // Gets instrument identifier
String getName()                    // Gets instrument name
OptionDescriptors getOptions()      // Gets instrument options
String getVersion()                 // Gets instrument version
<T> T lookup(Class<T> type)         // Looks up instrument service

Source Class

The Source class represents guest language source code.

// Static factory methods
Source create(String language, CharSequence source)  // Creates source from string
Source.Builder newBuilder(String language, CharSequence source) // Builder from string
Source.Builder newBuilder(String language, File file)          // Builder from file
Source.Builder newBuilder(String language, URL url)            // Builder from URL
Source.Builder newBuilder(String language, Reader reader, String name) // Builder from reader

// Source information
String getLanguage()                // Gets source language
String getName()                    // Gets source name
String getPath()                    // Gets source path
URL getURL()                        // Gets source URL
Reader getReader()                  // Gets source reader
int getLength()                     // Gets source length
CharSequence getCharacters()        // Gets source characters
CharSequence getCharacters(int lineNumber) // Gets line characters
int getLineCount()                  // Gets line count
int getLineNumber(int offset)       // Gets line number for offset
int getColumnNumber(int offset)     // Gets column number for offset
int getLineStartOffset(int lineNumber) // Gets line start offset
int getLineLength(int lineNumber)   // Gets line length
String getMimeType()                // Gets MIME type
URI getURI()                        // Gets source URI
boolean isInteractive()             // Tests if interactive
boolean isInternal()                // Tests if internal
boolean isCached()                  // Tests if cached

TypeLiteral Class

The TypeLiteral class captures generic type information for conversions.

// Usage for parameterized type conversions
Value listValue = context.eval("js", "[1, 2, 3]");
List<Integer> list = listValue.as(new TypeLiteral<List<Integer>>() {});

// Captures generic type T for Value.as() conversions
public abstract class TypeLiteral<T> {
    // Internal implementation handles generic type capture
}

SourceSection Class

The SourceSection class represents a contiguous section within a Source.

Source getSource()                  // Gets containing source
int getStartLine()                  // Gets start line number
int getStartColumn()                // Gets start column number
int getEndLine()                    // Gets end line number
int getEndColumn()                  // Gets end column number
int getCharIndex()                  // Gets character index
int getCharLength()                 // Gets character length
int getCharEndIndex()               // Gets end character index
CharSequence getCharacters()        // Gets section characters
boolean isAvailable()               // Tests if section is available

Types

Context Configuration

// Context builder with comprehensive configuration
Context.Builder contextBuilder = Context.newBuilder("python")
    // Security configuration
    .allowHostAccess(HostAccess.EXPLICIT)
    .allowPolyglotAccess(PolyglotAccess.NONE)
    .sandbox(SandboxPolicy.CONSTRAINED)
    
    // I/O configuration
    .allowIO(IOAccess.newBuilder()
        .allowHostFileAccess(false)
        .allowHostSocketAccess(false)
        .build())
    
    // Runtime permissions
    .allowCreateThread(false)
    .allowNativeAccess(false)
    .allowHostClassLoading(false)
    .allowExperimentalOptions(false)
    
    // Environment configuration
    .allowEnvironmentAccess(EnvironmentAccess.NONE)
    .allowCreateProcess(false)
    
    // Streams configuration
    .out(System.out)
    .err(System.err)
    .in(System.in)
    
    // Resource limits
    .resourceLimits(ResourceLimits.newBuilder()
        .statementLimit(50000, null)
        .build())
    
    // Options
    .option("python.ForceImportSite", "false")
    .option("python.DontWriteBytecodeFlag", "true");

Context context = contextBuilder.build();

Engine Configuration

// Engine configuration for shared runtime
Engine.Builder engineBuilder = Engine.newBuilder()
    .allowExperimentalOptions(true)
    .useSystemProperties(false)
    
    // Logging configuration
    .logHandler(Level.INFO, record -> {
        System.out.printf("[%s] %s: %s%n",
            record.getLevel(),
            record.getLoggerName(),
            record.getMessage());
    })
    
    // Options for performance
    .option("engine.WarnInterpreterOnly", "false")
    .option("engine.CompilationFailureAction", "ExitVM")
    .option("engine.CompilationStatistics", "true");

Engine engine = engineBuilder.build();

Value Type Operations

// Comprehensive value type checking and conversion
public class ValueProcessor {
    
    public static Object processValue(Value value) {
        // Type checking
        if (value.isNull()) {
            return null;
        } else if (value.isBoolean()) {
            return value.asBoolean();
        } else if (value.isNumber()) {
            if (value.fitsInInt()) {
                return value.asInt();
            } else if (value.fitsInLong()) {
                return value.asLong();
            } else if (value.fitsInDouble()) {
                return value.asDouble();
            }
        } else if (value.isString()) {
            return value.asString();
        } else if (value.isDate()) {
            return value.asDate();
        } else if (value.isTime()) {
            return value.asTime();
        } else if (value.isTimeZone()) {
            return value.asTimeZone();
        } else if (value.isInstant()) {
            return value.asInstant();
        } else if (value.isDuration()) {
            return value.asDuration();
        } else if (value.hasArrayElements()) {
            return processArray(value);
        } else if (value.hasMembers()) {
            return processObject(value);
        } else if (value.canExecute()) {
            return new ExecutableWrapper(value);
        }
        
        return value.toString();
    }
    
    private static List<Object> processArray(Value arrayValue) {
        List<Object> result = new ArrayList<>();
        long size = arrayValue.getArraySize();
        
        for (long i = 0; i < size; i++) {
            Value element = arrayValue.getArrayElement(i);
            result.add(processValue(element));
        }
        
        return result;
    }
    
    private static Map<String, Object> processObject(Value objectValue) {
        Map<String, Object> result = new HashMap<>();
        Set<String> memberKeys = objectValue.getMemberKeys();
        
        for (String key : memberKeys) {
            Value member = objectValue.getMember(key);
            result.put(key, processValue(member));
        }
        
        return result;
    }
    
    private static class ExecutableWrapper {
        private final Value executable;
        
        public ExecutableWrapper(Value executable) {
            this.executable = executable;
        }
        
        public Object call(Object... args) {
            Value result = executable.execute(args);
            return processValue(result);
        }
    }
}

Source Management

// Source creation and management
public class PythonSourceManager {
    
    public static Source createFromString(String code) {
        return Source.create("python", code);
    }
    
    public static Source createFromFile(Path filePath) throws IOException {
        return Source.newBuilder("python", filePath.toFile())
            .name(filePath.getFileName().toString())
            .cached(true)
            .build();
    }
    
    public static Source createInteractive(String code) {
        return Source.newBuilder("python", code)
            .name("interactive")
            .interactive(true)
            .cached(false)
            .build();
    }
    
    public static Source createModule(String moduleName, String code) {
        return Source.newBuilder("python", code)
            .name(moduleName + ".py")
            .mimeType("text/x-python")
            .cached(true)
            .build();
    }
}

Advanced Security Configuration

// Custom host access configuration
public class CustomHostAccess {
    
    public static HostAccess createRestrictedAccess() {
        return HostAccess.newBuilder()
            .allowPublicAccess(false)
            .allowArrayAccess(true)
            .allowListAccess(true)
            .allowMapAccess(false)
            .allowIterableAccess(true)
            .allowIteratorAccess(true)
            .allowBufferAccess(false)
            .allowAccessInheritance(false)
            .methodScoping(true)
            .build();
    }
    
    public static PolyglotAccess createIsolatedPolyglot() {
        return PolyglotAccess.newBuilder()
            .denyEval("python", "js")
            .denyEval("js", "python")
            .allowBindingsAccess("python")
            .build();
    }
}

Exception Information Extraction

// Comprehensive exception handling
public class PolyglotExceptionHandler {
    
    public static class ExceptionInfo {
        public final String type;
        public final String message;
        public final String sourceLocation;
        public final List<String> stackTrace;
        public final boolean isHostException;
        public final boolean isSyntaxError;
        
        public ExceptionInfo(PolyglotException e) {
            this.type = determineExceptionType(e);
            this.message = e.getMessage();
            this.sourceLocation = formatSourceLocation(e);
            this.stackTrace = extractStackTrace(e);
            this.isHostException = e.isHostException();
            this.isSyntaxError = e.isSyntaxError();
        }
        
        private String determineExceptionType(PolyglotException e) {
            if (e.isHostException()) return "HostException";
            if (e.isSyntaxError()) return "SyntaxError";
            if (e.isCancelled()) return "Cancelled";
            if (e.isExit()) return "Exit";
            if (e.isInterrupted()) return "Interrupted";
            if (e.isInternalError()) return "InternalError";
            if (e.isResourceExhausted()) return "ResourceExhausted";
            return "GuestException";
        }
        
        private String formatSourceLocation(PolyglotException e) {
            var location = e.getSourceLocation();
            if (location != null) {
                return String.format("%s:%d:%d",
                    location.getSource().getName(),
                    location.getStartLine(),
                    location.getStartColumn());
            }
            return "unknown";
        }
        
        private List<String> extractStackTrace(PolyglotException e) {
            List<String> trace = new ArrayList<>();
            for (var frame : e.getPolyglotStackTrace()) {
                trace.add(frame.toString());
            }
            return trace;
        }
    }
    
    public static ExceptionInfo analyzeException(PolyglotException e) {
        return new ExceptionInfo(e);
    }
}

PolyglotException Class

The PolyglotException class handles exceptions from guest language execution.

// Exception type checking methods
boolean isHostException()           // Tests if caused by host exception
boolean isGuestException()          // Tests if caused by guest language
boolean isSyntaxError()             // Tests if caused by syntax error
boolean isCancelled()               // Tests if caused by context cancellation
boolean isExit()                    // Tests if caused by context exit
boolean isInterrupted()             // Tests if caused by thread interruption
boolean isInternalError()           // Tests if caused by internal error
boolean isResourceExhausted()       // Tests if caused by resource exhaustion

// Exception information methods
int getExitStatus()                 // Gets exit status if isExit() returns true
Value getGuestObject()              // Gets guest language exception object
Throwable asHostException()         // Gets original host exception
SourceSection getSourceLocation()   // Gets source location of error
Iterable<StackFrame> getPolyglotStackTrace() // Gets polyglot stack trace

SandboxPolicy Enum

The SandboxPolicy enum defines security sandbox policies for contexts and engines.

// Enum constants
TRUSTED                             // No restrictions (default) - for fully trusted applications
CONSTRAINED                         // Trusted but potentially buggy applications - shared heap/VM
ISOLATED                            // Trusted applications with potential vulnerabilities - separate VM instances  
UNTRUSTED                           // Fully untrusted applications - additional hardening mechanisms

// Methods
boolean isStricterThan(SandboxPolicy other)     // Tests if this policy is stricter than other
boolean isStricterOrEqual(SandboxPolicy other)  // Tests if this policy is stricter or equal to other
String name()                                   // Gets policy name
static SandboxPolicy valueOf(String name)       // Gets policy by name
static SandboxPolicy[] values()                 // Gets all policies

Access Control APIs

Comprehensive access control and security configuration for polyglot contexts.

// HostAccess - Controls guest language access to host methods and fields
public final class HostAccess {
    // Predefined policies
    static final HostAccess EXPLICIT;              // Requires @Export annotation
    static final HostAccess SCOPED;                // Explicit with scoped callback parameters
    static final HostAccess NONE;                  // No access to methods or fields
    static final HostAccess ALL;                   // Full unrestricted access (discouraged)
    static final HostAccess CONSTRAINED;           // For CONSTRAINED sandbox policy
    static final HostAccess ISOLATED;              // For ISOLATED sandbox policy
    static final HostAccess UNTRUSTED;             // For UNTRUSTED sandbox policy
    
    // Factory methods
    static Builder newBuilder();                   // Creates custom host access builder
    static Builder newBuilder(HostAccess conf);    // Creates builder from existing config
    
    // Builder methods
    public static class Builder {
        Builder allowPublicAccess(boolean allow);           // Allows access to all public members
        Builder allowAccessInheritance(boolean allow);      // Allows access inheritance
        Builder allowArrayAccess(boolean allow);            // Allows array access
        Builder allowListAccess(boolean allow);             // Allows List access
        Builder allowBufferAccess(boolean allow);           // Allows buffer access
        Builder allowIterableAccess(boolean allow);         // Allows Iterable access
        Builder allowIteratorAccess(boolean allow);         // Allows Iterator access
        Builder allowMapAccess(boolean allow);              // Allows Map access
        Builder allowAllImplementations(boolean allow);     // Allows all interface implementations
        Builder allowAllClassImplementations(boolean allow); // Allows all class implementations
        Builder methodScoping(boolean enable);              // Enables method scoping
        HostAccess build();                                 // Creates HostAccess instance
    }
    
    // Export annotation for marking accessible members
    @interface Export {
        // Annotation to mark host methods/fields accessible to guest languages
    }
}

// PolyglotAccess - Controls access between different guest languages
public final class PolyglotAccess {
    // Predefined policies
    static final PolyglotAccess NONE;              // No access between languages
    static final PolyglotAccess ALL;               // Full access between all languages
    
    // Factory methods
    static Builder newBuilder();                   // Creates polyglot access builder
    
    // Builder methods
    public static class Builder {
        Builder allowEval(String fromLanguage, String toLanguage); // Allows evaluation access
        Builder allowBindingsAccess(String language);       // Allows bindings access
        Builder denyEval(String fromLanguage, String toLanguage); // Denies evaluation access
        Builder denyBindingsAccess(String language);        // Denies bindings access
        PolyglotAccess build();                             // Creates PolyglotAccess instance
    }
}

// EnvironmentAccess - Controls access to process environment variables
public final class EnvironmentAccess {
    // Predefined policies
    static final EnvironmentAccess NONE;           // No environment variable access
    static final EnvironmentAccess INHERIT;        // Inherits host process environment
}

// IOAccess - Controls guest language access to host I/O operations
public final class IOAccess {
    // Predefined policies
    static final IOAccess NONE;                    // No I/O access
    static final IOAccess ALL;                     // Full I/O access
    
    // Factory methods
    static Builder newBuilder();                   // Creates I/O access builder
    
    // Builder methods
    public static class Builder {
        Builder allowHostFileAccess(boolean allow); // Allows host file system access
        Builder allowHostSocketAccess(boolean allow); // Allows host socket access
        Builder fileSystem(FileSystem fileSystem);   // Sets custom file system
        IOAccess build();                           // Creates IOAccess instance
    }
}

Resource Management APIs

Resource limits and monitoring for controlling execution consumption.

// ResourceLimits - Configuration for resource consumption limits
public final class ResourceLimits {
    static Builder newBuilder();                   // Creates resource limits builder
    
    // Builder methods
    public static class Builder {
        Builder statementLimit(long limit, Predicate<Source> sourceFilter); // Sets statement execution limit
        Builder onLimit(Consumer<ResourceLimitEvent> onLimit); // Sets limit exceeded handler
        ResourceLimits build();                    // Creates ResourceLimits instance
    }
}

// ResourceLimitEvent - Event fired when resource limits are exceeded
public final class ResourceLimitEvent {
    Context getContext();                          // Gets context where limit was exceeded
    long getConsumed();                           // Gets amount of resource consumed
    long getLimit();                              // Gets configured resource limit
}

Proxy Interfaces

Comprehensive proxy interfaces for Java-guest language interoperability.

// Base proxy interface
public interface Proxy {}

// Object with members (properties)
public interface ProxyObject extends Proxy {
    Object getMember(String key);                    // Gets member value
    Object getMemberKeys();                          // Gets all member keys
    boolean hasMember(String key);                   // Tests if member exists
    void putMember(String key, Object value);        // Sets member value
    boolean removeMember(String key);                // Removes member
}

// Array-like objects
public interface ProxyArray extends ProxyIterable {
    Object get(long index);                          // Gets array element
    void set(long index, Value value);               // Sets array element
    long getSize();                                  // Gets array size
    boolean remove(long index);                      // Removes array element
}

// Executable objects (functions)
public interface ProxyExecutable extends Proxy {
    Object execute(Value... arguments);              // Executes with arguments
}

// Instantiable objects (constructors)
public interface ProxyInstantiable extends Proxy {
    Object newInstance(Value... arguments);          // Creates new instance
}

// Iterable objects
public interface ProxyIterable extends Proxy {
    Object getIterator();                            // Gets iterator object
}

// Iterator objects
public interface ProxyIterator extends Proxy {
    boolean hasNext();                               // Tests if more elements available
    Object getNext();                                // Gets next element
}

// Hash map objects
public interface ProxyHashMap extends Proxy {
    long getHashSize();                              // Gets hash map size
    boolean hasHashEntry(Object key);                // Tests if key exists
    Object getHashValue(Object key);                 // Gets value for key
    void putHashEntry(Object key, Value value);      // Sets key-value pair
    boolean removeHashEntry(Object key);             // Removes entry
    Object getHashEntriesIterator();                 // Gets entries iterator
}

// Date/Time proxy interfaces
public interface ProxyDate extends Proxy {
    LocalDate asDate();                              // Gets date value
}

public interface ProxyTime extends Proxy {
    LocalTime asTime();                              // Gets time value
}

public interface ProxyTimeZone extends Proxy {
    ZoneId asTimeZone();                             // Gets timezone value
}

public interface ProxyInstant extends Proxy {
    Instant asInstant();                             // Gets instant value
}

public interface ProxyDuration extends Proxy {
    Duration asDuration();                           // Gets duration value
}

// Native pointer objects
public interface ProxyNativeObject extends Proxy {
    long asPointer();                                // Gets native pointer value
}

I/O and Communication APIs

Advanced I/O and communication interfaces for polyglot contexts.

// File system interface for custom implementations
public interface FileSystem {
    Path parsePath(URI uri);                         // Parses URI to path
    Path parsePath(String path);                     // Parses string to path
    void checkAccess(Path path, Set<? extends AccessMode> modes, LinkOption... linkOptions);
    void createDirectory(Path dir, FileAttribute<?>... attrs); // Creates directory
    void delete(Path path);                          // Deletes file or directory
    SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs);
    DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter);
    Path toAbsolutePath(Path path);                  // Converts to absolute path
    Path toRealPath(Path path, LinkOption... linkOptions); // Gets real path
    Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options);
}

// Process handler for external process creation
public interface ProcessHandler {
    Process start(ProcessCommand command);           // Starts external process
}

// Message transport for server endpoints
public interface MessageTransport {
    MessageEndpoint open(URI uri, MessageEndpoint peerEndpoint); // Opens message endpoint
}

// Message communication endpoint
public interface MessageEndpoint {
    void sendText(String text);                      // Sends text message
    void sendBinary(ByteBuffer data);                // Sends binary message
    void sendPing(ByteBuffer data);                  // Sends ping
    void sendPong(ByteBuffer data);                  // Sends pong
    void sendClose();                                // Sends close frame
}

// Immutable byte sequence
public interface ByteSequence {
    int length();                                    // Gets sequence length
    byte byteAt(int index);                          // Gets byte at index
    ByteSequence subSequence(int startIndex, int endIndex); // Gets subsequence
    byte[] toByteArray();                            // Converts to byte array
    static ByteSequence create(byte[] buffer);       // Creates from byte array
}

Management and Monitoring

Execution monitoring and performance tracking APIs.

// Execution listener for monitoring guest language execution
public final class ExecutionListener implements AutoCloseable {
    static Builder newBuilder();                     // Creates execution listener builder
    void close();                                   // Closes listener and stops monitoring
    
    // Builder methods
    public static class Builder {
        Builder expressions(boolean expressions);    // Enables expression event collection
        Builder statements(boolean statements);      // Enables statement event collection
        Builder roots(boolean roots);               // Enables root event collection
        Builder onEnter(Consumer<ExecutionEvent> callback); // Sets enter event handler
        Builder onReturn(Consumer<ExecutionEvent> callback); // Sets return event handler
        Builder attach(Engine engine);              // Attaches to engine
        Builder attach(Context context);            // Attaches to context
        ExecutionListener install();                // Installs listener
    }
}

// Execution event fired during guest language execution
public final class ExecutionEvent {
    String getRootName();                           // Gets root function/method name
    SourceSection getLocation();                    // Gets source location
    boolean isExpression();                         // Tests if event is for expression
    boolean isStatement();                          // Tests if event is for statement
    boolean isRoot();                               // Tests if event is for root
    Value getReturnValue();                         // Gets return value (for return events)
    RuntimeException getException();                // Gets exception (for exception events)
}

Builder Pattern APIs

Comprehensive builder pattern documentation for context and engine configuration.

// Context.Builder methods
public static class Context.Builder {
    Builder engine(Engine engine);                  // Sets underlying engine
    Builder out(OutputStream out);                  // Sets standard output stream
    Builder err(OutputStream err);                  // Sets error output stream
    Builder in(InputStream in);                     // Sets input stream
    Builder allowHostAccess(HostAccess config);     // Configures host access policy
    Builder allowNativeAccess(boolean enabled);     // Allows native interface access
    Builder allowCreateThread(boolean enabled);     // Allows guest languages to create threads
    Builder allowAllAccess(boolean enabled);        // Sets default value for all privileges
    Builder allowHostClassLoading(boolean enabled); // Enables host class loading
    Builder allowHostClassLookup(Predicate<String> classFilter); // Sets host class lookup filter
    Builder allowExperimentalOptions(boolean enabled); // Allows experimental options
    Builder allowPolyglotAccess(PolyglotAccess accessPolicy); // Sets polyglot access policy
    Builder allowValueSharing(boolean enabled);     // Enables/disables value sharing
    Builder allowInnerContextOptions(boolean enabled); // Allows inner contexts to change options
    Builder option(String key, String value);       // Sets context option
    Builder options(Map<String, String> options);   // Sets multiple options
    Builder arguments(String language, String[] args); // Sets guest language application arguments
    Builder allowIO(IOAccess ioAccess);             // Configures IO access
    Builder allowCreateProcess(boolean enabled);     // Allows external process creation
    Builder allowEnvironmentAccess(EnvironmentAccess accessPolicy); // Sets environment access policy
    Builder environment(String name, String value); // Sets environment variable
    Builder resourceLimits(ResourceLimits limits);  // Assigns resource limit configuration
    Builder sandbox(SandboxPolicy policy);          // Sets sandbox policy
    Builder timeZone(ZoneId zone);                  // Sets default time zone
    Builder currentWorkingDirectory(Path workingDirectory); // Sets current working directory
    Builder hostClassLoader(ClassLoader classLoader); // Sets host class loader
    Builder useSystemExit(boolean enabled);         // Specifies System.exit usage for context exit
    Context build();                                // Creates context instance
}

// Engine.Builder methods
public static class Engine.Builder {
    Builder out(OutputStream out);                  // Sets standard output stream
    Builder err(OutputStream err);                  // Sets error output stream
    Builder in(InputStream in);                     // Sets input stream
    Builder allowExperimentalOptions(boolean enabled); // Allows experimental options
    Builder useSystemProperties(boolean enabled);   // Uses system properties for options
    Builder option(String key, String value);      // Sets engine option
    Builder options(Map<String, String> options);  // Sets multiple options
    Builder sandbox(SandboxPolicy policy);         // Sets sandbox policy
    Builder serverTransport(MessageTransport serverTransport); // Sets message transport
    Builder logHandler(Handler logHandler);        // Sets logging handler
    Builder logHandler(OutputStream logOut);       // Sets logging output stream
    Engine build();                                // Creates engine instance
}

// Source.Builder methods
public static class Source.Builder {
    Builder name(String name);                     // Sets source name
    Builder mimeType(String mimeType);             // Sets MIME type
    Builder content(String content);               // Sets content
    Builder cached(boolean cached);                // Sets caching behavior
    Builder interactive(boolean interactive);      // Sets interactive mode
    Builder internal(boolean internal);            // Sets internal mode
    Builder encoding(Charset encoding);            // Sets character encoding
    Builder uri(URI uri);                          // Sets URI
    Source build();                                // Creates source instance
}

This comprehensive documentation provides Java developers with everything needed to integrate Python functionality into their applications using GraalVM's polyglot platform. The examples demonstrate practical usage patterns, security considerations, performance monitoring, and advanced interoperability scenarios between Java and Python code.