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.binding.unifi.internal.api.cache;
15 import java.util.Collection;
16 import java.util.HashMap;
18 import java.util.stream.Collectors;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
24 * The {@link UniFiCache} is a specialised lookup table that stores objects using multiple keys in the form
25 * <code>prefix:suffix</code>. Each implementation is responsible for providing a list of supported prefixes and must
26 * implement {@link #getSuffix(Object, String)} to provide a value specific suffix derived from the prefix.
28 * Objects are then retrieved simply by using the <code>suffix</code> key component and all combinations of
29 * <code>prefix:suffix</code> are searched in the order of their priority.
31 * @author Matthew Bowman - Initial contribution
33 public abstract class UniFiCache<T> {
35 private static final String SEPARATOR = ":";
37 public static final String PREFIX_ALIAS = "alias";
39 public static final String PREFIX_DESC = "desc";
41 public static final String PREFIX_HOSTNAME = "hostname";
43 public static final String PREFIX_ID = "id";
45 public static final String PREFIX_IP = "ip";
47 public static final String PREFIX_MAC = "mac";
49 public static final String PREFIX_NAME = "name";
51 private final Logger logger = LoggerFactory.getLogger(getClass());
53 private Map<String, T> map = new HashMap<>();
55 private String[] prefixes;
57 protected UniFiCache(String... prefixes) {
58 this.prefixes = prefixes;
61 public final T get(Object id) {
63 for (String prefix : prefixes) {
64 String key = prefix + SEPARATOR + id;
65 if (map.containsKey(key)) {
67 logger.trace("Cache HIT : '{}' -> {}", key, value);
70 logger.trace("Cache MISS : '{}'", key);
76 public final void put(T value) {
77 for (String prefix : prefixes) {
78 String suffix = getSuffix(value, prefix);
79 if (suffix != null && !suffix.isBlank()) {
80 String key = prefix + SEPARATOR + suffix;
86 public final void putAll(UniFiCache<T> cache) {
87 map.putAll(cache.map);
90 public final Collection<T> values() {
91 return map.values().stream().distinct().collect(Collectors.toList());
94 protected abstract String getSuffix(T value, String prefix);