2
0
mirror of https://github.com/KDE/kdeconnect-android synced 2025-08-30 21:55:10 +00:00

Fix addPacket replacing existing and then adding duplicate item

This commit is contained in:
Erik Duisters
2023-08-03 12:24:38 +02:00
parent 7be8ced91c
commit 3da626156c
2 changed files with 72 additions and 10 deletions

View File

@@ -41,8 +41,14 @@ class DevicePacketQueue {
private boolean exit = false;
DevicePacketQueue(Device device) {
this(device, true);
}
DevicePacketQueue(Device device, Boolean startThread) {
mDevice = device;
ThreadHelper.execute(new SendingRunnable());
if (startThread) {
ThreadHelper.execute(new SendingRunnable());
}
}
/**
@@ -56,17 +62,23 @@ class DevicePacketQueue {
if (exit) {
callback.onFailure(new Exception("Device disconnected!"));
} else {
boolean replaced = false;
if (replaceID >= 0) {
final Optional<Item> itemOptional = items.stream()
.filter(item -> item.replaceID == replaceID).findFirst();
itemOptional.ifPresent(item -> {
//Replace contents with new contents
item.packet = packet;
item.callback = callback;
});
for (Item item : items) {
if (item.replaceID == replaceID) {
item.packet = packet;
item.callback = callback;
replaced = true;
break;
}
}
}
if (!replaced) {
items.addLast(new Item(packet, replaceID, callback));
lock.notify();
}
items.addLast(new Item(packet, replaceID, callback));
lock.notify();
}
}
}

View File

@@ -0,0 +1,50 @@
package org.kde.kdeconnect;
import static org.junit.Assert.*;
import org.junit.Test;
import org.mockito.Mockito;
public class DevicePacketQueueTest {
@Test
public void addPacketWithPositiveReplaceId() {
Device device = Mockito.mock(Device.class);
Device.SendPacketStatusCallback callback = Mockito.mock(Device.SendPacketStatusCallback.class);
DevicePacketQueue queue = new DevicePacketQueue(device, false);
queue.addPacket(new NetworkPacket("Test"), 0, callback);
queue.addPacket(new NetworkPacket("Test1"), 1, callback);
assertNotNull(queue.getAndRemoveUnsentPacket(0));
assertNotNull(queue.getAndRemoveUnsentPacket(1));
}
@Test
public void addPacketWithNegativeReplaceId() {
Device device = Mockito.mock(Device.class);
Device.SendPacketStatusCallback callback = Mockito.mock(Device.SendPacketStatusCallback.class);
DevicePacketQueue queue = new DevicePacketQueue(device, false);
queue.addPacket(new NetworkPacket("Test"), -1, callback);
queue.addPacket(new NetworkPacket("Test1"), -1, callback);
assertNotNull(queue.getAndRemoveUnsentPacket(-1));
assertNotNull(queue.getAndRemoveUnsentPacket(-1));
}
@Test
public void addPacketReplacesPacket() {
Device device = Mockito.mock(Device.class);
Device.SendPacketStatusCallback callback = Mockito.mock(Device.SendPacketStatusCallback.class);
DevicePacketQueue queue = new DevicePacketQueue(device, false);
queue.addPacket(new NetworkPacket("Test"), 1, callback);
queue.addPacket(new NetworkPacket("Test1"), 1, callback);
assertNotNull(queue.getAndRemoveUnsentPacket(1));
assertNull(queue.getAndRemoveUnsentPacket(1));
}
}