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
13 package org.openhab.automation.jsscripting.internal.scope;
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.HashMap;
20 import java.util.function.Supplier;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.openhab.core.automation.module.script.ScriptExtensionProvider;
25 import org.osgi.service.component.annotations.Component;
28 * Shared Cache implementation for JS scripting.
30 * @author Jonathan Gilbert - Initial contribution
32 @Component(immediate = true)
34 public class SharedCache implements ScriptExtensionProvider {
36 private static final String PRESET_NAME = "cache";
37 private static final String OBJECT_NAME = "sharedcache";
39 private JSCache cache = new JSCache();
42 public Collection<String> getDefaultPresets() {
43 return Set.of(PRESET_NAME);
47 public Collection<String> getPresets() {
48 return Set.of(PRESET_NAME);
52 public Collection<String> getTypes() {
53 return Set.of(OBJECT_NAME);
57 public @Nullable Object get(String scriptIdentifier, String type) throws IllegalArgumentException {
58 if (OBJECT_NAME.equals(type)) {
66 public Map<String, Object> importPreset(String scriptIdentifier, String preset) {
67 if (PRESET_NAME.equals(preset)) {
68 final Object requestedType = get(scriptIdentifier, OBJECT_NAME);
69 if (requestedType != null) {
70 return Map.of(OBJECT_NAME, requestedType);
74 return Collections.emptyMap();
78 public void unload(String scriptIdentifier) {
82 public static class JSCache {
83 private Map<String, Object> backingMap = new HashMap<>();
85 public void put(String k, Object v) {
89 public @Nullable Object remove(String k) {
90 return backingMap.remove(k);
93 public @Nullable Object get(String k) {
94 return backingMap.get(k);
97 public @Nullable Object get(String k, Supplier<Object> supplier) {
98 return backingMap.computeIfAbsent(k, (unused_key) -> supplier.get());