2 * Copyright (c) 2010-2021 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.concurrent.ConcurrentHashMap;
21 import java.util.function.Function;
23 import org.openhab.core.automation.module.script.ScriptExtensionProvider;
24 import org.osgi.framework.BundleContext;
25 import org.osgi.service.component.annotations.Activate;
28 * Base class to offer support for script extension providers
30 * @author Jonathan Gilbert - Initial contribution
32 public abstract class AbstractScriptExtensionProvider implements ScriptExtensionProvider {
33 private Map<String, Function<String, Object>> types;
34 private Map<String, Map<String, Object>> idToTypes = new ConcurrentHashMap<>();
36 protected abstract String getPresetName();
38 protected abstract void initializeTypes(final BundleContext context);
40 protected void addType(String name, Function<String, Object> value) {
41 types.put(name, value);
45 public void activate(final BundleContext context) {
46 types = new HashMap<>();
47 initializeTypes(context);
51 public Collection<String> getDefaultPresets() {
52 return Collections.emptyList();
56 public Collection<String> getPresets() {
57 return Collections.singleton(getPresetName());
61 public Collection<String> getTypes() {
62 return types.keySet();
66 public Object get(String scriptIdentifier, String type) throws IllegalArgumentException {
68 Map<String, Object> forScript = idToTypes.computeIfAbsent(scriptIdentifier, k -> new HashMap<>());
69 return forScript.computeIfAbsent(type, k -> types.get(k).apply(scriptIdentifier));
73 public Map<String, Object> importPreset(String scriptIdentifier, String preset) {
74 if (getPresetName().equals(preset)) {
75 Map<String, Object> results = new HashMap<>(types.size());
76 for (String type : types.keySet()) {
77 results.put(type, get(scriptIdentifier, type));
82 return Collections.emptyMap();
86 public void unload(String scriptIdentifier) {