From 418acd89c8b637630c20765d358aba71489441b7 Mon Sep 17 00:00:00 2001 From: philippe lhardy Date: Mon, 16 Sep 2024 08:49:15 +0200 Subject: [PATCH] fallback to rhino if no default javascript is found .3 (lscproject#280) (#304) * fallback to rhino if no default javascript is found .3 (lscproject#280) - avoid NullPointerException even if rhino and js are missing * #304: Using java 8 compatible Optional code --------- Co-authored-by: philha Co-authored-by: Abhishek Pai --- src/main/java/org/lsc/utils/ScriptingEvaluator.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/lsc/utils/ScriptingEvaluator.java b/src/main/java/org/lsc/utils/ScriptingEvaluator.java index 895c8fd1..b69c3b88 100644 --- a/src/main/java/org/lsc/utils/ScriptingEvaluator.java +++ b/src/main/java/org/lsc/utils/ScriptingEvaluator.java @@ -3,6 +3,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.function.Predicate; import javax.script.*; @@ -31,7 +32,7 @@ public class ScriptingEvaluator { private Map instancesTypeCache; - private ScriptableEvaluator defaultImplementation; + private Optional defaultImplementation; static { implementetionsCache = new HashMap>(); @@ -87,10 +88,11 @@ else if ("graal.js".equals(name)) { bindings.put( "polyglot.js.nashorn-compat", true); JScriptEvaluator graaljsevaluator = new JScriptEvaluator(graaljsEngine); instancesTypeCache.put("gj", graaljsevaluator); - defaultImplementation = graaljsevaluator; + defaultImplementation = Optional.of(graaljsevaluator); } else { - defaultImplementation = instancesTypeCache.get("js"); + defaultImplementation = Optional.ofNullable(Optional.ofNullable(instancesTypeCache.get("js")) + .orElse(instancesTypeCache.get("rjs"))); } } @@ -111,13 +113,13 @@ public static void contribute(String implementationName, implementetionsCache.put(implementationName, implementationClass); } - private ScriptableEvaluator identifyScriptingEngine(String expression) { + private ScriptableEvaluator identifyScriptingEngine(String expression) throws LscServiceException { String[] parts = expression.split(":"); if (parts != null && parts.length > 0 && parts[0].length() < 10 && instancesTypeCache.containsKey(parts[0])) { return instancesTypeCache.get(parts[0]); } - return defaultImplementation; + return defaultImplementation.orElseThrow(() -> new LscServiceException("Missing Script evaluator")); } /**