GraalVM Polyglot API for embedding and executing Python code within Java applications.
—
Source management provides comprehensive functionality for creating, configuring, and managing Python source code objects. The Source class abstracts different input formats and provides metadata management, automatic language detection, and flexible source creation patterns.
Create Source objects from various input formats including strings, files, URLs, and streams.
/**
* Creates a builder for constructing Source objects from string content
* @param language the language identifier (use "python" for Python)
* @param characters the source code content
* @param name a descriptive name for the source
* @return Source.Builder for configuration
*/
public static Builder newBuilder(String language, CharSequence characters, String name);
/**
* Creates a builder for constructing Source objects from files
* @param language the language identifier
* @param file the source file
* @return Source.Builder for configuration
*/
public static Builder newBuilder(String language, File file);
/**
* Creates a builder for constructing Source objects from URLs
* @param language the language identifier
* @param url the source URL
* @return Source.Builder for configuration
*/
public static Builder newBuilder(String language, URL url);
/**
* Creates a builder for constructing Source objects from readers
* @param language the language identifier
* @param source the Reader providing source content
* @param name a descriptive name for the source
* @return Source.Builder for configuration
*/
public static Builder newBuilder(String language, Reader source, String name);
/**
* Quick creation method for simple string sources
* @param language the language identifier
* @param source the source code content
* @return Source object ready for evaluation
*/
public static Source create(String language, CharSequence source);Usage Examples:
// Simple string source
Source simpleSource = Source.create("python", "print('Hello, World!')");
// Named string source with builder
Source namedSource = Source.newBuilder("python",
"def factorial(n):\n return 1 if n <= 1 else n * factorial(n-1)",
"factorial.py")
.build();
// File-based source
File pythonFile = new File("/path/to/script.py");
Source fileSource = Source.newBuilder("python", pythonFile)
.mimeType("text/x-python")
.build();
// URL-based source
URL scriptUrl = new URL("https://example.com/script.py");
Source urlSource = Source.newBuilder("python", scriptUrl)
.cached(true)
.build();
// Reader-based source
StringReader reader = new StringReader("import math\nprint(math.pi)");
Source readerSource = Source.newBuilder("python", reader, "math_example.py")
.build();
// Multi-line Python script
String pythonScript = """
import sys
import json
def process_data(data):
result = []
for item in data:
if isinstance(item, dict):
result.append(item.get('value', 0) * 2)
return result
data = [{'value': 1}, {'value': 2}, {'value': 3}]
print(json.dumps(process_data(data)))
""";
Source scriptSource = Source.newBuilder("python", pythonScript, "data_processor.py")
.uri(URI.create("file:///examples/data_processor.py"))
.build();Automatically detect the language of source files based on file extensions and content analysis.
/**
* Detects the language of a file based on its extension and content
* @param file the file to analyze
* @return language identifier string, or null if detection fails
*/
public static String findLanguage(File file);
/**
* Detects the language of a URL resource based on path and content
* @param url the URL to analyze
* @return language identifier string, or null if detection fails
*/
public static String findLanguage(URL url);
/**
* Detects the MIME type of a file
* @param file the file to analyze
* @return MIME type string, or null if detection fails
*/
public static String findMimeType(File file);
/**
* Detects the MIME type of a URL resource
* @param url the URL to analyze
* @return MIME type string, or null if detection fails
*/
public static String findMimeType(URL url);Usage Examples:
// Automatic language detection
File pythonFile = new File("script.py");
String detectedLanguage = Source.findLanguage(pythonFile); // "python"
File unknownFile = new File("mystery_script");
String language = Source.findLanguage(unknownFile);
if (language != null) {
Source source = Source.newBuilder(language, unknownFile).build();
} else {
// Fallback or manual specification
Source source = Source.newBuilder("python", unknownFile).build();
}
// MIME type detection
String mimeType = Source.findMimeType(pythonFile); // "text/x-python"
// URL-based detection
URL scriptUrl = new URL("https://raw.githubusercontent.com/user/repo/main/script.py");
String urlLanguage = Source.findLanguage(scriptUrl); // "python"
String urlMimeType = Source.findMimeType(scriptUrl); // "text/x-python"
// Combined detection and source creation
File sourceFile = new File("algorithms.py");
String detectedLang = Source.findLanguage(sourceFile);
if ("python".equals(detectedLang)) {
Source source = Source.newBuilder(detectedLang, sourceFile)
.mimeType(Source.findMimeType(sourceFile))
.build();
Value result = context.eval(source);
}Access metadata and content information from Source objects.
/**
* Gets the language identifier for this source
* @return the language identifier
*/
public String getLanguage();
/**
* Gets the name of this source
* @return the source name
*/
public String getName();
/**
* Gets the path of this source (if file-based)
* @return the file path, or null if not file-based
*/
public String getPath();
/**
* Gets the URI of this source
* @return the source URI
*/
public URI getURI();
/**
* Gets the MIME type of this source
* @return the MIME type, or null if not specified
*/
public String getMimeType();
/**
* Checks if this source has character-based content
* @return true if the source contains text
*/
public boolean hasCharacters();
/**
* Checks if this source has byte-based content
* @return true if the source contains binary data
*/
public boolean hasBytes();
/**
* Gets the character content of this source
* @return CharSequence containing the source text
* @throws UnsupportedOperationException if source has no characters
*/
public CharSequence getCharacters();
/**
* Gets the byte content of this source
* @return ByteSequence containing the source bytes
* @throws UnsupportedOperationException if source has no bytes
*/
public ByteSequence getBytes();
/**
* Gets a Reader for the source content
* @return Reader for streaming the source content
* @throws UnsupportedOperationException if source has no characters
*/
public Reader getReader();
/**
* Gets the length of the source content
* @return number of characters in the source
*/
public int getLength();
/**
* Gets the number of lines in the source
* @return line count
*/
public int getLineCount();
/**
* Checks if this source is marked as interactive
* @return true if source is for interactive evaluation
*/
public boolean isInteractive();Usage Examples:
// Source metadata inspection
Source source = Source.newBuilder("python",
"# Python script for data analysis\nimport pandas as pd\nprint('Hello')",
"analysis.py")
.mimeType("text/x-python")
.uri(URI.create("file:///projects/analysis.py"))
.build();
// Basic metadata
String language = source.getLanguage(); // "python"
String name = source.getName(); // "analysis.py"
String mimeType = source.getMimeType(); // "text/x-python"
URI uri = source.getURI(); // file:///projects/analysis.py
// Content inspection
boolean hasText = source.hasCharacters(); // true
boolean hasBinary = source.hasBytes(); // false (for text sources)
if (hasText) {
CharSequence content = source.getCharacters();
int length = source.getLength(); // Number of characters
int lines = source.getLineCount(); // Number of lines
System.out.println("Source length: " + length + " characters");
System.out.println("Source lines: " + lines);
System.out.println("Content preview: " + content.toString().substring(0, 50));
}
// Reader-based access for large sources
try (Reader reader = source.getReader()) {
BufferedReader buffered = new BufferedReader(reader);
String firstLine = buffered.readLine();
System.out.println("First line: " + firstLine);
}
// File path information (for file-based sources)
File pythonFile = new File("scripts/calculator.py");
Source fileSource = Source.newBuilder("python", pythonFile).build();
String filePath = fileSource.getPath(); // "scripts/calculator.py"Configure Source objects with advanced options using the builder pattern.
/**
* Builder class for constructing configured Source objects
*/
public static final class Source.Builder {
/**
* Sets the MIME type for this source
* @param mimeType the MIME type string
* @return this builder
*/
public Builder mimeType(String mimeType);
/**
* Sets the URI for this source
* @param uri the source URI
* @return this builder
*/
public Builder uri(URI uri);
/**
* Marks this source as cached for performance
* @param cached true to enable caching
* @return this builder
*/
public Builder cached(boolean cached);
/**
* Marks this source as interactive (REPL-style)
* @param interactive true for interactive mode
* @return this builder
*/
public Builder interactive(boolean interactive);
/**
* Marks this source as internal (not user code)
* @param internal true for internal sources
* @return this builder
*/
public Builder internal(boolean internal);
/**
* Sets the character encoding for file-based sources
* @param encoding the character encoding
* @return this builder
*/
public Builder encoding(Charset encoding);
/**
* Sets content directly as byte array
* @param bytes the source content as bytes
* @return this builder
*/
public Builder content(byte[] bytes);
/**
* Sets content directly as string
* @param content the source content
* @return this builder
*/
public Builder content(String content);
/**
* Builds the configured Source object
* @return new Source instance
*/
public Source build();
}Usage Examples:
// Advanced source configuration
Source configuredSource = Source.newBuilder("python", "print('Hello')", "hello.py")
.mimeType("text/x-python")
.uri(URI.create("memory:///hello.py"))
.cached(true)
.interactive(false)
.internal(false)
.build();
// Interactive source for REPL
Source replSource = Source.newBuilder("python", "x = 42", "<stdin>")
.interactive(true)
.build();
// File source with custom encoding
Source encodedSource = Source.newBuilder("python", new File("utf8_script.py"))
.encoding(StandardCharsets.UTF_8)
.cached(true)
.build();
// Binary content source
byte[] pythonBytecode = loadPythonBytecode(); // Custom method
Source bytecodeSource = Source.newBuilder("python", "", "compiled.pyc")
.content(pythonBytecode)
.mimeType("application/x-python-bytecode")
.build();
// Network source with caching
URL networkScript = new URL("https://cdn.example.com/utils.py");
Source networkSource = Source.newBuilder("python", networkScript)
.cached(true) // Cache for performance
.build();
// Internal library source
String internalLib = """
# Internal utility functions
def _internal_helper(value):
return value * 2
""";
Source internalSource = Source.newBuilder("python", internalLib, "<internal>")
.internal(true) // Mark as internal
.build();
// Template-based source generation
String template = "result = calculate(%s, %s)";
String pythonCode = String.format(template, 10, 20);
Source templateSource = Source.newBuilder("python", pythonCode, "generated.py")
.uri(URI.create("generated://template/calculate"))
.build();Work with source sections for error reporting and debugging support.
/**
* Creates a source section representing a portion of this source
* @param startIndex character index where section starts
* @param length number of characters in section
* @return SourceSection representing the specified range
*/
public SourceSection createSection(int startIndex, int length);
/**
* Creates a source section by line and column numbers
* @param startLine starting line (1-based)
* @param startColumn starting column (1-based)
* @param endLine ending line (1-based)
* @param endColumn ending column (1-based)
* @return SourceSection representing the specified range
*/
public SourceSection createSection(int startLine, int startColumn, int endLine, int endColumn);
/**
* Creates a source section for a specific line
* @param lineNumber the line number (1-based)
* @return SourceSection representing the entire line
*/
public SourceSection createSection(int lineNumber);Usage Examples:
String pythonCode = """
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
result = fibonacci(10)
print("Result:", result)
""";
Source source = Source.create("python", pythonCode);
// Create section for function definition (lines 1-4)
SourceSection funcSection = source.createSection(1, 1, 4, 40);
// Create section for specific line
SourceSection resultLine = source.createSection(6); // "result = fibonacci(10)"
// Create section by character index
SourceSection printSection = source.createSection(
pythonCode.indexOf("print"),
"print(\"Result:\", result)".length()
);
// Use sections for error reporting
try {
Value result = context.eval(source);
} catch (PolyglotException e) {
SourceSection errorLocation = e.getSourceLocation();
if (errorLocation != null && errorLocation.getSource().equals(source)) {
System.err.println("Error at line " + errorLocation.getStartLine() +
", column " + errorLocation.getStartColumn());
System.err.println("Code: " + errorLocation.getCharacters());
}
}/**
* Represents a sequence of bytes for binary source content
*/
public interface ByteSequence {
/**
* Gets the length of the byte sequence
* @return number of bytes
*/
int length();
/**
* Gets the byte at specified index
* @param index the byte index
* @return byte value at index
*/
byte byteAt(int index);
/**
* Creates a subsequence of bytes
* @param startIndex starting index (inclusive)
* @param endIndex ending index (exclusive)
* @return ByteSequence representing the subsequence
*/
ByteSequence subSequence(int startIndex, int endIndex);
/**
* Converts to byte array
* @return byte array containing the sequence
*/
byte[] toByteArray();
}
/**
* Represents a section within a source for error reporting and debugging
*/
public final class SourceSection {
/**
* Checks if this section is available
* @return true if section information is available
*/
public boolean isAvailable();
/**
* Gets the source containing this section
* @return the Source object
*/
public Source getSource();
/**
* Gets the starting line number (1-based)
* @return starting line number
*/
public int getStartLine();
/**
* Gets the ending line number (1-based)
* @return ending line number
*/
public int getEndLine();
/**
* Gets the starting column (1-based)
* @return starting column number
*/
public int getStartColumn();
/**
* Gets the ending column (1-based)
* @return ending column number
*/
public int getEndColumn();
/**
* Gets the character index where section starts
* @return starting character index
*/
public int getCharIndex();
/**
* Gets the character index where section ends
* @return ending character index
*/
public int getCharEndIndex();
/**
* Gets the length of this section in characters
* @return section length
*/
public int getCharLength();
/**
* Gets the text content of this section
* @return CharSequence containing the section text
*/
public CharSequence getCharacters();
}Install with Tessl CLI
npx tessl i tessl/maven-org-graalvm-polyglot--python