From 9db4acaa98783f08342a4b0e9053ab1682631967 Mon Sep 17 00:00:00 2001 From: NuttyShrimp Date: Mon, 25 Mar 2024 20:22:35 +0100 Subject: [PATCH] feat(BatonStatusHolder): implement default dict behavior in a custom getter --- .../java/telraam/database/daos/BatonDAO.java | 4 +++ .../telraam/monitoring/BatonStatusHolder.java | 29 +++++++++++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/main/java/telraam/database/daos/BatonDAO.java b/src/main/java/telraam/database/daos/BatonDAO.java index f0859d1..2aefda9 100644 --- a/src/main/java/telraam/database/daos/BatonDAO.java +++ b/src/main/java/telraam/database/daos/BatonDAO.java @@ -28,6 +28,10 @@ public interface BatonDAO extends DAO { @RegisterBeanMapper(Baton.class) Optional getById(@Bind("id") int id); + @SqlQuery("SELECT * FROM baton WHERE mac = :mac") + @RegisterBeanMapper(Baton.class) + Optional getByMac(@Bind("mac") String mac); + @Override @SqlUpdate("DELETE FROM baton WHERE id = :id") @RegisterBeanMapper(Baton.class) diff --git a/src/main/java/telraam/monitoring/BatonStatusHolder.java b/src/main/java/telraam/monitoring/BatonStatusHolder.java index 9966cee..e3e4f36 100644 --- a/src/main/java/telraam/monitoring/BatonStatusHolder.java +++ b/src/main/java/telraam/monitoring/BatonStatusHolder.java @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Optional; public class BatonStatusHolder { // Map from batonMac to batonStatus @@ -43,6 +44,30 @@ private void initStatus() { ); batonStatusMap.put(baton.getMac().toLowerCase(), batonStatus); } + } + + private BatonStatus getStatusForBaton(String batonMac) { + BatonStatus batonStatus = batonStatusMap.get(batonMac); + if (batonStatus == null) { + Optional optionalBaton = batonDAO.getByMac(batonMac); + if (optionalBaton.isEmpty()) { + return null; + } + Baton baton = optionalBaton.get(); + + batonStatus = new BatonStatus( + baton.getMac().toLowerCase(), + baton.getId(), + baton.getName(), + 0, + 0, + false, + null, + -1 + ); + batonStatusMap.put(baton.getMac().toLowerCase(), batonStatus); + } + return batonStatus; } @@ -87,14 +112,14 @@ public BatonStatus GetBatonStatus(Integer batonId) { baton.ifPresent(value -> batonIdToMac.put(batonId, value.getMac().toLowerCase())); } String batonMac = batonIdToMac.get(batonId); - return batonStatusMap.get(batonMac); + return getStatusForBaton(batonMac); } public BatonStatus createBatonStatus(Integer batonId) { this.initStatus(); String batonMac = batonIdToMac.get(batonId); if (batonMac != null) { - return batonStatusMap.get(batonMac); + return getStatusForBaton(batonMac); } var baton = batonDAO.getById(batonId); if (baton.isEmpty()) {