]> git.basschouten.com Git - openhab-addons.git/blob
a53fb534bb1f67a2280a5468e72f3044e9f1d598
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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 variables
65     private static Map.Entry<String, Object> mapGlobalPresets(Map.Entry<String, Object> entry) {
66         if (Character.isLowerCase(entry.getKey().charAt(0)) && !(entry.getValue() instanceof Class)
67                 && !(entry.getValue() instanceof Enum)) {
68             return Map.entry("$" + entry.getKey(), entry.getValue());
69         } else {
70             return entry;
71         }
72     }
73
74     @Activate
75     public JRubyScriptEngineFactory(Map<String, Object> config) {
76         jrubyDependencyTracker = new JRubyDependencyTracker(this);
77         modified(config);
78     }
79
80     @Deactivate
81     protected void deactivate() {
82         jrubyDependencyTracker.deactivate();
83     }
84
85     // The modified call updates configuration for the automation
86     @Modified
87     protected void modified(Map<String, Object> config) {
88         configuration.update(config, factory);
89         // Re-initialize the dependency tracker's watchers.
90         jrubyDependencyTracker.deactivate();
91         jrubyDependencyTracker.activate();
92     }
93
94     @Override
95     public List<String> getScriptTypes() {
96         return scriptTypes;
97     }
98
99     @Override
100     public void scopeValues(ScriptEngine scriptEngine, Map<String, Object> scopeValues) {
101         // Empty comments prevent the formatter from breaking up the correct streams chaining
102         logger.debug("Scope Values: {}", scopeValues);
103         Map<String, Object> filteredScopeValues = //
104                 scopeValues //
105                         .entrySet() //
106                         .stream() //
107                         .map(JRubyScriptEngineFactory::mapGlobalPresets) //
108                         .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue())); //
109
110         Map<Boolean, Map<String, Object>> partitionedMap = //
111                 filteredScopeValues.entrySet() //
112                         .stream() //
113                         .collect(Collectors.partitioningBy(entry -> (entry.getValue() instanceof Class),
114                                 Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
115
116         importClassesToRuby(scriptEngine, partitionedMap.getOrDefault(true, new HashMap<>()));
117         super.scopeValues(scriptEngine, partitionedMap.getOrDefault(false, new HashMap<>()));
118
119         Object scriptExtension = scopeValues.get("scriptExtension");
120         if (scriptExtension instanceof ScriptExtensionManagerWrapper) {
121             ScriptExtensionManagerWrapper wrapper = (ScriptExtensionManagerWrapper) scriptExtension;
122             // we inject like this instead of using the script context, because
123             // this is executed _before_ the dependency tracker is added to the script context.
124             // But we need this set up before we inject our requires
125             scriptEngine.put("$dependencyListener", jrubyDependencyTracker.getTracker(wrapper.getScriptIdentifier()));
126         }
127
128         // scopeValues is called twice. The first call only passed 'se'. The second call passed the rest of the
129         // presets, including 'ir'. We wait for the second call before running the require statements.
130         if (scopeValues.containsKey("ir")) {
131             configuration.injectRequire(scriptEngine);
132         }
133     }
134
135     private void importClassesToRuby(ScriptEngine scriptEngine, Map<String, Object> objects) {
136         try {
137             scriptEngine.put("__classes", objects);
138             final String code = "__classes.each { |(name, klass)| Object.const_set(name, klass.ruby_class) unless Object.const_defined?(name, false) }";
139             scriptEngine.eval(code);
140             // clean up our temporary variable
141             scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE).remove("__classes");
142         } catch (ScriptException e) {
143             logger.debug("Error importing java classes", e);
144         }
145     }
146
147     @Override
148     public @Nullable ScriptEngine createScriptEngine(String scriptType) {
149         if (!scriptTypes.contains(scriptType)) {
150             return null;
151         }
152         ScriptEngine engine = factory.getScriptEngine();
153         configuration.configureRubyEnvironment(engine);
154         return engine;
155     }
156
157     @Override
158     public @Nullable ScriptDependencyTracker getDependencyTracker() {
159         return jrubyDependencyTracker;
160     }
161
162     @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC, unbind = "removeChangeTracker")
163     public void addChangeTracker(ScriptDependencyTracker.Listener listener) {
164         jrubyDependencyTracker.addChangeTracker(listener);
165     }
166
167     public void removeChangeTracker(ScriptDependencyTracker.Listener listener) {
168         jrubyDependencyTracker.removeChangeTracker(listener);
169     }
170
171     public List<String> getRubyLibPaths() {
172         return configuration.getRubyLibPaths();
173     }
174
175     public boolean isFileInLoadPath(String file) {
176         for (String path : getRubyLibPaths()) {
177             if (file.startsWith(new File(path).toString() + File.separator)) {
178                 return true;
179             }
180         }
181         return false;
182     }
183
184     public String getGemHome() {
185         return configuration.getSpecificGemHome();
186     }
187
188     public boolean isFileInGemHome(String file) {
189         String gemHome = configuration.getGemHomeBase();
190         if (gemHome.isEmpty()) {
191             return false;
192         }
193         return file.startsWith(gemHome + File.separator);
194     }
195 }