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