Remove old pack if pack with newer ID is added
authorDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Wed, 29 Apr 2015 18:11:29 +0000 (20:11 +0200)
committerDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Wed, 29 Apr 2015 18:11:29 +0000 (20:11 +0200)
src/main/java/net/pterodactylus/xdcc/data/Bot.java
src/test/java/net/pterodactylus/xdcc/data/BotTest.java [new file with mode: 0644]

index 211dde7..3ca34f3 100644 (file)
@@ -39,6 +39,7 @@ public class Bot implements Iterable<Pack> {
 
        /** The packs this bot carries. */
        private final Map<String, Pack> packs = Maps.newHashMap();
 
        /** The packs this bot carries. */
        private final Map<String, Pack> packs = Maps.newHashMap();
+       private final Map<String, Pack> packsByName = Maps.newHashMap();
 
        /** The current name of the bot. */
        private String name;
 
        /** The current name of the bot. */
        private String name;
@@ -111,7 +112,14 @@ public class Bot implements Iterable<Pack> {
         *              The pack to add
         */
        public void addPack(Pack pack) {
         *              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 (file)
index 0000000..57e3de3
--- /dev/null
@@ -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 <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
+ */
+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));
+       }
+
+}