2 * Copyright (c) 2010-2020 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.apache.commons.lang.StringUtils;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
25 * The {@link UniFiCache} is a specialised lookup table that stores objects using multiple keys in the form
26 * <code>prefix:suffix</code>. Each implementation is responsible for providing a list of supported prefixes and must
27 * implement {@link #getSuffix(Object, String)} to provide a value specific suffix derived from the prefix.
29 * Objects are then retrieved simply by using the <code>suffix</code> key component and all combinations of
30 * <code>prefix:suffix</code> are searched in the order of their priority.
32 * @author Matthew Bowman - Initial contribution
34 public abstract class UniFiCache<T> {
36 private static final String SEPARATOR = ":";
38 public static final String PREFIX_ALIAS = "alias";
40 public static final String PREFIX_DESC = "desc";
42 public static final String PREFIX_HOSTNAME = "hostname";
44 public static final String PREFIX_ID = "id";
46 public static final String PREFIX_IP = "ip";
48 public static final String PREFIX_MAC = "mac";
50 public static final String PREFIX_NAME = "name";
52 private final Logger logger = LoggerFactory.getLogger(getClass());
54 private Map<String, T> map = new HashMap<>();
56 private String[] prefixes;
58 protected UniFiCache(String... prefixes) {
59 this.prefixes = prefixes;
62 public final T get(Object id) {
64 for (String prefix : prefixes) {
65 String key = prefix + SEPARATOR + id;
66 if (map.containsKey(key)) {
68 logger.trace("Cache HIT : '{}' -> {}", key, value);
71 logger.trace("Cache MISS : '{}'", key);
77 public final void put(T value) {
78 for (String prefix : prefixes) {
79 String suffix = getSuffix(value, prefix);
80 if (StringUtils.isNotBlank(suffix)) {
81 String key = prefix + SEPARATOR + suffix;
87 public final void putAll(UniFiCache<T> cache) {
88 map.putAll(cache.map);
91 public final Collection<T> values() {
92 return map.values().stream().distinct().collect(Collectors.toList());
95 protected abstract String getSuffix(T value, String prefix);