or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

context-management.mdengine-management.mdexecution-monitoring.mdindex.mdio-abstractions.mdproxy-system.mdsecurity-configuration.mdsource-management.mdvalue-operations.md
tile.json

tessl/maven-org-graalvm-polyglot--polyglot

GraalVM Polyglot API for embedding multiple programming languages in Java applications with secure language interoperability

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

To install, run

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

index.mddocs/

GraalVM Polyglot API

The GraalVM Polyglot API provides a comprehensive framework for embedding multiple programming languages in Java applications. It enables secure, high-performance polyglot programming with seamless language interoperability, allowing Java applications to execute code in languages like JavaScript, Python, R, Ruby, and LLVM-based languages while maintaining security boundaries and sharing data efficiently.

Package Information

  • Package Name: org.graalvm.polyglot:polyglot
  • Package Type: Maven
  • Language: Java (JDK 17+)
  • Installation: Add to Maven dependencies: <groupId>org.graalvm.polyglot</groupId><artifactId>polyglot</artifactId><version>25.0.0</version>

Core Imports

import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Engine;
import org.graalvm.polyglot.Value;
import org.graalvm.polyglot.Source;

Basic Usage

import org.graalvm.polyglot.*;

// Create a context for JavaScript execution
try (Context context = Context.create("js")) {
    // Execute JavaScript code
    Value result = context.eval("js", "40 + 2");
    System.out.println("Result: " + result.asInt()); // 42
    
    // Work with polyglot values
    context.getBindings("js").putMember("javaNumber", 123);
    Value jsFunction = context.eval("js", "(function(x) { return x * 2; })");
    Value doubled = jsFunction.execute(result);
    System.out.println("Doubled: " + doubled.asInt()); // 84
}

// Create an engine for reuse across contexts  
try (Engine engine = Engine.create()) {
    Context.Builder builder = Context.newBuilder()
        .engine(engine)
        .allowHostAccess(HostAccess.ALL)
        .allowPolyglotAccess(PolyglotAccess.ALL);
        
    try (Context context = builder.build()) {
        // Share Java objects with guest languages
        MyJavaObject javaObj = new MyJavaObject();
        context.getBindings("js").putMember("javaObj", javaObj);
        context.eval("js", "javaObj.someMethod('hello from JS')");
    }
}

Architecture

The GraalVM Polyglot API is built around several key components:

  • Engine: Central execution engine managing language implementations, shared caches, and instrument coordination
  • Context: Isolated execution environment for polyglot code with configurable security and resource policies
  • Value: Universal representation for values exchanged between languages, supporting all data types and operations
  • Source: Abstraction for executable source code with metadata support and caching capabilities
  • Proxy System: Interfaces enabling Java objects to be seamlessly used in guest languages with custom behaviors
  • Security Framework: Comprehensive access controls for host system resources, cross-language interactions, and sandboxing
  • I/O Abstraction: Pluggable file systems, process handlers, and message transports for controlled environment interaction

Capabilities

Context Management

Core context creation and lifecycle management for polyglot execution environments. Provides isolated execution spaces with configurable security policies, resource limits, and language access controls.

public final class Context implements AutoCloseable {
    // Static factory methods
    public static Context create(String... permittedLanguages);
    public static Context.Builder newBuilder(String... permittedLanguages);
    public static Context getCurrent();
    
    // Evaluation methods
    public Value eval(String languageId, CharSequence source);
    public Value eval(Source source);
    public Value parse(String languageId, CharSequence source);
    public Value parse(Source source);
    
    // Bindings and initialization
    public Value getBindings(String languageId);
    public Value getPolyglotBindings();
    public boolean initialize(String languageId);
    
    // Value conversion
    public Value asValue(Object hostValue);
    
    // Context lifecycle and thread management
    public void enter();
    public void leave();
    public void close();
    public void close(boolean cancelIfExecuting);
    public void interrupt(Duration timeout) throws TimeoutException;
    public void safepoint();
    
    // Resource management
    public void resetLimits();
    public Engine getEngine();
}

Context Management

Engine Management

Engine creation and management for shared polyglot execution infrastructure. Engines coordinate multiple contexts, manage compilation caches, and provide access to installed languages and instruments.

public final class Engine implements AutoCloseable {
    // Static factory methods
    public static Engine create();
    public static Engine create(String... permittedLanguages);
    public static Engine.Builder newBuilder();
    public static Engine.Builder newBuilder(String... permittedLanguages);
    public static Path findHome();
    public static boolean copyResources(Path targetFolder, String... components) throws IOException;
    
    // Engine information
    public Map<String, Language> getLanguages();
    public Map<String, Instrument> getInstruments();
    public OptionDescriptors getOptions();
    public String getVersion();
    public String getImplementationName();
    
    // Cache operations
    public Set<Source> getCachedSources();
    public boolean storeCache(Path targetFile) throws UnsupportedOperationException;
    public boolean storeCache(Path targetFile, WordPointer cancelledWord) throws CancellationException, UnsupportedOperationException;
    
    // Engine lifecycle
    public void close();
    public void close(boolean cancelIfExecuting);
}

Engine Management

Value Operations

Universal value representation and manipulation for cross-language data exchange. Values provide unified access to all language types including objects, arrays, functions, and primitives with automatic type conversions.

public final class Value extends AbstractValue {
    // Type checking
    public boolean isNull();
    public boolean isBoolean();
    public boolean isNumber();
    public boolean isString();
    public boolean isDate();
    public boolean isTime();
    public boolean isTimeZone();
    public boolean isInstant();
    public boolean isDuration();
    public boolean isHostObject();
    public boolean isProxyObject();
    public boolean isNativePointer();
    public boolean isException();
    public boolean isMetaObject();
    public boolean isScope();
    
    // Value conversion - basic types
    public boolean asBoolean();
    public String asString();
    public byte asByte();
    public short asShort();
    public int asInt();
    public long asLong();
    public BigInteger asBigInteger();
    public float asFloat();
    public double asDouble();
    public <T> T asHostObject();
    public long asNativePointer();
    
    // Advanced type fitting checks
    public boolean fitsInByte();
    public boolean fitsInShort();
    public boolean fitsInInt();
    public boolean fitsInLong();
    public boolean fitsInBigInteger();
    public boolean fitsInFloat();
    public boolean fitsInDouble();
    
    // Date/Time conversion
    public LocalDate asDate();
    public LocalTime asTime();
    public ZoneId asTimeZone();
    public Instant asInstant();
    public Duration asDuration();
    
    // Advanced conversion
    public <T> T as(Class<T> targetType);
    public <T> T as(TypeLiteral<T> targetType);
    
    // Member operations
    public boolean hasMembers();
    public Object getMemberKeys();
    public Value getMember(String key);
    public boolean hasMember(String key);
    public void putMember(String key, Object value);
    public boolean removeMember(String key);
    
    // Array operations
    public boolean hasArrayElements();
    public Value getArrayElement(long index);
    public void setArrayElement(long index, Object value);
    public boolean removeArrayElement(long index);
    public long getArraySize();
    
    // Buffer operations
    public boolean hasBufferElements();
    public boolean isBufferWritable();
    public long getBufferSize();
    public byte readBufferByte(long byteOffset);
    public void writeBufferByte(long byteOffset, byte value);
    // ... additional buffer read/write methods for other primitive types with ByteOrder
    
    // Execution
    public boolean canExecute();
    public Value execute(Object... arguments);
    public boolean canInstantiate();
    public Value newInstance(Object... arguments);
    
    // Iterator operations
    public boolean hasIterator();
    public Value getIterator();
    public boolean isIterator();
    public boolean hasIteratorNextElement();
    public Value getIteratorNextElement();
    
    // Hash/Map operations
    public boolean hasHashEntries();
    public long getHashSize();
    public boolean hasHashEntry(Object key);
    public Value getHashValue(Object key);
    public Value getHashValueOrDefault(Object key, Object defaultValue);
    public void putHashEntry(Object key, Object value);
    public boolean removeHashEntry(Object key);
    public Value getHashEntriesIterator();
    public Value getHashKeysIterator();
    public Value getHashValuesIterator();
    
    // Meta-object operations
    public Value getMetaObject();
    public String getMetaQualifiedName();
    public String getMetaSimpleName();
    public boolean isMetaInstance(Object instance);
    public boolean hasMetaParents();
    public Value getMetaParents();
    
    // Exception handling
    public RuntimeException throwException();
    
    // Scoped values
    public Value pin();
}

Value Operations

Source Management

Source code representation and management for polyglot execution. Provides creation from various inputs, metadata handling, and caching support for optimal performance.

public final class Source {
    public static Source create(String language, CharSequence source);
    public static Source.Builder newBuilder(String language, File file);
    public static Source.Builder newBuilder(String language, URL url);
    public static Source.Builder newBuilder(String language, Reader source, String name);
    public CharSequence getCharacters();
    public String getName();
    public String getMimeType();
    public String getLanguage();
}

Source Management

Security Configuration

Comprehensive security and access control configuration for polyglot environments. Enables fine-grained control over host system access, cross-language interactions, and resource consumption.

public final class HostAccess {
    public static final HostAccess ALL;
    public static final HostAccess EXPLICIT;
    public static final HostAccess SCOPED;
    public static final HostAccess NONE;
    public static final HostAccess CONSTRAINED;
    public static final HostAccess ISOLATED;
    public static final HostAccess UNTRUSTED;
    public static HostAccess.Builder newBuilder();
    public static HostAccess.Builder newBuilder(HostAccess prototype);
}

public final class PolyglotAccess {
    public static final PolyglotAccess ALL;
    public static final PolyglotAccess NONE; 
    public static PolyglotAccess.Builder newBuilder();
}

public final class IOAccess {
    public static final IOAccess ALL;
    public static final IOAccess NONE;
    public static IOAccess.Builder newBuilder();
    public static IOAccess.Builder newBuilder(IOAccess prototype);
}

public enum SandboxPolicy {
    TRUSTED, CONSTRAINED, ISOLATED, UNTRUSTED
}

Security Configuration

Proxy System

Interfaces for exposing Java objects to guest languages with customizable behaviors. Enables seamless integration of Java objects into polyglot environments with support for object members, arrays, functions, and specialized types.

public interface Proxy {
    // Base marker interface for all proxy types
}

public interface ProxyObject extends Proxy {
    Object getMember(String key);
    Object getMemberKeys();
    boolean hasMember(String key);
    void putMember(String key, Value value);
    default boolean removeMember(String key) { return false; }
}

public interface ProxyExecutable extends Proxy {
    Object execute(Value... arguments);
}

public interface ProxyInstantiable extends Proxy {
    Object newInstance(Value... arguments);
}

public interface ProxyArray extends Proxy {
    Object get(long index);
    void set(long index, Value value);
    long getSize();
    default boolean remove(long index) { return false; }
}

public interface ProxyIterable extends Proxy {
    Object getIterator();
}

public interface ProxyIterator extends Proxy {
    boolean hasIteratorNextElement();
    Object getIteratorNextElement();
}

public interface ProxyHashMap extends Proxy {
    long getHashSize();
    boolean hasHashEntry(Object key);
    Object getHashValue(Object key);
    void putHashEntry(Object key, Value value);
    boolean removeHashEntry(Object key);
    Object getHashEntriesIterator();
}

public interface ProxyNativeObject extends Proxy {
    // Native object representation
}

// Temporal proxy interfaces
public interface ProxyDate extends Proxy {
    LocalDate asDate();
}

public interface ProxyTime extends Proxy {
    LocalTime asTime();
}

public interface ProxyTimeZone extends Proxy {
    ZoneId asTimeZone();
}

public interface ProxyInstant extends Proxy {
    Instant asInstant();
}

public interface ProxyDuration extends Proxy {
    Duration asDuration();
}

Proxy System

I/O Abstractions

Pluggable I/O system for controlled file system access, process execution, and message communication. Enables sandboxed environments with custom I/O behavior while maintaining security boundaries.

public interface FileSystem {
    Path parsePath(URI uri);
    void checkAccess(Path path, Set<AccessMode> modes);
    void createDirectory(Path dir);
    SeekableByteChannel newByteChannel(Path path, Set<OpenOption> options);
    DirectoryStream<Path> newDirectoryStream(Path dir);
}

public interface ProcessHandler {
    Process start(ProcessCommand command);
}

public interface MessageTransport {
    MessageEndpoint open(URI uri, MessageEndpoint endpoint);
}

public final class IOHelper {
    // Utility methods for I/O operations
    public static FileSystem newDefaultFileSystem();
    public static ProcessHandler newDefaultProcessHandler();
}

I/O Abstractions

Execution Monitoring

Advanced execution monitoring and instrumentation capabilities for polyglot environments. Provides detailed execution events, performance metrics, and debugging support across all supported languages.

public final class ExecutionListener implements AutoCloseable {
    public static ExecutionListener.Builder newBuilder();
    public ExecutionListener attach(Engine engine);
    public void close();
}

public final class ExecutionEvent {
    public SourceSection getLocation();
    public Value getReturnValue();
    public RuntimeException getException();
    public List<Value> getInputValues();
}

Execution Monitoring

Types

public final class Language {
    public String getId();
    public String getName();
    public String getImplementationName();
    public String getVersion();
    public Set<String> getMimeTypes();
    public OptionValues getOptions();
}

public final class Instrument {
    public String getId();
    public String getName();
    public String getVersion();
    public OptionValues getOptions();
    public <T> T lookup(Class<T> type);
}

public final class PolyglotException extends RuntimeException {
    public boolean isGuestException();
    public boolean isHostException();
    public RuntimeException asHostException();
    public Value getGuestObject();
    public StackTraceElement[] getPolyglotStackTrace();
    public SourceSection getSourceLocation();
}

public final class SourceSection {
    public Source getSource();
    public int getStartLine();
    public int getEndLine();
    public int getStartColumn();
    public int getEndColumn();
    public CharSequence getCharacters();
}

public final class ResourceLimits {
    public static ResourceLimits.Builder newBuilder();
}

public final class ResourceLimitEvent {
    public String getLimit();
    public Context getContext();
}

public final class EnvironmentAccess {
    public static final EnvironmentAccess INHERIT;
    public static final EnvironmentAccess NONE;
    public static EnvironmentAccess.Builder newBuilder();
}

public final class TypeLiteral<T> {
    // Factory and utility methods for generic type handling
}

public interface ByteSequence {
    byte byteAt(int index);
    int length();
    ByteSequence subSequence(int start, int end);
    byte[] toByteArray();
}

public final class ByteArraySequence implements ByteSequence {
    public static ByteSequence create(byte[] buffer);
    public static ByteSequence create(byte[] buffer, int byteOffset, int length);
}

public interface MessageEndpoint {
    MessageEndpoint open(URI uri, MessageEndpoint endpoint) throws IOException;
    void sendText(String text) throws IOException;
    void sendBinary(ByteBuffer data) throws IOException;
    void sendPing(ByteBuffer data) throws IOException;
    void sendPong(ByteBuffer data) throws IOException;
    void sendClose();
}