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.ScriptEngine;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.graalvm.polyglot.PolyglotException;
20 import org.openhab.automation.jsscripting.internal.scriptengine.InvocationInterceptingScriptEngineWithInvocableAndAutoCloseable;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
25 * Wraps ScriptEngines provided by Graal to provide error messages and stack traces for scripts.
27 * @author Jonathan Gilbert - Initial contribution
29 class DebuggingGraalScriptEngine<T extends ScriptEngine & Invocable & AutoCloseable>
30 extends InvocationInterceptingScriptEngineWithInvocableAndAutoCloseable<T> {
32 private static final String SCRIPT_TRANSFORMATION_ENGINE_IDENTIFIER = "openhab-transformation-script-";
34 private @Nullable Logger logger;
36 public DebuggingGraalScriptEngine(T delegate) {
41 public Exception afterThrowsInvocation(Exception e) {
46 Throwable cause = e.getCause();
47 if (cause instanceof IllegalArgumentException) {
48 logger.error("Failed to execute script:", e);
50 if (cause instanceof PolyglotException) {
51 logger.error("Failed to execute script:", cause);
57 * Initializes the logger.
58 * This cannot be done on script engine creation because the context variables are not yet initialized.
59 * Therefore, the logger needs to be initialized on the first use after script engine creation.
61 private void initializeLogger() {
62 Object fileName = delegate.getContext().getAttribute("javax.script.filename");
63 Object ruleUID = delegate.getContext().getAttribute("ruleUID");
64 Object ohEngineIdentifier = delegate.getContext().getAttribute("oh.engine-identifier");
66 String identifier = "stack";
67 if (fileName != null) {
68 identifier = fileName.toString().replaceAll("^.*[/\\\\]", "");
69 } else if (ruleUID != null) {
70 identifier = ruleUID.toString();
71 } else if (ohEngineIdentifier != null) {
72 if (ohEngineIdentifier.toString().startsWith(SCRIPT_TRANSFORMATION_ENGINE_IDENTIFIER)) {
73 identifier = ohEngineIdentifier.toString().replaceAll(SCRIPT_TRANSFORMATION_ENGINE_IDENTIFIER,
78 logger = LoggerFactory.getLogger("org.openhab.automation.script.javascript." + identifier);