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