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
14 package org.openhab.automation.jsscripting.internal.scope;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.HashMap;
20 import java.util.Objects;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.function.Function;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.openhab.core.automation.module.script.ScriptExtensionProvider;
27 import org.osgi.framework.BundleContext;
28 import org.osgi.service.component.annotations.Activate;
31 * Base class to offer support for script extension providers
33 * @author Jonathan Gilbert - Initial contribution
35 public abstract class AbstractScriptExtensionProvider implements ScriptExtensionProvider {
36 private Map<String, Function<String, Object>> types = new HashMap<>();
37 private Map<String, Map<String, Object>> idToTypes = new ConcurrentHashMap<>();
39 protected abstract String getPresetName();
41 protected abstract void initializeTypes(final BundleContext context);
43 protected void addType(String name, Function<String, Object> value) {
44 types.put(name, value);
48 public void activate(final BundleContext context) {
50 initializeTypes(context);
54 public Collection<String> getDefaultPresets() {
55 return Collections.emptyList();
59 public Collection<String> getPresets() {
60 return Set.of(getPresetName());
64 public Collection<String> getTypes() {
65 return types.keySet();
69 public @Nullable Object get(String scriptIdentifier, String type) throws IllegalArgumentException {
70 Map<String, Object> forScript = idToTypes.computeIfAbsent(scriptIdentifier, k -> new HashMap<>());
71 return forScript.computeIfAbsent(type,
72 k -> Objects.nonNull(types.get(k)) ? types.get(k).apply(scriptIdentifier) : null);
76 public Map<String, Object> importPreset(String scriptIdentifier, String preset) {
77 if (getPresetName().equals(preset)) {
78 Map<String, Object> results = new HashMap<>(types.size());
79 for (String type : types.keySet()) {
80 results.put(type, get(scriptIdentifier, type));
85 return Collections.emptyMap();
89 public void unload(String scriptIdentifier) {