]> git.basschouten.com Git - openhab-addons.git/blob
4879b79227bbde1fd2a115aaeab0eec195f66c2f
[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.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     // Filter out the File entry to prevent shadowing the Ruby File class which breaks Ruby in spectacularly
50     // difficult ways to debug.
51     private static final Set<String> FILTERED_PRESETS = Set.of("File", "Files", "Path", "Paths");
52     private static final Set<String> INSTANCE_PRESETS = Set.of();
53
54     private final javax.script.ScriptEngineFactory factory = new org.jruby.embed.jsr223.JRubyEngineFactory();
55
56     private final List<String> scriptTypes = Stream
57             .concat(factory.getExtensions().stream(), factory.getMimeTypes().stream())
58             .collect(Collectors.toUnmodifiableList());
59
60     // Adds @ in front of a set of variables so that Ruby recognizes them as instance variables
61     private static Map.Entry<String, Object> mapInstancePresets(Map.Entry<String, Object> entry) {
62         if (INSTANCE_PRESETS.contains(entry.getKey())) {
63             return Map.entry("@" + entry.getKey(), entry.getValue());
64         } else {
65             return entry;
66         }
67     }
68
69     // Adds $ in front of a set of variables so that Ruby recognizes them as global variables
70     private static Map.Entry<String, Object> mapGlobalPresets(Map.Entry<String, Object> entry) {
71         if (Character.isLowerCase(entry.getKey().charAt(0)) && !(entry.getValue() instanceof Class)
72                 && !(entry.getValue() instanceof Enum)) {
73             return Map.entry("$" + entry.getKey(), entry.getValue());
74         } else {
75             return entry;
76         }
77     }
78
79     // The activate call activates the automation and sets its configuration
80     @Activate
81     protected void activate(Map<String, Object> config) {
82         configuration.update(config, factory);
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     }
90
91     @Override
92     public List<String> getScriptTypes() {
93         return scriptTypes;
94     }
95
96     @Override
97     public void scopeValues(ScriptEngine scriptEngine, Map<String, Object> scopeValues) {
98         // Empty comments prevent the formatter from breaking up the correct streams chaining
99         logger.debug("Scope Values: {}", scopeValues);
100         Map<String, Object> filteredScopeValues = //
101                 scopeValues //
102                         .entrySet() //
103                         .stream() //
104                         .filter(map -> !FILTERED_PRESETS.contains(map.getKey())) //
105                         .map(JRubyScriptEngineFactory::mapInstancePresets) //
106                         .map(JRubyScriptEngineFactory::mapGlobalPresets) //
107                         .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue())); //
108
109         Map<Boolean, Map<String, Object>> partitionedMap = //
110                 filteredScopeValues.entrySet() //
111                         .stream() //
112                         .collect(Collectors.partitioningBy(entry -> (entry.getValue() instanceof Class),
113                                 Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
114
115         importClassesToRuby(scriptEngine, partitionedMap.getOrDefault(true, new HashMap<>()));
116         super.scopeValues(scriptEngine, partitionedMap.getOrDefault(false, new HashMap<>()));
117
118         // scopeValues is called twice. The first call only passed 'se'. The second call passed the rest of the
119         // presets, including 'ir'. We wait for the second call before running the require statements.
120         if (scopeValues.containsKey("ir")) {
121             configuration.injectRequire(scriptEngine);
122         }
123     }
124
125     private void importClassesToRuby(ScriptEngine scriptEngine, Map<String, Object> objects) {
126         String import_statements = objects.entrySet() //
127                 .stream() //
128                 .map(entry -> "java_import " + ((Class<?>) entry.getValue()).getName() + " rescue nil") //
129                 .collect(Collectors.joining("\n"));
130         try {
131             scriptEngine.eval(import_statements);
132         } catch (ScriptException e) {
133             logger.debug("Error importing java classes", e);
134         }
135     }
136
137     @Override
138     public @Nullable ScriptEngine createScriptEngine(String scriptType) {
139         return scriptTypes.contains(scriptType) ? configuration.configureRubyEnvironment(factory.getScriptEngine())
140                 : null;
141     }
142 }