]> git.basschouten.com Git - openhab-addons.git/blob
8d3a37bdc1fda5d286ff50b859810571c64b6260
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.homeconnect.internal.handler.cache;
14
15 import java.time.Duration;
16 import java.util.concurrent.ConcurrentHashMap;
17 import java.util.concurrent.ConcurrentMap;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.openhab.binding.homeconnect.internal.client.exception.ApplianceOfflineException;
21 import org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException;
22 import org.openhab.binding.homeconnect.internal.client.exception.CommunicationException;
23 import org.openhab.binding.homeconnect.internal.handler.SupplierWithException;
24 import org.openhab.core.thing.ChannelUID;
25 import org.openhab.core.types.State;
26 import org.openhab.core.types.UnDefType;
27
28 /**
29  * This is a simple expiring state cache implementation. The state value expires after the
30  * specified duration has passed since the item was created.
31  *
32  * @author Jonas BrĂ¼stel - Initial contribution
33  */
34 @NonNullByDefault
35 public class ExpiringStateMap {
36     private final Duration expiry;
37     private final ConcurrentMap<ChannelUID, ExpiringStateCache> items;
38
39     /**
40      * Expiring state map.
41      *
42      * @param expiry expiry duration
43      */
44     public ExpiringStateMap(Duration expiry) {
45         this.expiry = expiry;
46         this.items = new ConcurrentHashMap<>();
47     }
48
49     /**
50      * Get cached value or retrieve new state value via supplier.
51      *
52      * @param channelUID cache key / channel uid
53      * @param supplier supplier
54      * @return current state
55      * @throws CommunicationException API communication exception
56      * @throws AuthorizationException oAuth authorization exception
57      * @throws ApplianceOfflineException appliance is not connected to the cloud
58      */
59     public State putIfAbsentAndGet(ChannelUID channelUID, SupplierWithException<State> supplier)
60             throws AuthorizationException, ApplianceOfflineException, CommunicationException {
61         items.putIfAbsent(channelUID, new ExpiringStateCache(expiry, supplier));
62
63         final ExpiringStateCache item = items.get(channelUID);
64         if (item == null) {
65             return UnDefType.UNDEF;
66         } else {
67             return item.getState();
68         }
69     }
70 }