2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.automation.jrubyscripting.internal;
15 import java.util.HashMap;
16 import java.util.List;
19 import java.util.stream.Collectors;
20 import java.util.stream.Stream;
22 import javax.script.ScriptEngine;
23 import javax.script.ScriptException;
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.service.component.annotations.Activate;
31 import org.osgi.service.component.annotations.Component;
32 import org.osgi.service.component.annotations.Modified;
35 * This is an implementation of a {@link ScriptEngineFactory} for Ruby.
37 * @author Brian O'Connell - Initial contribution
38 * @author Jimmy Tanagra - Add require injection
41 @Component(service = ScriptEngineFactory.class, configurationPid = "org.openhab.automation.jrubyscripting")
42 @ConfigurableService(category = "automation", label = "JRuby Scripting", description_uri = "automation:jruby")
43 public class JRubyScriptEngineFactory extends AbstractScriptEngineFactory {
45 private final JRubyScriptEngineConfiguration configuration = new JRubyScriptEngineConfiguration();
47 // Filter out the File entry to prevent shadowing the Ruby File class which breaks Ruby in spectacularly
48 // difficult ways to debug.
49 private static final Set<String> FILTERED_PRESETS = Set.of("File", "Files", "Path", "Paths");
50 private static final Set<String> INSTANCE_PRESETS = Set.of();
52 private final javax.script.ScriptEngineFactory factory = new org.jruby.embed.jsr223.JRubyEngineFactory();
54 private final List<String> scriptTypes = Stream
55 .concat(factory.getExtensions().stream(), factory.getMimeTypes().stream())
56 .collect(Collectors.toUnmodifiableList());
58 // Adds @ in front of a set of variables so that Ruby recognizes them as instance variables
59 private static Map.Entry<String, Object> mapInstancePresets(Map.Entry<String, Object> entry) {
60 if (INSTANCE_PRESETS.contains(entry.getKey())) {
61 return Map.entry("@" + entry.getKey(), entry.getValue());
67 // Adds $ in front of a set of variables so that Ruby recognizes them as global variables
68 private static Map.Entry<String, Object> mapGlobalPresets(Map.Entry<String, Object> entry) {
69 if (Character.isLowerCase(entry.getKey().charAt(0)) && !(entry.getValue() instanceof Class)
70 && !(entry.getValue() instanceof Enum)) {
71 return Map.entry("$" + entry.getKey(), entry.getValue());
77 // The activate call activates the automation and sets its configuration
79 protected void activate(Map<String, Object> config) {
80 configuration.update(config, factory);
83 // The modified call updates configuration for the automation
85 protected void modified(Map<String, Object> config) {
86 configuration.update(config, factory);
90 public List<String> getScriptTypes() {
95 public void scopeValues(ScriptEngine scriptEngine, Map<String, Object> scopeValues) {
96 // Empty comments prevent the formatter from breaking up the correct streams chaining
97 logger.debug("Scope Values: {}", scopeValues);
98 Map<String, Object> filteredScopeValues = //
102 .filter(map -> !FILTERED_PRESETS.contains(map.getKey())) //
103 .map(JRubyScriptEngineFactory::mapInstancePresets) //
104 .map(JRubyScriptEngineFactory::mapGlobalPresets) //
105 .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue())); //
107 Map<Boolean, Map<String, Object>> partitionedMap = //
108 filteredScopeValues.entrySet() //
110 .collect(Collectors.partitioningBy(entry -> (entry.getValue() instanceof Class),
111 Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
113 importClassesToRuby(scriptEngine, partitionedMap.getOrDefault(true, new HashMap<>()));
114 super.scopeValues(scriptEngine, partitionedMap.getOrDefault(false, new HashMap<>()));
116 // scopeValues is called twice. The first call only passed 'se'. The second call passed the rest of the
117 // presets, including 'ir'. We wait for the second call before running the require statements.
118 if (scopeValues.containsKey("ir")) {
119 configuration.injectRequire(scriptEngine);
123 private void importClassesToRuby(ScriptEngine scriptEngine, Map<String, Object> objects) {
124 String import_statements = objects.entrySet() //
126 .map(entry -> "java_import " + ((Class<?>) entry.getValue()).getName() + " rescue nil") //
127 .collect(Collectors.joining("\n"));
129 scriptEngine.eval(import_statements);
130 } catch (ScriptException e) {
131 logger.debug("Error importing java classes", e);
136 public @Nullable ScriptEngine createScriptEngine(String scriptType) {
137 return scriptTypes.contains(scriptType) ? configuration.configureRubyEnvironment(factory.getScriptEngine())