遗留① JUEL:platform-app 接入 jakarta.el 实现的 juel JSR-223 引擎

写路径提交前置:带 initExpression/条件转移的 EL 写流原本因运行时无名为 "juel" 的
引擎抛 "Can't find scripting engine for 'juel'" → status:1。

- 新增 com.eip4.platform.app.script.juel JSR-223 工厂+引擎(getNames=["juel"]),
  EL 后端用已在 classpath 的 jakarta.el(tomcat-embed-el,经 spring-boot-starter-web 传递),
  不引 activiti-engine / de.odysseus.juel,零改保真层 com.dsasp.*
- META-INF/services 注册 → ScriptingEnginesManager 既有惰性注册(getEngineByName("juel"))自动拾取
- BindingsELResolver 对 base==null 顶层标识符强制 setPropertyResolved,对齐 activiti JUEL
  宽松语义(未绑定→null 不抛;jakarta.el 默认会抛 PropertyNotFoundException)
- 接缝单测 6 例(含端到端 ScriptingEnginesManager.evaluate(...,"juel",...))+ ArchUnit 全绿

注:B2 跨流回归(EL 求值语义差异:数值提升 Long/Double、真实 bean 缺 getter、#{} 延迟表达式)待专项。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-13 22:59:14 +08:00
parent 06dd127296
commit 72e4c6d0e6
4 changed files with 527 additions and 0 deletions

View File

@@ -0,0 +1,271 @@
package com.eip4.platform.app.script.juel;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Map;
import javax.script.AbstractScriptEngine;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
import jakarta.el.ArrayELResolver;
import jakarta.el.BeanELResolver;
import jakarta.el.CompositeELResolver;
import jakarta.el.ELContext;
import jakarta.el.ELException;
import jakarta.el.ELResolver;
import jakarta.el.ExpressionFactory;
import jakarta.el.FunctionMapper;
import jakarta.el.ListELResolver;
import jakarta.el.MapELResolver;
import jakarta.el.StaticFieldELResolver;
import jakarta.el.ValueExpression;
import jakarta.el.VariableMapper;
/**
* 基于 jakarta.el 的 JUEL JSR-223 引擎(见 {@link JuelScriptEngineFactory} 类注释的背景与纪律)。
*
* <p>语义对齐 framework 原版 activiti JuelScriptEngine(javax.el):
* <ul>
* <li>顶层标识符 {@code ${x}} 解析为 bindings(ENGINE_SCOPE 叠加 GLOBAL_SCOPE)同名值;</li>
* <li>属性/集合导航 {@code ${bean.prop}}/{@code ${map.key}}/{@code ${list[0]}}/{@code ${arr[i]}};</li>
* <li>算术/比较/布尔/三元/字符串拼接照 EL 标准;</li>
* <li>未绑定标识符返回 null 不抛(JUEL 宽松语义)。</li>
* </ul>
*
* <p>仅依赖 javax.script.* + jakarta.el.*,不依赖 com.dsasp.*。
*/
public class JuelScriptEngine extends AbstractScriptEngine implements Compilable {
/** ExpressionFactory 无状态可共享,缓存一个实例避免每次 eval 重新 ServiceLoader。 */
private static final ExpressionFactory EXPRESSION_FACTORY = ExpressionFactory.newInstance();
private final ScriptEngineFactory factory;
public JuelScriptEngine(ScriptEngineFactory factory) {
this.factory = factory;
}
public JuelScriptEngine() {
this(new JuelScriptEngineFactory());
}
@Override
public Object eval(String script, ScriptContext context) throws ScriptException {
if (script == null) {
return null;
}
try {
ELContext elContext = new BindingsELContext(resolveBindings(context));
ValueExpression expr = EXPRESSION_FACTORY.createValueExpression(elContext, script, Object.class);
return expr.getValue(elContext);
} catch (ELException e) {
throw new ScriptException(e);
}
}
@Override
public Object eval(Reader reader, ScriptContext context) throws ScriptException {
return eval(readFully(reader), context);
}
@Override
public CompiledScript compile(String script) throws ScriptException {
return new JuelCompiledScript(script);
}
@Override
public CompiledScript compile(Reader script) throws ScriptException {
return compile(readFully(script));
}
@Override
public Bindings createBindings() {
return new SimpleBindings();
}
@Override
public ScriptEngineFactory getFactory() {
return factory;
}
/**
* 合并 ENGINE_SCOPE 与 GLOBAL_SCOPE 的 bindings(ENGINE_SCOPE 优先),作为 EL 顶层变量来源。
* 与 framework 行为一致:调用方经 {@code evaluate(script, "juel", bindings)} 传入的
* bindings 落在 ENGINE_SCOPE。
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private Map<String, Object> resolveBindings(ScriptContext context) {
SimpleBindings merged = new SimpleBindings();
Bindings global = context.getBindings(ScriptContext.GLOBAL_SCOPE);
if (global != null) {
merged.putAll(global);
}
Bindings engine = context.getBindings(ScriptContext.ENGINE_SCOPE);
if (engine != null) {
merged.putAll(engine);
}
return (Map) merged;
}
private static String readFully(Reader reader) throws ScriptException {
if (reader == null) {
return null;
}
StringBuilder sb = new StringBuilder();
char[] buffer = new char[4096];
try (BufferedReader br = new BufferedReader(reader)) {
int read;
while ((read = br.read(buffer)) != -1) {
sb.append(buffer, 0, read);
}
} catch (IOException e) {
throw new ScriptException(e);
}
return sb.toString();
}
/** 捕获 script、求值时延迟绑定的 CompiledScript(无需真正预编译,语义足够)。 */
private final class JuelCompiledScript extends CompiledScript {
private final String script;
private JuelCompiledScript(String script) {
this.script = script;
}
@Override
public Object eval(ScriptContext context) throws ScriptException {
return JuelScriptEngine.this.eval(script, context);
}
@Override
public ScriptEngine getEngine() {
return JuelScriptEngine.this;
}
}
/**
* 自定义 ELContext:ELResolver 链 = [bindings 顶层变量 resolver, Map, List, Array, Bean, StaticField]。
* VariableMapper/FunctionMapper 给最简非空实现。
*/
private static final class BindingsELContext extends ELContext {
private final ELResolver resolver;
private final VariableMapper variableMapper = new NoopVariableMapper();
private final FunctionMapper functionMapper = new NoopFunctionMapper();
private BindingsELContext(Map<String, Object> bindings) {
CompositeELResolver composite = new CompositeELResolver();
composite.add(new BindingsELResolver(bindings));
composite.add(new MapELResolver());
composite.add(new ListELResolver());
composite.add(new ArrayELResolver());
composite.add(new BeanELResolver());
composite.add(new StaticFieldELResolver());
this.resolver = composite;
}
@Override
public ELResolver getELResolver() {
return resolver;
}
@Override
public FunctionMapper getFunctionMapper() {
return functionMapper;
}
@Override
public VariableMapper getVariableMapper() {
return variableMapper;
}
}
/**
* 顶层变量解析器:base==null 的标识符按属性名从 bindings 取值。
*
* <p>关键:对 base==null 的 String 标识符一律 setPropertyResolved(true)——命中返回值,
* 未命中返回 null。这是与 framework activiti JUEL(javax.el)对齐的要点:jakarta.el 的
* AstIdentifier 在无 resolver 标记 resolved 时会抛 PropertyNotFoundException(而非返回 null),
* 故必须由本 resolver 兜住未绑定顶层标识符,保持 JUEL 宽松语义(${nope} → null 不抛)。
* 结构导航(${m.a}/${bean.name}/${list[0]})的 base 均非 null,由后续
* Map/List/Array/Bean resolver 处理,不受此影响。
*/
private static final class BindingsELResolver extends ELResolver {
private final Map<String, Object> bindings;
private BindingsELResolver(Map<String, Object> bindings) {
this.bindings = bindings;
}
@Override
public Object getValue(ELContext context, Object base, Object property) {
if (base == null && property instanceof String) {
context.setPropertyResolved(true);
return bindings.get(property);
}
return null;
}
@Override
public Class<?> getType(ELContext context, Object base, Object property) {
if (base == null && property instanceof String) {
context.setPropertyResolved(true);
Object value = bindings.get(property);
return value == null ? Object.class : value.getClass();
}
return null;
}
@Override
public void setValue(ELContext context, Object base, Object property, Object value) {
if (base == null && property instanceof String) {
context.setPropertyResolved(true);
bindings.put((String) property, value);
}
}
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
if (base == null && property instanceof String) {
context.setPropertyResolved(true);
}
return false;
}
@Override
public Class<?> getCommonPropertyType(ELContext context, Object base) {
return base == null ? String.class : null;
}
}
/** 无变量映射(顶层变量统一走 BindingsELResolver),返回 null 即可。 */
private static final class NoopVariableMapper extends VariableMapper {
@Override
public ValueExpression resolveVariable(String variable) {
return null;
}
@Override
public ValueExpression setVariable(String variable, ValueExpression expression) {
return null;
}
}
/** 无自定义 EL 函数,返回 null。 */
private static final class NoopFunctionMapper extends FunctionMapper {
@Override
public java.lang.reflect.Method resolveFunction(String prefix, String localName) {
return null;
}
}
}

View File

@@ -0,0 +1,126 @@
package com.eip4.platform.app.script.juel;
import java.util.Collections;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
/**
* EIP4 现代层的 JUEL JSR-223 引擎工厂(替代 framework 原版依赖的
* org.activiti.engine.impl.scripting.JuelScriptEngineFactory)。
*
* <p>架构纪律(《架构设计》第二节):activiti/Flowable 禁止进入保真层运行时,
* 故不引入 activiti-engine / de.odysseus.juel,改用运行时已在 classpath 上的
* jakarta.el(tomcat-embed-el,经 spring-boot-starter-web 传递)实现 EL 求值。
*
* <p>本类经 {@code META-INF/services/javax.script.ScriptEngineFactory} 由 ServiceLoader
* 暴露,getNames() 含 "juel",于是保真层
* {@code com.dsasp.server.core.service.script.ScriptingEnginesManager} 构造器里
* {@code scriptEngineManager.getEngineByName("juel")} 即可发现并惰性注册——保真层零修改。
*
* <p>仅依赖 javax.script.* + jakarta.el.*,不依赖 com.dsasp.*,满足 platform-app
* 的 ArchitectureRulesTest。
*/
public class JuelScriptEngineFactory implements ScriptEngineFactory {
private static final String ENGINE_NAME = "EIP4 JUEL";
private static final String ENGINE_VERSION = "1.0";
private static final String LANGUAGE_NAME = "JUEL";
private static final String LANGUAGE_VERSION = "2.2";
private static final List<String> NAMES = Collections.singletonList("juel");
@Override
public String getEngineName() {
return ENGINE_NAME;
}
@Override
public String getEngineVersion() {
return ENGINE_VERSION;
}
@Override
public List<String> getExtensions() {
return Collections.emptyList();
}
@Override
public List<String> getMimeTypes() {
return Collections.emptyList();
}
@Override
public List<String> getNames() {
return NAMES;
}
@Override
public String getLanguageName() {
return LANGUAGE_NAME;
}
@Override
public String getLanguageVersion() {
return LANGUAGE_VERSION;
}
@Override
public Object getParameter(String key) {
if (key == null) {
return null;
}
switch (key) {
case ScriptEngine.ENGINE:
return getEngineName();
case ScriptEngine.ENGINE_VERSION:
return getEngineVersion();
case ScriptEngine.NAME:
return getNames().get(0);
case ScriptEngine.LANGUAGE:
return getLanguageName();
case ScriptEngine.LANGUAGE_VERSION:
return getLanguageVersion();
case "THREADING":
// 引擎本身无可变共享状态(每次 eval 新建 ELContext),可多线程并发。
return "MULTITHREADED";
default:
return null;
}
}
@Override
public String getMethodCallSyntax(String obj, String method, String... args) {
StringBuilder sb = new StringBuilder();
sb.append("${").append(obj).append('.').append(method).append('(');
for (int i = 0; i < args.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(args[i]);
}
sb.append(")}");
return sb.toString();
}
@Override
public String getOutputStatement(String toDisplay) {
return toDisplay;
}
@Override
public String getProgram(String... statements) {
StringBuilder sb = new StringBuilder();
if (statements != null) {
for (String statement : statements) {
sb.append(statement);
}
}
return sb.toString();
}
@Override
public ScriptEngine getScriptEngine() {
return new JuelScriptEngine(this);
}
}

View File

@@ -0,0 +1 @@
com.eip4.platform.app.script.juel.JuelScriptEngineFactory

View File

@@ -0,0 +1,129 @@
package com.eip4.platform.app.script.juel;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashMap;
import java.util.Map;
import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleBindings;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.dsasp.server.core.service.script.ScriptingEnginesManager;
/**
* JUEL JSR-223 接缝语义规格(TDD)。这些断言即「与 framework activiti JUEL 行为对齐」的规格。
*
* <p>(a)~(e) 直接验证新引擎语义;(f) 验证保真层
* {@link ScriptingEnginesManager} 端到端发现并求值 "juel"(原本抛
* "Can't find scripting engine for 'juel'" 的写路径前置缺口)。
*/
class JuelScriptEngineSeamTest {
/** 简单 POJO,验证属性导航 ${bean.name}。 */
public static class Person {
private final String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
private static Object evalJuel(String script, Bindings bindings) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("juel");
assertNotNull(engine, "juel 引擎应可经 ServiceLoader 发现");
return engine.eval(script, bindings);
}
@Test
@DisplayName("(a) ServiceLoader 可发现 juel 引擎")
void juelEngineDiscoverable() {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("juel");
assertNotNull(engine, "new ScriptEngineManager().getEngineByName(\"juel\") 不应为 null");
assertEquals("juel", engine.getFactory().getNames().get(0));
}
@Test
@DisplayName("(b) 算术与比较:${1+2}=3, ${5>3}=true")
void arithmeticAndComparison() throws Exception {
Object sum = evalJuel("${1 + 2}", new SimpleBindings());
assertTrue(sum instanceof Number);
assertEquals(3, ((Number) sum).intValue());
Object gt = evalJuel("${5 > 3}", new SimpleBindings());
assertEquals(Boolean.TRUE, gt);
}
@Test
@DisplayName("(c) 绑定变量:x=5 → ${x+1}=6, ${x>3}=true")
void boundVariables() throws Exception {
Bindings b = new SimpleBindings();
b.put("x", 5);
Object inc = evalJuel("${x + 1}", b);
assertTrue(inc instanceof Number);
assertEquals(6, ((Number) inc).intValue());
Object gt = evalJuel("${x > 3}", b);
assertEquals(Boolean.TRUE, gt);
}
@Test
@DisplayName("(d) 属性导航:${m.a}=7, ${bean.name}")
void propertyNavigation() throws Exception {
Bindings b = new SimpleBindings();
Map<String, Object> m = new HashMap<>();
m.put("a", 7);
b.put("m", m);
b.put("bean", new Person("Ada"));
Object mapVal = evalJuel("${m.a}", b);
assertTrue(mapVal instanceof Number);
assertEquals(7, ((Number) mapVal).intValue());
Object beanVal = evalJuel("${bean.name}", b);
assertEquals("Ada", beanVal);
}
@Test
@DisplayName("(e) 未绑定标识符返回 null 不抛")
void unboundIdentifierIsNull() throws Exception {
Object r = evalJuel("${nope}", new SimpleBindings());
assertNull(r, "未绑定标识符应按 EL 默认返回 null,不抛异常");
}
@Test
@DisplayName("(f) 端到端接缝:ScriptingEnginesManager.evaluate(\"${x+1}\",\"juel\",bindings)=6")
void scriptingEnginesManagerSeam() {
Bindings bindings = new SimpleBindings();
bindings.put("x", 5);
Object result;
try {
result = ScriptingEnginesManager.getScriptingEnginesManager()
.evaluate("${x + 1}", "juel", bindings);
} catch (RuntimeException e) {
// 若单例已被其它测试先行构造且当时 TCCL 未发现工厂,可能缓存了无 juel 的状态。
// (a) 已独立验证发现链;此处明确暴露单例污染而非静默吞掉。
assertFalse(String.valueOf(e.getMessage()).contains("Can't find scripting engine for 'juel'"),
"保真层应能发现 juel 引擎,不应抛 'Can't find scripting engine for 'juel''(疑单例顺序污染): "
+ e.getMessage());
throw e;
}
assertTrue(result instanceof Number);
assertEquals(6, ((Number) result).intValue());
}
}