]> git.basschouten.com Git - openhab-addons.git/blob
6793fbc6270a01ef8f1c854f15329ad47765ae1c
[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.jsscripting.internal;
14
15 import java.io.IOException;
16 import java.util.HashMap;
17 import java.util.Map;
18 import java.util.Optional;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.graalvm.polyglot.Context;
22 import org.graalvm.polyglot.Source;
23 import org.graalvm.polyglot.Value;
24 import org.openhab.automation.jsscripting.internal.threading.ThreadsafeWrappingScriptedAutomationManagerDelegate;
25 import org.openhab.core.automation.module.script.ScriptExtensionAccessor;
26 import org.openhab.core.automation.module.script.rulesupport.shared.ScriptedAutomationManager;
27
28 /**
29  * Class providing script extensions via CommonJS modules.
30  *
31  * @author Jonathan Gilbert - Initial contribution
32  * @author Florian Hotze - Pass in lock object for multi-thread synchronization
33  */
34
35 @NonNullByDefault
36 public class ScriptExtensionModuleProvider {
37
38     private static final String RUNTIME_MODULE_PREFIX = "@runtime";
39     private static final String DEFAULT_MODULE_NAME = "Defaults";
40     private final Object lock;
41
42     private final ScriptExtensionAccessor scriptExtensionAccessor;
43
44     public ScriptExtensionModuleProvider(ScriptExtensionAccessor scriptExtensionAccessor, Object lock) {
45         this.scriptExtensionAccessor = scriptExtensionAccessor;
46         this.lock = lock;
47     }
48
49     public ModuleLocator locatorFor(Context ctx, String engineIdentifier) {
50         return name -> {
51             String[] segments = name.split("/");
52             if (segments[0].equals(RUNTIME_MODULE_PREFIX)) {
53                 if (segments.length == 1) {
54                     return runtimeModule(DEFAULT_MODULE_NAME, engineIdentifier, ctx);
55                 } else {
56                     return runtimeModule(segments[1], engineIdentifier, ctx);
57                 }
58             }
59
60             return Optional.empty();
61         };
62     }
63
64     private Optional<Value> runtimeModule(String name, String scriptIdentifier, Context ctx) {
65         Map<String, Object> symbols;
66
67         if (DEFAULT_MODULE_NAME.equals(name)) {
68             symbols = scriptExtensionAccessor.findDefaultPresets(scriptIdentifier);
69         } else {
70             symbols = scriptExtensionAccessor.findPreset(name, scriptIdentifier);
71         }
72
73         return Optional.of(symbols).map(this::processValues).map(v -> toValue(ctx, v));
74     }
75
76     private Value toValue(Context ctx, Map<String, Object> map) {
77         try {
78             return ctx.eval(Source.newBuilder( // convert to Map to JS Object
79                     "js",
80                     "(function (mapOfValues) {\n" + "let rv = {};\n" + "for (var key in mapOfValues) {\n"
81                             + "    rv[key] = mapOfValues.get(key);\n" + "}\n" + "return rv;\n" + "})",
82                     "<generated>").build()).execute(map);
83         } catch (IOException e) {
84             throw new IllegalArgumentException("Failed to generate exports", e);
85         }
86     }
87
88     /**
89      * Some specific objects need wrapping when exposed to a GraalJS environment. This method does this.
90      *
91      * @param values the map of names to values of things to process
92      * @return a map of the processed keys and values
93      */
94     private Map<String, Object> processValues(Map<String, Object> values) {
95         Map<String, Object> rv = new HashMap<>(values);
96
97         for (Map.Entry<String, Object> entry : rv.entrySet()) {
98             if (entry.getValue() instanceof ScriptedAutomationManager) {
99                 entry.setValue(new ThreadsafeWrappingScriptedAutomationManagerDelegate(
100                         (ScriptedAutomationManager) entry.getValue(), lock));
101             }
102         }
103
104         return rv;
105     }
106 }