]> git.basschouten.com Git - openhab-addons.git/blob
6c79729dbb33e360d407dd5e4072bb94be3dfeca
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.io.File;
16 import java.util.HashMap;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Objects;
20 import java.util.stream.Collectors;
21 import java.util.stream.Stream;
22
23 import javax.script.ScriptContext;
24 import javax.script.ScriptEngine;
25 import javax.script.ScriptException;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.automation.jrubyscripting.internal.watch.JRubyDependencyTracker;
30 import org.openhab.core.automation.module.script.AbstractScriptEngineFactory;
31 import org.openhab.core.automation.module.script.ScriptDependencyTracker;
32 import org.openhab.core.automation.module.script.ScriptEngineFactory;
33 import org.openhab.core.automation.module.script.ScriptExtensionManagerWrapper;
34 import org.openhab.core.config.core.ConfigurableService;
35 import org.openhab.core.service.WatchService;
36 import org.osgi.framework.Constants;
37 import org.osgi.service.component.annotations.Activate;
38 import org.osgi.service.component.annotations.Component;
39 import org.osgi.service.component.annotations.Deactivate;
40 import org.osgi.service.component.annotations.Modified;
41 import org.osgi.service.component.annotations.Reference;
42 import org.osgi.service.component.annotations.ReferenceCardinality;
43 import org.osgi.service.component.annotations.ReferencePolicy;
44
45 /**
46  * This is an implementation of a {@link ScriptEngineFactory} for Ruby.
47  *
48  * @author Brian O'Connell - Initial contribution
49  * @author Jimmy Tanagra - Add require injection
50  */
51 @NonNullByDefault
52 @Component(service = ScriptEngineFactory.class, configurationPid = "org.openhab.automation.jrubyscripting", property = Constants.SERVICE_PID
53         + "=org.openhab.automation.jrubyscripting")
54 @ConfigurableService(category = "automation", label = "JRuby Scripting", description_uri = "automation:jrubyscripting")
55 public class JRubyScriptEngineFactory extends AbstractScriptEngineFactory {
56     private final JRubyScriptEngineConfiguration configuration = new JRubyScriptEngineConfiguration();
57
58     private final javax.script.ScriptEngineFactory factory = new org.jruby.embed.jsr223.JRubyEngineFactory();
59
60     private final List<String> scriptTypes = Stream.concat(Objects.requireNonNull(factory.getExtensions()).stream(),
61             Objects.requireNonNull(factory.getMimeTypes()).stream()).toList();
62
63     private final JRubyDependencyTracker jrubyDependencyTracker;
64
65     // Adds $ in front of a set of variables so that Ruby recognizes them as global
66     // variables
67     private static Map.Entry<String, Object> mapGlobalPresets(Map.Entry<String, Object> entry) {
68         if (Character.isLowerCase(entry.getKey().charAt(0)) && !(entry.getValue() instanceof Class)
69                 && !(entry.getValue() instanceof Enum)) {
70             return Map.entry("$" + entry.getKey(), entry.getValue());
71         } else {
72             return entry;
73         }
74     }
75
76     @Activate
77     public JRubyScriptEngineFactory(@Reference(target = WatchService.CONFIG_WATCHER_FILTER) WatchService watchService,
78             Map<String, Object> config) {
79         jrubyDependencyTracker = new JRubyDependencyTracker(watchService, this);
80         modified(config);
81     }
82
83     @Deactivate
84     protected void deactivate() {
85         jrubyDependencyTracker.deactivate();
86     }
87
88     // The modified call updates configuration for the automation
89     @Modified
90     protected void modified(Map<String, Object> config) {
91         configuration.update(config, factory);
92         // Re-initialize the dependency tracker's watchers.
93         jrubyDependencyTracker.deactivate();
94         if (configuration.enableDependencyTracking()) {
95             jrubyDependencyTracker.activate();
96         }
97     }
98
99     @Override
100     public List<String> getScriptTypes() {
101         return scriptTypes;
102     }
103
104     @Override
105     public void scopeValues(ScriptEngine scriptEngine, Map<String, Object> scopeValues) {
106         // Empty comments prevent the formatter from breaking up the correct streams
107         // chaining
108         logger.debug("Scope Values: {}", scopeValues);
109         Map<String, Object> filteredScopeValues = //
110                 scopeValues //
111                         .entrySet() //
112                         .stream() //
113                         .map(JRubyScriptEngineFactory::mapGlobalPresets) //
114                         .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue())); //
115
116         Map<Boolean, Map<String, Object>> partitionedMap = //
117                 filteredScopeValues.entrySet() //
118                         .stream() //
119                         .collect(Collectors.partitioningBy(entry -> (entry.getValue() instanceof Class),
120                                 Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
121
122         super.scopeValues(scriptEngine, partitionedMap.getOrDefault(false, new HashMap<>()));
123         importClassesToRuby(scriptEngine, partitionedMap.getOrDefault(true, new HashMap<>()));
124
125         Object scriptExtension = scopeValues.get("scriptExtension");
126         if (scriptExtension instanceof ScriptExtensionManagerWrapper && configuration.enableDependencyTracking()) {
127             ScriptExtensionManagerWrapper wrapper = (ScriptExtensionManagerWrapper) scriptExtension;
128             // we inject like this instead of using the script context, because
129             // this is executed _before_ the dependency tracker is added to the script
130             // context.
131             // But we need this set up before we inject our requires
132             scriptEngine.put("$dependencyListener", jrubyDependencyTracker.getTracker(wrapper.getScriptIdentifier()));
133         }
134
135         // scopeValues is called twice. The first call only passed 'se'. The second call
136         // passed the rest of the
137         // presets, including 'ir'. We wait for the second call before running the
138         // require statements.
139         if (scopeValues.containsKey("ir")) {
140             configuration.injectRequire(scriptEngine);
141         }
142     }
143
144     private void importClassesToRuby(ScriptEngine scriptEngine, Map<String, Object> objects) {
145         try {
146             scriptEngine.put("__classes", objects);
147             final String code = "__classes.each { |(name, klass)| Object.const_set(name, klass.ruby_class) unless Object.const_defined?(name, false) }";
148             scriptEngine.eval(code);
149             // clean up our temporary variable
150             scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE).remove("__classes");
151         } catch (ScriptException e) {
152             logger.debug("Error importing java classes", e);
153         }
154     }
155
156     @Override
157     public @Nullable ScriptEngine createScriptEngine(String scriptType) {
158         if (!scriptTypes.contains(scriptType)) {
159             return null;
160         }
161         ScriptEngine engine = factory.getScriptEngine();
162         configuration.configureRubyEnvironment(engine);
163         return engine;
164     }
165
166     @Override
167     public @Nullable ScriptDependencyTracker getDependencyTracker() {
168         return jrubyDependencyTracker;
169     }
170
171     @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC, unbind = "removeChangeTracker")
172     public void addChangeTracker(ScriptDependencyTracker.Listener listener) {
173         jrubyDependencyTracker.addChangeTracker(listener);
174     }
175
176     public void removeChangeTracker(ScriptDependencyTracker.Listener listener) {
177         jrubyDependencyTracker.removeChangeTracker(listener);
178     }
179
180     public List<String> getRubyLibPaths() {
181         return configuration.getRubyLibPaths();
182     }
183
184     public boolean isFileInLoadPath(String file) {
185         for (String path : getRubyLibPaths()) {
186             if (file.startsWith(new File(path).toString() + File.separator)) {
187                 return true;
188             }
189         }
190         return false;
191     }
192
193     public String getGemHome() {
194         return configuration.getSpecificGemHome();
195     }
196
197     public boolean isFileInGemHome(String file) {
198         String gemHome = configuration.getGemHomeBase();
199         if (gemHome.isEmpty()) {
200             return false;
201         }
202         return file.startsWith(gemHome + File.separator);
203     }
204 }