Pass script context to script engines (#1837)

Signed-off-by: Jonathan Gilbert <jpg@trillica.com>
pull/1843/head
Jonathan Gilbert 2020-11-22 20:52:22 +11:00 committed by GitHub
parent 065177b730
commit 60edebc111
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 0 deletions

View File

@ -28,12 +28,18 @@ import org.openhab.core.automation.module.script.internal.provider.ScriptModuleT
*
* @author Simon Merschjohann - Initial contribution
* @author Scott Rushworth - added/changed methods and parameters when implementing {@link ScriptModuleTypeProvider}
* @author Jonathan Gilbert - added context keys
*/
@NonNullByDefault
public interface ScriptEngineFactory {
static final ScriptEngineManager ENGINE_MANAGER = new ScriptEngineManager();
/**
* Key to access engine identifier in script context.
*/
String CONTEXT_KEY_ENGINE_IDENTIFIER = "oh.engine-identifier";
/**
* This method returns a list of file extensions and MimeTypes that are supported by the ScriptEngine, e.g. py,
* application/python, js, application/javascript, etc.

View File

@ -12,14 +12,18 @@
*/
package org.openhab.core.automation.module.script.internal;
import static org.openhab.core.automation.module.script.ScriptEngineFactory.CONTEXT_KEY_ENGINE_IDENTIFIER;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@ -38,6 +42,7 @@ import org.slf4j.LoggerFactory;
*
* @author Simon Merschjohann - Initial contribution
* @author Scott Rushworth - replaced GenericScriptEngineFactory with a service and cleaned up logging
* @author Jonathan Gilbert - included passing of context to script engines
*/
@NonNullByDefault
@Component(service = ScriptEngineManager.class)
@ -129,6 +134,16 @@ public class ScriptEngineManagerImpl implements ScriptEngineManager {
loadedScriptEngineInstances.put(engineIdentifier, result);
logger.debug("Added ScriptEngine for language '{}' with identifier: {}", scriptType,
engineIdentifier);
ScriptContext scriptContext = engine.getContext();
if (scriptContext == null) {
scriptContext = new SimpleScriptContext();
engine.setContext(scriptContext);
}
scriptContext.setAttribute(CONTEXT_KEY_ENGINE_IDENTIFIER, engineIdentifier,
ScriptContext.ENGINE_SCOPE);
} else {
logger.error("ScriptEngine for language '{}' could not be created for identifier: {}", scriptType,
engineIdentifier);