Scripting Support
rulii 1.2.0 introduces a scripting layer that lets you embed dynamic expressions — written in JavaScript, Groovy, or any JSR-223 language — directly inside rules, conditions, actions, and functions. Scripts are first-class citizens: they are compiled once, cached, and evaluated against the current RuleContext.
The Script API
Section titled “The Script API”A Script<T> is a typed, named script. Build one with Script.builder():
// A boolean script using JavaScript via JSR-223Script<Boolean> script = Script.builder() .with("js", "ctx.age >= 18") .build();
// Reference bindings by name directly in the script bodyScript<Boolean> script = Script.builder() .with("js", "ctx.age >= ctx.minAge") .build();The ctx Binding Object
Section titled “The ctx Binding Object”Rather than injecting each binding as a top-level variable in the script scope, rulii exposes all bindings as a single object named ctx. This was a deliberate design decision for two reasons:
- Namespace separation. Injecting every binding as its own top-level variable creates collisions with local script variables and language built-ins. Accessing bindings through
ctxkeeps the binding namespace isolated from anything the script declares locally. - Performance. Building a flat variable scope for a scripting engine requires copying every binding into the engine’s bindings map on each evaluation. With
ctx, only a single object reference is injected — the engine receives one binding regardless of how many values theRuleContextholds, which is significantly cheaper at runtime.
// All rule context bindings are accessed through ctxScript<Boolean> check = Script.builder() .with("js", "ctx.age >= 18 && ctx.country === 'US'") .build();
// Local script variables do not pollute the binding namespaceScript<Integer> calc = Script.builder() .with("js", "var tax = ctx.price * 0.2; ctx.price + tax") .build();// 'tax' is a local variable — it never leaks into the RuleContext bindingsUsing Scripts in Conditions, Actions and Functions
Section titled “Using Scripts in Conditions, Actions and Functions”The builder classes for Condition, Action, and Function all accept a Script directly:
Script<Boolean> ageCheck = Script.builder() .with("js", "ctx.age >= 18") .build();
// Wrap the script as a ConditionCondition condition = Condition.builder().build(ageCheck);
// Use it in a RuleRule rule = Rule.builder() .with("AgeCheck") .given(condition) .then(Action.builder().build(Script.builder() .with("js", "ctx.status = 'approved'") .build())) .build();Script Processors & the Registry
Section titled “Script Processors & the Registry”A ScriptProcessor evaluates scripts for a specific language. The ScriptProcessorRegistry maps language names to their processors and is held by the RuleContext.
// Build a registry with JSR-223 auto-discovery enabledScriptProcessorRegistry registry = ScriptProcessorRegistry.builder() .autoIncludeJSR223(true) .build();
// Register a custom processorregistry.register(myCustomProcessor);
// Wire into RuleContextRuleContext ctx = RuleContext.builder() .with("MyContext") .scriptProcessorRegistry(registry) .build();JSR-223 Bridge
Section titled “JSR-223 Bridge”When autoIncludeJSR223 is enabled, rulii automatically discovers a javax.script.ScriptEngine by language name on first use. If the engine implements Compilable, the script is compiled and cached in a WeakHashMap for reuse. The RuleContext bindings are injected into the script scope under the configured bindings name ("ctx" by default).
// Access bindings in the script via "ctx"// The bindings map is exposed as a plain Map, so dot-access// syntax depends on the scripting language.
// JavaScript — language name "js" (Nashorn / GraalJS)"ctx.age >= 18 && ctx.country === 'US'"
// Groovy"ctx.age >= 18 && ctx.country == 'US'"Built-in Script Engines
Section titled “Built-in Script Engines”rulii ships with three optional script engines — GraalJS, Janino and, since 2.2.0, Jakarta Expression Language. Each provides a ScriptProcessorFactory that is auto-discovered via Java’s ServiceLoader. Add the dependency to your build and the engine registers itself automatically — no additional wiring required.
GraalJS — language "js"
Section titled “GraalJS — language "js"”GraalJS is Oracle’s high-performance JavaScript engine built on the Truffle framework. rulii’s GraalJsScriptProcessorFactory creates an engine pre-configured with ECMAScript 2022, full host access (HostAccess.ALL), and unrestricted host class lookup — so scripts can call Java methods directly via ctx. If the GraalJS classes are not on the classpath isAvailable() returns false and the engine is silently skipped.
Maven
<!-- GraalJS script engine --><dependency> <groupId>org.graalvm.js</groupId> <artifactId>js-scriptengine</artifactId> <version>24.1.0</version></dependency><dependency> <groupId>org.graalvm.polyglot</groupId> <artifactId>js-community</artifactId> <version>24.1.0</version> <type>pom</type></dependency>Gradle
implementation "org.graalvm.js:js-scriptengine:24.1.0"implementation "org.graalvm.polyglot:js-community:24.1.0"Once the dependencies are present, scripts using language "js" are compiled and cached automatically. Bindings are exposed through ctx and full Java interop is available.
// Boolean condition — age checkScript<Boolean> ageCheck = Script.builder() .with("js", "ctx.age >= 18 && ctx.country === 'US'") .build();
// Action — write a computed value back to a bindingScript<Void> applyDiscount = Script.builder() .with("js", "ctx.total = ctx.price * (1 - ctx.discountRate)") .build();
// Local variables are isolated from the RuleContextScript<Void> withLocal = Script.builder() .with("js", "var tax = ctx.price * 0.2; ctx.total = ctx.price + tax;") .build();// 'tax' stays local — it is never written back to the RuleContextJanino — language "java"
Section titled “Janino — language "java"”Janino is a lightweight Java compiler that compiles script fragments to bytecode at runtime. Unlike the JSR-223 bridge, rulii’s Janino integration uses a custom compiler that reads the live bindings at compile time to generate a fully typed method signature — each binding becomes a typed parameter, producing a JIT-compiled evaluator with no reflection overhead per call. The compiled evaluator is cached in the Script instance and reused on subsequent runs.
Maven
<!-- Janino JIT Java compiler --><dependency> <groupId>org.codehaus.janino</groupId> <artifactId>janino</artifactId> <version>3.1.12</version></dependency>Gradle
implementation "org.codehaus.janino:janino:3.1.12"Scripts are standard Java statement blocks. All bindings are accessed through ctx using the same dot-access syntax as the JavaScript engine. The Java standard library is available without any imports.
// Read a binding and write a result backScript.<Void>builder() .with("java", "ctx.total = ctx.price * ctx.quantity;") .build();
// Local typed variable — stays local, never leaks into RuleContextScript.<Void>builder() .with("java", "int square = ctx.base * ctx.base;\nctx.result = square + ctx.base;") .build();
// Ternary and standard library methods work as expectedScript.<Void>builder() .with("java", "ctx.label = ctx.score >= 90 ? \"A\" : ctx.score >= 80 ? \"B\" : \"C\";") .build();
Script.<Void>builder() .with("java", "ctx.output = ctx.input.trim().toUpperCase();") .build();Constraints to be aware of
- Bindings must exist at compile time. Because the compiler generates a typed method signature from the live bindings, referencing a binding that has not been added to the
RuleContextbefore the script first runs will throw aBuildScriptException. ctxis reserved. Declaring a local variable namedctxis rejected at compile time.- No increment/decrement operators on bindings.
ctx.counter++andctx.counter--are not supported — usectx.counter = ctx.counter + 1instead.
Jakarta Expression Language — language "jakarta-el" (new in 2.2.0)
Section titled “Jakarta Expression Language — language "jakarta-el" (new in 2.2.0)”Jakarta Expression Language is registered as jakarta-el (alias jel) by org.rulii.script.el.ElScriptProcessorFactory. It is available when the EL API and an implementation are on the classpath: jakarta.el:jakarta.el-api is a provided dependency of rulii, as the GraalJS and Janino engines are, and Expressly or Tomcat’s tomcat-embed-el supplies the implementation. It is the language Bean Validation message templates are written in, which is why rulii-bean-validation needs it.
Maven
<dependency> <groupId>jakarta.el</groupId> <artifactId>jakarta.el-api</artifactId> <version>5.0.1</version></dependency><dependency> <groupId>org.glassfish.expressly</groupId> <artifactId>expressly</artifactId> <version>5.0.0</version></dependency>An EL script is written in EL’s own delimiters, #{...} or ${...}; the two evaluate the same here, and the examples use #{...}. The bindings are reachable through the root object (ctx, as in the other languages) and — because EL resolves a base-less identifier through its resolver chain rather than a scope — as bare identifiers too. Beyond that the standard resolvers apply: bean properties, map keys, list and array indexes, method calls.
// Through the root object ...Script<Boolean> adult = Script.builder() .with("jakarta-el", "#{ctx.age >= 18}") .build();
// ... or as bare identifiersScript<Boolean> sameCheck = Script.builder() .with("jel", "#{age >= 18 && person.country == 'US'}") .build();
// A binding named like an EL reserved word (empty, and, ...) — bracket form onlyScript<Boolean> reserved = Script.builder() .with("jakarta-el", "#{ctx['empty'] == null}") .build();Things to know
- Compiled once, evaluated per call.
ElScriptCompilerparses the expression once (the result is coerced to the script’s return type);ElScriptProcessorbuilds a fresh EL context for each evaluation, so compiled scripts are shared freely between threads. - Bindings are read-only from EL. Use EL for conditions and functions; an action that must write a binding belongs in another language.
- EL text is not pre-processed.
${...}is also the placeholder syntax a script-text resolver (ScriptProcessorManager.setScriptTextResolver) rewrites, and rulii-spring installs one for Spring property placeholders. From 2.3.0 a language can opt out of the resolver (ScriptProcessorFactory.resolvesScriptText(),trueby default), and Jakarta EL does: an EL script reaches the compiler as written, so${...}and#{...}both work in a Spring application. The other side of that: a property placeholder inside ajakarta-elscript is not resolved; pass the value in as a binding. In 2.2.0 an EL script written as${...}was taken for a placeholder under rulii-spring and failed. - Not
el. In rulii-spring the plain nameelis Spring Expression Language, so XML rules declared withlanguage="el"keep their meaning; Jakarta EL is alwaysjakarta-elorjel.
What’s New in 2.1.0 (GraalJS)
Section titled “What’s New in 2.1.0 (GraalJS)”rulii 2.1.0 reworks the GraalJS integration: scripts can read Java bean properties directly, a polyglot context leak is fixed, every name GraalJS answers to resolves to the configured factory, and factories can be unregistered.
Nashorn Compatibility Mode (on by default)
Section titled “Nashorn Compatibility Mode (on by default)”The shared GraalJS engine now sets js.nashorn-compat=true, so scripts read Java bean properties directly: ctx.person.name instead of ctx.person.getName(), ctx.person.active for isActive(), and assignment calls the setter. Previously such reads silently evaluated to null. The explicit ES2022 setting still applies.
// 2.1.0 — bean properties work directly (previously evaluated to null)Script<Boolean> vipCheck = Script.builder() .with("js", "ctx.person.age >= 18 && ctx.person.active") .build();// ctx.person.age calls getAge(); ctx.person.active calls isActive()
// Assignment calls the setterScript<Void> promote = Script.builder() .with("js", "ctx.person.status = 'gold'") .build();// calls setStatus("gold")The mode also enables the Nashorn Java.* helpers, JavaImporter, and the exit() / quit() globals — which end the script with an exception, not the JVM.
Context Lifecycle & Value Detaching
Section titled “Context Lifecycle & Value Detaching”GraalJS backs every evaluation with a polyglot context that is reclaimed only by an explicit close. In earlier releases that context was never closed, which exhausted the heap under sustained evaluation. 2.1.0 fixes the leak: the processor releases the context after each evaluation whenever the result does not depend on it. To make that possible almost always, GraalJS values are now detached into plain Java objects as they cross into Java — this applies to evaluation results and to values a script writes into the bindings:
- JavaScript arrays,
Sets and iterables becomeArrayLists - Object literals and
Maps becomeLinkedHashMaps Dates becomeInstants
// A JS array crossing into Java arrives as a java.util.ArrayListScript<Void> collect = Script.builder() .with("js", "ctx.out = [1, 2, 3]; ctx.out.add(4);") .build();// ctx.out is already a Java List — use add(), not push()Factory Aliases & Unregistration
Section titled “Factory Aliases & Unregistration”A ScriptProcessorFactory can now declare alternate names via getAliases(). The GraalJS factory reports every name GraalJS itself registers with JSR-223 (JS, JavaScript, ECMAScript, graal.js, …), so all of them resolve to the configured factory. Previously anything but js fell through to the generic JSR-223 wrapper, which had none of the factory’s configuration.
Factories can also be taken back out: ScriptProcessorManager.unregister(factory) removes every name that maps to that exact instance and reports whether any did. Names the factory had displaced are refilled from service-loader discovery, so removing an override restores the stock factory for that language. This lets an integration that registers factories tied to its own lifecycle (rulii-spring registers ScriptProcessorFactory beans) take them out when that lifecycle ends.
Source Text vs Resolved Text
Section titled “Source Text vs Resolved Text”Script.getSourceText() returns the script text as written, before ${...} placeholder resolution; getScript() is still the resolved text the compiler saw. Both surface in a script-backed runnable’s ExpressionInfo — see Introspection & Metadata for the full picture.
What’s New in 2.2.0 (Default Language)
Section titled “What’s New in 2.2.0 (Default Language)”ScriptProcessorManager now holds a process-wide default scripting language — the language a script is compiled in when none is named. It is declared, never inferred from the classpath, in one of two ways:
setDefaultLanguage(name)— validated through the normal lookup, so a registered name and a JSR-223 engine name are both accepted, and a misspelt one fails where it is set, listing the available languages.- The system property
rulii.script.defaultLanguage(ScriptProcessorManager.DEFAULT_LANGUAGE_PROPERTY) — read while nothing is set and kept once it names a language; a property naming an unknown language fails every read rather than running without a default. rulii-spring also reads it from the SpringEnvironment.
ScriptProcessorManager manager = ScriptProcessorManager.getInstance();manager.setDefaultLanguage("jakarta-el");manager.getDefaultLanguage(); // "jakarta-el" — the setter's value, else the property's, else null
// No language named: compiled in the default languageScript<Boolean> adult = Script.builder().with("#{age >= 18}").build();Script<Boolean> same = Script.builder().build("#{age >= 18}");
// Tear down only what you installed — a later default is left alonemanager.clearDefaultLanguage("jakarta-el"); // true if it was the active default
// What can a script be compiled in right now?Set<String> languages = manager.getAvailableLanguages(); // e.g. [jakarta-el, java, js]Script.builder().with(script)andbuild(script)compile in the default language, and throw anUnrulyExceptionnaming both ways to declare one when there is none.clearDefaultLanguage(expected)clears only when the active default is the expected one (asclearScriptTextResolverdoes), so an integration can tear down what it installed without clobbering a later one; after clearing, the property is read again.getAvailableLanguages()lists the language name of every registered (or service-loaded) factory plus every JSR-223 engine the JVM reports that no registered factory already covers — an engine is covered when any name it answers to is a registered name or alias, so GraalJS registered asjsis listed once. Aliases are not listed. The set is sorted, unmodifiable and computed per call.
What’s New in 2.3.0 (GraalJS Context Reuse)
Section titled “What’s New in 2.3.0 (GraalJS Context Reuse)”Every JavaScript evaluation runs in a JavaScript context of its own, created for it and closed after it. Creating the context is nearly all of what the evaluation costs: about 127 µs, against a few microseconds for the script. From 2.3.0 a GraalJS factory can keep a pool of contexts instead, and an evaluation then costs about 6 µs. It is opt-in: nothing changes unless you turn it on.
// Per factoryScriptProcessorManager.getInstance().register( new GraalJsScriptProcessorFactory("js", "ctx", GraalJsPoolOptions.DEFAULT));# Or for every GraalJS factory in the JVM-Drulii.script.graaljs.reuseContexts=trueWith reuse on, a script gives what it gives without it: the same results, failures and messages. What it declares (var, let, const, functions) ends with it, the rule bindings are a global for the length of the evaluation, and a global the script leaves behind (a variable assigned without being declared) is removed before the context is used again.
GraalJsPoolOptions sets how many contexts are kept and when one is retired. The same names work as system properties under rulii.script.graaljs.pool., with durations written as PT5M.
| Option | Default | Meaning |
|---|---|---|
maxIdle |
one per processor, at least two | Contexts kept between evaluations |
idleTimeout |
5 minutes | An idle context older than this is closed |
maxAge |
30 minutes | A context is retired at this age |
maxUses |
1,000 | Evaluations per context; 1 gives every evaluation a context of its own again |
initialSize |
0 | Contexts created up front, with the factory’s first processor |
cleanGlobals |
on | Remove globals a script leaves behind |
- The pool never makes a caller wait and runs no thread: evaluations at the same moment each get a context, spare ones are closed afterwards, and age and idle time are looked at when the pool is used.
- A context whose script failed is closed. One whose result is still a JavaScript object (a function) stays alive for that result and is not reused.
discardContexts()on the factory retires every context created so far, for when a script is known to have left them in a state others should not see. The factory isAutoCloseable, andclose()does the same, so a factory declared as a Spring bean releases its contexts on shutdown.getPoolStatistics()reports contexts created, reused, retired, cleaned, closed and idle.
Optimising Another Script Engine
Section titled “Optimising Another Script Engine”Any JSR-223 engine works through JSR223ScriptProcessor, which asks the engine for new bindings (ScriptEngine.createBindings()) for every evaluation, so that no script sees what another left behind. For an engine whose bindings are a plain map that costs nothing. For an engine whose bindings carry a whole language environment it is most of the bill: on Nashorn 15.4 an evaluation costs about 33 µs, about 30 µs of it the new bindings, while the compiled script alone runs in well under a microsecond when the bindings are kept.
Keeping bindings between evaluations is therefore where the speed is, and the pool that does it for GraalJS is ordinary bookkeeping that would suit any engine. What does not carry over, and has to be answered per engine before bindings are kept:
- What a script leaves behind. In both Nashorn and GraalJS a top-level
varor function of a compiled script stays in kept bindings and cannot be removed through the JSR-223 API, and in GraalJS a top-levelletorconstmakes the script fail the second time. GraalJS reuse runs the script throughevalinside a function to keep declarations local; on an engine that compiles to bytecode that gives the compiled script away. - Threads. JSR-223 leaves thread safety to the engine. GraalJS allows one thread at a time in a context; Nashorn ran several threads on one engine with bindings each.
- Results that belong to the bindings. A script can hand back an object of its language (a function, say) that stops working when its bindings are closed or reused; see
JSR223ScriptProcessor.isContextReleasable.
To do it for an engine, subclass JSR223ScriptProcessor (buildContext, releaseContext, isContextReleasable) and register a ScriptProcessorFactory that hands it out. GraalJsScriptProcessor is the worked example.
Error Handling
Section titled “Error Handling”Two exceptions cover the scripting error surface:
| Exception | When Thrown |
|---|---|
| BuildScriptException | Script compilation fails (syntax error, unknown language) |
| EvaluationException | Script evaluation fails at runtime (type error, missing binding) |