2 * Copyright (c) 2010-2023 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.dwdunwetter.internal.dto;
15 import java.time.Instant;
16 import java.time.temporal.ChronoUnit;
17 import java.util.HashMap;
18 import java.util.List;
20 import java.util.Map.Entry;
21 import java.util.stream.Collectors;
24 * Cache of Warnings to update the {@link DwdUnwetterBindingConstants#CHANNEL_UPDATED} if a new warning is sent to a
27 * @author Martin Koehler - Initial contribution
29 public class DwdWarningCache {
31 // Remove Entries 30 Minutes after they expired
32 private static final long WAIT_TIME_IN_MINUTES = 30;
34 private final Map<String, Instant> idExpiresMap;
36 public DwdWarningCache() {
37 idExpiresMap = new HashMap<>();
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);
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.
51 public boolean addEntry(DwdWarningData data) {
52 return idExpiresMap.put(data.getId(), data.getExpires()) == null;
56 * Removes the expired Entries
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);