]> git.basschouten.com Git - openhab-addons.git/blob
326ffbc594b62d20431a82b5aadeb2493b12af8c
[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.util.HashMap;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Set;
19 import java.util.stream.Collectors;
20 import java.util.stream.Stream;
21
22 import javax.script.ScriptContext;
23 import javax.script.ScriptEngine;
24 import javax.script.ScriptException;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.core.automation.module.script.AbstractScriptEngineFactory;
29 import org.openhab.core.automation.module.script.ScriptEngineFactory;
30 import org.openhab.core.config.core.ConfigurableService;
31 import org.osgi.framework.Constants;
32 import org.osgi.service.component.annotations.Activate;
33 import org.osgi.service.component.annotations.Component;
34 import org.osgi.service.component.annotations.Modified;
35
36 /**
37  * This is an implementation of a {@link ScriptEngineFactory} for Ruby.
38  *
39  * @author Brian O'Connell - Initial contribution
40  * @author Jimmy Tanagra - Add require injection
41  */
42 @NonNullByDefault
43 @Component(service = ScriptEngineFactory.class, configurationPid = "org.openhab.automation.jrubyscripting", property = Constants.SERVICE_PID
44         + "=org.openhab.automation.jrubyscripting")
45 @ConfigurableService(category = "automation", label = "JRuby Scripting", description_uri = "automation:jruby")
46 public class JRubyScriptEngineFactory extends AbstractScriptEngineFactory {
47
48     private final JRubyScriptEngineConfiguration configuration = new JRubyScriptEngineConfiguration();
49
50     // Filter out the File entry to prevent shadowing the Ruby File class which breaks Ruby in spectacularly
51     // difficult ways to debug.
52     private static final Set<String> FILTERED_PRESETS = Set.of("File", "Files", "Path", "Paths");
53     private static final Set<String> INSTANCE_PRESETS = Set.of();
54
55     private final javax.script.ScriptEngineFactory factory = new org.jruby.embed.jsr223.JRubyEngineFactory();
56
57     private final List<String> scriptTypes = Stream
58             .concat(factory.getExtensions().stream(), factory.getMimeTypes().stream())
59             .collect(Collectors.toUnmodifiableList());
60
61     // Adds @ in front of a set of variables so that Ruby recognizes them as instance variables
62     private static Map.Entry<String, Object> mapInstancePresets(Map.Entry<String, Object> entry) {
63         if (INSTANCE_PRESETS.contains(entry.getKey())) {
64             return Map.entry("@" + entry.getKey(), entry.getValue());
65         } else {
66             return entry;
67         }
68     }
69
70     // Adds $ in front of a set of variables so that Ruby recognizes them as global variables
71     private static Map.Entry<String, Object> mapGlobalPresets(Map.Entry<String, Object> entry) {
72         if (Character.isLowerCase(entry.getKey().charAt(0)) && !(entry.getValue() instanceof Class)
73                 && !(entry.getValue() instanceof Enum)) {
74             return Map.entry("$" + entry.getKey(), entry.getValue());
75         } else {
76             return entry;
77         }
78     }
79
80     // The activate call activates the automation and sets its configuration
81     @Activate
82     protected void activate(Map<String, Object> config) {
83         configuration.update(config, factory);
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     }
91
92     @Override
93     public List<String> getScriptTypes() {
94         return scriptTypes;
95     }
96
97     @Override
98     public void scopeValues(ScriptEngine scriptEngine, Map<String, Object> scopeValues) {
99         // Empty comments prevent the formatter from breaking up the correct streams chaining
100         logger.debug("Scope Values: {}", scopeValues);
101         Map<String, Object> filteredScopeValues = //
102                 scopeValues //
103                         .entrySet() //
104                         .stream() //
105                         .filter(map -> !FILTERED_PRESETS.contains(map.getKey())) //
106                         .map(JRubyScriptEngineFactory::mapInstancePresets) //
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         // scopeValues is called twice. The first call only passed 'se'. The second call passed the rest of the
120         // presets, including 'ir'. We wait for the second call before running the require statements.
121         if (scopeValues.containsKey("ir")) {
122             configuration.injectRequire(scriptEngine);
123         }
124     }
125
126     private void importClassesToRuby(ScriptEngine scriptEngine, Map<String, Object> objects) {
127         try {
128             scriptEngine.put("__classes", objects);
129             final String code = "__classes.each { |(name, klass)| Object.const_set(name, klass.ruby_class) }";
130             scriptEngine.eval(code);
131             // clean up our temporary variable
132             scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE).remove("__classes");
133         } catch (ScriptException e) {
134             logger.debug("Error importing java classes", e);
135         }
136     }
137
138     @Override
139     public @Nullable ScriptEngine createScriptEngine(String scriptType) {
140         return scriptTypes.contains(scriptType) ? configuration.configureRubyEnvironment(factory.getScriptEngine())
141                 : null;
142     }
143 }