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
25 * {@link org.openhab.binding.dwdunwetter.internal.DwdUnwetterBindingConstants#CHANNEL_UPDATED}
26 * if a new warning is sent to a channel.
28 * @author Martin Koehler - Initial contribution
30 public class DwdWarningCache {
32 // Remove Entries 30 Minutes after they expired
33 private static final long WAIT_TIME_IN_MINUTES = 30;
35 private final Map<String, Instant> idExpiresMap;
37 public DwdWarningCache() {
38 idExpiresMap = new HashMap<>();
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);
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.
52 public boolean addEntry(DwdWarningData data) {
53 return idExpiresMap.put(data.getId(), data.getExpires()) == null;
57 * Removes the expired Entries
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);