|
| 1 | +/** |
| 2 | + * Copyright (c) 2010-2024 Contributors to the openHAB project |
| 3 | + * |
| 4 | + * See the NOTICE file(s) distributed with this work for additional |
| 5 | + * information. |
| 6 | + * |
| 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 |
| 10 | + * |
| 11 | + * SPDX-License-Identifier: EPL-2.0 |
| 12 | + */ |
| 13 | +package org.openhab.automation.jrubyscripting.internal; |
| 14 | + |
| 15 | +import java.util.Objects; |
| 16 | + |
| 17 | +import javax.script.CompiledScript; |
| 18 | +import javax.script.ScriptContext; |
| 19 | +import javax.script.ScriptEngine; |
| 20 | +import javax.script.ScriptException; |
| 21 | + |
| 22 | +import org.eclipse.jdt.annotation.NonNullByDefault; |
| 23 | +import org.eclipse.jdt.annotation.Nullable; |
| 24 | + |
| 25 | +/** |
| 26 | + * This is a wrapper for {@link CompiledScript}. |
| 27 | + * |
| 28 | + * The purpose of this class is to intercept the call to eval and save the context into |
| 29 | + * a global variable for use in the helper library. |
| 30 | + * |
| 31 | + * @author Jimmy Tanagra - Initial contribution |
| 32 | + */ |
| 33 | +@NonNullByDefault |
| 34 | +public class JRubyCompiledScriptWrapper extends CompiledScript { |
| 35 | + |
| 36 | + private final CompiledScript compiledScript; |
| 37 | + |
| 38 | + private static final String CONTEXT_VAR_NAME = "ctx"; |
| 39 | + private static final String GLOBAL_VAR_NAME = "$" + CONTEXT_VAR_NAME; |
| 40 | + |
| 41 | + JRubyCompiledScriptWrapper(CompiledScript compiledScript) { |
| 42 | + this.compiledScript = Objects.requireNonNull(compiledScript); |
| 43 | + } |
| 44 | + |
| 45 | + @Override |
| 46 | + public Object eval(@Nullable ScriptContext context) throws ScriptException { |
| 47 | + Object ctx = Objects.requireNonNull(context).getBindings(ScriptContext.ENGINE_SCOPE).get(CONTEXT_VAR_NAME); |
| 48 | + if (ctx == null) { |
| 49 | + return compiledScript.eval(context); |
| 50 | + } |
| 51 | + |
| 52 | + context.setAttribute(GLOBAL_VAR_NAME, ctx, ScriptContext.ENGINE_SCOPE); |
| 53 | + try { |
| 54 | + return compiledScript.eval(context); |
| 55 | + } finally { |
| 56 | + context.removeAttribute(GLOBAL_VAR_NAME, ScriptContext.ENGINE_SCOPE); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + @Override |
| 61 | + public ScriptEngine getEngine() { |
| 62 | + return compiledScript.getEngine(); |
| 63 | + } |
| 64 | +} |
0 commit comments