]> git.basschouten.com Git - openhab-addons.git/blob
6db2e0db73cd829aba9a0095814ad8bd7a931166
[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.dwdunwetter.internal.dto;
14
15 import java.time.Instant;
16 import java.time.temporal.ChronoUnit;
17 import java.util.HashMap;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Map.Entry;
21 import java.util.stream.Collectors;
22
23 /**
24  * Cache of Warnings to update the {@link DwdUnwetterBindingConstants#CHANNEL_UPDATED} if a new warning is sent to a
25  * channel.
26  *
27  * @author Martin Koehler - Initial contribution
28  */
29 public class DwdWarningCache {
30
31     // Remove Entries 30 Minutes after they expired
32     private static final long WAIT_TIME_IN_MINUTES = 30;
33
34     private final Map<String, Instant> idExpiresMap;
35
36     public DwdWarningCache() {
37         idExpiresMap = new HashMap<>();
38     }
39
40     private boolean isExpired(Entry<String, Instant> entry) {
41         Instant expireTime = entry.getValue().plus(WAIT_TIME_IN_MINUTES, ChronoUnit.MINUTES);
42         return Instant.now().isAfter(expireTime);
43     }
44
45     /**
46      * Adds a Warning
47      *
48      * @param data The warning data
49      * @return <code>true</code> if it is a new warning, <code>false</code> if the warning is not new.
50      */
51     public boolean addEntry(DwdWarningData data) {
52         return idExpiresMap.put(data.getId(), data.getExpires()) == null;
53     }
54
55     /**
56      * Removes the expired Entries
57      */
58     public void deleteOldEntries() {
59         List<String> oldEntries = idExpiresMap.entrySet().stream().filter(this::isExpired).map(Entry::getKey)
60                 .collect(Collectors.toList());
61         oldEntries.forEach(idExpiresMap::remove);
62     }
63 }