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