2 * Copyright (c) 2010-2024 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.automation.jsscripting.internal;
15 import javax.script.Invocable;
16 import javax.script.ScriptContext;
17 import javax.script.ScriptEngine;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.graalvm.polyglot.PolyglotException;
21 import org.openhab.automation.jsscripting.internal.scriptengine.InvocationInterceptingScriptEngineWithInvocableAndAutoCloseable;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
26 * Wraps ScriptEngines provided by Graal to provide error messages and stack traces for scripts.
28 * @author Jonathan Gilbert - Initial contribution
30 class DebuggingGraalScriptEngine<T extends ScriptEngine & Invocable & AutoCloseable>
31 extends InvocationInterceptingScriptEngineWithInvocableAndAutoCloseable<T> {
33 private static final String SCRIPT_TRANSFORMATION_ENGINE_IDENTIFIER = "openhab-transformation-script-";
35 private @Nullable Logger logger;
37 public DebuggingGraalScriptEngine(T delegate) {
42 protected void beforeInvocation() {
43 super.beforeInvocation();
50 public Exception afterThrowsInvocation(Exception e) {
51 Throwable cause = e.getCause();
52 if (cause instanceof IllegalArgumentException) {
53 logger.error("Failed to execute script:", e);
55 if (cause instanceof PolyglotException) {
56 logger.error("Failed to execute script:", cause);
62 * Initializes the logger.
63 * This cannot be done on script engine creation because the context variables are not yet initialized.
64 * Therefore, the logger needs to be initialized on the first use after script engine creation.
66 private void initializeLogger() {
67 ScriptContext ctx = delegate.getContext();
68 Object fileName = ctx.getAttribute("javax.script.filename");
69 Object ruleUID = ctx.getAttribute("ruleUID");
70 Object ohEngineIdentifier = ctx.getAttribute("oh.engine-identifier");
72 String identifier = "stack";
73 if (fileName != null) {
74 identifier = fileName.toString().replaceAll("^.*[/\\\\]", "");
75 } else if (ruleUID != null) {
76 identifier = ruleUID.toString();
77 } else if (ohEngineIdentifier != null) {
78 if (ohEngineIdentifier.toString().startsWith(SCRIPT_TRANSFORMATION_ENGINE_IDENTIFIER)) {
79 identifier = ohEngineIdentifier.toString().replaceAll(SCRIPT_TRANSFORMATION_ENGINE_IDENTIFIER,
84 logger = LoggerFactory.getLogger("org.openhab.automation.script.javascript." + identifier);