or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# GraalVM Polyglot API

1

2

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

3

4

## Package Information

5

6

**Maven Coordinates**: `org.graalvm:polyglot:24.2.1`

7

**License**: Universal Permissive License (UPL) 1.0

8

**Platform**: GraalVM Community Edition

9

**Documentation**: https://www.graalvm.org/latest/docs/

10

11

## Core Imports

12

13

```java { .api }

14

// Core polyglot API

15

import org.graalvm.polyglot.Context;

16

import org.graalvm.polyglot.Engine;

17

import org.graalvm.polyglot.Value;

18

import org.graalvm.polyglot.Source;

19

import org.graalvm.polyglot.PolyglotException;

20

21

// Access control and security

22

import org.graalvm.polyglot.HostAccess;

23

import org.graalvm.polyglot.SandboxPolicy;

24

import org.graalvm.polyglot.PolyglotAccess;

25

import org.graalvm.polyglot.EnvironmentAccess;

26

27

// Resource management

28

import org.graalvm.polyglot.ResourceLimits;

29

import org.graalvm.polyglot.ResourceLimitEvent;

30

31

// I/O operations

32

import org.graalvm.polyglot.io.IOAccess;

33

import org.graalvm.polyglot.io.FileSystem;

34

35

// Proxy objects for interoperability

36

import org.graalvm.polyglot.proxy.*;

37

38

// Monitoring and management

39

import org.graalvm.polyglot.management.ExecutionListener;

40

import org.graalvm.polyglot.management.ExecutionEvent;

41

```

42

43

## Basic Usage

44

45

### Simple Code Execution

46

47

```java { .api }

48

// Basic JavaScript execution

49

try (Context context = Context.create("js")) {

50

// Execute expressions

51

Value result = context.eval("js", "2 + 3 * 4");

52

int value = result.asInt(); // 14

53

54

// Execute statements

55

context.eval("js", "var x = 'Hello from JavaScript'");

56

Value greeting = context.eval("js", "x");

57

String message = greeting.asString(); // "Hello from JavaScript"

58

}

59

60

// Python execution

61

try (Context context = Context.create("python")) {

62

Value result = context.eval("python", "len('Hello World')");

63

int length = result.asInt(); // 11

64

}

65

```

66

67

### Data Exchange Between Java and Guest Languages

68

69

```java { .api }

70

try (Context context = Context.create("js")) {

71

Value bindings = context.getBindings("js");

72

73

// Pass Java data to guest language

74

bindings.putMember("java_number", 42);

75

bindings.putMember("java_string", "Hello");

76

bindings.putMember("java_array", new int[]{1, 2, 3, 4, 5});

77

78

// Access from JavaScript

79

context.eval("js", """

80

var result = java_number * 2;

81

var message = java_string + " World!";

82

var array_sum = java_array.reduce((a, b) => a + b, 0);

83

""");

84

85

// Get results back to Java

86

Value result = bindings.getMember("result");

87

Value message = bindings.getMember("message");

88

Value arraySum = bindings.getMember("array_sum");

89

90

System.out.println(result.asInt()); // 84

91

System.out.println(message.asString()); // "Hello World!"

92

System.out.println(arraySum.asInt()); // 15

93

}

94

```

95

96

## Capabilities

97

98

### Guest Language Code Execution

99

100

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

101

102

```java { .api }

103

// JavaScript execution

104

try (Context context = Context.create("js")) {

105

// Define and call JavaScript functions

106

context.eval("js", """

107

function factorial(n) {

108

if (n <= 1) return 1;

109

return n * factorial(n - 1);

110

}

111

112

function fibonacci(n) {

113

let a = 0, b = 1;

114

for (let i = 0; i < n; i++) {

115

[a, b] = [b, a + b];

116

}

117

return a;

118

}

119

""");

120

121

Value bindings = context.getBindings("js");

122

Value factorial = bindings.getMember("factorial");

123

Value fibonacci = bindings.getMember("fibonacci");

124

125

// Call JavaScript functions from Java

126

int fact5 = factorial.execute(5).asInt(); // 120

127

int fib10 = fibonacci.execute(10).asInt(); // 55

128

}

129

130

// Python execution example

131

try (Context context = Context.create("python")) {

132

context.eval("python", "import math");

133

Value result = context.eval("python", "math.sqrt(16)");

134

double sqrtResult = result.asDouble(); // 4.0

135

}

136

```

137

138

### Host Object Integration

139

140

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

141

142

```java { .api }

143

public class MathUtils {

144

@HostAccess.Export

145

public double sqrt(double value) {

146

return Math.sqrt(value);

147

}

148

149

@HostAccess.Export

150

public double pow(double base, double exponent) {

151

return Math.pow(base, exponent);

152

}

153

154

@HostAccess.Export

155

public final String PI = String.valueOf(Math.PI);

156

}

157

158

try (Context context = Context.newBuilder("python")

159

.allowHostAccess(HostAccess.EXPLICIT)

160

.build()) {

161

162

// Make Java object available to Python

163

context.getBindings("python").putMember("math_utils", new MathUtils());

164

165

// Use Java methods in Python

166

Value result = context.eval("python", """

167

import math

168

169

# Use Java methods

170

sqrt_2 = math_utils.sqrt(2)

171

power = math_utils.pow(2, 8)

172

pi_value = float(math_utils.PI)

173

174

# Combine with Python math

175

result = sqrt_2 + power + pi_value

176

result

177

""");

178

179

double finalResult = result.asDouble();

180

}

181

```

182

183

### File System Operations

184

185

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

186

187

```java { .api }

188

try (Context context = Context.newBuilder("python")

189

.allowIO(IOAccess.newBuilder()

190

.allowHostFileAccess(true)

191

.build())

192

.build()) {

193

194

// Python code can access files

195

context.eval("python", """

196

with open('example.txt', 'w') as f:

197

f.write('Hello from GraalVM Python!')

198

199

with open('example.txt', 'r') as f:

200

content = f.read()

201

202

print(f"File content: {content}")

203

""");

204

}

205

```

206

207

### Multi-Language Polyglot Integration

208

209

Combine Python with other languages in the same context.

210

211

```java { .api }

212

try (Context context = Context.newBuilder("python", "js")

213

.allowPolyglotAccess(PolyglotAccess.ALL)

214

.build()) {

215

216

Value polyglotBindings = context.getPolyglotBindings();

217

218

// Define JavaScript function

219

context.eval("js", """

220

var jsFunction = function(x, y) {

221

return x * y + Math.random();

222

};

223

""");

224

225

polyglotBindings.putMember("jsFunc",

226

context.getBindings("js").getMember("jsFunction"));

227

228

// Use JavaScript function from Python

229

Value result = context.eval("python", """

230

import polyglot

231

232

# Access JavaScript function

233

js_func = polyglot.import_value("jsFunc")

234

result = js_func(10, 20)

235

result

236

""");

237

238

double value = result.asDouble();

239

}

240

```

241

242

### Resource Management and Security

243

244

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

245

246

```java { .api }

247

// Configure resource limits

248

ResourceLimits limits = ResourceLimits.newBuilder()

249

.statementLimit(100000, null) // Limit statements executed

250

.onLimit(event -> {

251

System.err.printf("Resource limit exceeded: %d/%d statements\n",

252

event.getConsumed(), event.getLimit());

253

})

254

.build();

255

256

try (Context context = Context.newBuilder("python")

257

.sandbox(SandboxPolicy.CONSTRAINED)

258

.allowHostAccess(HostAccess.CONSTRAINED)

259

.allowIO(IOAccess.NONE) // No file system access

260

.allowCreateThread(false) // No thread creation

261

.allowNativeAccess(false) // No native code

262

.resourceLimits(limits)

263

.build()) {

264

265

// Execute untrusted Python code safely

266

Value result = context.eval("python", """

267

# This code runs with security restrictions

268

total = 0

269

for i in range(1000):

270

total += i * i

271

total

272

""");

273

274

long safeResult = result.asLong();

275

}

276

```

277

278

### Exception Handling and Error Management

279

280

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

281

282

```java { .api }

283

try (Context context = Context.create("python")) {

284

try {

285

// Execute Python code that may throw

286

context.eval("python", """

287

def divide(a, b):

288

if b == 0:

289

raise ValueError("Cannot divide by zero")

290

return a / b

291

292

result = divide(10, 0)

293

""");

294

} catch (PolyglotException e) {

295

if (e.isGuestException()) {

296

System.err.println("Python exception: " + e.getMessage());

297

298

// Get Python exception object

299

Value guestException = e.getGuestObject();

300

if (guestException != null && guestException.hasMember("__class__")) {

301

Value exceptionType = guestException.getMember("__class__")

302

.getMember("__name__");

303

System.err.println("Exception type: " + exceptionType.asString());

304

}

305

306

// Print stack trace

307

if (e.getSourceLocation() != null) {

308

System.err.println("Location: " + e.getSourceLocation());

309

}

310

}

311

}

312

}

313

```

314

315

### Advanced Python Module Usage

316

317

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

318

319

```java { .api }

320

try (Context context = Context.create("python")) {

321

// Import and use Python standard library

322

context.eval("python", """

323

import json

324

import datetime

325

import urllib.parse

326

327

# JSON operations

328

data = {"name": "GraalVM", "version": "24.2.1", "languages": ["Python", "Java", "JS"]}

329

json_str = json.dumps(data, indent=2)

330

parsed_data = json.loads(json_str)

331

332

# Date operations

333

now = datetime.datetime.now()

334

formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")

335

336

# URL operations

337

url = "https://example.com/api?name=GraalVM&version=24.2.1"

338

parsed_url = urllib.parse.urlparse(url)

339

query_params = urllib.parse.parse_qs(parsed_url.query)

340

341

# Create result dictionary

342

result = {

343

"json_data": parsed_data,

344

"timestamp": formatted_date,

345

"url_host": parsed_url.netloc,

346

"params": query_params

347

}

348

""");

349

350

Value bindings = context.getBindings("python");

351

Value result = bindings.getMember("result");

352

353

// Access complex Python data structures

354

Value jsonData = result.getMember("json_data");

355

String projectName = jsonData.getMember("name").asString();

356

Value languages = jsonData.getMember("languages");

357

358

System.out.println("Project: " + projectName);

359

System.out.println("Languages count: " + languages.getArraySize());

360

}

361

```

362

363

### Custom Proxy Objects

364

365

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

366

367

```java { .api }

368

// Custom proxy for Python list-like behavior

369

public class JavaList implements ProxyArray {

370

private final List<Object> list = new ArrayList<>();

371

372

@Override

373

public Object get(long index) {

374

return list.get((int) index);

375

}

376

377

@Override

378

public void set(long index, Value value) {

379

Object javaValue = value.isHostObject() ?

380

value.asHostObject() : value.as(Object.class);

381

382

if (index == list.size()) {

383

list.add(javaValue);

384

} else {

385

list.set((int) index, javaValue);

386

}

387

}

388

389

@Override

390

public long getSize() {

391

return list.size();

392

}

393

394

@Override

395

public boolean remove(long index) {

396

if (index >= 0 && index < list.size()) {

397

list.remove((int) index);

398

return true;

399

}

400

return false;

401

}

402

}

403

404

// Custom proxy for Python callable behavior

405

public class JavaFunction implements ProxyExecutable {

406

@Override

407

public Object execute(Value... arguments) {

408

// Convert arguments and execute Java logic

409

double sum = 0;

410

for (Value arg : arguments) {

411

if (arg.isNumber()) {

412

sum += arg.asDouble();

413

}

414

}

415

return sum;

416

}

417

}

418

419

try (Context context = Context.newBuilder("python")

420

.allowHostAccess(HostAccess.ALL)

421

.build()) {

422

423

Value bindings = context.getBindings("python");

424

425

// Provide custom proxy objects to Python

426

bindings.putMember("java_list", new JavaList());

427

bindings.putMember("java_func", new JavaFunction());

428

429

context.eval("python", """

430

# Use Java list like a Python list

431

java_list.append(10)

432

java_list.append(20)

433

java_list.append(30)

434

435

print(f"List size: {len(java_list)}")

436

print(f"First item: {java_list[0]}")

437

438

# Use Java function like Python function

439

result = java_func(1, 2, 3, 4, 5)

440

print(f"Sum result: {result}")

441

""");

442

}

443

```

444

445

### Performance Monitoring and Execution Tracking

446

447

Monitor Python execution with detailed event tracking and performance metrics.

448

449

```java { .api }

450

try (Context context = Context.create("python")) {

451

452

// Create execution listener for monitoring

453

ExecutionListener listener = ExecutionListener.newBuilder()

454

.statements(true)

455

.expressions(true)

456

.onEnter(event -> {

457

if (event.isStatement()) {

458

System.out.println("Executing statement at: " +

459

event.getLocation());

460

}

461

})

462

.onReturn(event -> {

463

if (event.getReturnValue() != null) {

464

System.out.println("Statement returned: " +

465

event.getReturnValue());

466

}

467

})

468

.attach(context)

469

.install();

470

471

try {

472

// Execute Python code with monitoring

473

context.eval("python", """

474

def calculate_fibonacci(n):

475

if n <= 1:

476

return n

477

478

a, b = 0, 1

479

for i in range(2, n + 1):

480

a, b = b, a + b

481

482

return b

483

484

result = calculate_fibonacci(10)

485

print(f"Fibonacci(10) = {result}")

486

""");

487

488

} finally {

489

listener.close();

490

}

491

}

492

```

493

494

## Core API Reference

495

496

### Context Class

497

498

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

499

500

```java { .api }

501

// Static factory methods

502

Context create(String... permittedLanguages) // Creates context with default config

503

Context.Builder newBuilder(String... permittedLanguages) // Creates builder for custom config

504

Context getCurrent() // Returns currently entered context

505

506

// Evaluation methods

507

Value eval(Source source) // Evaluates a source object

508

Value eval(String languageId, CharSequence source) // Evaluates code literal

509

Value parse(Source source) // Parses but doesn't evaluate source

510

Value parse(String languageId, CharSequence source) // Parses code literal

511

512

// Bindings and values

513

Value getPolyglotBindings() // Returns polyglot bindings

514

Value getBindings(String languageId) // Returns language-specific bindings

515

Value asValue(Object hostValue) // Converts host value to Value

516

517

// Context management

518

Engine getEngine() // Gets underlying engine

519

boolean initialize(String languageId) // Forces language initialization

520

void enter() // Enters context on current thread

521

void leave() // Leaves context on current thread

522

void close() // Closes context and frees resources

523

void close(boolean cancelIfExecuting) // Closes with cancellation option

524

void interrupt(Duration timeout) // Interrupts execution (non-destructive)

525

void safepoint() // Polls safepoint events

526

void resetLimits() // Resets resource limit accumulators

527

```

528

529

### Engine Class

530

531

The `Engine` class manages language runtimes and provides execution environments.

532

533

```java { .api }

534

// Static factory methods

535

Engine create() // Creates engine with default config

536

Engine create(String... permittedLanguages) // Creates engine with permitted languages

537

Engine.Builder newBuilder() // Creates engine builder

538

Engine.Builder newBuilder(String... permittedLanguages) // Creates builder with languages

539

Path findHome() // Finds GraalVM home folder

540

boolean copyResources(Path targetFolder, String... components) // Copies GraalVM resources

541

542

// Engine information

543

Map<String, Language> getLanguages() // Gets installed languages

544

Map<String, Instrument> getInstruments() // Gets installed instruments

545

OptionDescriptors getOptions() // Gets available engine options

546

String getVersion() // Gets engine version

547

String getImplementationName() // Gets implementation name

548

Set<Source> getCachedSources() // Returns cached sources

549

550

// Engine lifecycle

551

void close() // Closes engine and frees resources

552

void close(boolean cancelIfExecuting) // Closes with cancellation option

553

```

554

555

### Value Class

556

557

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

558

559

```java { .api }

560

// Type checking methods

561

boolean isNull() // Tests if value is null

562

boolean isBoolean() // Tests if value is boolean

563

boolean isNumber() // Tests if value is number

564

boolean isString() // Tests if value is string

565

boolean isDate() // Tests if value is date

566

boolean isTime() // Tests if value is time

567

boolean isTimeZone() // Tests if value is timezone

568

boolean isInstant() // Tests if value is instant

569

boolean isDuration() // Tests if value is duration

570

boolean isHostObject() // Tests if value is host object

571

boolean isProxyObject() // Tests if value is proxy object

572

boolean isNativePointer() // Tests if value is native pointer

573

boolean isException() // Tests if value is exception

574

boolean isMetaObject() // Tests if value is metaobject

575

boolean isIterator() // Tests if value is iterator

576

boolean hasMembers() // Tests if value has members

577

boolean hasArrayElements() // Tests if value has array elements

578

boolean hasBufferElements() // Tests if value has buffer elements

579

boolean hasHashEntries() // Tests if value has hash entries

580

boolean hasIterator() // Tests if value has iterator

581

boolean canExecute() // Tests if value can be executed

582

boolean canInstantiate() // Tests if value can be instantiated

583

boolean canInvoke(String identifier) // Tests if member can be invoked

584

585

// Value conversion methods

586

boolean asBoolean() // Converts to boolean

587

byte asByte() // Converts to byte

588

short asShort() // Converts to short

589

int asInt() // Converts to int

590

long asLong() // Converts to long

591

float asFloat() // Converts to float

592

double asDouble() // Converts to double

593

BigInteger asBigInteger() // Converts to BigInteger

594

String asString() // Converts to string

595

LocalDate asDate() // Converts to LocalDate

596

LocalTime asTime() // Converts to LocalTime

597

ZoneId asTimeZone() // Converts to ZoneId

598

Instant asInstant() // Converts to Instant

599

Duration asDuration() // Converts to Duration

600

long asNativePointer() // Converts to native pointer

601

<T> T asHostObject() // Converts to host object

602

<T> T as(Class<T> targetType) // Converts to target type

603

604

// Member access methods

605

Value getMember(String identifier) // Gets member by identifier

606

boolean hasMember(String identifier) // Tests if member exists

607

Set<String> getMemberKeys() // Gets all member keys

608

void putMember(String identifier, Object value) // Sets member value

609

boolean removeMember(String identifier) // Removes member

610

611

// Array access methods

612

Value getArrayElement(long index) // Gets array element

613

void setArrayElement(long index, Object value) // Sets array element

614

boolean removeArrayElement(long index) // Removes array element

615

long getArraySize() // Gets array size

616

617

// Execution methods

618

Value execute(Object... arguments) // Executes with arguments

619

Value newInstance(Object... arguments) // Creates new instance

620

Value invoke(String identifier, Object... arguments) // Invokes member

621

```

622

623

### Language Class

624

625

The `Language` class represents an installed guest language.

626

627

```java { .api }

628

String getId() // Gets language identifier

629

String getName() // Gets language name

630

String getImplementationName() // Gets implementation name

631

String getVersion() // Gets language version

632

OptionDescriptors getOptions() // Gets language options

633

Set<String> getMimeTypes() // Gets supported MIME types

634

boolean isInteractive() // Tests if supports interactive evaluation

635

String getDefaultMimeType() // Gets default MIME type

636

```

637

638

### Instrument Class

639

640

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

641

642

```java { .api }

643

String getId() // Gets instrument identifier

644

String getName() // Gets instrument name

645

OptionDescriptors getOptions() // Gets instrument options

646

String getVersion() // Gets instrument version

647

<T> T lookup(Class<T> type) // Looks up instrument service

648

```

649

650

### Source Class

651

652

The `Source` class represents guest language source code.

653

654

```java { .api }

655

// Static factory methods

656

Source create(String language, CharSequence source) // Creates source from string

657

Source.Builder newBuilder(String language, CharSequence source) // Builder from string

658

Source.Builder newBuilder(String language, File file) // Builder from file

659

Source.Builder newBuilder(String language, URL url) // Builder from URL

660

Source.Builder newBuilder(String language, Reader reader, String name) // Builder from reader

661

662

// Source information

663

String getLanguage() // Gets source language

664

String getName() // Gets source name

665

String getPath() // Gets source path

666

URL getURL() // Gets source URL

667

Reader getReader() // Gets source reader

668

int getLength() // Gets source length

669

CharSequence getCharacters() // Gets source characters

670

CharSequence getCharacters(int lineNumber) // Gets line characters

671

int getLineCount() // Gets line count

672

int getLineNumber(int offset) // Gets line number for offset

673

int getColumnNumber(int offset) // Gets column number for offset

674

int getLineStartOffset(int lineNumber) // Gets line start offset

675

int getLineLength(int lineNumber) // Gets line length

676

String getMimeType() // Gets MIME type

677

URI getURI() // Gets source URI

678

boolean isInteractive() // Tests if interactive

679

boolean isInternal() // Tests if internal

680

boolean isCached() // Tests if cached

681

```

682

683

### TypeLiteral Class

684

685

The `TypeLiteral` class captures generic type information for conversions.

686

687

```java { .api }

688

// Usage for parameterized type conversions

689

Value listValue = context.eval("js", "[1, 2, 3]");

690

List<Integer> list = listValue.as(new TypeLiteral<List<Integer>>() {});

691

692

// Captures generic type T for Value.as() conversions

693

public abstract class TypeLiteral<T> {

694

// Internal implementation handles generic type capture

695

}

696

```

697

698

### SourceSection Class

699

700

The `SourceSection` class represents a contiguous section within a Source.

701

702

```java { .api }

703

Source getSource() // Gets containing source

704

int getStartLine() // Gets start line number

705

int getStartColumn() // Gets start column number

706

int getEndLine() // Gets end line number

707

int getEndColumn() // Gets end column number

708

int getCharIndex() // Gets character index

709

int getCharLength() // Gets character length

710

int getCharEndIndex() // Gets end character index

711

CharSequence getCharacters() // Gets section characters

712

boolean isAvailable() // Tests if section is available

713

```

714

715

## Types

716

717

### Context Configuration

718

719

```java { .api }

720

// Context builder with comprehensive configuration

721

Context.Builder contextBuilder = Context.newBuilder("python")

722

// Security configuration

723

.allowHostAccess(HostAccess.EXPLICIT)

724

.allowPolyglotAccess(PolyglotAccess.NONE)

725

.sandbox(SandboxPolicy.CONSTRAINED)

726

727

// I/O configuration

728

.allowIO(IOAccess.newBuilder()

729

.allowHostFileAccess(false)

730

.allowHostSocketAccess(false)

731

.build())

732

733

// Runtime permissions

734

.allowCreateThread(false)

735

.allowNativeAccess(false)

736

.allowHostClassLoading(false)

737

.allowExperimentalOptions(false)

738

739

// Environment configuration

740

.allowEnvironmentAccess(EnvironmentAccess.NONE)

741

.allowCreateProcess(false)

742

743

// Streams configuration

744

.out(System.out)

745

.err(System.err)

746

.in(System.in)

747

748

// Resource limits

749

.resourceLimits(ResourceLimits.newBuilder()

750

.statementLimit(50000, null)

751

.build())

752

753

// Options

754

.option("python.ForceImportSite", "false")

755

.option("python.DontWriteBytecodeFlag", "true");

756

757

Context context = contextBuilder.build();

758

```

759

760

### Engine Configuration

761

762

```java { .api }

763

// Engine configuration for shared runtime

764

Engine.Builder engineBuilder = Engine.newBuilder()

765

.allowExperimentalOptions(true)

766

.useSystemProperties(false)

767

768

// Logging configuration

769

.logHandler(Level.INFO, record -> {

770

System.out.printf("[%s] %s: %s%n",

771

record.getLevel(),

772

record.getLoggerName(),

773

record.getMessage());

774

})

775

776

// Options for performance

777

.option("engine.WarnInterpreterOnly", "false")

778

.option("engine.CompilationFailureAction", "ExitVM")

779

.option("engine.CompilationStatistics", "true");

780

781

Engine engine = engineBuilder.build();

782

```

783

784

### Value Type Operations

785

786

```java { .api }

787

// Comprehensive value type checking and conversion

788

public class ValueProcessor {

789

790

public static Object processValue(Value value) {

791

// Type checking

792

if (value.isNull()) {

793

return null;

794

} else if (value.isBoolean()) {

795

return value.asBoolean();

796

} else if (value.isNumber()) {

797

if (value.fitsInInt()) {

798

return value.asInt();

799

} else if (value.fitsInLong()) {

800

return value.asLong();

801

} else if (value.fitsInDouble()) {

802

return value.asDouble();

803

}

804

} else if (value.isString()) {

805

return value.asString();

806

} else if (value.isDate()) {

807

return value.asDate();

808

} else if (value.isTime()) {

809

return value.asTime();

810

} else if (value.isTimeZone()) {

811

return value.asTimeZone();

812

} else if (value.isInstant()) {

813

return value.asInstant();

814

} else if (value.isDuration()) {

815

return value.asDuration();

816

} else if (value.hasArrayElements()) {

817

return processArray(value);

818

} else if (value.hasMembers()) {

819

return processObject(value);

820

} else if (value.canExecute()) {

821

return new ExecutableWrapper(value);

822

}

823

824

return value.toString();

825

}

826

827

private static List<Object> processArray(Value arrayValue) {

828

List<Object> result = new ArrayList<>();

829

long size = arrayValue.getArraySize();

830

831

for (long i = 0; i < size; i++) {

832

Value element = arrayValue.getArrayElement(i);

833

result.add(processValue(element));

834

}

835

836

return result;

837

}

838

839

private static Map<String, Object> processObject(Value objectValue) {

840

Map<String, Object> result = new HashMap<>();

841

Set<String> memberKeys = objectValue.getMemberKeys();

842

843

for (String key : memberKeys) {

844

Value member = objectValue.getMember(key);

845

result.put(key, processValue(member));

846

}

847

848

return result;

849

}

850

851

private static class ExecutableWrapper {

852

private final Value executable;

853

854

public ExecutableWrapper(Value executable) {

855

this.executable = executable;

856

}

857

858

public Object call(Object... args) {

859

Value result = executable.execute(args);

860

return processValue(result);

861

}

862

}

863

}

864

```

865

866

### Source Management

867

868

```java { .api }

869

// Source creation and management

870

public class PythonSourceManager {

871

872

public static Source createFromString(String code) {

873

return Source.create("python", code);

874

}

875

876

public static Source createFromFile(Path filePath) throws IOException {

877

return Source.newBuilder("python", filePath.toFile())

878

.name(filePath.getFileName().toString())

879

.cached(true)

880

.build();

881

}

882

883

public static Source createInteractive(String code) {

884

return Source.newBuilder("python", code)

885

.name("interactive")

886

.interactive(true)

887

.cached(false)

888

.build();

889

}

890

891

public static Source createModule(String moduleName, String code) {

892

return Source.newBuilder("python", code)

893

.name(moduleName + ".py")

894

.mimeType("text/x-python")

895

.cached(true)

896

.build();

897

}

898

}

899

```

900

901

### Advanced Security Configuration

902

903

```java { .api }

904

// Custom host access configuration

905

public class CustomHostAccess {

906

907

public static HostAccess createRestrictedAccess() {

908

return HostAccess.newBuilder()

909

.allowPublicAccess(false)

910

.allowArrayAccess(true)

911

.allowListAccess(true)

912

.allowMapAccess(false)

913

.allowIterableAccess(true)

914

.allowIteratorAccess(true)

915

.allowBufferAccess(false)

916

.allowAccessInheritance(false)

917

.methodScoping(true)

918

.build();

919

}

920

921

public static PolyglotAccess createIsolatedPolyglot() {

922

return PolyglotAccess.newBuilder()

923

.denyEval("python", "js")

924

.denyEval("js", "python")

925

.allowBindingsAccess("python")

926

.build();

927

}

928

}

929

```

930

931

### Exception Information Extraction

932

933

```java { .api }

934

// Comprehensive exception handling

935

public class PolyglotExceptionHandler {

936

937

public static class ExceptionInfo {

938

public final String type;

939

public final String message;

940

public final String sourceLocation;

941

public final List<String> stackTrace;

942

public final boolean isHostException;

943

public final boolean isSyntaxError;

944

945

public ExceptionInfo(PolyglotException e) {

946

this.type = determineExceptionType(e);

947

this.message = e.getMessage();

948

this.sourceLocation = formatSourceLocation(e);

949

this.stackTrace = extractStackTrace(e);

950

this.isHostException = e.isHostException();

951

this.isSyntaxError = e.isSyntaxError();

952

}

953

954

private String determineExceptionType(PolyglotException e) {

955

if (e.isHostException()) return "HostException";

956

if (e.isSyntaxError()) return "SyntaxError";

957

if (e.isCancelled()) return "Cancelled";

958

if (e.isExit()) return "Exit";

959

if (e.isInterrupted()) return "Interrupted";

960

if (e.isInternalError()) return "InternalError";

961

if (e.isResourceExhausted()) return "ResourceExhausted";

962

return "GuestException";

963

}

964

965

private String formatSourceLocation(PolyglotException e) {

966

var location = e.getSourceLocation();

967

if (location != null) {

968

return String.format("%s:%d:%d",

969

location.getSource().getName(),

970

location.getStartLine(),

971

location.getStartColumn());

972

}

973

return "unknown";

974

}

975

976

private List<String> extractStackTrace(PolyglotException e) {

977

List<String> trace = new ArrayList<>();

978

for (var frame : e.getPolyglotStackTrace()) {

979

trace.add(frame.toString());

980

}

981

return trace;

982

}

983

}

984

985

public static ExceptionInfo analyzeException(PolyglotException e) {

986

return new ExceptionInfo(e);

987

}

988

}

989

```

990

991

### PolyglotException Class

992

993

The `PolyglotException` class handles exceptions from guest language execution.

994

995

```java { .api }

996

// Exception type checking methods

997

boolean isHostException() // Tests if caused by host exception

998

boolean isGuestException() // Tests if caused by guest language

999

boolean isSyntaxError() // Tests if caused by syntax error

1000

boolean isCancelled() // Tests if caused by context cancellation

1001

boolean isExit() // Tests if caused by context exit

1002

boolean isInterrupted() // Tests if caused by thread interruption

1003

boolean isInternalError() // Tests if caused by internal error

1004

boolean isResourceExhausted() // Tests if caused by resource exhaustion

1005

1006

// Exception information methods

1007

int getExitStatus() // Gets exit status if isExit() returns true

1008

Value getGuestObject() // Gets guest language exception object

1009

Throwable asHostException() // Gets original host exception

1010

SourceSection getSourceLocation() // Gets source location of error

1011

Iterable<StackFrame> getPolyglotStackTrace() // Gets polyglot stack trace

1012

```

1013

1014

### SandboxPolicy Enum

1015

1016

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

1017

1018

```java { .api }

1019

// Enum constants

1020

TRUSTED // No restrictions (default) - for fully trusted applications

1021

CONSTRAINED // Trusted but potentially buggy applications - shared heap/VM

1022

ISOLATED // Trusted applications with potential vulnerabilities - separate VM instances

1023

UNTRUSTED // Fully untrusted applications - additional hardening mechanisms

1024

1025

// Methods

1026

boolean isStricterThan(SandboxPolicy other) // Tests if this policy is stricter than other

1027

boolean isStricterOrEqual(SandboxPolicy other) // Tests if this policy is stricter or equal to other

1028

String name() // Gets policy name

1029

static SandboxPolicy valueOf(String name) // Gets policy by name

1030

static SandboxPolicy[] values() // Gets all policies

1031

```

1032

1033

### Access Control APIs

1034

1035

Comprehensive access control and security configuration for polyglot contexts.

1036

1037

```java { .api }

1038

// HostAccess - Controls guest language access to host methods and fields

1039

public final class HostAccess {

1040

// Predefined policies

1041

static final HostAccess EXPLICIT; // Requires @Export annotation

1042

static final HostAccess SCOPED; // Explicit with scoped callback parameters

1043

static final HostAccess NONE; // No access to methods or fields

1044

static final HostAccess ALL; // Full unrestricted access (discouraged)

1045

static final HostAccess CONSTRAINED; // For CONSTRAINED sandbox policy

1046

static final HostAccess ISOLATED; // For ISOLATED sandbox policy

1047

static final HostAccess UNTRUSTED; // For UNTRUSTED sandbox policy

1048

1049

// Factory methods

1050

static Builder newBuilder(); // Creates custom host access builder

1051

static Builder newBuilder(HostAccess conf); // Creates builder from existing config

1052

1053

// Builder methods

1054

public static class Builder {

1055

Builder allowPublicAccess(boolean allow); // Allows access to all public members

1056

Builder allowAccessInheritance(boolean allow); // Allows access inheritance

1057

Builder allowArrayAccess(boolean allow); // Allows array access

1058

Builder allowListAccess(boolean allow); // Allows List access

1059

Builder allowBufferAccess(boolean allow); // Allows buffer access

1060

Builder allowIterableAccess(boolean allow); // Allows Iterable access

1061

Builder allowIteratorAccess(boolean allow); // Allows Iterator access

1062

Builder allowMapAccess(boolean allow); // Allows Map access

1063

Builder allowAllImplementations(boolean allow); // Allows all interface implementations

1064

Builder allowAllClassImplementations(boolean allow); // Allows all class implementations

1065

Builder methodScoping(boolean enable); // Enables method scoping

1066

HostAccess build(); // Creates HostAccess instance

1067

}

1068

1069

// Export annotation for marking accessible members

1070

@interface Export {

1071

// Annotation to mark host methods/fields accessible to guest languages

1072

}

1073

}

1074

1075

// PolyglotAccess - Controls access between different guest languages

1076

public final class PolyglotAccess {

1077

// Predefined policies

1078

static final PolyglotAccess NONE; // No access between languages

1079

static final PolyglotAccess ALL; // Full access between all languages

1080

1081

// Factory methods

1082

static Builder newBuilder(); // Creates polyglot access builder

1083

1084

// Builder methods

1085

public static class Builder {

1086

Builder allowEval(String fromLanguage, String toLanguage); // Allows evaluation access

1087

Builder allowBindingsAccess(String language); // Allows bindings access

1088

Builder denyEval(String fromLanguage, String toLanguage); // Denies evaluation access

1089

Builder denyBindingsAccess(String language); // Denies bindings access

1090

PolyglotAccess build(); // Creates PolyglotAccess instance

1091

}

1092

}

1093

1094

// EnvironmentAccess - Controls access to process environment variables

1095

public final class EnvironmentAccess {

1096

// Predefined policies

1097

static final EnvironmentAccess NONE; // No environment variable access

1098

static final EnvironmentAccess INHERIT; // Inherits host process environment

1099

}

1100

1101

// IOAccess - Controls guest language access to host I/O operations

1102

public final class IOAccess {

1103

// Predefined policies

1104

static final IOAccess NONE; // No I/O access

1105

static final IOAccess ALL; // Full I/O access

1106

1107

// Factory methods

1108

static Builder newBuilder(); // Creates I/O access builder

1109

1110

// Builder methods

1111

public static class Builder {

1112

Builder allowHostFileAccess(boolean allow); // Allows host file system access

1113

Builder allowHostSocketAccess(boolean allow); // Allows host socket access

1114

Builder fileSystem(FileSystem fileSystem); // Sets custom file system

1115

IOAccess build(); // Creates IOAccess instance

1116

}

1117

}

1118

```

1119

1120

### Resource Management APIs

1121

1122

Resource limits and monitoring for controlling execution consumption.

1123

1124

```java { .api }

1125

// ResourceLimits - Configuration for resource consumption limits

1126

public final class ResourceLimits {

1127

static Builder newBuilder(); // Creates resource limits builder

1128

1129

// Builder methods

1130

public static class Builder {

1131

Builder statementLimit(long limit, Predicate<Source> sourceFilter); // Sets statement execution limit

1132

Builder onLimit(Consumer<ResourceLimitEvent> onLimit); // Sets limit exceeded handler

1133

ResourceLimits build(); // Creates ResourceLimits instance

1134

}

1135

}

1136

1137

// ResourceLimitEvent - Event fired when resource limits are exceeded

1138

public final class ResourceLimitEvent {

1139

Context getContext(); // Gets context where limit was exceeded

1140

long getConsumed(); // Gets amount of resource consumed

1141

long getLimit(); // Gets configured resource limit

1142

}

1143

```

1144

1145

### Proxy Interfaces

1146

1147

Comprehensive proxy interfaces for Java-guest language interoperability.

1148

1149

```java { .api }

1150

// Base proxy interface

1151

public interface Proxy {}

1152

1153

// Object with members (properties)

1154

public interface ProxyObject extends Proxy {

1155

Object getMember(String key); // Gets member value

1156

Object getMemberKeys(); // Gets all member keys

1157

boolean hasMember(String key); // Tests if member exists

1158

void putMember(String key, Object value); // Sets member value

1159

boolean removeMember(String key); // Removes member

1160

}

1161

1162

// Array-like objects

1163

public interface ProxyArray extends ProxyIterable {

1164

Object get(long index); // Gets array element

1165

void set(long index, Value value); // Sets array element

1166

long getSize(); // Gets array size

1167

boolean remove(long index); // Removes array element

1168

}

1169

1170

// Executable objects (functions)

1171

public interface ProxyExecutable extends Proxy {

1172

Object execute(Value... arguments); // Executes with arguments

1173

}

1174

1175

// Instantiable objects (constructors)

1176

public interface ProxyInstantiable extends Proxy {

1177

Object newInstance(Value... arguments); // Creates new instance

1178

}

1179

1180

// Iterable objects

1181

public interface ProxyIterable extends Proxy {

1182

Object getIterator(); // Gets iterator object

1183

}

1184

1185

// Iterator objects

1186

public interface ProxyIterator extends Proxy {

1187

boolean hasNext(); // Tests if more elements available

1188

Object getNext(); // Gets next element

1189

}

1190

1191

// Hash map objects

1192

public interface ProxyHashMap extends Proxy {

1193

long getHashSize(); // Gets hash map size

1194

boolean hasHashEntry(Object key); // Tests if key exists

1195

Object getHashValue(Object key); // Gets value for key

1196

void putHashEntry(Object key, Value value); // Sets key-value pair

1197

boolean removeHashEntry(Object key); // Removes entry

1198

Object getHashEntriesIterator(); // Gets entries iterator

1199

}

1200

1201

// Date/Time proxy interfaces

1202

public interface ProxyDate extends Proxy {

1203

LocalDate asDate(); // Gets date value

1204

}

1205

1206

public interface ProxyTime extends Proxy {

1207

LocalTime asTime(); // Gets time value

1208

}

1209

1210

public interface ProxyTimeZone extends Proxy {

1211

ZoneId asTimeZone(); // Gets timezone value

1212

}

1213

1214

public interface ProxyInstant extends Proxy {

1215

Instant asInstant(); // Gets instant value

1216

}

1217

1218

public interface ProxyDuration extends Proxy {

1219

Duration asDuration(); // Gets duration value

1220

}

1221

1222

// Native pointer objects

1223

public interface ProxyNativeObject extends Proxy {

1224

long asPointer(); // Gets native pointer value

1225

}

1226

```

1227

1228

### I/O and Communication APIs

1229

1230

Advanced I/O and communication interfaces for polyglot contexts.

1231

1232

```java { .api }

1233

// File system interface for custom implementations

1234

public interface FileSystem {

1235

Path parsePath(URI uri); // Parses URI to path

1236

Path parsePath(String path); // Parses string to path

1237

void checkAccess(Path path, Set<? extends AccessMode> modes, LinkOption... linkOptions);

1238

void createDirectory(Path dir, FileAttribute<?>... attrs); // Creates directory

1239

void delete(Path path); // Deletes file or directory

1240

SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs);

1241

DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter);

1242

Path toAbsolutePath(Path path); // Converts to absolute path

1243

Path toRealPath(Path path, LinkOption... linkOptions); // Gets real path

1244

Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options);

1245

}

1246

1247

// Process handler for external process creation

1248

public interface ProcessHandler {

1249

Process start(ProcessCommand command); // Starts external process

1250

}

1251

1252

// Message transport for server endpoints

1253

public interface MessageTransport {

1254

MessageEndpoint open(URI uri, MessageEndpoint peerEndpoint); // Opens message endpoint

1255

}

1256

1257

// Message communication endpoint

1258

public interface MessageEndpoint {

1259

void sendText(String text); // Sends text message

1260

void sendBinary(ByteBuffer data); // Sends binary message

1261

void sendPing(ByteBuffer data); // Sends ping

1262

void sendPong(ByteBuffer data); // Sends pong

1263

void sendClose(); // Sends close frame

1264

}

1265

1266

// Immutable byte sequence

1267

public interface ByteSequence {

1268

int length(); // Gets sequence length

1269

byte byteAt(int index); // Gets byte at index

1270

ByteSequence subSequence(int startIndex, int endIndex); // Gets subsequence

1271

byte[] toByteArray(); // Converts to byte array

1272

static ByteSequence create(byte[] buffer); // Creates from byte array

1273

}

1274

```

1275

1276

### Management and Monitoring

1277

1278

Execution monitoring and performance tracking APIs.

1279

1280

```java { .api }

1281

// Execution listener for monitoring guest language execution

1282

public final class ExecutionListener implements AutoCloseable {

1283

static Builder newBuilder(); // Creates execution listener builder

1284

void close(); // Closes listener and stops monitoring

1285

1286

// Builder methods

1287

public static class Builder {

1288

Builder expressions(boolean expressions); // Enables expression event collection

1289

Builder statements(boolean statements); // Enables statement event collection

1290

Builder roots(boolean roots); // Enables root event collection

1291

Builder onEnter(Consumer<ExecutionEvent> callback); // Sets enter event handler

1292

Builder onReturn(Consumer<ExecutionEvent> callback); // Sets return event handler

1293

Builder attach(Engine engine); // Attaches to engine

1294

Builder attach(Context context); // Attaches to context

1295

ExecutionListener install(); // Installs listener

1296

}

1297

}

1298

1299

// Execution event fired during guest language execution

1300

public final class ExecutionEvent {

1301

String getRootName(); // Gets root function/method name

1302

SourceSection getLocation(); // Gets source location

1303

boolean isExpression(); // Tests if event is for expression

1304

boolean isStatement(); // Tests if event is for statement

1305

boolean isRoot(); // Tests if event is for root

1306

Value getReturnValue(); // Gets return value (for return events)

1307

RuntimeException getException(); // Gets exception (for exception events)

1308

}

1309

```

1310

1311

### Builder Pattern APIs

1312

1313

Comprehensive builder pattern documentation for context and engine configuration.

1314

1315

```java { .api }

1316

// Context.Builder methods

1317

public static class Context.Builder {

1318

Builder engine(Engine engine); // Sets underlying engine

1319

Builder out(OutputStream out); // Sets standard output stream

1320

Builder err(OutputStream err); // Sets error output stream

1321

Builder in(InputStream in); // Sets input stream

1322

Builder allowHostAccess(HostAccess config); // Configures host access policy

1323

Builder allowNativeAccess(boolean enabled); // Allows native interface access

1324

Builder allowCreateThread(boolean enabled); // Allows guest languages to create threads

1325

Builder allowAllAccess(boolean enabled); // Sets default value for all privileges

1326

Builder allowHostClassLoading(boolean enabled); // Enables host class loading

1327

Builder allowHostClassLookup(Predicate<String> classFilter); // Sets host class lookup filter

1328

Builder allowExperimentalOptions(boolean enabled); // Allows experimental options

1329

Builder allowPolyglotAccess(PolyglotAccess accessPolicy); // Sets polyglot access policy

1330

Builder allowValueSharing(boolean enabled); // Enables/disables value sharing

1331

Builder allowInnerContextOptions(boolean enabled); // Allows inner contexts to change options

1332

Builder option(String key, String value); // Sets context option

1333

Builder options(Map<String, String> options); // Sets multiple options

1334

Builder arguments(String language, String[] args); // Sets guest language application arguments

1335

Builder allowIO(IOAccess ioAccess); // Configures IO access

1336

Builder allowCreateProcess(boolean enabled); // Allows external process creation

1337

Builder allowEnvironmentAccess(EnvironmentAccess accessPolicy); // Sets environment access policy

1338

Builder environment(String name, String value); // Sets environment variable

1339

Builder resourceLimits(ResourceLimits limits); // Assigns resource limit configuration

1340

Builder sandbox(SandboxPolicy policy); // Sets sandbox policy

1341

Builder timeZone(ZoneId zone); // Sets default time zone

1342

Builder currentWorkingDirectory(Path workingDirectory); // Sets current working directory

1343

Builder hostClassLoader(ClassLoader classLoader); // Sets host class loader

1344

Builder useSystemExit(boolean enabled); // Specifies System.exit usage for context exit

1345

Context build(); // Creates context instance

1346

}

1347

1348

// Engine.Builder methods

1349

public static class Engine.Builder {

1350

Builder out(OutputStream out); // Sets standard output stream

1351

Builder err(OutputStream err); // Sets error output stream

1352

Builder in(InputStream in); // Sets input stream

1353

Builder allowExperimentalOptions(boolean enabled); // Allows experimental options

1354

Builder useSystemProperties(boolean enabled); // Uses system properties for options

1355

Builder option(String key, String value); // Sets engine option

1356

Builder options(Map<String, String> options); // Sets multiple options

1357

Builder sandbox(SandboxPolicy policy); // Sets sandbox policy

1358

Builder serverTransport(MessageTransport serverTransport); // Sets message transport

1359

Builder logHandler(Handler logHandler); // Sets logging handler

1360

Builder logHandler(OutputStream logOut); // Sets logging output stream

1361

Engine build(); // Creates engine instance

1362

}

1363

1364

// Source.Builder methods

1365

public static class Source.Builder {

1366

Builder name(String name); // Sets source name

1367

Builder mimeType(String mimeType); // Sets MIME type

1368

Builder content(String content); // Sets content

1369

Builder cached(boolean cached); // Sets caching behavior

1370

Builder interactive(boolean interactive); // Sets interactive mode

1371

Builder internal(boolean internal); // Sets internal mode

1372

Builder encoding(Charset encoding); // Sets character encoding

1373

Builder uri(URI uri); // Sets URI

1374

Source build(); // Creates source instance

1375

}

1376

```

1377

1378

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.