From d49f842f12ca9cd27b4d649c53b4edeeaf58133a Mon Sep 17 00:00:00 2001 From: =?utf8?q?David=20=E2=80=98Bombe=E2=80=99=20Roden?= Date: Wed, 29 Apr 2015 20:11:29 +0200 Subject: [PATCH] Remove old pack if pack with newer ID is added --- src/main/java/net/pterodactylus/xdcc/data/Bot.java | 10 +++++++- .../java/net/pterodactylus/xdcc/data/BotTest.java | 27 ++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 src/test/java/net/pterodactylus/xdcc/data/BotTest.java diff --git a/src/main/java/net/pterodactylus/xdcc/data/Bot.java b/src/main/java/net/pterodactylus/xdcc/data/Bot.java index 211dde7..3ca34f3 100644 --- a/src/main/java/net/pterodactylus/xdcc/data/Bot.java +++ b/src/main/java/net/pterodactylus/xdcc/data/Bot.java @@ -39,6 +39,7 @@ public class Bot implements Iterable { /** The packs this bot carries. */ private final Map packs = Maps.newHashMap(); + private final Map packsByName = Maps.newHashMap(); /** The current name of the bot. */ private String name; @@ -111,7 +112,14 @@ public class Bot implements Iterable { * The pack to add */ public void addPack(Pack pack) { - packs.put(pack.id(), pack); + synchronized (this) { + if (packsByName.containsKey(pack.name())) { + Pack oldPack = packsByName.remove(pack.name()); + packs.remove(oldPack.id()); + } + packs.put(pack.id(), pack); + packsByName.put(pack.name(), pack); + } } // diff --git a/src/test/java/net/pterodactylus/xdcc/data/BotTest.java b/src/test/java/net/pterodactylus/xdcc/data/BotTest.java new file mode 100644 index 0000000..57e3de3 --- /dev/null +++ b/src/test/java/net/pterodactylus/xdcc/data/BotTest.java @@ -0,0 +1,27 @@ +package net.pterodactylus.xdcc.data; + +import org.hamcrest.MatcherAssert; +import org.hamcrest.Matchers; +import org.junit.Test; +import org.mockito.Mockito; + +/** + * Unit test for {@link Bot}. + * + * @author David ‘Bombe’ Roden + */ +public class BotTest { + + private final Network network = Mockito.mock(Network.class); + private final Bot bot = new Bot(network, "#test", "Test-Bot"); + private final Pack oldPack = new Pack("7", "123", "new-file.dat"); + private final Pack newPack = new Pack("15", "234", "new-file.dat"); + + @Test + public void addingOneFileWithTwoIdsRemovesTheOldId() { + bot.addPack(oldPack); + bot.addPack(newPack); + MatcherAssert.assertThat(bot.packs(), Matchers.contains(newPack)); + } + +} -- 2.7.4