2 * Copyright (c) 2010-2023 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.jsscriptingnashorn.internal;
15 import java.util.HashSet;
16 import java.util.List;
18 import java.util.Map.Entry;
20 import java.util.stream.Collectors;
21 import java.util.stream.Stream;
23 import javax.script.ScriptEngine;
24 import javax.script.ScriptException;
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.osgi.service.component.annotations.Component;
33 * This is an implementation of a {@link ScriptEngineFactory} for Nashorn.
35 * @author Wouter Born - Initial contribution
37 @Component(service = ScriptEngineFactory.class)
39 public class NashornScriptEngineFactory extends AbstractScriptEngineFactory {
41 private final org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory factory = new org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory();
43 private final List<String> scriptTypes = createScriptTypes();
45 private List<String> createScriptTypes() {
46 List<String> extensions = List.of("nashornjs");
48 String mimeTypeVersion = ";version=ECMAScript-5.1";
49 List<String> mimeTypes = factory.getMimeTypes().stream().map(mimeType -> mimeType + mimeTypeVersion)
50 .collect(Collectors.toUnmodifiableList());
52 return Stream.of(extensions, mimeTypes).flatMap(List::stream).collect(Collectors.toUnmodifiableList());
56 public List<String> getScriptTypes() {
61 public void scopeValues(ScriptEngine scriptEngine, Map<String, Object> scopeValues) {
62 Set<String> expressions = new HashSet<>();
64 for (Entry<String, Object> entry : scopeValues.entrySet()) {
65 scriptEngine.put(entry.getKey(), entry.getValue());
66 if (entry.getValue() instanceof Class) {
67 expressions.add(String.format("%s = %<s.static;", entry.getKey()));
70 String scriptToEval = String.join("\n", expressions);
72 scriptEngine.eval(scriptToEval);
73 } catch (ScriptException ex) {
74 logger.error("ScriptException while importing scope: {}", ex.getMessage());
79 public @Nullable ScriptEngine createScriptEngine(String scriptType) {
80 return scriptTypes.contains(scriptType)
81 ? factory.getScriptEngine(NashornScriptEngineFactory.class.getClassLoader())