Effectively final.

This commit is contained in:
akwizgran
2017-11-17 15:40:54 +00:00
committed by Torsten Grote
parent a5b321a93b
commit d7383a3361
153 changed files with 1337 additions and 1396 deletions

View File

@@ -45,7 +45,7 @@ public class AndroidPluginModule {
backoffFactory); backoffFactory);
DuplexPluginFactory lan = new AndroidLanTcpPluginFactory(ioExecutor, DuplexPluginFactory lan = new AndroidLanTcpPluginFactory(ioExecutor,
backoffFactory, appContext); backoffFactory, appContext);
final Collection<DuplexPluginFactory> duplex = Collection<DuplexPluginFactory> duplex =
Arrays.asList(bluetooth, tor, lan); Arrays.asList(bluetooth, tor, lan);
@NotNullByDefault @NotNullByDefault
PluginConfig pluginConfig = new PluginConfig() { PluginConfig pluginConfig = new PluginConfig() {

View File

@@ -285,11 +285,11 @@ class DroidtoothPlugin implements DuplexPlugin, EventListener {
Map<ContactId, TransportProperties> remote = Map<ContactId, TransportProperties> remote =
callback.getRemoteProperties(); callback.getRemoteProperties();
for (Entry<ContactId, TransportProperties> e : remote.entrySet()) { for (Entry<ContactId, TransportProperties> e : remote.entrySet()) {
final ContactId c = e.getKey(); ContactId c = e.getKey();
if (connected.contains(c)) continue; if (connected.contains(c)) continue;
final String address = e.getValue().get(PROP_ADDRESS); String address = e.getValue().get(PROP_ADDRESS);
if (StringUtils.isNullOrEmpty(address)) continue; if (StringUtils.isNullOrEmpty(address)) continue;
final String uuid = e.getValue().get(PROP_UUID); String uuid = e.getValue().get(PROP_UUID);
if (StringUtils.isNullOrEmpty(uuid)) continue; if (StringUtils.isNullOrEmpty(uuid)) continue;
ioExecutor.execute(() -> { ioExecutor.execute(() -> {
if (!running) return; if (!running) return;

View File

@@ -400,7 +400,7 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
} }
socket = ss; socket = ss;
// Store the port number // Store the port number
final String localPort = String.valueOf(ss.getLocalPort()); String localPort = String.valueOf(ss.getLocalPort());
Settings s = new Settings(); Settings s = new Settings();
s.put(PREF_TOR_PORT, localPort); s.put(PREF_TOR_PORT, localPort);
callback.mergeSettings(s); callback.mergeSettings(s);
@@ -536,8 +536,7 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
} }
} }
private void connectAndCallBack(final ContactId c, private void connectAndCallBack(ContactId c, TransportProperties p) {
final TransportProperties p) {
ioExecutor.execute(() -> { ioExecutor.execute(() -> {
if (!isRunning()) return; if (!isRunning()) return;
DuplexTransportConnection d = createConnection(p); DuplexTransportConnection d = createConnection(p);

View File

@@ -48,8 +48,8 @@ public class PoliteExecutor implements Executor {
} }
@Override @Override
public void execute(final Runnable r) { public void execute(Runnable r) {
final long submitted = System.currentTimeMillis(); long submitted = System.currentTimeMillis();
Runnable wrapped = () -> { Runnable wrapped = () -> {
if (log.isLoggable(LOG_LEVEL)) { if (log.isLoggable(LOG_LEVEL)) {
long queued = System.currentTimeMillis() - submitted; long queued = System.currentTimeMillis() - submitted;

View File

@@ -28,9 +28,9 @@ public class TimeLoggingExecutor extends ThreadPoolExecutor {
} }
@Override @Override
public void execute(final Runnable r) { public void execute(Runnable r) {
if (log.isLoggable(LOG_LEVEL)) { if (log.isLoggable(LOG_LEVEL)) {
final long submitted = System.currentTimeMillis(); long submitted = System.currentTimeMillis();
super.execute(() -> { super.execute(() -> {
long started = System.currentTimeMillis(); long started = System.currentTimeMillis();
long queued = started - submitted; long queued = started - submitted;

View File

@@ -88,7 +88,7 @@ class LifecycleManagerImpl implements LifecycleManager {
executors.add(e); executors.add(e);
} }
private LocalAuthor createLocalAuthor(final String nickname) { private LocalAuthor createLocalAuthor(String nickname) {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
KeyPair keyPair = crypto.generateSignatureKeyPair(); KeyPair keyPair = crypto.generateSignatureKeyPair();
byte[] publicKey = keyPair.getPublic().getEncoded(); byte[] publicKey = keyPair.getPublic().getEncoded();

View File

@@ -111,7 +111,7 @@ class Poller implements EventListener {
connectToContact(c, (DuplexPlugin) p); connectToContact(c, (DuplexPlugin) p);
} }
private void connectToContact(final ContactId c, final SimplexPlugin p) { private void connectToContact(ContactId c, SimplexPlugin p) {
ioExecutor.execute(() -> { ioExecutor.execute(() -> {
TransportId t = p.getId(); TransportId t = p.getId();
if (!connectionRegistry.isConnected(c, t)) { if (!connectionRegistry.isConnected(c, t)) {
@@ -122,7 +122,7 @@ class Poller implements EventListener {
}); });
} }
private void connectToContact(final ContactId c, final DuplexPlugin p) { private void connectToContact(ContactId c, DuplexPlugin p) {
ioExecutor.execute(() -> { ioExecutor.execute(() -> {
TransportId t = p.getId(); TransportId t = p.getId();
if (!connectionRegistry.isConnected(c, t)) { if (!connectionRegistry.isConnected(c, t)) {
@@ -153,7 +153,7 @@ class Poller implements EventListener {
try { try {
PollTask scheduled = tasks.get(t); PollTask scheduled = tasks.get(t);
if (scheduled == null || due < scheduled.due) { if (scheduled == null || due < scheduled.due) {
final PollTask task = new PollTask(p, due, randomiseNext); PollTask task = new PollTask(p, due, randomiseNext);
tasks.put(t, task); tasks.put(t, task);
scheduler.schedule( scheduler.schedule(
() -> ioExecutor.execute(task), delay, MILLISECONDS); () -> ioExecutor.execute(task), delay, MILLISECONDS);
@@ -164,7 +164,7 @@ class Poller implements EventListener {
} }
@IoExecutor @IoExecutor
private void poll(final Plugin p) { private void poll(Plugin p) {
TransportId t = p.getId(); TransportId t = p.getId();
if (LOG.isLoggable(INFO)) LOG.info("Polling plugin " + t); if (LOG.isLoggable(INFO)) LOG.info("Polling plugin " + t);
p.poll(connectionRegistry.getConnectedContacts(t)); p.poll(connectionRegistry.getConnectedContacts(t));

View File

@@ -108,7 +108,7 @@ abstract class FilePlugin implements SimplexPlugin {
} }
} }
protected void createReaderFromFile(final File f) { protected void createReaderFromFile(File f) {
if (!running) return; if (!running) return;
ioExecutor.execute(new ReaderCreator(f)); ioExecutor.execute(new ReaderCreator(f));
} }

View File

@@ -37,7 +37,7 @@ class PortMapperImpl implements PortMapper {
} }
@Override @Override
public MappingResult map(final int port) { public MappingResult map(int port) {
if (!started.getAndSet(true)) start(); if (!started.getAndSet(true)) start();
if (gateway == null) return null; if (gateway == null) return null;
InetAddress internal = gateway.getLocalAddress(); InetAddress internal = gateway.getLocalAddress();

View File

@@ -214,8 +214,7 @@ abstract class TcpPlugin implements DuplexPlugin {
} }
} }
private void connectAndCallBack(final ContactId c, private void connectAndCallBack(ContactId c, TransportProperties p) {
final TransportProperties p) {
ioExecutor.execute(() -> { ioExecutor.execute(() -> {
if (!isRunning()) return; if (!isRunning()) return;
DuplexTransportConnection d = createConnection(p); DuplexTransportConnection d = createConnection(p);

View File

@@ -48,7 +48,7 @@ class ReliabilityLayerImpl implements ReliabilityLayer, WriteHandler {
@Override @Override
public void start() { public void start() {
SlipEncoder encoder = new SlipEncoder(this); SlipEncoder encoder = new SlipEncoder(this);
final Sender sender = new Sender(clock, encoder); Sender sender = new Sender(clock, encoder);
receiver = new Receiver(clock, sender); receiver = new Receiver(clock, sender);
decoder = new SlipDecoder(receiver, Data.MAX_LENGTH); decoder = new SlipDecoder(receiver, Data.MAX_LENGTH);
inputStream = new ReceiverInputStream(receiver); inputStream = new ReceiverInputStream(receiver);

View File

@@ -93,7 +93,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
hooks.put(c, hook); hooks.put(c, hook);
} }
private void validateOutstandingMessagesAsync(final ClientId c) { private void validateOutstandingMessagesAsync(ClientId c) {
dbExecutor.execute(() -> validateOutstandingMessages(c)); dbExecutor.execute(() -> validateOutstandingMessages(c));
} }
@@ -114,7 +114,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
} }
} }
private void validateNextMessageAsync(final Queue<MessageId> unvalidated) { private void validateNextMessageAsync(Queue<MessageId> unvalidated) {
if (unvalidated.isEmpty()) return; if (unvalidated.isEmpty()) return;
dbExecutor.execute(() -> validateNextMessage(unvalidated)); dbExecutor.execute(() -> validateNextMessage(unvalidated));
} }
@@ -148,7 +148,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
} }
} }
private void deliverOutstandingMessagesAsync(final ClientId c) { private void deliverOutstandingMessagesAsync(ClientId c) {
dbExecutor.execute(() -> deliverOutstandingMessages(c)); dbExecutor.execute(() -> deliverOutstandingMessages(c));
} }
@@ -169,8 +169,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
} }
} }
private void deliverNextPendingMessageAsync( private void deliverNextPendingMessageAsync(Queue<MessageId> pending) {
final Queue<MessageId> pending) {
if (pending.isEmpty()) return; if (pending.isEmpty()) return;
dbExecutor.execute(() -> deliverNextPendingMessage(pending)); dbExecutor.execute(() -> deliverNextPendingMessage(pending));
} }
@@ -234,7 +233,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
} }
} }
private void validateMessageAsync(final Message m, final Group g) { private void validateMessageAsync(Message m, Group g) {
validationExecutor.execute(() -> validateMessage(m, g)); validationExecutor.execute(() -> validateMessage(m, g));
} }
@@ -258,8 +257,8 @@ class ValidationManagerImpl implements ValidationManager, Service,
} }
} }
private void storeMessageContextAsync(final Message m, final ClientId c, private void storeMessageContextAsync(Message m, ClientId c,
final MessageContext result) { MessageContext result) {
dbExecutor.execute(() -> storeMessageContext(m, c, result)); dbExecutor.execute(() -> storeMessageContext(m, c, result));
} }
@@ -354,7 +353,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
return pending; return pending;
} }
private void shareOutstandingMessagesAsync(final ClientId c) { private void shareOutstandingMessagesAsync(ClientId c) {
dbExecutor.execute(() -> shareOutstandingMessages(c)); dbExecutor.execute(() -> shareOutstandingMessages(c));
} }
@@ -381,7 +380,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
* This method should only be called for messages that have all their * This method should only be called for messages that have all their
* dependencies delivered and have been delivered themselves. * dependencies delivered and have been delivered themselves.
*/ */
private void shareNextMessageAsync(final Queue<MessageId> toShare) { private void shareNextMessageAsync(Queue<MessageId> toShare) {
if (toShare.isEmpty()) return; if (toShare.isEmpty()) return;
dbExecutor.execute(() -> shareNextMessage(toShare)); dbExecutor.execute(() -> shareNextMessage(toShare));
} }
@@ -410,7 +409,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
} }
} }
private void invalidateNextMessageAsync(final Queue<MessageId> invalidate) { private void invalidateNextMessageAsync(Queue<MessageId> invalidate) {
if (invalidate.isEmpty()) return; if (invalidate.isEmpty()) return;
dbExecutor.execute(() -> invalidateNextMessage(invalidate)); dbExecutor.execute(() -> invalidateNextMessage(invalidate));
} }
@@ -467,12 +466,12 @@ class ValidationManagerImpl implements ValidationManager, Service,
} }
} }
private void loadGroupAndValidateAsync(final Message m) { private void loadGroupAndValidateAsync(Message m) {
dbExecutor.execute(() -> loadGroupAndValidate(m)); dbExecutor.execute(() -> loadGroupAndValidate(m));
} }
@DatabaseExecutor @DatabaseExecutor
private void loadGroupAndValidate(final Message m) { private void loadGroupAndValidate(Message m) {
try { try {
Group g; Group g;
Transaction txn = db.startTransaction(true); Transaction txn = db.startTransaction(true);

View File

@@ -155,7 +155,7 @@ class KeyManagerImpl implements KeyManager, Service, EventListener {
} }
} }
private void removeContact(final ContactId c) { private void removeContact(ContactId c) {
activeContacts.remove(c); activeContacts.remove(c);
dbExecutor.execute(() -> { dbExecutor.execute(() -> {
for (TransportKeyManager m : managers.values()) m.removeContact(c); for (TransportKeyManager m : managers.values()) m.removeContact(c);

View File

@@ -24,10 +24,10 @@ public class PoliteExecutorTest extends BrambleTestCase {
Executor delegate = Executors.newSingleThreadExecutor(); Executor delegate = Executors.newSingleThreadExecutor();
// Allow all the tasks to be delegated straight away // Allow all the tasks to be delegated straight away
PoliteExecutor polite = new PoliteExecutor(TAG, delegate, TASKS * 2); PoliteExecutor polite = new PoliteExecutor(TAG, delegate, TASKS * 2);
final List<Integer> list = new Vector<>(); List<Integer> list = new Vector<>();
final CountDownLatch latch = new CountDownLatch(TASKS); CountDownLatch latch = new CountDownLatch(TASKS);
for (int i = 0; i < TASKS; i++) { for (int i = 0; i < TASKS; i++) {
final int result = i; int result = i;
polite.execute(() -> { polite.execute(() -> {
list.add(result); list.add(result);
latch.countDown(); latch.countDown();
@@ -46,10 +46,10 @@ public class PoliteExecutorTest extends BrambleTestCase {
Executor delegate = Executors.newSingleThreadExecutor(); Executor delegate = Executors.newSingleThreadExecutor();
// Allow two tasks to be delegated at a time // Allow two tasks to be delegated at a time
PoliteExecutor polite = new PoliteExecutor(TAG, delegate, 2); PoliteExecutor polite = new PoliteExecutor(TAG, delegate, 2);
final List<Integer> list = new Vector<>(); List<Integer> list = new Vector<>();
final CountDownLatch latch = new CountDownLatch(TASKS); CountDownLatch latch = new CountDownLatch(TASKS);
for (int i = 0; i < TASKS; i++) { for (int i = 0; i < TASKS; i++) {
final int result = i; int result = i;
polite.execute(() -> { polite.execute(() -> {
list.add(result); list.add(result);
latch.countDown(); latch.countDown();
@@ -67,11 +67,11 @@ public class PoliteExecutorTest extends BrambleTestCase {
Executor delegate = Executors.newCachedThreadPool(); Executor delegate = Executors.newCachedThreadPool();
// Allow all the tasks to be delegated straight away // Allow all the tasks to be delegated straight away
PoliteExecutor polite = new PoliteExecutor(TAG, delegate, TASKS * 2); PoliteExecutor polite = new PoliteExecutor(TAG, delegate, TASKS * 2);
final List<Integer> list = new Vector<>(); List<Integer> list = new Vector<>();
final CountDownLatch[] latches = new CountDownLatch[TASKS]; CountDownLatch[] latches = new CountDownLatch[TASKS];
for (int i = 0; i < TASKS; i++) latches[i] = new CountDownLatch(1); for (int i = 0; i < TASKS; i++) latches[i] = new CountDownLatch(1);
for (int i = 0; i < TASKS; i++) { for (int i = 0; i < TASKS; i++) {
final int result = i; int result = i;
polite.execute(() -> { polite.execute(() -> {
try { try {
// Each task waits for the next task, if any, to finish // Each task waits for the next task, if any, to finish
@@ -95,10 +95,10 @@ public class PoliteExecutorTest extends BrambleTestCase {
Executor delegate = Executors.newCachedThreadPool(); Executor delegate = Executors.newCachedThreadPool();
// Allow one task to be delegated at a time // Allow one task to be delegated at a time
PoliteExecutor polite = new PoliteExecutor(TAG, delegate, 1); PoliteExecutor polite = new PoliteExecutor(TAG, delegate, 1);
final List<Integer> list = new Vector<>(); List<Integer> list = new Vector<>();
final CountDownLatch latch = new CountDownLatch(TASKS); CountDownLatch latch = new CountDownLatch(TASKS);
for (int i = 0; i < TASKS; i++) { for (int i = 0; i < TASKS; i++) {
final int result = i; int result = i;
polite.execute(() -> { polite.execute(() -> {
try { try {
// Each task runs faster than the previous task // Each task runs faster than the previous task

View File

@@ -83,9 +83,9 @@ public class BdfMessageValidatorTest extends ValidatorTestCase {
@Test(expected = InvalidMessageException.class) @Test(expected = InvalidMessageException.class)
public void testRejectsTooShortMessage() throws Exception { public void testRejectsTooShortMessage() throws Exception {
final byte[] invalidRaw = new byte[MESSAGE_HEADER_LENGTH]; byte[] invalidRaw = new byte[MESSAGE_HEADER_LENGTH];
// Use a mock message so the length of the raw message can be invalid // Use a mock message so the length of the raw message can be invalid
final Message invalidMessage = context.mock(Message.class); Message invalidMessage = context.mock(Message.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(invalidMessage).getTimestamp(); oneOf(invalidMessage).getTimestamp();
@@ -101,8 +101,8 @@ public class BdfMessageValidatorTest extends ValidatorTestCase {
@Test @Test
public void testAcceptsMinLengthMessage() throws Exception { public void testAcceptsMinLengthMessage() throws Exception {
final byte[] shortRaw = new byte[MESSAGE_HEADER_LENGTH + 1]; byte[] shortRaw = new byte[MESSAGE_HEADER_LENGTH + 1];
final Message shortMessage = Message shortMessage =
new Message(messageId, groupId, timestamp, shortRaw); new Message(messageId, groupId, timestamp, shortRaw);
context.checking(new Expectations() {{ context.checking(new Expectations() {{

View File

@@ -76,8 +76,8 @@ public class ClientHelperImplTest extends BrambleTestCase {
@Test @Test
public void testAddLocalMessage() throws Exception { public void testAddLocalMessage() throws Exception {
final boolean shared = true; boolean shared = true;
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(false); oneOf(db).startTransaction(false);
@@ -95,7 +95,7 @@ public class ClientHelperImplTest extends BrambleTestCase {
@Test @Test
public void testCreateMessage() throws Exception { public void testCreateMessage() throws Exception {
final byte[] bytes = expectToByteArray(list); byte[] bytes = expectToByteArray(list);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(messageFactory).createMessage(groupId, timestamp, bytes); oneOf(messageFactory).createMessage(groupId, timestamp, bytes);
@@ -107,7 +107,7 @@ public class ClientHelperImplTest extends BrambleTestCase {
@Test @Test
public void testGetMessageAsList() throws Exception { public void testGetMessageAsList() throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
expectToList(true); expectToList(true);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
@@ -125,7 +125,7 @@ public class ClientHelperImplTest extends BrambleTestCase {
@Test @Test
public void testGetGroupMetadataAsDictionary() throws Exception { public void testGetGroupMetadataAsDictionary() throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(true); oneOf(db).startTransaction(true);
@@ -145,7 +145,7 @@ public class ClientHelperImplTest extends BrambleTestCase {
@Test @Test
public void testGetMessageMetadataAsDictionary() throws Exception { public void testGetMessageMetadataAsDictionary() throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(true); oneOf(db).startTransaction(true);
@@ -165,9 +165,9 @@ public class ClientHelperImplTest extends BrambleTestCase {
@Test @Test
public void testGetMessageMetadataAsDictionaryMap() throws Exception { public void testGetMessageMetadataAsDictionaryMap() throws Exception {
final Map<MessageId, BdfDictionary> map = new HashMap<>(); Map<MessageId, BdfDictionary> map = new HashMap<>();
map.put(messageId, dictionary); map.put(messageId, dictionary);
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(true); oneOf(db).startTransaction(true);
@@ -187,13 +187,13 @@ public class ClientHelperImplTest extends BrambleTestCase {
@Test @Test
public void testGetMessageMetadataAsDictionaryQuery() throws Exception { public void testGetMessageMetadataAsDictionaryQuery() throws Exception {
final Map<MessageId, BdfDictionary> map = new HashMap<>(); Map<MessageId, BdfDictionary> map = new HashMap<>();
map.put(messageId, dictionary); map.put(messageId, dictionary);
final BdfDictionary query = BdfDictionary query =
BdfDictionary.of(new BdfEntry("query", "me")); BdfDictionary.of(new BdfEntry("query", "me"));
final Metadata queryMetadata = new Metadata(); Metadata queryMetadata = new Metadata();
queryMetadata.put("query", getRandomBytes(42)); queryMetadata.put("query", getRandomBytes(42));
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(true); oneOf(db).startTransaction(true);
@@ -215,7 +215,7 @@ public class ClientHelperImplTest extends BrambleTestCase {
@Test @Test
public void testMergeGroupMetadata() throws Exception { public void testMergeGroupMetadata() throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(false); oneOf(db).startTransaction(false);
@@ -233,7 +233,7 @@ public class ClientHelperImplTest extends BrambleTestCase {
@Test @Test
public void testMergeMessageMetadata() throws Exception { public void testMergeMessageMetadata() throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(false); oneOf(db).startTransaction(false);
@@ -280,10 +280,10 @@ public class ClientHelperImplTest extends BrambleTestCase {
@Test @Test
public void testSign() throws Exception { public void testSign() throws Exception {
final byte[] privateKey = getRandomBytes(42); byte[] privateKey = getRandomBytes(42);
final byte[] signed = getRandomBytes(42); byte[] signed = getRandomBytes(42);
final byte[] bytes = expectToByteArray(list); byte[] bytes = expectToByteArray(list);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(cryptoComponent).sign(label, bytes, privateKey); oneOf(cryptoComponent).sign(label, bytes, privateKey);
will(returnValue(signed)); will(returnValue(signed));
@@ -295,8 +295,8 @@ public class ClientHelperImplTest extends BrambleTestCase {
@Test @Test
public void testVerifySignature() throws Exception { public void testVerifySignature() throws Exception {
final byte[] publicKey = getRandomBytes(42); byte[] publicKey = getRandomBytes(42);
final byte[] bytes = expectToByteArray(list); byte[] bytes = expectToByteArray(list);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(cryptoComponent).verify(label, bytes, publicKey, rawMessage); oneOf(cryptoComponent).verify(label, bytes, publicKey, rawMessage);
@@ -309,8 +309,8 @@ public class ClientHelperImplTest extends BrambleTestCase {
@Test @Test
public void testVerifyWrongSignature() throws Exception { public void testVerifyWrongSignature() throws Exception {
final byte[] publicKey = getRandomBytes(42); byte[] publicKey = getRandomBytes(42);
final byte[] bytes = expectToByteArray(list); byte[] bytes = expectToByteArray(list);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(cryptoComponent).verify(label, bytes, publicKey, rawMessage); oneOf(cryptoComponent).verify(label, bytes, publicKey, rawMessage);
@@ -327,8 +327,8 @@ public class ClientHelperImplTest extends BrambleTestCase {
} }
} }
private byte[] expectToByteArray(final BdfList list) throws Exception { private byte[] expectToByteArray(BdfList list) throws Exception {
final BdfWriter bdfWriter = context.mock(BdfWriter.class); BdfWriter bdfWriter = context.mock(BdfWriter.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(bdfWriterFactory) oneOf(bdfWriterFactory)
@@ -339,8 +339,8 @@ public class ClientHelperImplTest extends BrambleTestCase {
return new byte[0]; return new byte[0];
} }
private void expectToList(final boolean eof) throws Exception { private void expectToList(boolean eof) throws Exception {
final BdfReader bdfReader = context.mock(BdfReader.class); BdfReader bdfReader = context.mock(BdfReader.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(bdfReaderFactory) oneOf(bdfReaderFactory)

View File

@@ -46,10 +46,10 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testAddContact() throws Exception { public void testAddContact() throws Exception {
final SecretKey master = getSecretKey(); SecretKey master = getSecretKey();
final long timestamp = 42; long timestamp = 42;
final boolean alice = true; boolean alice = true;
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(false); oneOf(db).startTransaction(false);
@@ -64,14 +64,13 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
oneOf(db).endTransaction(txn); oneOf(db).endTransaction(txn);
}}); }});
assertEquals(contactId, contactManager assertEquals(contactId, contactManager.addContact(remote, local,
.addContact(remote, local, master, timestamp, alice, verified, master, timestamp, alice, verified, active));
active));
} }
@Test @Test
public void testGetContact() throws Exception { public void testGetContact() throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(true); oneOf(db).startTransaction(true);
will(returnValue(txn)); will(returnValue(txn));
@@ -86,8 +85,8 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testGetContactByAuthor() throws Exception { public void testGetContactByAuthor() throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Collection<Contact> contacts = Collections.singleton(contact); Collection<Contact> contacts = Collections.singleton(contact);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(true); oneOf(db).startTransaction(true);
will(returnValue(txn)); will(returnValue(txn));
@@ -102,7 +101,7 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
@Test(expected = NoSuchContactException.class) @Test(expected = NoSuchContactException.class)
public void testGetContactByUnknownAuthor() throws Exception { public void testGetContactByUnknownAuthor() throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(true); oneOf(db).startTransaction(true);
will(returnValue(txn)); will(returnValue(txn));
@@ -116,8 +115,8 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
@Test(expected = NoSuchContactException.class) @Test(expected = NoSuchContactException.class)
public void testGetContactByUnknownLocalAuthor() throws Exception { public void testGetContactByUnknownLocalAuthor() throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Collection<Contact> contacts = Collections.singleton(contact); Collection<Contact> contacts = Collections.singleton(contact);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(true); oneOf(db).startTransaction(true);
will(returnValue(txn)); will(returnValue(txn));
@@ -132,9 +131,9 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testActiveContacts() throws Exception { public void testActiveContacts() throws Exception {
Collection<Contact> activeContacts = Collections.singletonList(contact); Collection<Contact> activeContacts = Collections.singletonList(contact);
final Collection<Contact> contacts = new ArrayList<>(activeContacts); Collection<Contact> contacts = new ArrayList<>(activeContacts);
contacts.add(new Contact(new ContactId(3), remote, local, true, false)); contacts.add(new Contact(new ContactId(3), remote, local, true, false));
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(true); oneOf(db).startTransaction(true);
will(returnValue(txn)); will(returnValue(txn));
@@ -149,7 +148,7 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testRemoveContact() throws Exception { public void testRemoveContact() throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(false); oneOf(db).startTransaction(false);
will(returnValue(txn)); will(returnValue(txn));
@@ -165,7 +164,7 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testSetContactActive() throws Exception { public void testSetContactActive() throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).setContactActive(txn, contactId, active); oneOf(db).setContactActive(txn, contactId, active);
}}); }});
@@ -175,7 +174,7 @@ public class ContactManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testContactExists() throws Exception { public void testContactExists() throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(true); oneOf(db).startTransaction(true);
will(returnValue(txn)); will(returnValue(txn));

View File

@@ -127,11 +127,11 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
@Test @Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testSimpleCalls() throws Exception { public void testSimpleCalls() throws Exception {
final int shutdownHandle = 12345; int shutdownHandle = 12345;
Mockery context = new Mockery(); Mockery context = new Mockery();
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// open() // open()
oneOf(database).open(); oneOf(database).open();
@@ -230,9 +230,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
throws Exception { throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
will(returnValue(txn)); will(returnValue(txn));
@@ -260,9 +260,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
public void testAddLocalMessage() throws Exception { public void testAddLocalMessage() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
will(returnValue(txn)); will(returnValue(txn));
@@ -303,9 +303,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
throws Exception { throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Check whether the contact is in the DB (which it's not) // Check whether the contact is in the DB (which it's not)
exactly(18).of(database).startTransaction(); exactly(18).of(database).startTransaction();
@@ -509,9 +509,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
throws Exception { throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Check whether the pseudonym is in the DB (which it's not) // Check whether the pseudonym is in the DB (which it's not)
exactly(3).of(database).startTransaction(); exactly(3).of(database).startTransaction();
@@ -561,9 +561,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
throws Exception { throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Check whether the group is in the DB (which it's not) // Check whether the group is in the DB (which it's not)
exactly(8).of(database).startTransaction(); exactly(8).of(database).startTransaction();
@@ -666,9 +666,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
throws Exception { throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Check whether the message is in the DB (which it's not) // Check whether the message is in the DB (which it's not)
exactly(11).of(database).startTransaction(); exactly(11).of(database).startTransaction();
@@ -801,9 +801,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
throws Exception { throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// startTransaction() // startTransaction()
oneOf(database).startTransaction(); oneOf(database).startTransaction();
@@ -896,13 +896,13 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
@Test @Test
public void testGenerateAck() throws Exception { public void testGenerateAck() throws Exception {
final Collection<MessageId> messagesToAck = Arrays.asList(messageId, Collection<MessageId> messagesToAck = Arrays.asList(messageId,
messageId1); messageId1);
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
will(returnValue(txn)); will(returnValue(txn));
@@ -931,14 +931,14 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
@Test @Test
public void testGenerateBatch() throws Exception { public void testGenerateBatch() throws Exception {
final byte[] raw1 = new byte[size]; byte[] raw1 = new byte[size];
final Collection<MessageId> ids = Arrays.asList(messageId, messageId1); Collection<MessageId> ids = Arrays.asList(messageId, messageId1);
final Collection<byte[]> messages = Arrays.asList(raw, raw1); Collection<byte[]> messages = Arrays.asList(raw, raw1);
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
will(returnValue(txn)); will(returnValue(txn));
@@ -975,13 +975,13 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
@Test @Test
public void testGenerateOffer() throws Exception { public void testGenerateOffer() throws Exception {
final MessageId messageId1 = new MessageId(TestUtils.getRandomId()); MessageId messageId1 = new MessageId(TestUtils.getRandomId());
final Collection<MessageId> ids = Arrays.asList(messageId, messageId1); Collection<MessageId> ids = Arrays.asList(messageId, messageId1);
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
will(returnValue(txn)); will(returnValue(txn));
@@ -1013,13 +1013,13 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
@Test @Test
public void testGenerateRequest() throws Exception { public void testGenerateRequest() throws Exception {
final MessageId messageId1 = new MessageId(TestUtils.getRandomId()); MessageId messageId1 = new MessageId(TestUtils.getRandomId());
final Collection<MessageId> ids = Arrays.asList(messageId, messageId1); Collection<MessageId> ids = Arrays.asList(messageId, messageId1);
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
will(returnValue(txn)); will(returnValue(txn));
@@ -1048,14 +1048,14 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
@Test @Test
public void testGenerateRequestedBatch() throws Exception { public void testGenerateRequestedBatch() throws Exception {
final byte[] raw1 = new byte[size]; byte[] raw1 = new byte[size];
final Collection<MessageId> ids = Arrays.asList(messageId, messageId1); Collection<MessageId> ids = Arrays.asList(messageId, messageId1);
final Collection<byte[]> messages = Arrays.asList(raw, raw1); Collection<byte[]> messages = Arrays.asList(raw, raw1);
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
will(returnValue(txn)); will(returnValue(txn));
@@ -1095,9 +1095,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
public void testReceiveAck() throws Exception { public void testReceiveAck() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
will(returnValue(txn)); will(returnValue(txn));
@@ -1128,9 +1128,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
public void testReceiveMessage() throws Exception { public void testReceiveMessage() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
will(returnValue(txn)); will(returnValue(txn));
@@ -1183,9 +1183,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
public void testReceiveDuplicateMessage() throws Exception { public void testReceiveDuplicateMessage() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
will(returnValue(txn)); will(returnValue(txn));
@@ -1220,9 +1220,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
public void testReceiveMessageWithoutVisibleGroup() throws Exception { public void testReceiveMessageWithoutVisibleGroup() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
will(returnValue(txn)); will(returnValue(txn));
@@ -1248,14 +1248,14 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
@Test @Test
public void testReceiveOffer() throws Exception { public void testReceiveOffer() throws Exception {
final MessageId messageId1 = new MessageId(TestUtils.getRandomId()); MessageId messageId1 = new MessageId(TestUtils.getRandomId());
final MessageId messageId2 = new MessageId(TestUtils.getRandomId()); MessageId messageId2 = new MessageId(TestUtils.getRandomId());
final MessageId messageId3 = new MessageId(TestUtils.getRandomId()); MessageId messageId3 = new MessageId(TestUtils.getRandomId());
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
will(returnValue(txn)); will(returnValue(txn));
@@ -1304,9 +1304,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
public void testReceiveRequest() throws Exception { public void testReceiveRequest() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
will(returnValue(txn)); will(returnValue(txn));
@@ -1338,9 +1338,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
public void testChangingVisibilityCallsListeners() throws Exception { public void testChangingVisibilityCallsListeners() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
will(returnValue(txn)); will(returnValue(txn));
@@ -1379,9 +1379,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
throws Exception { throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
will(returnValue(txn)); will(returnValue(txn));
@@ -1409,14 +1409,14 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
@Test @Test
public void testTransportKeys() throws Exception { public void testTransportKeys() throws Exception {
final TransportKeys transportKeys = createTransportKeys(); TransportKeys transportKeys = createTransportKeys();
final Map<ContactId, TransportKeys> keys = Collections.singletonMap( Map<ContactId, TransportKeys> keys = Collections.singletonMap(
contactId, transportKeys); contactId, transportKeys);
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// startTransaction() // startTransaction()
oneOf(database).startTransaction(); oneOf(database).startTransaction();
@@ -1472,19 +1472,19 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
@Test @Test
public void testMergeSettings() throws Exception { public void testMergeSettings() throws Exception {
final Settings before = new Settings(); Settings before = new Settings();
before.put("foo", "bar"); before.put("foo", "bar");
before.put("baz", "bam"); before.put("baz", "bam");
final Settings update = new Settings(); Settings update = new Settings();
update.put("baz", "qux"); update.put("baz", "qux");
final Settings merged = new Settings(); Settings merged = new Settings();
merged.put("foo", "bar"); merged.put("foo", "bar");
merged.put("baz", "qux"); merged.put("baz", "qux");
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// startTransaction() // startTransaction()
oneOf(database).startTransaction(); oneOf(database).startTransaction();
@@ -1547,9 +1547,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
throws Exception { throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
@@ -1572,9 +1572,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
public void testCannotAddLocalIdentityAsContact() throws Exception { public void testCannotAddLocalIdentityAsContact() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
@@ -1607,9 +1607,9 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
public void testCannotAddDuplicateContact() throws Exception { public void testCannotAddDuplicateContact() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(database).startTransaction(); oneOf(database).startTransaction();
@@ -1643,12 +1643,12 @@ public class DatabaseComponentImplTest extends BrambleTestCase {
@Test @Test
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void testMessageDependencies() throws Exception { public void testMessageDependencies() throws Exception {
final int shutdownHandle = 12345; int shutdownHandle = 12345;
Mockery context = new Mockery(); Mockery context = new Mockery();
final Database<Object> database = context.mock(Database.class); Database<Object> database = context.mock(Database.class);
final ShutdownManager shutdown = context.mock(ShutdownManager.class); ShutdownManager shutdown = context.mock(ShutdownManager.class);
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
final MessageId messageId2 = new MessageId(TestUtils.getRandomId()); MessageId messageId2 = new MessageId(TestUtils.getRandomId());
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// open() // open()
oneOf(database).open(); oneOf(database).open();

View File

@@ -464,11 +464,11 @@ public class H2DatabaseTest extends BrambleTestCase {
@Test @Test
public void testCloseWaitsForCommit() throws Exception { public void testCloseWaitsForCommit() throws Exception {
final CountDownLatch closing = new CountDownLatch(1); CountDownLatch closing = new CountDownLatch(1);
final CountDownLatch closed = new CountDownLatch(1); CountDownLatch closed = new CountDownLatch(1);
final AtomicBoolean transactionFinished = new AtomicBoolean(false); AtomicBoolean transactionFinished = new AtomicBoolean(false);
final AtomicBoolean error = new AtomicBoolean(false); AtomicBoolean error = new AtomicBoolean(false);
final Database<Connection> db = open(false); Database<Connection> db = open(false);
// Start a transaction // Start a transaction
Connection txn = db.startTransaction(); Connection txn = db.startTransaction();
@@ -501,11 +501,11 @@ public class H2DatabaseTest extends BrambleTestCase {
@Test @Test
public void testCloseWaitsForAbort() throws Exception { public void testCloseWaitsForAbort() throws Exception {
final CountDownLatch closing = new CountDownLatch(1); CountDownLatch closing = new CountDownLatch(1);
final CountDownLatch closed = new CountDownLatch(1); CountDownLatch closed = new CountDownLatch(1);
final AtomicBoolean transactionFinished = new AtomicBoolean(false); AtomicBoolean transactionFinished = new AtomicBoolean(false);
final AtomicBoolean error = new AtomicBoolean(false); AtomicBoolean error = new AtomicBoolean(false);
final Database<Connection> db = open(false); Database<Connection> db = open(false);
// Start a transaction // Start a transaction
Connection txn = db.startTransaction(); Connection txn = db.startTransaction();

View File

@@ -17,11 +17,11 @@ public class LockFairnessTest extends BrambleTestCase {
@Test @Test
public void testReadersCanShareTheLock() throws Exception { public void testReadersCanShareTheLock() throws Exception {
// Use a fair lock // Use a fair lock
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true); ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
final CountDownLatch firstReaderHasLock = new CountDownLatch(1); CountDownLatch firstReaderHasLock = new CountDownLatch(1);
final CountDownLatch firstReaderHasFinished = new CountDownLatch(1); CountDownLatch firstReaderHasFinished = new CountDownLatch(1);
final CountDownLatch secondReaderHasLock = new CountDownLatch(1); CountDownLatch secondReaderHasLock = new CountDownLatch(1);
final CountDownLatch secondReaderHasFinished = new CountDownLatch(1); CountDownLatch secondReaderHasFinished = new CountDownLatch(1);
// First reader // First reader
Thread first = new Thread() { Thread first = new Thread() {
@Override @Override
@@ -76,13 +76,13 @@ public class LockFairnessTest extends BrambleTestCase {
@Test @Test
public void testWritersDoNotStarve() throws Exception { public void testWritersDoNotStarve() throws Exception {
// Use a fair lock // Use a fair lock
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true); ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
final CountDownLatch firstReaderHasLock = new CountDownLatch(1); CountDownLatch firstReaderHasLock = new CountDownLatch(1);
final CountDownLatch firstReaderHasFinished = new CountDownLatch(1); CountDownLatch firstReaderHasFinished = new CountDownLatch(1);
final CountDownLatch secondReaderHasFinished = new CountDownLatch(1); CountDownLatch secondReaderHasFinished = new CountDownLatch(1);
final CountDownLatch writerHasFinished = new CountDownLatch(1); CountDownLatch writerHasFinished = new CountDownLatch(1);
final AtomicBoolean secondReaderHasHeldLock = new AtomicBoolean(false); AtomicBoolean secondReaderHasHeldLock = new AtomicBoolean(false);
final AtomicBoolean writerHasHeldLock = new AtomicBoolean(false); AtomicBoolean writerHasHeldLock = new AtomicBoolean(false);
// First reader // First reader
Thread first = new Thread() { Thread first = new Thread() {
@Override @Override

View File

@@ -80,8 +80,8 @@ public class IdentityManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testGetAuthorStatus() throws DbException { public void testGetAuthorStatus() throws DbException {
final AuthorId authorId = new AuthorId(TestUtils.getRandomId()); AuthorId authorId = new AuthorId(TestUtils.getRandomId());
final Collection<Contact> contacts = new ArrayList<>(); Collection<Contact> contacts = new ArrayList<>();
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(true); oneOf(db).startTransaction(true);
@@ -125,8 +125,8 @@ public class IdentityManagerImplTest extends BrambleMockTestCase {
identityManager.getAuthorStatus(localAuthor.getId())); identityManager.getAuthorStatus(localAuthor.getId()));
} }
private void checkAuthorStatusContext(final AuthorId authorId, private void checkAuthorStatusContext(AuthorId authorId,
final Collection<Contact> contacts) throws DbException { Collection<Contact> contacts) throws DbException {
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(true); oneOf(db).startTransaction(true);
will(returnValue(txn)); will(returnValue(txn));

View File

@@ -65,11 +65,11 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
@Test @Test
public void testAliceProtocol() throws Exception { public void testAliceProtocol() throws Exception {
// set up // set up
final Payload theirPayload = new Payload(BOB_COMMIT, null); Payload theirPayload = new Payload(BOB_COMMIT, null);
final Payload ourPayload = new Payload(ALICE_COMMIT, null); Payload ourPayload = new Payload(ALICE_COMMIT, null);
final KeyPair ourKeyPair = new KeyPair(ourPubKey, null); KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
final SecretKey sharedSecret = TestUtils.getSecretKey(); SecretKey sharedSecret = TestUtils.getSecretKey();
final SecretKey masterSecret = TestUtils.getSecretKey(); SecretKey masterSecret = TestUtils.getSecretKey();
KeyAgreementProtocol protocol = KeyAgreementProtocol protocol =
new KeyAgreementProtocol(callbacks, crypto, payloadEncoder, new KeyAgreementProtocol(callbacks, crypto, payloadEncoder,
@@ -129,11 +129,11 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
@Test @Test
public void testBobProtocol() throws Exception { public void testBobProtocol() throws Exception {
// set up // set up
final Payload theirPayload = new Payload(ALICE_COMMIT, null); Payload theirPayload = new Payload(ALICE_COMMIT, null);
final Payload ourPayload = new Payload(BOB_COMMIT, null); Payload ourPayload = new Payload(BOB_COMMIT, null);
final KeyPair ourKeyPair = new KeyPair(ourPubKey, null); KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
final SecretKey sharedSecret = TestUtils.getSecretKey(); SecretKey sharedSecret = TestUtils.getSecretKey();
final SecretKey masterSecret = TestUtils.getSecretKey(); SecretKey masterSecret = TestUtils.getSecretKey();
KeyAgreementProtocol protocol = KeyAgreementProtocol protocol =
new KeyAgreementProtocol(callbacks, crypto, payloadEncoder, new KeyAgreementProtocol(callbacks, crypto, payloadEncoder,
@@ -192,9 +192,9 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
@Test(expected = AbortException.class) @Test(expected = AbortException.class)
public void testAliceProtocolAbortOnBadKey() throws Exception { public void testAliceProtocolAbortOnBadKey() throws Exception {
// set up // set up
final Payload theirPayload = new Payload(BOB_COMMIT, null); Payload theirPayload = new Payload(BOB_COMMIT, null);
final Payload ourPayload = new Payload(ALICE_COMMIT, null); Payload ourPayload = new Payload(ALICE_COMMIT, null);
final KeyPair ourKeyPair = new KeyPair(ourPubKey, null); KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
KeyAgreementProtocol protocol = KeyAgreementProtocol protocol =
new KeyAgreementProtocol(callbacks, crypto, payloadEncoder, new KeyAgreementProtocol(callbacks, crypto, payloadEncoder,
@@ -233,9 +233,9 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
@Test(expected = AbortException.class) @Test(expected = AbortException.class)
public void testBobProtocolAbortOnBadKey() throws Exception { public void testBobProtocolAbortOnBadKey() throws Exception {
// set up // set up
final Payload theirPayload = new Payload(ALICE_COMMIT, null); Payload theirPayload = new Payload(ALICE_COMMIT, null);
final Payload ourPayload = new Payload(BOB_COMMIT, null); Payload ourPayload = new Payload(BOB_COMMIT, null);
final KeyPair ourKeyPair = new KeyPair(ourPubKey, null); KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
KeyAgreementProtocol protocol = KeyAgreementProtocol protocol =
new KeyAgreementProtocol(callbacks, crypto, payloadEncoder, new KeyAgreementProtocol(callbacks, crypto, payloadEncoder,
@@ -270,10 +270,10 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
@Test(expected = AbortException.class) @Test(expected = AbortException.class)
public void testAliceProtocolAbortOnBadConfirm() throws Exception { public void testAliceProtocolAbortOnBadConfirm() throws Exception {
// set up // set up
final Payload theirPayload = new Payload(BOB_COMMIT, null); Payload theirPayload = new Payload(BOB_COMMIT, null);
final Payload ourPayload = new Payload(ALICE_COMMIT, null); Payload ourPayload = new Payload(ALICE_COMMIT, null);
final KeyPair ourKeyPair = new KeyPair(ourPubKey, null); KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
final SecretKey sharedSecret = TestUtils.getSecretKey(); SecretKey sharedSecret = TestUtils.getSecretKey();
KeyAgreementProtocol protocol = KeyAgreementProtocol protocol =
new KeyAgreementProtocol(callbacks, crypto, payloadEncoder, new KeyAgreementProtocol(callbacks, crypto, payloadEncoder,
@@ -335,10 +335,10 @@ public class KeyAgreementProtocolTest extends BrambleTestCase {
@Test(expected = AbortException.class) @Test(expected = AbortException.class)
public void testBobProtocolAbortOnBadConfirm() throws Exception { public void testBobProtocolAbortOnBadConfirm() throws Exception {
// set up // set up
final Payload theirPayload = new Payload(ALICE_COMMIT, null); Payload theirPayload = new Payload(ALICE_COMMIT, null);
final Payload ourPayload = new Payload(BOB_COMMIT, null); Payload ourPayload = new Payload(BOB_COMMIT, null);
final KeyPair ourKeyPair = new KeyPair(ourPubKey, null); KeyPair ourKeyPair = new KeyPair(ourPubKey, null);
final SecretKey sharedSecret = TestUtils.getSecretKey(); SecretKey sharedSecret = TestUtils.getSecretKey();
KeyAgreementProtocol protocol = KeyAgreementProtocol protocol =
new KeyAgreementProtocol(callbacks, crypto, payloadEncoder, new KeyAgreementProtocol(callbacks, crypto, payloadEncoder,

View File

@@ -35,7 +35,7 @@ public class ConnectionRegistryImplTest extends BrambleTestCase {
@Test @Test
public void testRegisterAndUnregister() { public void testRegisterAndUnregister() {
Mockery context = new Mockery(); Mockery context = new Mockery();
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
exactly(5).of(eventBus).broadcast(with(any( exactly(5).of(eventBus).broadcast(with(any(
ConnectionOpenedEvent.class))); ConnectionOpenedEvent.class)));

View File

@@ -30,36 +30,36 @@ public class PluginManagerImplTest extends BrambleTestCase {
Mockery context = new Mockery() {{ Mockery context = new Mockery() {{
setThreadingPolicy(new Synchroniser()); setThreadingPolicy(new Synchroniser());
}}; }};
final Executor ioExecutor = Executors.newSingleThreadExecutor(); Executor ioExecutor = Executors.newSingleThreadExecutor();
final EventBus eventBus = context.mock(EventBus.class); EventBus eventBus = context.mock(EventBus.class);
final PluginConfig pluginConfig = context.mock(PluginConfig.class); PluginConfig pluginConfig = context.mock(PluginConfig.class);
final ConnectionManager connectionManager = ConnectionManager connectionManager =
context.mock(ConnectionManager.class); context.mock(ConnectionManager.class);
final SettingsManager settingsManager = SettingsManager settingsManager =
context.mock(SettingsManager.class); context.mock(SettingsManager.class);
final TransportPropertyManager transportPropertyManager = TransportPropertyManager transportPropertyManager =
context.mock(TransportPropertyManager.class); context.mock(TransportPropertyManager.class);
final UiCallback uiCallback = context.mock(UiCallback.class); UiCallback uiCallback = context.mock(UiCallback.class);
// Two simplex plugin factories: both create plugins, one fails to start // Two simplex plugin factories: both create plugins, one fails to start
final SimplexPluginFactory simplexFactory = SimplexPluginFactory simplexFactory =
context.mock(SimplexPluginFactory.class); context.mock(SimplexPluginFactory.class);
final SimplexPlugin simplexPlugin = context.mock(SimplexPlugin.class); SimplexPlugin simplexPlugin = context.mock(SimplexPlugin.class);
final TransportId simplexId = new TransportId("simplex"); TransportId simplexId = new TransportId("simplex");
final SimplexPluginFactory simplexFailFactory = SimplexPluginFactory simplexFailFactory =
context.mock(SimplexPluginFactory.class, "simplexFailFactory"); context.mock(SimplexPluginFactory.class, "simplexFailFactory");
final SimplexPlugin simplexFailPlugin = SimplexPlugin simplexFailPlugin =
context.mock(SimplexPlugin.class, "simplexFailPlugin"); context.mock(SimplexPlugin.class, "simplexFailPlugin");
final TransportId simplexFailId = new TransportId("simplex1"); TransportId simplexFailId = new TransportId("simplex1");
// Two duplex plugin factories: one creates a plugin, the other fails // Two duplex plugin factories: one creates a plugin, the other fails
final DuplexPluginFactory duplexFactory = DuplexPluginFactory duplexFactory =
context.mock(DuplexPluginFactory.class); context.mock(DuplexPluginFactory.class);
final DuplexPlugin duplexPlugin = context.mock(DuplexPlugin.class); DuplexPlugin duplexPlugin = context.mock(DuplexPlugin.class);
final TransportId duplexId = new TransportId("duplex"); TransportId duplexId = new TransportId("duplex");
final DuplexPluginFactory duplexFailFactory = DuplexPluginFactory duplexFailFactory =
context.mock(DuplexPluginFactory.class, "duplexFailFactory"); context.mock(DuplexPluginFactory.class, "duplexFailFactory");
final TransportId duplexFailId = new TransportId("duplex1"); TransportId duplexFailId = new TransportId("duplex1");
context.checking(new Expectations() {{ context.checking(new Expectations() {{
allowing(simplexPlugin).getId(); allowing(simplexPlugin).getId();

View File

@@ -42,35 +42,35 @@ public class PollerTest extends BrambleTestCase {
public void testConnectOnContactStatusChanged() throws Exception { public void testConnectOnContactStatusChanged() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
context.setImposteriser(ClassImposteriser.INSTANCE); context.setImposteriser(ClassImposteriser.INSTANCE);
final Executor ioExecutor = new ImmediateExecutor(); Executor ioExecutor = new ImmediateExecutor();
final ScheduledExecutorService scheduler = ScheduledExecutorService scheduler =
context.mock(ScheduledExecutorService.class); context.mock(ScheduledExecutorService.class);
final ConnectionManager connectionManager = ConnectionManager connectionManager =
context.mock(ConnectionManager.class); context.mock(ConnectionManager.class);
final ConnectionRegistry connectionRegistry = ConnectionRegistry connectionRegistry =
context.mock(ConnectionRegistry.class); context.mock(ConnectionRegistry.class);
final PluginManager pluginManager = context.mock(PluginManager.class); PluginManager pluginManager = context.mock(PluginManager.class);
final SecureRandom random = context.mock(SecureRandom.class); SecureRandom random = context.mock(SecureRandom.class);
final Clock clock = context.mock(Clock.class); Clock clock = context.mock(Clock.class);
// Two simplex plugins: one supports polling, the other doesn't // Two simplex plugins: one supports polling, the other doesn't
final SimplexPlugin simplexPlugin = context.mock(SimplexPlugin.class); SimplexPlugin simplexPlugin = context.mock(SimplexPlugin.class);
final SimplexPlugin simplexPlugin1 = SimplexPlugin simplexPlugin1 =
context.mock(SimplexPlugin.class, "simplexPlugin1"); context.mock(SimplexPlugin.class, "simplexPlugin1");
final TransportId simplexId1 = new TransportId("simplex1"); TransportId simplexId1 = new TransportId("simplex1");
final List<SimplexPlugin> simplexPlugins = Arrays.asList(simplexPlugin, List<SimplexPlugin> simplexPlugins = Arrays.asList(simplexPlugin,
simplexPlugin1); simplexPlugin1);
final TransportConnectionWriter simplexWriter = TransportConnectionWriter simplexWriter =
context.mock(TransportConnectionWriter.class); context.mock(TransportConnectionWriter.class);
// Two duplex plugins: one supports polling, the other doesn't // Two duplex plugins: one supports polling, the other doesn't
final DuplexPlugin duplexPlugin = context.mock(DuplexPlugin.class); DuplexPlugin duplexPlugin = context.mock(DuplexPlugin.class);
final TransportId duplexId = new TransportId("duplex"); TransportId duplexId = new TransportId("duplex");
final DuplexPlugin duplexPlugin1 = DuplexPlugin duplexPlugin1 =
context.mock(DuplexPlugin.class, "duplexPlugin1"); context.mock(DuplexPlugin.class, "duplexPlugin1");
final List<DuplexPlugin> duplexPlugins = Arrays.asList(duplexPlugin, List<DuplexPlugin> duplexPlugins = Arrays.asList(duplexPlugin,
duplexPlugin1); duplexPlugin1);
final DuplexTransportConnection duplexConnection = DuplexTransportConnection duplexConnection =
context.mock(DuplexTransportConnection.class); context.mock(DuplexTransportConnection.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
@@ -129,20 +129,20 @@ public class PollerTest extends BrambleTestCase {
throws Exception { throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
context.setImposteriser(ClassImposteriser.INSTANCE); context.setImposteriser(ClassImposteriser.INSTANCE);
final Executor ioExecutor = new ImmediateExecutor(); Executor ioExecutor = new ImmediateExecutor();
final ScheduledExecutorService scheduler = ScheduledExecutorService scheduler =
context.mock(ScheduledExecutorService.class); context.mock(ScheduledExecutorService.class);
final ConnectionManager connectionManager = ConnectionManager connectionManager =
context.mock(ConnectionManager.class); context.mock(ConnectionManager.class);
final ConnectionRegistry connectionRegistry = ConnectionRegistry connectionRegistry =
context.mock(ConnectionRegistry.class); context.mock(ConnectionRegistry.class);
final PluginManager pluginManager = context.mock(PluginManager.class); PluginManager pluginManager = context.mock(PluginManager.class);
final SecureRandom random = context.mock(SecureRandom.class); SecureRandom random = context.mock(SecureRandom.class);
final Clock clock = context.mock(Clock.class); Clock clock = context.mock(Clock.class);
final DuplexPlugin plugin = context.mock(DuplexPlugin.class); DuplexPlugin plugin = context.mock(DuplexPlugin.class);
final TransportId transportId = new TransportId("id"); TransportId transportId = new TransportId("id");
final DuplexTransportConnection duplexConnection = DuplexTransportConnection duplexConnection =
context.mock(DuplexTransportConnection.class); context.mock(DuplexTransportConnection.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
@@ -194,19 +194,19 @@ public class PollerTest extends BrambleTestCase {
public void testRescheduleOnConnectionOpened() throws Exception { public void testRescheduleOnConnectionOpened() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
context.setImposteriser(ClassImposteriser.INSTANCE); context.setImposteriser(ClassImposteriser.INSTANCE);
final Executor ioExecutor = new ImmediateExecutor(); Executor ioExecutor = new ImmediateExecutor();
final ScheduledExecutorService scheduler = ScheduledExecutorService scheduler =
context.mock(ScheduledExecutorService.class); context.mock(ScheduledExecutorService.class);
final ConnectionManager connectionManager = ConnectionManager connectionManager =
context.mock(ConnectionManager.class); context.mock(ConnectionManager.class);
final ConnectionRegistry connectionRegistry = ConnectionRegistry connectionRegistry =
context.mock(ConnectionRegistry.class); context.mock(ConnectionRegistry.class);
final PluginManager pluginManager = context.mock(PluginManager.class); PluginManager pluginManager = context.mock(PluginManager.class);
final SecureRandom random = context.mock(SecureRandom.class); SecureRandom random = context.mock(SecureRandom.class);
final Clock clock = context.mock(Clock.class); Clock clock = context.mock(Clock.class);
final DuplexPlugin plugin = context.mock(DuplexPlugin.class); DuplexPlugin plugin = context.mock(DuplexPlugin.class);
final TransportId transportId = new TransportId("id"); TransportId transportId = new TransportId("id");
context.checking(new Expectations() {{ context.checking(new Expectations() {{
allowing(plugin).getId(); allowing(plugin).getId();
@@ -239,19 +239,19 @@ public class PollerTest extends BrambleTestCase {
public void testRescheduleDoesNotReplaceEarlierTask() throws Exception { public void testRescheduleDoesNotReplaceEarlierTask() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
context.setImposteriser(ClassImposteriser.INSTANCE); context.setImposteriser(ClassImposteriser.INSTANCE);
final Executor ioExecutor = new ImmediateExecutor(); Executor ioExecutor = new ImmediateExecutor();
final ScheduledExecutorService scheduler = ScheduledExecutorService scheduler =
context.mock(ScheduledExecutorService.class); context.mock(ScheduledExecutorService.class);
final ConnectionManager connectionManager = ConnectionManager connectionManager =
context.mock(ConnectionManager.class); context.mock(ConnectionManager.class);
final ConnectionRegistry connectionRegistry = ConnectionRegistry connectionRegistry =
context.mock(ConnectionRegistry.class); context.mock(ConnectionRegistry.class);
final PluginManager pluginManager = context.mock(PluginManager.class); PluginManager pluginManager = context.mock(PluginManager.class);
final SecureRandom random = context.mock(SecureRandom.class); SecureRandom random = context.mock(SecureRandom.class);
final Clock clock = context.mock(Clock.class); Clock clock = context.mock(Clock.class);
final DuplexPlugin plugin = context.mock(DuplexPlugin.class); DuplexPlugin plugin = context.mock(DuplexPlugin.class);
final TransportId transportId = new TransportId("id"); TransportId transportId = new TransportId("id");
context.checking(new Expectations() {{ context.checking(new Expectations() {{
allowing(plugin).getId(); allowing(plugin).getId();
@@ -299,20 +299,20 @@ public class PollerTest extends BrambleTestCase {
public void testPollOnTransportEnabled() throws Exception { public void testPollOnTransportEnabled() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
context.setImposteriser(ClassImposteriser.INSTANCE); context.setImposteriser(ClassImposteriser.INSTANCE);
final Executor ioExecutor = new ImmediateExecutor(); Executor ioExecutor = new ImmediateExecutor();
final ScheduledExecutorService scheduler = ScheduledExecutorService scheduler =
context.mock(ScheduledExecutorService.class); context.mock(ScheduledExecutorService.class);
final ConnectionManager connectionManager = ConnectionManager connectionManager =
context.mock(ConnectionManager.class); context.mock(ConnectionManager.class);
final ConnectionRegistry connectionRegistry = ConnectionRegistry connectionRegistry =
context.mock(ConnectionRegistry.class); context.mock(ConnectionRegistry.class);
final PluginManager pluginManager = context.mock(PluginManager.class); PluginManager pluginManager = context.mock(PluginManager.class);
final SecureRandom random = context.mock(SecureRandom.class); SecureRandom random = context.mock(SecureRandom.class);
final Clock clock = context.mock(Clock.class); Clock clock = context.mock(Clock.class);
final Plugin plugin = context.mock(Plugin.class); Plugin plugin = context.mock(Plugin.class);
final TransportId transportId = new TransportId("id"); TransportId transportId = new TransportId("id");
final List<ContactId> connected = Collections.singletonList(contactId); List<ContactId> connected = Collections.singletonList(contactId);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
allowing(plugin).getId(); allowing(plugin).getId();

View File

@@ -145,11 +145,11 @@ public class LanTcpPluginTest extends BrambleTestCase {
assertEquals(2, split.length); assertEquals(2, split.length);
String addrString = split[0]; String addrString = split[0];
// Listen on the same interface as the plugin // Listen on the same interface as the plugin
final ServerSocket ss = new ServerSocket(); ServerSocket ss = new ServerSocket();
ss.bind(new InetSocketAddress(addrString, 0), 10); ss.bind(new InetSocketAddress(addrString, 0), 10);
int port = ss.getLocalPort(); int port = ss.getLocalPort();
final CountDownLatch latch = new CountDownLatch(1); CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean error = new AtomicBoolean(false); AtomicBoolean error = new AtomicBoolean(false);
new Thread() { new Thread() {
@Override @Override
public void run() { public void run() {
@@ -239,10 +239,10 @@ public class LanTcpPluginTest extends BrambleTestCase {
assertEquals(2, split.length); assertEquals(2, split.length);
String addrString = split[0]; String addrString = split[0];
// Listen on the same interface as the plugin // Listen on the same interface as the plugin
final ServerSocket ss = new ServerSocket(); ServerSocket ss = new ServerSocket();
ss.bind(new InetSocketAddress(addrString, 0), 10); ss.bind(new InetSocketAddress(addrString, 0), 10);
final CountDownLatch latch = new CountDownLatch(1); CountDownLatch latch = new CountDownLatch(1);
final AtomicBoolean error = new AtomicBoolean(false); AtomicBoolean error = new AtomicBoolean(false);
new Thread() { new Thread() {
@Override @Override
public void run() { public void run() {

View File

@@ -87,11 +87,11 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testCreatesGroupsAtStartup() throws Exception { public void testCreatesGroupsAtStartup() throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
final Contact contact1 = getContact(true); Contact contact1 = getContact(true);
final Contact contact2 = getContact(true); Contact contact2 = getContact(true);
final List<Contact> contacts = Arrays.asList(contact1, contact2); List<Contact> contacts = Arrays.asList(contact1, contact2);
final Group contactGroup1 = getGroup(), contactGroup2 = getGroup(); Group contactGroup1 = getGroup(), contactGroup2 = getGroup();
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).addGroup(txn, localGroup); oneOf(db).addGroup(txn, localGroup);
@@ -124,9 +124,9 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testCreatesGroupWhenAddingContact() throws Exception { public void testCreatesGroupWhenAddingContact() throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
final Contact contact = getContact(true); Contact contact = getContact(true);
final Group contactGroup = getGroup(); Group contactGroup = getGroup();
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Create the group and share it with the contact // Create the group and share it with the contact
@@ -151,9 +151,9 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testRemovesGroupWhenRemovingContact() throws Exception { public void testRemovesGroupWhenRemovingContact() throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
final Contact contact = getContact(true); Contact contact = getContact(true);
final Group contactGroup = getGroup(); Group contactGroup = getGroup();
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(contactGroupFactory).createContactGroup(CLIENT_ID, contact); oneOf(contactGroupFactory).createContactGroup(CLIENT_ID, contact);
@@ -168,17 +168,17 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testDoesNotDeleteAnythingWhenFirstUpdateIsDelivered() public void testDoesNotDeleteAnythingWhenFirstUpdateIsDelivered()
throws Exception { throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
final GroupId contactGroupId = new GroupId(getRandomId()); GroupId contactGroupId = new GroupId(getRandomId());
final long timestamp = 123456789; long timestamp = 123456789;
final Message message = getMessage(contactGroupId, timestamp); Message message = getMessage(contactGroupId, timestamp);
final Metadata meta = new Metadata(); Metadata meta = new Metadata();
final BdfDictionary metaDictionary = BdfDictionary.of( BdfDictionary metaDictionary = BdfDictionary.of(
new BdfEntry("transportId", "foo"), new BdfEntry("transportId", "foo"),
new BdfEntry("version", 2), new BdfEntry("version", 2),
new BdfEntry("local", false) new BdfEntry("local", false)
); );
final Map<MessageId, BdfDictionary> messageMetadata = Map<MessageId, BdfDictionary> messageMetadata =
new LinkedHashMap<>(); new LinkedHashMap<>();
// A remote update for another transport should be ignored // A remote update for another transport should be ignored
MessageId barUpdateId = new MessageId(getRandomId()); MessageId barUpdateId = new MessageId(getRandomId());
@@ -210,32 +210,32 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testDeletesOlderUpdatesWhenUpdateIsDelivered() public void testDeletesOlderUpdatesWhenUpdateIsDelivered()
throws Exception { throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
final GroupId contactGroupId = new GroupId(getRandomId()); GroupId contactGroupId = new GroupId(getRandomId());
final long timestamp = 123456789; long timestamp = 123456789;
final Message message = getMessage(contactGroupId, timestamp); Message message = getMessage(contactGroupId, timestamp);
final Metadata meta = new Metadata(); Metadata meta = new Metadata();
final BdfDictionary metaDictionary = BdfDictionary.of( BdfDictionary metaDictionary = BdfDictionary.of(
new BdfEntry("transportId", "foo"), new BdfEntry("transportId", "foo"),
new BdfEntry("version", 4), new BdfEntry("version", 4),
new BdfEntry("local", false) new BdfEntry("local", false)
); );
final Map<MessageId, BdfDictionary> messageMetadata = Map<MessageId, BdfDictionary> messageMetadata =
new LinkedHashMap<>(); new LinkedHashMap<>();
// Old remote updates for the same transport should be deleted // Old remote updates for the same transport should be deleted
final MessageId fooVersion2 = new MessageId(getRandomId()); MessageId fooVersion2 = new MessageId(getRandomId());
messageMetadata.put(fooVersion2, BdfDictionary.of( messageMetadata.put(fooVersion2, BdfDictionary.of(
new BdfEntry("transportId", "foo"), new BdfEntry("transportId", "foo"),
new BdfEntry("version", 2), new BdfEntry("version", 2),
new BdfEntry("local", false) new BdfEntry("local", false)
)); ));
final MessageId fooVersion1 = new MessageId(getRandomId()); MessageId fooVersion1 = new MessageId(getRandomId());
messageMetadata.put(fooVersion1, BdfDictionary.of( messageMetadata.put(fooVersion1, BdfDictionary.of(
new BdfEntry("transportId", "foo"), new BdfEntry("transportId", "foo"),
new BdfEntry("version", 1), new BdfEntry("version", 1),
new BdfEntry("local", false) new BdfEntry("local", false)
)); ));
final MessageId fooVersion3 = new MessageId(getRandomId()); MessageId fooVersion3 = new MessageId(getRandomId());
messageMetadata.put(fooVersion3, BdfDictionary.of( messageMetadata.put(fooVersion3, BdfDictionary.of(
new BdfEntry("transportId", "foo"), new BdfEntry("transportId", "foo"),
new BdfEntry("version", 3), new BdfEntry("version", 3),
@@ -263,33 +263,33 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testDeletesObsoleteUpdateWhenDelivered() throws Exception { public void testDeletesObsoleteUpdateWhenDelivered() throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
final GroupId contactGroupId = new GroupId(getRandomId()); GroupId contactGroupId = new GroupId(getRandomId());
final long timestamp = 123456789; long timestamp = 123456789;
final Message message = getMessage(contactGroupId, timestamp); Message message = getMessage(contactGroupId, timestamp);
final Metadata meta = new Metadata(); Metadata meta = new Metadata();
final BdfDictionary metaDictionary = BdfDictionary.of( BdfDictionary metaDictionary = BdfDictionary.of(
new BdfEntry("transportId", "foo"), new BdfEntry("transportId", "foo"),
new BdfEntry("version", 3), new BdfEntry("version", 3),
new BdfEntry("local", false) new BdfEntry("local", false)
); );
final Map<MessageId, BdfDictionary> messageMetadata = Map<MessageId, BdfDictionary> messageMetadata =
new LinkedHashMap<>(); new LinkedHashMap<>();
// Old remote updates for the same transport should be deleted // Old remote updates for the same transport should be deleted
final MessageId fooVersion2 = new MessageId(getRandomId()); MessageId fooVersion2 = new MessageId(getRandomId());
messageMetadata.put(fooVersion2, BdfDictionary.of( messageMetadata.put(fooVersion2, BdfDictionary.of(
new BdfEntry("transportId", "foo"), new BdfEntry("transportId", "foo"),
new BdfEntry("version", 2), new BdfEntry("version", 2),
new BdfEntry("local", false) new BdfEntry("local", false)
)); ));
final MessageId fooVersion1 = new MessageId(getRandomId()); MessageId fooVersion1 = new MessageId(getRandomId());
messageMetadata.put(fooVersion1, BdfDictionary.of( messageMetadata.put(fooVersion1, BdfDictionary.of(
new BdfEntry("transportId", "foo"), new BdfEntry("transportId", "foo"),
new BdfEntry("version", 1), new BdfEntry("version", 1),
new BdfEntry("local", false) new BdfEntry("local", false)
)); ));
// A newer remote update for the same transport should not be deleted // A newer remote update for the same transport should not be deleted
final MessageId fooVersion4 = new MessageId(getRandomId()); MessageId fooVersion4 = new MessageId(getRandomId());
messageMetadata.put(fooVersion4, BdfDictionary.of( messageMetadata.put(fooVersion4, BdfDictionary.of(
new BdfEntry("transportId", "foo"), new BdfEntry("transportId", "foo"),
new BdfEntry("version", 4), new BdfEntry("version", 4),
@@ -318,9 +318,9 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testStoresRemotePropertiesWithVersion0() throws Exception { public void testStoresRemotePropertiesWithVersion0() throws Exception {
final Contact contact = getContact(true); Contact contact = getContact(true);
final Group contactGroup = getGroup(); Group contactGroup = getGroup();
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
Map<TransportId, TransportProperties> properties = Map<TransportId, TransportProperties> properties =
new LinkedHashMap<>(); new LinkedHashMap<>();
properties.put(new TransportId("foo"), fooProperties); properties.put(new TransportId("foo"), fooProperties);
@@ -357,8 +357,8 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testReturnsEmptyPropertiesIfNoLocalPropertiesAreFound() public void testReturnsEmptyPropertiesIfNoLocalPropertiesAreFound()
throws Exception { throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
final Map<MessageId, BdfDictionary> messageMetadata = Map<MessageId, BdfDictionary> messageMetadata =
new LinkedHashMap<>(); new LinkedHashMap<>();
// A local update for another transport should be ignored // A local update for another transport should be ignored
MessageId barUpdateId = new MessageId(getRandomId()); MessageId barUpdateId = new MessageId(getRandomId());
@@ -384,8 +384,8 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testReturnsLocalProperties() throws Exception { public void testReturnsLocalProperties() throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
final Map<MessageId, BdfDictionary> messageMetadata = Map<MessageId, BdfDictionary> messageMetadata =
new LinkedHashMap<>(); new LinkedHashMap<>();
// A local update for another transport should be ignored // A local update for another transport should be ignored
MessageId barUpdateId = new MessageId(getRandomId()); MessageId barUpdateId = new MessageId(getRandomId());
@@ -395,13 +395,13 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
new BdfEntry("local", true) new BdfEntry("local", true)
)); ));
// A local update for the right transport should be returned // A local update for the right transport should be returned
final MessageId fooUpdateId = new MessageId(getRandomId()); MessageId fooUpdateId = new MessageId(getRandomId());
messageMetadata.put(fooUpdateId, BdfDictionary.of( messageMetadata.put(fooUpdateId, BdfDictionary.of(
new BdfEntry("transportId", "foo"), new BdfEntry("transportId", "foo"),
new BdfEntry("version", 1), new BdfEntry("version", 1),
new BdfEntry("local", true) new BdfEntry("local", true)
)); ));
final BdfList fooUpdate = BdfList.of("foo", 1, fooPropertiesDict); BdfList fooUpdate = BdfList.of("foo", 1, fooPropertiesDict);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(false); oneOf(db).startTransaction(false);
@@ -423,15 +423,15 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testReturnsRemotePropertiesOrEmptyProperties() public void testReturnsRemotePropertiesOrEmptyProperties()
throws Exception { throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
Contact contact1 = getContact(false); Contact contact1 = getContact(false);
final Contact contact2 = getContact(true); Contact contact2 = getContact(true);
final Contact contact3 = getContact(true); Contact contact3 = getContact(true);
final List<Contact> contacts = List<Contact> contacts =
Arrays.asList(contact1, contact2, contact3); Arrays.asList(contact1, contact2, contact3);
final Group contactGroup2 = getGroup(); Group contactGroup2 = getGroup();
final Group contactGroup3 = getGroup(); Group contactGroup3 = getGroup();
final Map<MessageId, BdfDictionary> messageMetadata3 = Map<MessageId, BdfDictionary> messageMetadata3 =
new LinkedHashMap<>(); new LinkedHashMap<>();
// A remote update for another transport should be ignored // A remote update for another transport should be ignored
MessageId barUpdateId = new MessageId(getRandomId()); MessageId barUpdateId = new MessageId(getRandomId());
@@ -448,13 +448,13 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
new BdfEntry("local", true) new BdfEntry("local", true)
)); ));
// A remote update for the right transport should be returned // A remote update for the right transport should be returned
final MessageId fooUpdateId = new MessageId(getRandomId()); MessageId fooUpdateId = new MessageId(getRandomId());
messageMetadata3.put(fooUpdateId, BdfDictionary.of( messageMetadata3.put(fooUpdateId, BdfDictionary.of(
new BdfEntry("transportId", "foo"), new BdfEntry("transportId", "foo"),
new BdfEntry("version", 1), new BdfEntry("version", 1),
new BdfEntry("local", false) new BdfEntry("local", false)
)); ));
final BdfList fooUpdate = BdfList.of("foo", 1, fooPropertiesDict); BdfList fooUpdate = BdfList.of("foo", 1, fooPropertiesDict);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(false); oneOf(db).startTransaction(false);
@@ -492,15 +492,15 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testMergingUnchangedPropertiesDoesNotCreateUpdate() public void testMergingUnchangedPropertiesDoesNotCreateUpdate()
throws Exception { throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
final MessageId updateId = new MessageId(getRandomId()); MessageId updateId = new MessageId(getRandomId());
final Map<MessageId, BdfDictionary> messageMetadata = Map<MessageId, BdfDictionary> messageMetadata =
Collections.singletonMap(updateId, BdfDictionary.of( Collections.singletonMap(updateId, BdfDictionary.of(
new BdfEntry("transportId", "foo"), new BdfEntry("transportId", "foo"),
new BdfEntry("version", 1), new BdfEntry("version", 1),
new BdfEntry("local", true) new BdfEntry("local", true)
)); ));
final BdfList update = BdfList.of("foo", 1, fooPropertiesDict); BdfList update = BdfList.of("foo", 1, fooPropertiesDict);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(false); oneOf(db).startTransaction(false);
@@ -522,9 +522,9 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testMergingNewPropertiesCreatesUpdate() throws Exception { public void testMergingNewPropertiesCreatesUpdate() throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
final Contact contact = getContact(true); Contact contact = getContact(true);
final Group contactGroup = getGroup(); Group contactGroup = getGroup();
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(db).startTransaction(false); oneOf(db).startTransaction(false);
@@ -556,21 +556,21 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testMergingUpdatedPropertiesCreatesUpdate() throws Exception { public void testMergingUpdatedPropertiesCreatesUpdate() throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
final Contact contact = getContact(true); Contact contact = getContact(true);
final Group contactGroup = getGroup(); Group contactGroup = getGroup();
BdfDictionary oldMetadata = BdfDictionary.of( BdfDictionary oldMetadata = BdfDictionary.of(
new BdfEntry("transportId", "foo"), new BdfEntry("transportId", "foo"),
new BdfEntry("version", 1), new BdfEntry("version", 1),
new BdfEntry("local", true) new BdfEntry("local", true)
); );
final MessageId localGroupUpdateId = new MessageId(getRandomId()); MessageId localGroupUpdateId = new MessageId(getRandomId());
final Map<MessageId, BdfDictionary> localGroupMessageMetadata = Map<MessageId, BdfDictionary> localGroupMessageMetadata =
Collections.singletonMap(localGroupUpdateId, oldMetadata); Collections.singletonMap(localGroupUpdateId, oldMetadata);
final MessageId contactGroupUpdateId = new MessageId(getRandomId()); MessageId contactGroupUpdateId = new MessageId(getRandomId());
final Map<MessageId, BdfDictionary> contactGroupMessageMetadata = Map<MessageId, BdfDictionary> contactGroupMessageMetadata =
Collections.singletonMap(contactGroupUpdateId, oldMetadata); Collections.singletonMap(contactGroupUpdateId, oldMetadata);
final BdfList oldUpdate = BdfList.of("foo", 1, BdfDictionary.of( BdfList oldUpdate = BdfList.of("foo", 1, BdfDictionary.of(
new BdfEntry("fooKey1", "oldFooValue1") new BdfEntry("fooKey1", "oldFooValue1")
)); ));
@@ -638,36 +638,36 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
return new Message(messageId, g, timestamp, raw); return new Message(messageId, g, timestamp, raw);
} }
private void expectGetLocalProperties(final Transaction txn) private void expectGetLocalProperties(Transaction txn)
throws Exception { throws Exception {
final Map<MessageId, BdfDictionary> messageMetadata = Map<MessageId, BdfDictionary> messageMetadata =
new LinkedHashMap<>(); new LinkedHashMap<>();
// The only update for transport "foo" should be returned // The only update for transport "foo" should be returned
final MessageId fooVersion999 = new MessageId(getRandomId()); MessageId fooVersion999 = new MessageId(getRandomId());
messageMetadata.put(fooVersion999, BdfDictionary.of( messageMetadata.put(fooVersion999, BdfDictionary.of(
new BdfEntry("transportId", "foo"), new BdfEntry("transportId", "foo"),
new BdfEntry("version", 999) new BdfEntry("version", 999)
)); ));
// An old update for transport "bar" should be deleted // An old update for transport "bar" should be deleted
final MessageId barVersion2 = new MessageId(getRandomId()); MessageId barVersion2 = new MessageId(getRandomId());
messageMetadata.put(barVersion2, BdfDictionary.of( messageMetadata.put(barVersion2, BdfDictionary.of(
new BdfEntry("transportId", "bar"), new BdfEntry("transportId", "bar"),
new BdfEntry("version", 2) new BdfEntry("version", 2)
)); ));
// An even older update for transport "bar" should be deleted // An even older update for transport "bar" should be deleted
final MessageId barVersion1 = new MessageId(getRandomId()); MessageId barVersion1 = new MessageId(getRandomId());
messageMetadata.put(barVersion1, BdfDictionary.of( messageMetadata.put(barVersion1, BdfDictionary.of(
new BdfEntry("transportId", "bar"), new BdfEntry("transportId", "bar"),
new BdfEntry("version", 1) new BdfEntry("version", 1)
)); ));
// The latest update for transport "bar" should be returned // The latest update for transport "bar" should be returned
final MessageId barVersion3 = new MessageId(getRandomId()); MessageId barVersion3 = new MessageId(getRandomId());
messageMetadata.put(barVersion3, BdfDictionary.of( messageMetadata.put(barVersion3, BdfDictionary.of(
new BdfEntry("transportId", "bar"), new BdfEntry("transportId", "bar"),
new BdfEntry("version", 3) new BdfEntry("version", 3)
)); ));
final BdfList fooUpdate = BdfList.of("foo", 999, fooPropertiesDict); BdfList fooUpdate = BdfList.of("foo", 999, fooPropertiesDict);
final BdfList barUpdate = BdfList.of("bar", 3, barPropertiesDict); BdfList barUpdate = BdfList.of("bar", 3, barPropertiesDict);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Find the latest local update for each transport // Find the latest local update for each transport
@@ -684,13 +684,13 @@ public class TransportPropertyManagerImplTest extends BrambleMockTestCase {
}}); }});
} }
private void expectStoreMessage(final Transaction txn, final GroupId g, private void expectStoreMessage(Transaction txn, GroupId g,
String transportId, final BdfDictionary properties, long version, String transportId, BdfDictionary properties, long version,
boolean local, final boolean shared) throws Exception { boolean local, boolean shared) throws Exception {
final long timestamp = 123456789; long timestamp = 123456789;
final BdfList body = BdfList.of(transportId, version, properties); BdfList body = BdfList.of(transportId, version, properties);
final Message message = getMessage(g, timestamp); Message message = getMessage(g, timestamp);
final BdfDictionary meta = BdfDictionary.of( BdfDictionary meta = BdfDictionary.of(
new BdfEntry("transportId", transportId), new BdfEntry("transportId", transportId),
new BdfEntry("version", version), new BdfEntry("version", version),
new BdfEntry("local", local) new BdfEntry("local", local)

View File

@@ -6,10 +6,10 @@ import org.briarproject.bramble.api.db.Transaction;
import org.briarproject.bramble.api.event.EventBus; import org.briarproject.bramble.api.event.EventBus;
import org.briarproject.bramble.api.sync.Ack; import org.briarproject.bramble.api.sync.Ack;
import org.briarproject.bramble.api.sync.MessageId; import org.briarproject.bramble.api.sync.MessageId;
import org.briarproject.bramble.api.sync.RecordWriter;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.briarproject.bramble.test.ImmediateExecutor; import org.briarproject.bramble.test.ImmediateExecutor;
import org.briarproject.bramble.test.TestUtils; import org.briarproject.bramble.test.TestUtils;
import org.briarproject.bramble.api.sync.RecordWriter;
import org.jmock.Expectations; import org.jmock.Expectations;
import org.jmock.Mockery; import org.jmock.Mockery;
import org.junit.Test; import org.junit.Test;
@@ -44,10 +44,10 @@ public class SimplexOutgoingSessionTest extends BrambleTestCase {
@Test @Test
public void testNothingToSend() throws Exception { public void testNothingToSend() throws Exception {
final SimplexOutgoingSession session = new SimplexOutgoingSession(db, SimplexOutgoingSession session = new SimplexOutgoingSession(db,
dbExecutor, eventBus, contactId, maxLatency, recordWriter); dbExecutor, eventBus, contactId, maxLatency, recordWriter);
final Transaction noAckTxn = new Transaction(null, false); Transaction noAckTxn = new Transaction(null, false);
final Transaction noMsgTxn = new Transaction(null, false); Transaction noMsgTxn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Add listener // Add listener
@@ -80,14 +80,14 @@ public class SimplexOutgoingSessionTest extends BrambleTestCase {
@Test @Test
public void testSomethingToSend() throws Exception { public void testSomethingToSend() throws Exception {
final Ack ack = new Ack(Collections.singletonList(messageId)); Ack ack = new Ack(Collections.singletonList(messageId));
final byte[] raw = new byte[1234]; byte[] raw = new byte[1234];
final SimplexOutgoingSession session = new SimplexOutgoingSession(db, SimplexOutgoingSession session = new SimplexOutgoingSession(db,
dbExecutor, eventBus, contactId, maxLatency, recordWriter); dbExecutor, eventBus, contactId, maxLatency, recordWriter);
final Transaction ackTxn = new Transaction(null, false); Transaction ackTxn = new Transaction(null, false);
final Transaction noAckTxn = new Transaction(null, false); Transaction noAckTxn = new Transaction(null, false);
final Transaction msgTxn = new Transaction(null, false); Transaction msgTxn = new Transaction(null, false);
final Transaction noMsgTxn = new Transaction(null, false); Transaction noMsgTxn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Add listener // Add listener

View File

@@ -92,9 +92,9 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testStartAndStop() throws Exception { public void testStartAndStop() throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Transaction txn1 = new Transaction(null, true); Transaction txn1 = new Transaction(null, true);
final Transaction txn2 = new Transaction(null, true); Transaction txn2 = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// validateOutstandingMessages() // validateOutstandingMessages()
@@ -126,13 +126,13 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testMessagesAreValidatedAtStartup() throws Exception { public void testMessagesAreValidatedAtStartup() throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Transaction txn1 = new Transaction(null, true); Transaction txn1 = new Transaction(null, true);
final Transaction txn2 = new Transaction(null, false); Transaction txn2 = new Transaction(null, false);
final Transaction txn3 = new Transaction(null, true); Transaction txn3 = new Transaction(null, true);
final Transaction txn4 = new Transaction(null, false); Transaction txn4 = new Transaction(null, false);
final Transaction txn5 = new Transaction(null, true); Transaction txn5 = new Transaction(null, true);
final Transaction txn6 = new Transaction(null, true); Transaction txn6 = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Get messages to validate // Get messages to validate
@@ -217,11 +217,11 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testPendingMessagesAreDeliveredAtStartup() throws Exception { public void testPendingMessagesAreDeliveredAtStartup() throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Transaction txn1 = new Transaction(null, true); Transaction txn1 = new Transaction(null, true);
final Transaction txn2 = new Transaction(null, false); Transaction txn2 = new Transaction(null, false);
final Transaction txn3 = new Transaction(null, false); Transaction txn3 = new Transaction(null, false);
final Transaction txn4 = new Transaction(null, true); Transaction txn4 = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Get messages to validate // Get messages to validate
@@ -303,11 +303,11 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testMessagesAreSharedAtStartup() throws Exception { public void testMessagesAreSharedAtStartup() throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Transaction txn1 = new Transaction(null, true); Transaction txn1 = new Transaction(null, true);
final Transaction txn2 = new Transaction(null, true); Transaction txn2 = new Transaction(null, true);
final Transaction txn3 = new Transaction(null, false); Transaction txn3 = new Transaction(null, false);
final Transaction txn4 = new Transaction(null, false); Transaction txn4 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// No messages to validate // No messages to validate
@@ -355,9 +355,9 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testIncomingMessagesAreShared() throws Exception { public void testIncomingMessagesAreShared() throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
final Transaction txn2 = new Transaction(null, false); Transaction txn2 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Load the group // Load the group
@@ -405,12 +405,12 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testValidationContinuesAfterNoSuchMessageException() public void testValidationContinuesAfterNoSuchMessageException()
throws Exception { throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Transaction txn1 = new Transaction(null, true); Transaction txn1 = new Transaction(null, true);
final Transaction txn2 = new Transaction(null, true); Transaction txn2 = new Transaction(null, true);
final Transaction txn3 = new Transaction(null, false); Transaction txn3 = new Transaction(null, false);
final Transaction txn4 = new Transaction(null, true); Transaction txn4 = new Transaction(null, true);
final Transaction txn5 = new Transaction(null, true); Transaction txn5 = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Get messages to validate // Get messages to validate
@@ -476,12 +476,12 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testValidationContinuesAfterNoSuchGroupException() public void testValidationContinuesAfterNoSuchGroupException()
throws Exception { throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Transaction txn1 = new Transaction(null, true); Transaction txn1 = new Transaction(null, true);
final Transaction txn2 = new Transaction(null, true); Transaction txn2 = new Transaction(null, true);
final Transaction txn3 = new Transaction(null, false); Transaction txn3 = new Transaction(null, false);
final Transaction txn4 = new Transaction(null, true); Transaction txn4 = new Transaction(null, true);
final Transaction txn5 = new Transaction(null, true); Transaction txn5 = new Transaction(null, true);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Get messages to validate // Get messages to validate
@@ -551,8 +551,8 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testNonLocalMessagesAreValidatedWhenAdded() throws Exception { public void testNonLocalMessagesAreValidatedWhenAdded() throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Load the group // Load the group
@@ -591,8 +591,8 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testMessagesWithUndeliveredDependenciesArePending() public void testMessagesWithUndeliveredDependenciesArePending()
throws Exception { throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Load the group // Load the group
@@ -624,8 +624,8 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testMessagesWithDeliveredDependenciesGetDelivered() public void testMessagesWithDeliveredDependenciesGetDelivered()
throws Exception { throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Load the group // Load the group
@@ -663,9 +663,9 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testMessagesWithInvalidDependenciesAreInvalid() public void testMessagesWithInvalidDependenciesAreInvalid()
throws Exception { throws Exception {
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
final Transaction txn2 = new Transaction(null, false); Transaction txn2 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Load the group // Load the group
@@ -716,18 +716,18 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testRecursiveInvalidation() throws Exception { public void testRecursiveInvalidation() throws Exception {
final MessageId messageId3 = new MessageId(TestUtils.getRandomId()); MessageId messageId3 = new MessageId(TestUtils.getRandomId());
final MessageId messageId4 = new MessageId(TestUtils.getRandomId()); MessageId messageId4 = new MessageId(TestUtils.getRandomId());
final Map<MessageId, State> twoDependents = new LinkedHashMap<>(); Map<MessageId, State> twoDependents = new LinkedHashMap<>();
twoDependents.put(messageId1, PENDING); twoDependents.put(messageId1, PENDING);
twoDependents.put(messageId2, PENDING); twoDependents.put(messageId2, PENDING);
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
final Transaction txn2 = new Transaction(null, false); Transaction txn2 = new Transaction(null, false);
final Transaction txn3 = new Transaction(null, false); Transaction txn3 = new Transaction(null, false);
final Transaction txn4 = new Transaction(null, false); Transaction txn4 = new Transaction(null, false);
final Transaction txn5 = new Transaction(null, false); Transaction txn5 = new Transaction(null, false);
final Transaction txn6 = new Transaction(null, false); Transaction txn6 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Load the group // Load the group
@@ -819,25 +819,25 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testPendingDependentsGetDelivered() throws Exception { public void testPendingDependentsGetDelivered() throws Exception {
final MessageId messageId3 = new MessageId(TestUtils.getRandomId()); MessageId messageId3 = new MessageId(TestUtils.getRandomId());
final MessageId messageId4 = new MessageId(TestUtils.getRandomId()); MessageId messageId4 = new MessageId(TestUtils.getRandomId());
final Message message3 = new Message(messageId3, groupId, timestamp, Message message3 = new Message(messageId3, groupId, timestamp,
raw); raw);
final Message message4 = new Message(messageId4, groupId, timestamp, Message message4 = new Message(messageId4, groupId, timestamp,
raw); raw);
final Map<MessageId, State> twoDependents = new LinkedHashMap<>(); Map<MessageId, State> twoDependents = new LinkedHashMap<>();
twoDependents.put(messageId1, PENDING); twoDependents.put(messageId1, PENDING);
twoDependents.put(messageId2, PENDING); twoDependents.put(messageId2, PENDING);
final Map<MessageId, State> twoDependencies = new LinkedHashMap<>(); Map<MessageId, State> twoDependencies = new LinkedHashMap<>();
twoDependencies.put(messageId1, DELIVERED); twoDependencies.put(messageId1, DELIVERED);
twoDependencies.put(messageId2, DELIVERED); twoDependencies.put(messageId2, DELIVERED);
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
final Transaction txn2 = new Transaction(null, false); Transaction txn2 = new Transaction(null, false);
final Transaction txn3 = new Transaction(null, false); Transaction txn3 = new Transaction(null, false);
final Transaction txn4 = new Transaction(null, false); Transaction txn4 = new Transaction(null, false);
final Transaction txn5 = new Transaction(null, false); Transaction txn5 = new Transaction(null, false);
final Transaction txn6 = new Transaction(null, false); Transaction txn6 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Load the group // Load the group
@@ -976,12 +976,12 @@ public class ValidationManagerImplTest extends BrambleMockTestCase {
@Test @Test
public void testOnlyReadyPendingDependentsGetDelivered() throws Exception { public void testOnlyReadyPendingDependentsGetDelivered() throws Exception {
final Map<MessageId, State> twoDependencies = new LinkedHashMap<>(); Map<MessageId, State> twoDependencies = new LinkedHashMap<>();
twoDependencies.put(messageId, DELIVERED); twoDependencies.put(messageId, DELIVERED);
twoDependencies.put(messageId2, UNKNOWN); twoDependencies.put(messageId2, UNKNOWN);
final Transaction txn = new Transaction(null, true); Transaction txn = new Transaction(null, true);
final Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
final Transaction txn2 = new Transaction(null, false); Transaction txn2 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Load the group // Load the group

View File

@@ -58,21 +58,21 @@ public class KeyManagerImplTest extends BrambleTestCase {
@Before @Before
public void testStartService() throws Exception { public void testStartService() throws Exception {
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
AuthorId remoteAuthorId = new AuthorId(getRandomId()); AuthorId remoteAuthorId = new AuthorId(getRandomId());
Author remoteAuthor = new Author(remoteAuthorId, "author", Author remoteAuthor = new Author(remoteAuthorId, "author",
getRandomBytes(42)); getRandomBytes(42));
AuthorId localAuthorId = new AuthorId(getRandomId()); AuthorId localAuthorId = new AuthorId(getRandomId());
final Collection<Contact> contacts = new ArrayList<>(); Collection<Contact> contacts = new ArrayList<>();
contacts.add(new Contact(contactId, remoteAuthor, localAuthorId, true, contacts.add(new Contact(contactId, remoteAuthor, localAuthorId, true,
true)); true));
contacts.add(new Contact(inactiveContactId, remoteAuthor, localAuthorId, contacts.add(new Contact(inactiveContactId, remoteAuthor, localAuthorId,
true, false)); true, false));
final SimplexPluginFactory pluginFactory = SimplexPluginFactory pluginFactory =
context.mock(SimplexPluginFactory.class); context.mock(SimplexPluginFactory.class);
final Collection<SimplexPluginFactory> factories = Collections Collection<SimplexPluginFactory> factories = Collections
.singletonList(pluginFactory); .singletonList(pluginFactory);
final int maxLatency = 1337; int maxLatency = 1337;
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(pluginConfig).getSimplexFactories(); oneOf(pluginConfig).getSimplexFactories();
@@ -100,9 +100,9 @@ public class KeyManagerImplTest extends BrambleTestCase {
@Test @Test
public void testAddContact() throws Exception { public void testAddContact() throws Exception {
final SecretKey secretKey = getSecretKey(); SecretKey secretKey = getSecretKey();
final long timestamp = 42L; long timestamp = 42L;
final boolean alice = true; boolean alice = true;
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(transportKeyManager) oneOf(transportKeyManager)

View File

@@ -14,7 +14,7 @@ public class StreamReaderImplTest extends BrambleTestCase {
@Test @Test
public void testEmptyFramesAreSkipped() throws Exception { public void testEmptyFramesAreSkipped() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final StreamDecrypter decrypter = context.mock(StreamDecrypter.class); StreamDecrypter decrypter = context.mock(StreamDecrypter.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(decrypter).readFrame(with(any(byte[].class))); oneOf(decrypter).readFrame(with(any(byte[].class)));
will(returnValue(0)); // Empty frame will(returnValue(0)); // Empty frame
@@ -37,7 +37,7 @@ public class StreamReaderImplTest extends BrambleTestCase {
@Test @Test
public void testEmptyFramesAreSkippedWithBuffer() throws Exception { public void testEmptyFramesAreSkippedWithBuffer() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final StreamDecrypter decrypter = context.mock(StreamDecrypter.class); StreamDecrypter decrypter = context.mock(StreamDecrypter.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(decrypter).readFrame(with(any(byte[].class))); oneOf(decrypter).readFrame(with(any(byte[].class)));
will(returnValue(0)); // Empty frame will(returnValue(0)); // Empty frame
@@ -63,7 +63,7 @@ public class StreamReaderImplTest extends BrambleTestCase {
@Test @Test
public void testMultipleReadsPerFrame() throws Exception { public void testMultipleReadsPerFrame() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final StreamDecrypter decrypter = context.mock(StreamDecrypter.class); StreamDecrypter decrypter = context.mock(StreamDecrypter.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(decrypter).readFrame(with(any(byte[].class))); oneOf(decrypter).readFrame(with(any(byte[].class)));
will(returnValue(MAX_PAYLOAD_LENGTH)); // Nice long frame will(returnValue(MAX_PAYLOAD_LENGTH)); // Nice long frame
@@ -85,7 +85,7 @@ public class StreamReaderImplTest extends BrambleTestCase {
@Test @Test
public void testMultipleReadsPerFrameWithOffsets() throws Exception { public void testMultipleReadsPerFrameWithOffsets() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final StreamDecrypter decrypter = context.mock(StreamDecrypter.class); StreamDecrypter decrypter = context.mock(StreamDecrypter.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(decrypter).readFrame(with(any(byte[].class))); oneOf(decrypter).readFrame(with(any(byte[].class)));
will(returnValue(MAX_PAYLOAD_LENGTH)); // Nice long frame will(returnValue(MAX_PAYLOAD_LENGTH)); // Nice long frame

View File

@@ -14,7 +14,7 @@ public class StreamWriterImplTest extends BrambleTestCase {
@Test @Test
public void testCloseWithoutWritingWritesFinalFrame() throws Exception { public void testCloseWithoutWritingWritesFinalFrame() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final StreamEncrypter encrypter = context.mock(StreamEncrypter.class); StreamEncrypter encrypter = context.mock(StreamEncrypter.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Write an empty final frame // Write an empty final frame
oneOf(encrypter).writeFrame(with(any(byte[].class)), with(0), oneOf(encrypter).writeFrame(with(any(byte[].class)), with(0),
@@ -31,7 +31,7 @@ public class StreamWriterImplTest extends BrambleTestCase {
public void testFlushWithoutBufferedDataWritesFrameAndFlushes() public void testFlushWithoutBufferedDataWritesFrameAndFlushes()
throws Exception { throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final StreamEncrypter encrypter = context.mock(StreamEncrypter.class); StreamEncrypter encrypter = context.mock(StreamEncrypter.class);
StreamWriterImpl w = new StreamWriterImpl(encrypter); StreamWriterImpl w = new StreamWriterImpl(encrypter);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Write a non-final frame with an empty payload // Write a non-final frame with an empty payload
@@ -58,7 +58,7 @@ public class StreamWriterImplTest extends BrambleTestCase {
public void testFlushWithBufferedDataWritesFrameAndFlushes() public void testFlushWithBufferedDataWritesFrameAndFlushes()
throws Exception { throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final StreamEncrypter encrypter = context.mock(StreamEncrypter.class); StreamEncrypter encrypter = context.mock(StreamEncrypter.class);
StreamWriterImpl w = new StreamWriterImpl(encrypter); StreamWriterImpl w = new StreamWriterImpl(encrypter);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Write a non-final frame with one payload byte // Write a non-final frame with one payload byte
@@ -85,7 +85,7 @@ public class StreamWriterImplTest extends BrambleTestCase {
@Test @Test
public void testSingleByteWritesWriteFullFrame() throws Exception { public void testSingleByteWritesWriteFullFrame() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final StreamEncrypter encrypter = context.mock(StreamEncrypter.class); StreamEncrypter encrypter = context.mock(StreamEncrypter.class);
StreamWriterImpl w = new StreamWriterImpl(encrypter); StreamWriterImpl w = new StreamWriterImpl(encrypter);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Write a full non-final frame // Write a full non-final frame
@@ -109,7 +109,7 @@ public class StreamWriterImplTest extends BrambleTestCase {
@Test @Test
public void testMultiByteWritesWriteFullFrames() throws Exception { public void testMultiByteWritesWriteFullFrames() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final StreamEncrypter encrypter = context.mock(StreamEncrypter.class); StreamEncrypter encrypter = context.mock(StreamEncrypter.class);
StreamWriterImpl w = new StreamWriterImpl(encrypter); StreamWriterImpl w = new StreamWriterImpl(encrypter);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Write two full non-final frames // Write two full non-final frames
@@ -140,7 +140,7 @@ public class StreamWriterImplTest extends BrambleTestCase {
@Test @Test
public void testLargeMultiByteWriteWritesFullFrames() throws Exception { public void testLargeMultiByteWriteWritesFullFrames() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final StreamEncrypter encrypter = context.mock(StreamEncrypter.class); StreamEncrypter encrypter = context.mock(StreamEncrypter.class);
StreamWriterImpl w = new StreamWriterImpl(encrypter); StreamWriterImpl w = new StreamWriterImpl(encrypter);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Write two full non-final frames // Write two full non-final frames

View File

@@ -56,20 +56,20 @@ public class TransportKeyManagerImplTest extends BrambleTestCase {
@Test @Test
public void testKeysAreRotatedAtStartup() throws Exception { public void testKeysAreRotatedAtStartup() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final DatabaseComponent db = context.mock(DatabaseComponent.class); DatabaseComponent db = context.mock(DatabaseComponent.class);
final CryptoComponent crypto = context.mock(CryptoComponent.class); CryptoComponent crypto = context.mock(CryptoComponent.class);
final Executor dbExecutor = context.mock(Executor.class); Executor dbExecutor = context.mock(Executor.class);
final ScheduledExecutorService scheduler = ScheduledExecutorService scheduler =
context.mock(ScheduledExecutorService.class); context.mock(ScheduledExecutorService.class);
final Clock clock = context.mock(Clock.class); Clock clock = context.mock(Clock.class);
final Map<ContactId, TransportKeys> loaded = new LinkedHashMap<>(); Map<ContactId, TransportKeys> loaded = new LinkedHashMap<>();
final TransportKeys shouldRotate = createTransportKeys(900, 0); TransportKeys shouldRotate = createTransportKeys(900, 0);
final TransportKeys shouldNotRotate = createTransportKeys(1000, 0); TransportKeys shouldNotRotate = createTransportKeys(1000, 0);
loaded.put(contactId, shouldRotate); loaded.put(contactId, shouldRotate);
loaded.put(contactId1, shouldNotRotate); loaded.put(contactId1, shouldNotRotate);
final TransportKeys rotated = createTransportKeys(1000, 0); TransportKeys rotated = createTransportKeys(1000, 0);
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Get the current time (1 ms after start of rotation period 1000) // Get the current time (1 ms after start of rotation period 1000)
@@ -108,17 +108,17 @@ public class TransportKeyManagerImplTest extends BrambleTestCase {
@Test @Test
public void testKeysAreRotatedWhenAddingContact() throws Exception { public void testKeysAreRotatedWhenAddingContact() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final DatabaseComponent db = context.mock(DatabaseComponent.class); DatabaseComponent db = context.mock(DatabaseComponent.class);
final CryptoComponent crypto = context.mock(CryptoComponent.class); CryptoComponent crypto = context.mock(CryptoComponent.class);
final Executor dbExecutor = context.mock(Executor.class); Executor dbExecutor = context.mock(Executor.class);
final ScheduledExecutorService scheduler = ScheduledExecutorService scheduler =
context.mock(ScheduledExecutorService.class); context.mock(ScheduledExecutorService.class);
final Clock clock = context.mock(Clock.class); Clock clock = context.mock(Clock.class);
final boolean alice = true; boolean alice = true;
final TransportKeys transportKeys = createTransportKeys(999, 0); TransportKeys transportKeys = createTransportKeys(999, 0);
final TransportKeys rotated = createTransportKeys(1000, 0); TransportKeys rotated = createTransportKeys(1000, 0);
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(crypto).deriveTransportKeys(transportId, masterKey, 999, oneOf(crypto).deriveTransportKeys(transportId, masterKey, 999,
@@ -155,14 +155,14 @@ public class TransportKeyManagerImplTest extends BrambleTestCase {
public void testOutgoingStreamContextIsNullIfContactIsNotFound() public void testOutgoingStreamContextIsNullIfContactIsNotFound()
throws Exception { throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final DatabaseComponent db = context.mock(DatabaseComponent.class); DatabaseComponent db = context.mock(DatabaseComponent.class);
final CryptoComponent crypto = context.mock(CryptoComponent.class); CryptoComponent crypto = context.mock(CryptoComponent.class);
final Executor dbExecutor = context.mock(Executor.class); Executor dbExecutor = context.mock(Executor.class);
final ScheduledExecutorService scheduler = ScheduledExecutorService scheduler =
context.mock(ScheduledExecutorService.class); context.mock(ScheduledExecutorService.class);
final Clock clock = context.mock(Clock.class); Clock clock = context.mock(Clock.class);
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
TransportKeyManager TransportKeyManager
transportKeyManager = new TransportKeyManagerImpl(db, transportKeyManager = new TransportKeyManagerImpl(db,
@@ -176,18 +176,18 @@ public class TransportKeyManagerImplTest extends BrambleTestCase {
public void testOutgoingStreamContextIsNullIfStreamCounterIsExhausted() public void testOutgoingStreamContextIsNullIfStreamCounterIsExhausted()
throws Exception { throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final DatabaseComponent db = context.mock(DatabaseComponent.class); DatabaseComponent db = context.mock(DatabaseComponent.class);
final CryptoComponent crypto = context.mock(CryptoComponent.class); CryptoComponent crypto = context.mock(CryptoComponent.class);
final Executor dbExecutor = context.mock(Executor.class); Executor dbExecutor = context.mock(Executor.class);
final ScheduledExecutorService scheduler = ScheduledExecutorService scheduler =
context.mock(ScheduledExecutorService.class); context.mock(ScheduledExecutorService.class);
final Clock clock = context.mock(Clock.class); Clock clock = context.mock(Clock.class);
final boolean alice = true; boolean alice = true;
// The stream counter has been exhausted // The stream counter has been exhausted
final TransportKeys transportKeys = createTransportKeys(1000, TransportKeys transportKeys = createTransportKeys(1000,
MAX_32_BIT_UNSIGNED + 1); MAX_32_BIT_UNSIGNED + 1);
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(crypto).deriveTransportKeys(transportId, masterKey, 1000, oneOf(crypto).deriveTransportKeys(transportId, masterKey, 1000,
@@ -224,18 +224,18 @@ public class TransportKeyManagerImplTest extends BrambleTestCase {
@Test @Test
public void testOutgoingStreamCounterIsIncremented() throws Exception { public void testOutgoingStreamCounterIsIncremented() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final DatabaseComponent db = context.mock(DatabaseComponent.class); DatabaseComponent db = context.mock(DatabaseComponent.class);
final CryptoComponent crypto = context.mock(CryptoComponent.class); CryptoComponent crypto = context.mock(CryptoComponent.class);
final Executor dbExecutor = context.mock(Executor.class); Executor dbExecutor = context.mock(Executor.class);
final ScheduledExecutorService scheduler = ScheduledExecutorService scheduler =
context.mock(ScheduledExecutorService.class); context.mock(ScheduledExecutorService.class);
final Clock clock = context.mock(Clock.class); Clock clock = context.mock(Clock.class);
final boolean alice = true; boolean alice = true;
// The stream counter can be used one more time before being exhausted // The stream counter can be used one more time before being exhausted
final TransportKeys transportKeys = createTransportKeys(1000, TransportKeys transportKeys = createTransportKeys(1000,
MAX_32_BIT_UNSIGNED); MAX_32_BIT_UNSIGNED);
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(crypto).deriveTransportKeys(transportId, masterKey, 1000, oneOf(crypto).deriveTransportKeys(transportId, masterKey, 1000,
@@ -285,16 +285,16 @@ public class TransportKeyManagerImplTest extends BrambleTestCase {
public void testIncomingStreamContextIsNullIfTagIsNotFound() public void testIncomingStreamContextIsNullIfTagIsNotFound()
throws Exception { throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final DatabaseComponent db = context.mock(DatabaseComponent.class); DatabaseComponent db = context.mock(DatabaseComponent.class);
final CryptoComponent crypto = context.mock(CryptoComponent.class); CryptoComponent crypto = context.mock(CryptoComponent.class);
final Executor dbExecutor = context.mock(Executor.class); Executor dbExecutor = context.mock(Executor.class);
final ScheduledExecutorService scheduler = ScheduledExecutorService scheduler =
context.mock(ScheduledExecutorService.class); context.mock(ScheduledExecutorService.class);
final Clock clock = context.mock(Clock.class); Clock clock = context.mock(Clock.class);
final boolean alice = true; boolean alice = true;
final TransportKeys transportKeys = createTransportKeys(1000, 0); TransportKeys transportKeys = createTransportKeys(1000, 0);
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(crypto).deriveTransportKeys(transportId, masterKey, 1000, oneOf(crypto).deriveTransportKeys(transportId, masterKey, 1000,
@@ -332,18 +332,18 @@ public class TransportKeyManagerImplTest extends BrambleTestCase {
@Test @Test
public void testTagIsNotRecognisedTwice() throws Exception { public void testTagIsNotRecognisedTwice() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final DatabaseComponent db = context.mock(DatabaseComponent.class); DatabaseComponent db = context.mock(DatabaseComponent.class);
final CryptoComponent crypto = context.mock(CryptoComponent.class); CryptoComponent crypto = context.mock(CryptoComponent.class);
final Executor dbExecutor = context.mock(Executor.class); Executor dbExecutor = context.mock(Executor.class);
final ScheduledExecutorService scheduler = ScheduledExecutorService scheduler =
context.mock(ScheduledExecutorService.class); context.mock(ScheduledExecutorService.class);
final Clock clock = context.mock(Clock.class); Clock clock = context.mock(Clock.class);
final boolean alice = true; boolean alice = true;
final TransportKeys transportKeys = createTransportKeys(1000, 0); TransportKeys transportKeys = createTransportKeys(1000, 0);
// Keep a copy of the tags // Keep a copy of the tags
final List<byte[]> tags = new ArrayList<>(); List<byte[]> tags = new ArrayList<>();
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(crypto).deriveTransportKeys(transportId, masterKey, 1000, oneOf(crypto).deriveTransportKeys(transportId, masterKey, 1000,
@@ -402,19 +402,19 @@ public class TransportKeyManagerImplTest extends BrambleTestCase {
@Test @Test
public void testKeysAreRotatedToCurrentPeriod() throws Exception { public void testKeysAreRotatedToCurrentPeriod() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final DatabaseComponent db = context.mock(DatabaseComponent.class); DatabaseComponent db = context.mock(DatabaseComponent.class);
final CryptoComponent crypto = context.mock(CryptoComponent.class); CryptoComponent crypto = context.mock(CryptoComponent.class);
final Executor dbExecutor = context.mock(Executor.class); Executor dbExecutor = context.mock(Executor.class);
final ScheduledExecutorService scheduler = ScheduledExecutorService scheduler =
context.mock(ScheduledExecutorService.class); context.mock(ScheduledExecutorService.class);
final Clock clock = context.mock(Clock.class); Clock clock = context.mock(Clock.class);
final TransportKeys transportKeys = createTransportKeys(1000, 0); TransportKeys transportKeys = createTransportKeys(1000, 0);
final Map<ContactId, TransportKeys> loaded = Map<ContactId, TransportKeys> loaded =
Collections.singletonMap(contactId, transportKeys); Collections.singletonMap(contactId, transportKeys);
final TransportKeys rotated = createTransportKeys(1001, 0); TransportKeys rotated = createTransportKeys(1001, 0);
final Transaction txn = new Transaction(null, false); Transaction txn = new Transaction(null, false);
final Transaction txn1 = new Transaction(null, false); Transaction txn1 = new Transaction(null, false);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// Get the current time (the start of rotation period 1000) // Get the current time (the start of rotation period 1000)

View File

@@ -110,7 +110,7 @@ class WindowsShutdownManagerImpl extends ShutdownManagerImpl {
public void run() { public void run() {
try { try {
// Load user32.dll // Load user32.dll
final User32 user32 = (User32) Native.loadLibrary("user32", User32 user32 = (User32) Native.loadLibrary("user32",
User32.class, options); User32.class, options);
// Create a callback to handle the WM_QUERYENDSESSION message // Create a callback to handle the WM_QUERYENDSESSION message
WindowProc proc = (hwnd, msg, wp, lp) -> { WindowProc proc = (hwnd, msg, wp, lp) -> {

View File

@@ -41,9 +41,9 @@ public class DesktopPluginModule extends PluginModule {
backoffFactory, shutdownManager); backoffFactory, shutdownManager);
SimplexPluginFactory removable = SimplexPluginFactory removable =
new RemovableDrivePluginFactory(ioExecutor); new RemovableDrivePluginFactory(ioExecutor);
final Collection<SimplexPluginFactory> simplex = Collection<SimplexPluginFactory> simplex =
Collections.singletonList(removable); Collections.singletonList(removable);
final Collection<DuplexPluginFactory> duplex = Collection<DuplexPluginFactory> duplex =
Arrays.asList(bluetooth, modem, lan, wan); Arrays.asList(bluetooth, modem, lan, wan);
@NotNullByDefault @NotNullByDefault
PluginConfig pluginConfig = new PluginConfig() { PluginConfig pluginConfig = new PluginConfig() {

View File

@@ -204,18 +204,18 @@ class BluetoothPlugin implements DuplexPlugin {
} }
@Override @Override
public void poll(final Collection<ContactId> connected) { public void poll(Collection<ContactId> connected) {
if (!running) return; if (!running) return;
backoff.increment(); backoff.increment();
// Try to connect to known devices in parallel // Try to connect to known devices in parallel
Map<ContactId, TransportProperties> remote = Map<ContactId, TransportProperties> remote =
callback.getRemoteProperties(); callback.getRemoteProperties();
for (Entry<ContactId, TransportProperties> e : remote.entrySet()) { for (Entry<ContactId, TransportProperties> e : remote.entrySet()) {
final ContactId c = e.getKey(); ContactId c = e.getKey();
if (connected.contains(c)) continue; if (connected.contains(c)) continue;
final String address = e.getValue().get(PROP_ADDRESS); String address = e.getValue().get(PROP_ADDRESS);
if (StringUtils.isNullOrEmpty(address)) continue; if (StringUtils.isNullOrEmpty(address)) continue;
final String uuid = e.getValue().get(PROP_UUID); String uuid = e.getValue().get(PROP_UUID);
if (StringUtils.isNullOrEmpty(uuid)) continue; if (StringUtils.isNullOrEmpty(uuid)) continue;
ioExecutor.execute(() -> { ioExecutor.execute(() -> {
if (!running) return; if (!running) return;
@@ -270,7 +270,7 @@ class BluetoothPlugin implements DuplexPlugin {
// Make the device discoverable if possible // Make the device discoverable if possible
makeDeviceDiscoverable(); makeDeviceDiscoverable();
// Bind a server socket for receiving key agreementconnections // Bind a server socket for receiving key agreementconnections
final StreamConnectionNotifier ss; StreamConnectionNotifier ss;
try { try {
ss = (StreamConnectionNotifier) Connector.open(url); ss = (StreamConnectionNotifier) Connector.open(url);
} catch (IOException e) { } catch (IOException e) {

View File

@@ -26,10 +26,10 @@ public class PollingRemovableDriveMonitorTest extends BrambleTestCase {
@Test @Test
public void testOneCallbackPerFile() throws Exception { public void testOneCallbackPerFile() throws Exception {
// Create a finder that returns no files the first time, then two files // Create a finder that returns no files the first time, then two files
final File file1 = new File("foo"); File file1 = new File("foo");
final File file2 = new File("bar"); File file2 = new File("bar");
@NotNullByDefault @NotNullByDefault
final RemovableDriveFinder finder = new RemovableDriveFinder() { RemovableDriveFinder finder = new RemovableDriveFinder() {
private AtomicBoolean firstCall = new AtomicBoolean(true); private AtomicBoolean firstCall = new AtomicBoolean(true);
@@ -40,8 +40,8 @@ public class PollingRemovableDriveMonitorTest extends BrambleTestCase {
} }
}; };
// Create a callback that waits for two files // Create a callback that waits for two files
final CountDownLatch latch = new CountDownLatch(2); CountDownLatch latch = new CountDownLatch(2);
final List<File> detected = new ArrayList<>(); List<File> detected = new ArrayList<>();
@NotNullByDefault @NotNullByDefault
Callback callback = new Callback() { Callback callback = new Callback() {
@@ -57,7 +57,7 @@ public class PollingRemovableDriveMonitorTest extends BrambleTestCase {
} }
}; };
// Create the monitor and start it // Create the monitor and start it
final RemovableDriveMonitor monitor = new PollingRemovableDriveMonitor( RemovableDriveMonitor monitor = new PollingRemovableDriveMonitor(
Executors.newCachedThreadPool(), finder, 1); Executors.newCachedThreadPool(), finder, 1);
monitor.start(callback); monitor.start(callback);
// Wait for the monitor to detect the files // Wait for the monitor to detect the files
@@ -72,7 +72,7 @@ public class PollingRemovableDriveMonitorTest extends BrambleTestCase {
@Test @Test
public void testExceptionCallback() throws Exception { public void testExceptionCallback() throws Exception {
// Create a finder that throws an exception the second time it's polled // Create a finder that throws an exception the second time it's polled
final RemovableDriveFinder finder = new RemovableDriveFinder() { RemovableDriveFinder finder = new RemovableDriveFinder() {
private AtomicBoolean firstCall = new AtomicBoolean(true); private AtomicBoolean firstCall = new AtomicBoolean(true);
@@ -83,7 +83,7 @@ public class PollingRemovableDriveMonitorTest extends BrambleTestCase {
} }
}; };
// Create a callback that waits for an exception // Create a callback that waits for an exception
final CountDownLatch latch = new CountDownLatch(1); CountDownLatch latch = new CountDownLatch(1);
@NotNullByDefault @NotNullByDefault
Callback callback = new Callback() { Callback callback = new Callback() {
@@ -98,7 +98,7 @@ public class PollingRemovableDriveMonitorTest extends BrambleTestCase {
} }
}; };
// Create the monitor and start it // Create the monitor and start it
final RemovableDriveMonitor monitor = new PollingRemovableDriveMonitor( RemovableDriveMonitor monitor = new PollingRemovableDriveMonitor(
Executors.newCachedThreadPool(), finder, 1); Executors.newCachedThreadPool(), finder, 1);
monitor.start(callback); monitor.start(callback);
assertTrue(latch.await(10, SECONDS)); assertTrue(latch.await(10, SECONDS));

View File

@@ -41,17 +41,17 @@ public class RemovableDrivePluginTest extends BrambleTestCase {
@Test @Test
public void testWriterIsNullIfNoDrivesAreFound() throws Exception { public void testWriterIsNullIfNoDrivesAreFound() throws Exception {
final List<File> drives = Collections.emptyList(); List<File> drives = Collections.emptyList();
Mockery context = new Mockery() {{ Mockery context = new Mockery() {{
setThreadingPolicy(new Synchroniser()); setThreadingPolicy(new Synchroniser());
}}; }};
final Executor executor = context.mock(Executor.class); Executor executor = context.mock(Executor.class);
final SimplexPluginCallback callback = SimplexPluginCallback callback =
context.mock(SimplexPluginCallback.class); context.mock(SimplexPluginCallback.class);
final RemovableDriveFinder finder = RemovableDriveFinder finder =
context.mock(RemovableDriveFinder.class); context.mock(RemovableDriveFinder.class);
final RemovableDriveMonitor monitor = RemovableDriveMonitor monitor =
context.mock(RemovableDriveMonitor.class); context.mock(RemovableDriveMonitor.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
@@ -71,21 +71,21 @@ public class RemovableDrivePluginTest extends BrambleTestCase {
@Test @Test
public void testWriterIsNullIfNoDriveIsChosen() throws Exception { public void testWriterIsNullIfNoDriveIsChosen() throws Exception {
final File drive1 = new File(testDir, "1"); File drive1 = new File(testDir, "1");
final File drive2 = new File(testDir, "2"); File drive2 = new File(testDir, "2");
final List<File> drives = new ArrayList<>(); List<File> drives = new ArrayList<>();
drives.add(drive1); drives.add(drive1);
drives.add(drive2); drives.add(drive2);
Mockery context = new Mockery() {{ Mockery context = new Mockery() {{
setThreadingPolicy(new Synchroniser()); setThreadingPolicy(new Synchroniser());
}}; }};
final Executor executor = context.mock(Executor.class); Executor executor = context.mock(Executor.class);
final SimplexPluginCallback callback = SimplexPluginCallback callback =
context.mock(SimplexPluginCallback.class); context.mock(SimplexPluginCallback.class);
final RemovableDriveFinder finder = RemovableDriveFinder finder =
context.mock(RemovableDriveFinder.class); context.mock(RemovableDriveFinder.class);
final RemovableDriveMonitor monitor = RemovableDriveMonitor monitor =
context.mock(RemovableDriveMonitor.class); context.mock(RemovableDriveMonitor.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
@@ -110,21 +110,21 @@ public class RemovableDrivePluginTest extends BrambleTestCase {
@Test @Test
public void testWriterIsNullIfOutputDirDoesNotExist() throws Exception { public void testWriterIsNullIfOutputDirDoesNotExist() throws Exception {
final File drive1 = new File(testDir, "1"); File drive1 = new File(testDir, "1");
final File drive2 = new File(testDir, "2"); File drive2 = new File(testDir, "2");
final List<File> drives = new ArrayList<>(); List<File> drives = new ArrayList<>();
drives.add(drive1); drives.add(drive1);
drives.add(drive2); drives.add(drive2);
Mockery context = new Mockery() {{ Mockery context = new Mockery() {{
setThreadingPolicy(new Synchroniser()); setThreadingPolicy(new Synchroniser());
}}; }};
final Executor executor = context.mock(Executor.class); Executor executor = context.mock(Executor.class);
final SimplexPluginCallback callback = SimplexPluginCallback callback =
context.mock(SimplexPluginCallback.class); context.mock(SimplexPluginCallback.class);
final RemovableDriveFinder finder = RemovableDriveFinder finder =
context.mock(RemovableDriveFinder.class); context.mock(RemovableDriveFinder.class);
final RemovableDriveMonitor monitor = RemovableDriveMonitor monitor =
context.mock(RemovableDriveMonitor.class); context.mock(RemovableDriveMonitor.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
@@ -149,9 +149,9 @@ public class RemovableDrivePluginTest extends BrambleTestCase {
@Test @Test
public void testWriterIsNullIfOutputDirIsAFile() throws Exception { public void testWriterIsNullIfOutputDirIsAFile() throws Exception {
final File drive1 = new File(testDir, "1"); File drive1 = new File(testDir, "1");
final File drive2 = new File(testDir, "2"); File drive2 = new File(testDir, "2");
final List<File> drives = new ArrayList<>(); List<File> drives = new ArrayList<>();
drives.add(drive1); drives.add(drive1);
drives.add(drive2); drives.add(drive2);
// Create drive1 as a file rather than a directory // Create drive1 as a file rather than a directory
@@ -160,12 +160,12 @@ public class RemovableDrivePluginTest extends BrambleTestCase {
Mockery context = new Mockery() {{ Mockery context = new Mockery() {{
setThreadingPolicy(new Synchroniser()); setThreadingPolicy(new Synchroniser());
}}; }};
final Executor executor = context.mock(Executor.class); Executor executor = context.mock(Executor.class);
final SimplexPluginCallback callback = SimplexPluginCallback callback =
context.mock(SimplexPluginCallback.class); context.mock(SimplexPluginCallback.class);
final RemovableDriveFinder finder = RemovableDriveFinder finder =
context.mock(RemovableDriveFinder.class); context.mock(RemovableDriveFinder.class);
final RemovableDriveMonitor monitor = RemovableDriveMonitor monitor =
context.mock(RemovableDriveMonitor.class); context.mock(RemovableDriveMonitor.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
@@ -190,9 +190,9 @@ public class RemovableDrivePluginTest extends BrambleTestCase {
@Test @Test
public void testWriterIsNotNullIfOutputDirIsADir() throws Exception { public void testWriterIsNotNullIfOutputDirIsADir() throws Exception {
final File drive1 = new File(testDir, "1"); File drive1 = new File(testDir, "1");
final File drive2 = new File(testDir, "2"); File drive2 = new File(testDir, "2");
final List<File> drives = new ArrayList<>(); List<File> drives = new ArrayList<>();
drives.add(drive1); drives.add(drive1);
drives.add(drive2); drives.add(drive2);
// Create drive1 as a directory // Create drive1 as a directory
@@ -201,12 +201,12 @@ public class RemovableDrivePluginTest extends BrambleTestCase {
Mockery context = new Mockery() {{ Mockery context = new Mockery() {{
setThreadingPolicy(new Synchroniser()); setThreadingPolicy(new Synchroniser());
}}; }};
final Executor executor = context.mock(Executor.class); Executor executor = context.mock(Executor.class);
final SimplexPluginCallback callback = SimplexPluginCallback callback =
context.mock(SimplexPluginCallback.class); context.mock(SimplexPluginCallback.class);
final RemovableDriveFinder finder = RemovableDriveFinder finder =
context.mock(RemovableDriveFinder.class); context.mock(RemovableDriveFinder.class);
final RemovableDriveMonitor monitor = RemovableDriveMonitor monitor =
context.mock(RemovableDriveMonitor.class); context.mock(RemovableDriveMonitor.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
@@ -234,9 +234,9 @@ public class RemovableDrivePluginTest extends BrambleTestCase {
@Test @Test
public void testWritingToWriter() throws Exception { public void testWritingToWriter() throws Exception {
final File drive1 = new File(testDir, "1"); File drive1 = new File(testDir, "1");
final File drive2 = new File(testDir, "2"); File drive2 = new File(testDir, "2");
final List<File> drives = new ArrayList<>(); List<File> drives = new ArrayList<>();
drives.add(drive1); drives.add(drive1);
drives.add(drive2); drives.add(drive2);
// Create drive1 as a directory // Create drive1 as a directory
@@ -245,12 +245,12 @@ public class RemovableDrivePluginTest extends BrambleTestCase {
Mockery context = new Mockery() {{ Mockery context = new Mockery() {{
setThreadingPolicy(new Synchroniser()); setThreadingPolicy(new Synchroniser());
}}; }};
final Executor executor = context.mock(Executor.class); Executor executor = context.mock(Executor.class);
final SimplexPluginCallback callback = SimplexPluginCallback callback =
context.mock(SimplexPluginCallback.class); context.mock(SimplexPluginCallback.class);
final RemovableDriveFinder finder = RemovableDriveFinder finder =
context.mock(RemovableDriveFinder.class); context.mock(RemovableDriveFinder.class);
final RemovableDriveMonitor monitor = RemovableDriveMonitor monitor =
context.mock(RemovableDriveMonitor.class); context.mock(RemovableDriveMonitor.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
@@ -292,12 +292,12 @@ public class RemovableDrivePluginTest extends BrambleTestCase {
Mockery context = new Mockery() {{ Mockery context = new Mockery() {{
setThreadingPolicy(new Synchroniser()); setThreadingPolicy(new Synchroniser());
}}; }};
final Executor executor = context.mock(Executor.class); Executor executor = context.mock(Executor.class);
final SimplexPluginCallback callback = SimplexPluginCallback callback =
context.mock(SimplexPluginCallback.class); context.mock(SimplexPluginCallback.class);
final RemovableDriveFinder finder = RemovableDriveFinder finder =
context.mock(RemovableDriveFinder.class); context.mock(RemovableDriveFinder.class);
final RemovableDriveMonitor monitor = RemovableDriveMonitor monitor =
context.mock(RemovableDriveMonitor.class); context.mock(RemovableDriveMonitor.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
@@ -318,12 +318,12 @@ public class RemovableDrivePluginTest extends BrambleTestCase {
Mockery context = new Mockery() {{ Mockery context = new Mockery() {{
setThreadingPolicy(new Synchroniser()); setThreadingPolicy(new Synchroniser());
}}; }};
final Executor executor = context.mock(Executor.class); Executor executor = context.mock(Executor.class);
final SimplexPluginCallback callback = SimplexPluginCallback callback =
context.mock(SimplexPluginCallback.class); context.mock(SimplexPluginCallback.class);
final RemovableDriveFinder finder = RemovableDriveFinder finder =
context.mock(RemovableDriveFinder.class); context.mock(RemovableDriveFinder.class);
final RemovableDriveMonitor monitor = RemovableDriveMonitor monitor =
context.mock(RemovableDriveMonitor.class); context.mock(RemovableDriveMonitor.class);
RemovableDrivePlugin plugin = new RemovableDrivePlugin(executor, RemovableDrivePlugin plugin = new RemovableDrivePlugin(executor,
@@ -344,11 +344,11 @@ public class RemovableDrivePluginTest extends BrambleTestCase {
Mockery context = new Mockery() {{ Mockery context = new Mockery() {{
setThreadingPolicy(new Synchroniser()); setThreadingPolicy(new Synchroniser());
}}; }};
final SimplexPluginCallback callback = SimplexPluginCallback callback =
context.mock(SimplexPluginCallback.class); context.mock(SimplexPluginCallback.class);
final RemovableDriveFinder finder = RemovableDriveFinder finder =
context.mock(RemovableDriveFinder.class); context.mock(RemovableDriveFinder.class);
final RemovableDriveMonitor monitor = RemovableDriveMonitor monitor =
context.mock(RemovableDriveMonitor.class); context.mock(RemovableDriveMonitor.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{

View File

@@ -61,10 +61,10 @@ public class UnixRemovableDriveMonitorTest extends BrambleTestCase {
return; return;
} }
// Create a callback that will wait for two files before stopping // Create a callback that will wait for two files before stopping
final List<File> detected = new ArrayList<>(); List<File> detected = new ArrayList<>();
final CountDownLatch latch = new CountDownLatch(2); CountDownLatch latch = new CountDownLatch(2);
@NotNullByDefault @NotNullByDefault
final Callback callback = new Callback() { Callback callback = new Callback() {
@Override @Override
public void driveInserted(File f) { public void driveInserted(File f) {
@@ -99,7 +99,7 @@ public class UnixRemovableDriveMonitorTest extends BrambleTestCase {
TestUtils.deleteTestDirectory(testDir); TestUtils.deleteTestDirectory(testDir);
} }
private RemovableDriveMonitor createMonitor(final File dir) { private RemovableDriveMonitor createMonitor(File dir) {
@NotNullByDefault @NotNullByDefault
RemovableDriveMonitor monitor = new UnixRemovableDriveMonitor() { RemovableDriveMonitor monitor = new UnixRemovableDriveMonitor() {
@Override @Override

View File

@@ -21,12 +21,12 @@ public class ModemPluginTest extends BrambleTestCase {
@Test @Test
public void testModemCreation() throws Exception { public void testModemCreation() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final ModemFactory modemFactory = context.mock(ModemFactory.class); ModemFactory modemFactory = context.mock(ModemFactory.class);
final SerialPortList serialPortList = SerialPortList serialPortList =
context.mock(SerialPortList.class); context.mock(SerialPortList.class);
final ModemPlugin plugin = new ModemPlugin(modemFactory, ModemPlugin plugin = new ModemPlugin(modemFactory,
serialPortList, null, 0); serialPortList, null, 0);
final Modem modem = context.mock(Modem.class); Modem modem = context.mock(Modem.class);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
oneOf(serialPortList).getPortNames(); oneOf(serialPortList).getPortNames();
will(returnValue(new String[] { "foo", "bar", "baz" })); will(returnValue(new String[] { "foo", "bar", "baz" }));
@@ -53,20 +53,20 @@ public class ModemPluginTest extends BrambleTestCase {
@Test @Test
public void testCreateConnection() throws Exception { public void testCreateConnection() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final ModemFactory modemFactory = context.mock(ModemFactory.class); ModemFactory modemFactory = context.mock(ModemFactory.class);
final SerialPortList serialPortList = SerialPortList serialPortList =
context.mock(SerialPortList.class); context.mock(SerialPortList.class);
final DuplexPluginCallback callback = DuplexPluginCallback callback =
context.mock(DuplexPluginCallback.class); context.mock(DuplexPluginCallback.class);
final ModemPlugin plugin = new ModemPlugin(modemFactory, ModemPlugin plugin = new ModemPlugin(modemFactory,
serialPortList, callback, 0); serialPortList, callback, 0);
final Modem modem = context.mock(Modem.class); Modem modem = context.mock(Modem.class);
final TransportProperties local = new TransportProperties(); TransportProperties local = new TransportProperties();
local.put("iso3166", ISO_1336); local.put("iso3166", ISO_1336);
final TransportProperties remote = new TransportProperties(); TransportProperties remote = new TransportProperties();
remote.put("iso3166", ISO_1336); remote.put("iso3166", ISO_1336);
remote.put("number", NUMBER); remote.put("number", NUMBER);
final ContactId contactId = new ContactId(234); ContactId contactId = new ContactId(234);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// start() // start()
oneOf(serialPortList).getPortNames(); oneOf(serialPortList).getPortNames();
@@ -92,20 +92,20 @@ public class ModemPluginTest extends BrambleTestCase {
@Test @Test
public void testCreateConnectionWhenDialReturnsFalse() throws Exception { public void testCreateConnectionWhenDialReturnsFalse() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final ModemFactory modemFactory = context.mock(ModemFactory.class); ModemFactory modemFactory = context.mock(ModemFactory.class);
final SerialPortList serialPortList = SerialPortList serialPortList =
context.mock(SerialPortList.class); context.mock(SerialPortList.class);
final DuplexPluginCallback callback = DuplexPluginCallback callback =
context.mock(DuplexPluginCallback.class); context.mock(DuplexPluginCallback.class);
final ModemPlugin plugin = new ModemPlugin(modemFactory, ModemPlugin plugin = new ModemPlugin(modemFactory,
serialPortList, callback, 0); serialPortList, callback, 0);
final Modem modem = context.mock(Modem.class); Modem modem = context.mock(Modem.class);
final TransportProperties local = new TransportProperties(); TransportProperties local = new TransportProperties();
local.put("iso3166", ISO_1336); local.put("iso3166", ISO_1336);
final TransportProperties remote = new TransportProperties(); TransportProperties remote = new TransportProperties();
remote.put("iso3166", ISO_1336); remote.put("iso3166", ISO_1336);
remote.put("number", NUMBER); remote.put("number", NUMBER);
final ContactId contactId = new ContactId(234); ContactId contactId = new ContactId(234);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// start() // start()
oneOf(serialPortList).getPortNames(); oneOf(serialPortList).getPortNames();
@@ -131,20 +131,20 @@ public class ModemPluginTest extends BrambleTestCase {
@Test @Test
public void testCreateConnectionWhenDialThrowsException() throws Exception { public void testCreateConnectionWhenDialThrowsException() throws Exception {
Mockery context = new Mockery(); Mockery context = new Mockery();
final ModemFactory modemFactory = context.mock(ModemFactory.class); ModemFactory modemFactory = context.mock(ModemFactory.class);
final SerialPortList serialPortList = SerialPortList serialPortList =
context.mock(SerialPortList.class); context.mock(SerialPortList.class);
final DuplexPluginCallback callback = DuplexPluginCallback callback =
context.mock(DuplexPluginCallback.class); context.mock(DuplexPluginCallback.class);
final ModemPlugin plugin = new ModemPlugin(modemFactory, ModemPlugin plugin = new ModemPlugin(modemFactory,
serialPortList, callback, 0); serialPortList, callback, 0);
final Modem modem = context.mock(Modem.class); Modem modem = context.mock(Modem.class);
final TransportProperties local = new TransportProperties(); TransportProperties local = new TransportProperties();
local.put("iso3166", ISO_1336); local.put("iso3166", ISO_1336);
final TransportProperties remote = new TransportProperties(); TransportProperties remote = new TransportProperties();
remote.put("iso3166", ISO_1336); remote.put("iso3166", ISO_1336);
remote.put("number", NUMBER); remote.put("number", NUMBER);
final ContactId contactId = new ContactId(234); ContactId contactId = new ContactId(234);
context.checking(new Expectations() {{ context.checking(new Expectations() {{
// start() // start()
oneOf(serialPortList).getPortNames(); oneOf(serialPortList).getPortNames();

View File

@@ -242,7 +242,7 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
}); });
} }
private void showContactNotification(final ContactId c) { private void showContactNotification(ContactId c) {
androidExecutor.runOnUiThread(() -> { androidExecutor.runOnUiThread(() -> {
if (blockContacts) return; if (blockContacts) return;
if (c.equals(blockedContact)) return; if (c.equals(blockedContact)) return;
@@ -255,7 +255,7 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
} }
@Override @Override
public void clearContactNotification(final ContactId c) { public void clearContactNotification(ContactId c) {
androidExecutor.runOnUiThread(() -> { androidExecutor.runOnUiThread(() -> {
Integer count = contactCounts.remove(c); Integer count = contactCounts.remove(c);
if (count == null) return; // Already cleared if (count == null) return; // Already cleared
@@ -350,7 +350,7 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
} }
@UiThread @UiThread
private void showGroupMessageNotification(final GroupId g) { private void showGroupMessageNotification(GroupId g) {
androidExecutor.runOnUiThread(() -> { androidExecutor.runOnUiThread(() -> {
if (blockGroups) return; if (blockGroups) return;
if (g.equals(blockedGroup)) return; if (g.equals(blockedGroup)) return;
@@ -363,7 +363,7 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
} }
@Override @Override
public void clearGroupMessageNotification(final GroupId g) { public void clearGroupMessageNotification(GroupId g) {
androidExecutor.runOnUiThread(() -> { androidExecutor.runOnUiThread(() -> {
Integer count = groupCounts.remove(g); Integer count = groupCounts.remove(g);
if (count == null) return; // Already cleared if (count == null) return; // Already cleared
@@ -427,7 +427,7 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
} }
@UiThread @UiThread
private void showForumPostNotification(final GroupId g) { private void showForumPostNotification(GroupId g) {
androidExecutor.runOnUiThread(() -> { androidExecutor.runOnUiThread(() -> {
if (blockForums) return; if (blockForums) return;
if (g.equals(blockedGroup)) return; if (g.equals(blockedGroup)) return;
@@ -440,7 +440,7 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
} }
@Override @Override
public void clearForumPostNotification(final GroupId g) { public void clearForumPostNotification(GroupId g) {
androidExecutor.runOnUiThread(() -> { androidExecutor.runOnUiThread(() -> {
Integer count = forumCounts.remove(g); Integer count = forumCounts.remove(g);
if (count == null) return; // Already cleared if (count == null) return; // Already cleared
@@ -504,7 +504,7 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
} }
@UiThread @UiThread
private void showBlogPostNotification(final GroupId g) { private void showBlogPostNotification(GroupId g) {
androidExecutor.runOnUiThread(() -> { androidExecutor.runOnUiThread(() -> {
if (blockBlogs) return; if (blockBlogs) return;
if (g.equals(blockedGroup)) return; if (g.equals(blockedGroup)) return;
@@ -517,7 +517,7 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
} }
@Override @Override
public void clearBlogPostNotification(final GroupId g) { public void clearBlogPostNotification(GroupId g) {
androidExecutor.runOnUiThread(() -> { androidExecutor.runOnUiThread(() -> {
Integer count = blogCounts.remove(g); Integer count = blogCounts.remove(g);
if (count == null) return; // Already cleared if (count == null) return; // Already cleared
@@ -611,24 +611,24 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
} }
@Override @Override
public void blockNotification(final GroupId g) { public void blockNotification(GroupId g) {
androidExecutor.runOnUiThread((Runnable) () -> blockedGroup = g); androidExecutor.runOnUiThread((Runnable) () -> blockedGroup = g);
} }
@Override @Override
public void unblockNotification(final GroupId g) { public void unblockNotification(GroupId g) {
androidExecutor.runOnUiThread(() -> { androidExecutor.runOnUiThread(() -> {
if (g.equals(blockedGroup)) blockedGroup = null; if (g.equals(blockedGroup)) blockedGroup = null;
}); });
} }
@Override @Override
public void blockContactNotification(final ContactId c) { public void blockContactNotification(ContactId c) {
androidExecutor.runOnUiThread((Runnable) () -> blockedContact = c); androidExecutor.runOnUiThread((Runnable) () -> blockedContact = c);
} }
@Override @Override
public void unblockContactNotification(final ContactId c) { public void unblockContactNotification(ContactId c) {
androidExecutor.runOnUiThread(() -> { androidExecutor.runOnUiThread(() -> {
if (c.equals(blockedContact)) blockedContact = null; if (c.equals(blockedContact)) blockedContact = null;
}); });

View File

@@ -80,7 +80,7 @@ public class AppModule {
@Provides @Provides
@Singleton @Singleton
DatabaseConfig provideDatabaseConfig(Application app) { DatabaseConfig provideDatabaseConfig(Application app) {
final File dir = app.getApplicationContext().getDir("db", MODE_PRIVATE); File dir = app.getApplicationContext().getDir("db", MODE_PRIVATE);
@MethodsNotNullByDefault @MethodsNotNullByDefault
@ParametersNotNullByDefault @ParametersNotNullByDefault
DatabaseConfig databaseConfig = new DatabaseConfig() { DatabaseConfig databaseConfig = new DatabaseConfig() {
@@ -132,7 +132,7 @@ public class AppModule {
@Provides @Provides
@Singleton @Singleton
DevConfig provideDevConfig(final CryptoComponent crypto) { DevConfig provideDevConfig(CryptoComponent crypto) {
@NotNullByDefault @NotNullByDefault
DevConfig devConfig = new DevConfig() { DevConfig devConfig = new DevConfig() {

View File

@@ -111,7 +111,7 @@ public class BriarService extends Service {
}.start(); }.start();
} }
private void showStartupFailureNotification(final StartResult result) { private void showStartupFailureNotification(StartResult result) {
androidExecutor.runOnUiThread(() -> { androidExecutor.runOnUiThread(() -> {
NotificationCompat.Builder b = NotificationCompat.Builder b =
new NotificationCompat.Builder(BriarService.this); new NotificationCompat.Builder(BriarService.this);

View File

@@ -151,7 +151,7 @@ public abstract class BaseActivity extends AppCompatActivity
} }
@Override @Override
public void runOnUiThreadUnlessDestroyed(final Runnable r) { public void runOnUiThreadUnlessDestroyed(Runnable r) {
runOnUiThread(() -> { runOnUiThread(() -> {
if (!destroyed && !isFinishing()) r.run(); if (!destroyed && !isFinishing()) r.run();
}); });

View File

@@ -97,7 +97,7 @@ public abstract class BriarActivity extends BaseActivity {
return toolbar; return toolbar;
} }
protected void signOut(final boolean removeFromRecentApps) { protected void signOut(boolean removeFromRecentApps) {
if (briarController.hasEncryptionKey()) { if (briarController.hasEncryptionKey()) {
// Don't use UiResultHandler because we want the result even if // Don't use UiResultHandler because we want the result even if
// this activity has been destroyed // this activity has been destroyed

View File

@@ -84,7 +84,7 @@ abstract class BaseControllerImpl extends DbControllerImpl
this.listener = listener; this.listener = listener;
} }
void onBlogPostAdded(final BlogPostHeader h, final boolean local) { void onBlogPostAdded(BlogPostHeader h, boolean local) {
listener.runOnUiThreadUnlessDestroyed( listener.runOnUiThreadUnlessDestroyed(
() -> listener.onBlogPostAdded(h, local)); () -> listener.onBlogPostAdded(h, local));
} }
@@ -94,8 +94,8 @@ abstract class BaseControllerImpl extends DbControllerImpl
} }
@Override @Override
public void loadBlogPosts(final GroupId groupId, public void loadBlogPosts(GroupId groupId,
final ResultExceptionHandler<Collection<BlogPostItem>, DbException> handler) { ResultExceptionHandler<Collection<BlogPostItem>, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
Collection<BlogPostItem> items = loadItems(groupId); Collection<BlogPostItem> items = loadItems(groupId);
@@ -129,8 +129,8 @@ abstract class BaseControllerImpl extends DbControllerImpl
} }
@Override @Override
public void loadBlogPost(final BlogPostHeader header, public void loadBlogPost(BlogPostHeader header,
final ResultExceptionHandler<BlogPostItem, DbException> handler) { ResultExceptionHandler<BlogPostItem, DbException> handler) {
String body = bodyCache.get(header.getId()); String body = bodyCache.get(header.getId());
if (body != null) { if (body != null) {
@@ -155,8 +155,8 @@ abstract class BaseControllerImpl extends DbControllerImpl
} }
@Override @Override
public void loadBlogPost(final GroupId g, final MessageId m, public void loadBlogPost(GroupId g, MessageId m,
final ResultExceptionHandler<BlogPostItem, DbException> handler) { ResultExceptionHandler<BlogPostItem, DbException> handler) {
BlogPostHeader header = headerCache.get(m); BlogPostHeader header = headerCache.get(m);
if (header != null) { if (header != null) {
@@ -182,9 +182,8 @@ abstract class BaseControllerImpl extends DbControllerImpl
} }
@Override @Override
public void repeatPost(final BlogPostItem item, public void repeatPost(BlogPostItem item, @Nullable String comment,
final @Nullable String comment, ExceptionHandler<DbException> handler) {
final ExceptionHandler<DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
LocalAuthor a = identityManager.getLocalAuthor(); LocalAuthor a = identityManager.getLocalAuthor();

View File

@@ -32,7 +32,7 @@ public class BlogActivity extends BriarActivity
Intent i = getIntent(); Intent i = getIntent();
byte[] b = i.getByteArrayExtra(GROUP_ID); byte[] b = i.getByteArrayExtra(GROUP_ID);
if (b == null) throw new IllegalStateException("No group ID in intent"); if (b == null) throw new IllegalStateException("No group ID in intent");
final GroupId groupId = new GroupId(b); GroupId groupId = new GroupId(b);
blogController.setGroupId(groupId); blogController.setGroupId(groupId);
setContentView(R.layout.activity_fragment_container_toolbar); setContentView(R.layout.activity_fragment_container_toolbar);

View File

@@ -125,32 +125,32 @@ class BlogControllerImpl extends BaseControllerImpl
} }
} }
private void onBlogInvitationAccepted(final ContactId c) { private void onBlogInvitationAccepted(ContactId c) {
listener.runOnUiThreadUnlessDestroyed( listener.runOnUiThreadUnlessDestroyed(
() -> listener.onBlogInvitationAccepted(c)); () -> listener.onBlogInvitationAccepted(c));
} }
private void onBlogLeft(final ContactId c) { private void onBlogLeft(ContactId c) {
listener.runOnUiThreadUnlessDestroyed(() -> listener.onBlogLeft(c)); listener.runOnUiThreadUnlessDestroyed(() -> listener.onBlogLeft(c));
} }
@Override @Override
public void loadBlogPosts( public void loadBlogPosts(
final ResultExceptionHandler<Collection<BlogPostItem>, DbException> handler) { ResultExceptionHandler<Collection<BlogPostItem>, DbException> handler) {
if (groupId == null) throw new IllegalStateException(); if (groupId == null) throw new IllegalStateException();
loadBlogPosts(groupId, handler); loadBlogPosts(groupId, handler);
} }
@Override @Override
public void loadBlogPost(final MessageId m, public void loadBlogPost(MessageId m,
final ResultExceptionHandler<BlogPostItem, DbException> handler) { ResultExceptionHandler<BlogPostItem, DbException> handler) {
if (groupId == null) throw new IllegalStateException(); if (groupId == null) throw new IllegalStateException();
loadBlogPost(groupId, m, handler); loadBlogPost(groupId, m, handler);
} }
@Override @Override
public void loadBlog( public void loadBlog(
final ResultExceptionHandler<BlogItem, DbException> handler) { ResultExceptionHandler<BlogItem, DbException> handler) {
if (groupId == null) throw new IllegalStateException(); if (groupId == null) throw new IllegalStateException();
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
@@ -173,8 +173,7 @@ class BlogControllerImpl extends BaseControllerImpl
} }
@Override @Override
public void deleteBlog( public void deleteBlog(ResultExceptionHandler<Void, DbException> handler) {
final ResultExceptionHandler<Void, DbException> handler) {
if (groupId == null) throw new IllegalStateException(); if (groupId == null) throw new IllegalStateException();
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
@@ -195,7 +194,7 @@ class BlogControllerImpl extends BaseControllerImpl
@Override @Override
public void loadSharingContacts( public void loadSharingContacts(
final ResultExceptionHandler<Collection<ContactId>, DbException> handler) { ResultExceptionHandler<Collection<ContactId>, DbException> handler) {
if (groupId == null) throw new IllegalStateException(); if (groupId == null) throw new IllegalStateException();
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {

View File

@@ -137,7 +137,7 @@ public class BlogFragment extends BaseFragment
} }
@Override @Override
public boolean onOptionsItemSelected(final MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.action_write_blog_post: case R.id.action_write_blog_post:
Intent i = new Intent(getActivity(), Intent i = new Intent(getActivity(),
@@ -184,7 +184,7 @@ public class BlogFragment extends BaseFragment
} }
@Override @Override
public void onBlogPostAdded(BlogPostHeader header, final boolean local) { public void onBlogPostAdded(BlogPostHeader header, boolean local) {
blogController.loadBlogPost(header, blogController.loadBlogPost(header,
new UiResultExceptionHandler<BlogPostItem, DbException>( new UiResultExceptionHandler<BlogPostItem, DbException>(
this) { this) {
@@ -224,7 +224,7 @@ public class BlogFragment extends BaseFragment
getContext().startActivity(i); getContext().startActivity(i);
} }
private void loadBlogPosts(final boolean reload) { private void loadBlogPosts(boolean reload) {
blogController.loadBlogPosts( blogController.loadBlogPosts(
new UiResultExceptionHandler<Collection<BlogPostItem>, new UiResultExceptionHandler<Collection<BlogPostItem>,
DbException>(this) { DbException>(this) {

View File

@@ -88,7 +88,7 @@ class BlogPostViewHolder extends RecyclerView.ViewHolder {
return "blogPost" + id.hashCode(); return "blogPost" + id.hashCode();
} }
void bindItem(@Nullable final BlogPostItem item) { void bindItem(@Nullable BlogPostItem item) {
if (item == null) return; if (item == null) return;
setTransitionName(item.getId()); setTransitionName(item.getId());
@@ -152,7 +152,7 @@ class BlogPostViewHolder extends RecyclerView.ViewHolder {
} }
} }
private void onBindComment(final BlogCommentItem item) { private void onBindComment(BlogCommentItem item) {
// reblogger // reblogger
reblogger.setAuthor(item.getAuthor()); reblogger.setAuthor(item.getAuthor());
reblogger.setAuthorStatus(item.getAuthorStatus()); reblogger.setAuthorStatus(item.getAuthorStatus());

View File

@@ -96,7 +96,7 @@ class FeedControllerImpl extends BaseControllerImpl
@Override @Override
public void loadBlogPosts( public void loadBlogPosts(
final ResultExceptionHandler<Collection<BlogPostItem>, DbException> handler) { ResultExceptionHandler<Collection<BlogPostItem>, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@@ -122,7 +122,7 @@ class FeedControllerImpl extends BaseControllerImpl
@Override @Override
public void loadPersonalBlog( public void loadPersonalBlog(
final ResultExceptionHandler<Blog, DbException> handler) { ResultExceptionHandler<Blog, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();

View File

@@ -135,8 +135,8 @@ public class FeedFragment extends BaseFragment implements
}); });
} }
private void loadBlogPosts(final boolean clear) { private void loadBlogPosts(boolean clear) {
final int revision = adapter.getRevision(); int revision = adapter.getRevision();
feedController.loadBlogPosts( feedController.loadBlogPosts(
new UiResultExceptionHandler<Collection<BlogPostItem>, DbException>( new UiResultExceptionHandler<Collection<BlogPostItem>, DbException>(
this) { this) {
@@ -167,7 +167,7 @@ public class FeedFragment extends BaseFragment implements
} }
@Override @Override
public boolean onOptionsItemSelected(final MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
if (personalBlog == null) return false; if (personalBlog == null) return false;
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.action_write_blog_post: case R.id.action_write_blog_post:
@@ -193,7 +193,7 @@ public class FeedFragment extends BaseFragment implements
} }
@Override @Override
public void onBlogPostAdded(BlogPostHeader header, final boolean local) { public void onBlogPostAdded(BlogPostHeader header, boolean local) {
feedController.loadBlogPost(header, feedController.loadBlogPost(header,
new UiResultExceptionHandler<BlogPostItem, DbException>( new UiResultExceptionHandler<BlogPostItem, DbException>(
this) { this) {

View File

@@ -34,7 +34,7 @@ class RssFeedAdapter extends BriarAdapter<Feed, RssFeedAdapter.FeedViewHolder> {
@Override @Override
public void onBindViewHolder(FeedViewHolder ui, int position) { public void onBindViewHolder(FeedViewHolder ui, int position) {
final Feed item = getItemAt(position); Feed item = getItemAt(position);
if (item == null) return; if (item == null) return;
// Feed Title // Feed Title

View File

@@ -118,7 +118,7 @@ public class RssFeedImportActivity extends BriarActivity {
importFeed(url); importFeed(url);
} }
private void importFeed(final String url) { private void importFeed(String url) {
ioExecutor.execute(() -> { ioExecutor.execute(() -> {
try { try {
feedManager.addFeed(url); feedManager.addFeed(url);

View File

@@ -103,7 +103,7 @@ public class RssFeedManageActivity extends BriarActivity
} }
@Override @Override
public void onDeleteClick(final Feed feed) { public void onDeleteClick(Feed feed) {
DialogInterface.OnClickListener okListener = DialogInterface.OnClickListener okListener =
(dialog, which) -> deleteFeed(feed); (dialog, which) -> deleteFeed(feed);
AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog.Builder builder = new AlertDialog.Builder(this,
@@ -118,7 +118,7 @@ public class RssFeedManageActivity extends BriarActivity
} }
private void loadFeeds() { private void loadFeeds() {
final int revision = adapter.getRevision(); int revision = adapter.getRevision();
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
displayFeeds(revision, feedManager.getFeeds()); displayFeeds(revision, feedManager.getFeeds());
@@ -129,7 +129,7 @@ public class RssFeedManageActivity extends BriarActivity
}); });
} }
private void displayFeeds(final int revision, final List<Feed> feeds) { private void displayFeeds(int revision, List<Feed> feeds) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
if (revision == adapter.getRevision()) { if (revision == adapter.getRevision()) {
adapter.incrementRevision(); adapter.incrementRevision();
@@ -142,7 +142,7 @@ public class RssFeedManageActivity extends BriarActivity
}); });
} }
private void deleteFeed(final Feed feed) { private void deleteFeed(Feed feed) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
feedManager.removeFeed(feed); feedManager.removeFeed(feed);
@@ -161,7 +161,7 @@ public class RssFeedManageActivity extends BriarActivity
}); });
} }
private void onFeedDeleted(final Feed feed) { private void onFeedDeleted(Feed feed) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
adapter.incrementRevision(); adapter.incrementRevision();
adapter.remove(feed); adapter.remove(feed);

View File

@@ -140,7 +140,7 @@ public class WriteBlogPostActivity extends BriarActivity
storePost(body); storePost(body);
} }
private void storePost(final String body) { private void storePost(String body) {
runOnDbThread(() -> { runOnDbThread(() -> {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
try { try {

View File

@@ -23,7 +23,7 @@ public abstract class BaseContactListAdapter<I extends ContactItem, VH extends C
} }
@Override @Override
public void onBindViewHolder(final VH ui, int position) { public void onBindViewHolder(VH ui, int position) {
I item = items.get(position); I item = items.get(position);
ui.bind(item, listener); ui.bind(item, listener);
} }

View File

@@ -37,8 +37,7 @@ public class ContactItemViewHolder<I extends ContactItem>
bulb = (ImageView) v.findViewById(R.id.bulbView); bulb = (ImageView) v.findViewById(R.id.bulbView);
} }
protected void bind(final I item, protected void bind(I item, @Nullable OnContactClickListener<I> listener) {
@Nullable final OnContactClickListener<I> listener) {
Author author = item.getContact().getAuthor(); Author author = item.getContact().getAuthor();
avatar.setImageDrawable( avatar.setImageDrawable(
new IdenticonDrawable(author.getId().getBytes())); new IdenticonDrawable(author.getId().getBytes()));

View File

@@ -158,7 +158,7 @@ public class ContactListFragment extends BaseFragment implements EventListener {
} }
@Override @Override
public boolean onOptionsItemSelected(final MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items // Handle presses on the action bar items
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.action_add_contact: case R.id.action_add_contact:
@@ -191,7 +191,7 @@ public class ContactListFragment extends BaseFragment implements EventListener {
} }
private void loadContacts() { private void loadContacts() {
final int revision = adapter.getRevision(); int revision = adapter.getRevision();
listener.runOnDbThread(() -> { listener.runOnDbThread(() -> {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@@ -218,8 +218,7 @@ public class ContactListFragment extends BaseFragment implements EventListener {
}); });
} }
private void displayContacts(final int revision, private void displayContacts(int revision, List<ContactListItem> contacts) {
final List<ContactListItem> contacts) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
if (revision == adapter.getRevision()) { if (revision == adapter.getRevision()) {
adapter.incrementRevision(); adapter.incrementRevision();
@@ -282,7 +281,7 @@ public class ContactListFragment extends BaseFragment implements EventListener {
} }
} }
private void updateItem(final ContactId c, final BaseMessageHeader h) { private void updateItem(ContactId c, BaseMessageHeader h) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
adapter.incrementRevision(); adapter.incrementRevision();
int position = adapter.findItemPosition(c); int position = adapter.findItemPosition(c);
@@ -295,7 +294,7 @@ public class ContactListFragment extends BaseFragment implements EventListener {
}); });
} }
private void removeItem(final ContactId c) { private void removeItem(ContactId c) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
adapter.incrementRevision(); adapter.incrementRevision();
int position = adapter.findItemPosition(c); int position = adapter.findItemPosition(c);
@@ -304,7 +303,7 @@ public class ContactListFragment extends BaseFragment implements EventListener {
}); });
} }
private void setConnected(final ContactId c, final boolean connected) { private void setConnected(ContactId c, boolean connected) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
adapter.incrementRevision(); adapter.incrementRevision();
int position = adapter.findItemPosition(c); int position = adapter.findItemPosition(c);

View File

@@ -268,7 +268,7 @@ public class ConversationActivity extends BriarActivity
} }
@Override @Override
public boolean onOptionsItemSelected(final MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items // Handle presses on the action bar items
switch (item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
@@ -338,7 +338,7 @@ public class ConversationActivity extends BriarActivity
} }
private void loadMessages() { private void loadMessages() {
final int revision = adapter.getRevision(); int revision = adapter.getRevision();
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@@ -370,10 +370,10 @@ public class ConversationActivity extends BriarActivity
}); });
} }
private void displayMessages(final int revision, private void displayMessages(int revision,
final Collection<PrivateMessageHeader> headers, Collection<PrivateMessageHeader> headers,
final Collection<IntroductionMessage> introductions, Collection<IntroductionMessage> introductions,
final Collection<InvitationMessage> invitations) { Collection<InvitationMessage> invitations) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
if (revision == adapter.getRevision()) { if (revision == adapter.getRevision()) {
adapter.incrementRevision(); adapter.incrementRevision();
@@ -436,7 +436,7 @@ public class ConversationActivity extends BriarActivity
return items; return items;
} }
private void loadMessageBody(final MessageId m) { private void loadMessageBody(MessageId m) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@@ -451,7 +451,7 @@ public class ConversationActivity extends BriarActivity
}); });
} }
private void displayMessageBody(final MessageId m, final String body) { private void displayMessageBody(MessageId m, String body) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
bodyCache.put(m, body); bodyCache.put(m, body);
SparseArray<ConversationItem> messages = SparseArray<ConversationItem> messages =
@@ -543,7 +543,7 @@ public class ConversationActivity extends BriarActivity
} }
} }
private void addConversationItem(final ConversationItem item) { private void addConversationItem(ConversationItem item) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
adapter.incrementRevision(); adapter.incrementRevision();
adapter.add(item); adapter.add(item);
@@ -552,10 +552,10 @@ public class ConversationActivity extends BriarActivity
}); });
} }
private void handleIntroductionRequest(final IntroductionRequest m) { private void handleIntroductionRequest(IntroductionRequest m) {
getContactNameTask().addListener(new FutureTaskListener<String>() { getContactNameTask().addListener(new FutureTaskListener<String>() {
@Override @Override
public void onSuccess(final String contactName) { public void onSuccess(String contactName) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
ConversationItem item = ConversationItem ConversationItem item = ConversationItem
.from(ConversationActivity.this, contactName, m); .from(ConversationActivity.this, contactName, m);
@@ -563,17 +563,17 @@ public class ConversationActivity extends BriarActivity
}); });
} }
@Override @Override
public void onFailure(final Throwable exception) { public void onFailure(Throwable exception) {
runOnUiThreadUnlessDestroyed( runOnUiThreadUnlessDestroyed(
() -> handleDbException((DbException) exception)); () -> handleDbException((DbException) exception));
} }
}); });
} }
private void handleIntroductionResponse(final IntroductionResponse m) { private void handleIntroductionResponse(IntroductionResponse m) {
getContactNameTask().addListener(new FutureTaskListener<String>() { getContactNameTask().addListener(new FutureTaskListener<String>() {
@Override @Override
public void onSuccess(final String contactName) { public void onSuccess(String contactName) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
ConversationItem item = ConversationItem ConversationItem item = ConversationItem
.from(ConversationActivity.this, contactName, m); .from(ConversationActivity.this, contactName, m);
@@ -581,17 +581,17 @@ public class ConversationActivity extends BriarActivity
}); });
} }
@Override @Override
public void onFailure(final Throwable exception) { public void onFailure(Throwable exception) {
runOnUiThreadUnlessDestroyed( runOnUiThreadUnlessDestroyed(
() -> handleDbException((DbException) exception)); () -> handleDbException((DbException) exception));
} }
}); });
} }
private void handleInvitationRequest(final InvitationRequest m) { private void handleInvitationRequest(InvitationRequest m) {
getContactNameTask().addListener(new FutureTaskListener<String>() { getContactNameTask().addListener(new FutureTaskListener<String>() {
@Override @Override
public void onSuccess(final String contactName) { public void onSuccess(String contactName) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
ConversationItem item = ConversationItem ConversationItem item = ConversationItem
.from(ConversationActivity.this, contactName, m); .from(ConversationActivity.this, contactName, m);
@@ -599,17 +599,17 @@ public class ConversationActivity extends BriarActivity
}); });
} }
@Override @Override
public void onFailure(final Throwable exception) { public void onFailure(Throwable exception) {
runOnUiThreadUnlessDestroyed( runOnUiThreadUnlessDestroyed(
() -> handleDbException((DbException) exception)); () -> handleDbException((DbException) exception));
} }
}); });
} }
private void handleInvitationResponse(final InvitationResponse m) { private void handleInvitationResponse(InvitationResponse m) {
getContactNameTask().addListener(new FutureTaskListener<String>() { getContactNameTask().addListener(new FutureTaskListener<String>() {
@Override @Override
public void onSuccess(final String contactName) { public void onSuccess(String contactName) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
ConversationItem item = ConversationItem ConversationItem item = ConversationItem
.from(ConversationActivity.this, contactName, m); .from(ConversationActivity.this, contactName, m);
@@ -617,15 +617,15 @@ public class ConversationActivity extends BriarActivity
}); });
} }
@Override @Override
public void onFailure(final Throwable exception) { public void onFailure(Throwable exception) {
runOnUiThreadUnlessDestroyed( runOnUiThreadUnlessDestroyed(
() -> handleDbException((DbException) exception)); () -> handleDbException((DbException) exception));
} }
}); });
} }
private void markMessages(final Collection<MessageId> messageIds, private void markMessages(Collection<MessageId> messageIds,
final boolean sent, final boolean seen) { boolean sent, boolean seen) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
adapter.incrementRevision(); adapter.incrementRevision();
Set<MessageId> messages = new HashSet<>(messageIds); Set<MessageId> messages = new HashSet<>(messageIds);
@@ -659,7 +659,7 @@ public class ConversationActivity extends BriarActivity
return item == null ? 0 : item.getTime() + 1; return item == null ? 0 : item.getTime() + 1;
} }
private void loadGroupId(final String body, final long timestamp) { private void loadGroupId(String body, long timestamp) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
messagingGroupId = messagingGroupId =
@@ -672,7 +672,7 @@ public class ConversationActivity extends BriarActivity
}); });
} }
private void createMessage(final String body, final long timestamp) { private void createMessage(String body, long timestamp) {
cryptoExecutor.execute(() -> { cryptoExecutor.execute(() -> {
try { try {
//noinspection ConstantConditions init in loadGroupId() //noinspection ConstantConditions init in loadGroupId()
@@ -683,7 +683,7 @@ public class ConversationActivity extends BriarActivity
}); });
} }
private void storeMessage(final PrivateMessage m, final String body) { private void storeMessage(PrivateMessage m, String body) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@@ -739,7 +739,7 @@ public class ConversationActivity extends BriarActivity
}); });
} }
private void enableIntroductionActionIfAvailable(final MenuItem item) { private void enableIntroductionActionIfAvailable(MenuItem item) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
if (contactManager.getActiveContacts().size() > 1) { if (contactManager.getActiveContacts().size() > 1) {
@@ -757,7 +757,7 @@ public class ConversationActivity extends BriarActivity
}); });
} }
private void enableIntroductionAction(final MenuItem item) { private void enableIntroductionAction(MenuItem item) {
runOnUiThreadUnlessDestroyed(() -> item.setEnabled(true)); runOnUiThreadUnlessDestroyed(() -> item.setEnabled(true));
} }
@@ -817,7 +817,7 @@ public class ConversationActivity extends BriarActivity
if (!item.isRead()) markMessageRead(item.getGroupId(), item.getId()); if (!item.isRead()) markMessageRead(item.getGroupId(), item.getId());
} }
private void markMessageRead(final GroupId g, final MessageId m) { private void markMessageRead(GroupId g, MessageId m) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@@ -833,8 +833,7 @@ public class ConversationActivity extends BriarActivity
@UiThread @UiThread
@Override @Override
public void respondToRequest(final ConversationRequestItem item, public void respondToRequest(ConversationRequestItem item, boolean accept) {
final boolean accept) {
item.setAnswered(true); item.setAnswered(true);
int position = adapter.findItemPosition(item); int position = adapter.findItemPosition(item);
if (position != INVALID_POSITION) { if (position != INVALID_POSITION) {

View File

@@ -25,10 +25,10 @@ class ConversationRequestViewHolder extends ConversationNoticeInViewHolder {
} }
void bind(ConversationItem conversationItem, void bind(ConversationItem conversationItem,
final ConversationListener listener) { ConversationListener listener) {
super.bind(conversationItem); super.bind(conversationItem);
final ConversationRequestItem item = ConversationRequestItem item =
(ConversationRequestItem) conversationItem; (ConversationRequestItem) conversationItem;
if (item.wasAnswered() && item.canBeOpened()) { if (item.wasAnswered() && item.canBeOpened()) {

View File

@@ -117,7 +117,7 @@ public abstract class BaseContactSelectorFragment<I extends SelectableContactIte
onSelectionChanged(); onSelectionChanged();
} }
private void loadContacts(final Collection<ContactId> selection) { private void loadContacts(Collection<ContactId> selection) {
getController().loadContacts(groupId, selection, getController().loadContacts(groupId, selection,
new UiResultExceptionHandler<Collection<I>, DbException>( new UiResultExceptionHandler<Collection<I>, DbException>(
this) { this) {

View File

@@ -25,7 +25,7 @@ public abstract class ContactSelectorActivity
extends BriarActivity extends BriarActivity
implements BaseFragmentListener, ContactSelectorListener { implements BaseFragmentListener, ContactSelectorListener {
final static String CONTACTS = "contacts"; protected final static String CONTACTS = "contacts";
// Subclasses may initialise the group ID in different places // Subclasses may initialise the group ID in different places
protected GroupId groupId; protected GroupId groupId;

View File

@@ -38,9 +38,8 @@ public abstract class ContactSelectorControllerImpl
} }
@Override @Override
public void loadContacts(final GroupId g, public void loadContacts(GroupId g, Collection<ContactId> selection,
final Collection<ContactId> selection, ResultExceptionHandler<Collection<SelectableContactItem>, DbException> handler) {
final ResultExceptionHandler<Collection<SelectableContactItem>, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
Collection<SelectableContactItem> contacts = new ArrayList<>(); Collection<SelectableContactItem> contacts = new ArrayList<>();

View File

@@ -36,7 +36,7 @@ public abstract class ContactSelectorFragment extends
} }
@Override @Override
public boolean onOptionsItemSelected(final MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.action_contacts_selected: case R.id.action_contacts_selected:
selectedContacts = adapter.getSelectedContactIds(); selectedContacts = adapter.getSelectedContactIds();

View File

@@ -66,7 +66,7 @@ public class BriarControllerImpl implements BriarController {
} }
@Override @Override
public void signOut(final ResultHandler<Void> eventHandler) { public void signOut(ResultHandler<Void> eventHandler) {
new Thread() { new Thread() {
@Override @Override
public void run() { public void run() {

View File

@@ -28,7 +28,7 @@ public class DbControllerImpl implements DbController {
} }
@Override @Override
public void runOnDbThread(final Runnable task) { public void runOnDbThread(Runnable task) {
dbExecutor.execute(() -> { dbExecutor.execute(() -> {
try { try {
lifecycleManager.waitForDatabase(); lifecycleManager.waitForDatabase();

View File

@@ -58,7 +58,7 @@ public class SharingControllerImpl implements SharingController, EventListener {
} }
} }
private void setConnected(final ContactId c) { private void setConnected(ContactId c) {
if (listener == null) return; if (listener == null) return;
listener.runOnUiThreadUnlessDestroyed(() -> { listener.runOnUiThreadUnlessDestroyed(() -> {
if (contacts.contains(c)) { if (contacts.contains(c)) {

View File

@@ -19,7 +19,7 @@ public abstract class UiExceptionHandler<E extends Exception>
} }
@Override @Override
public void onException(final E exception) { public void onException(E exception) {
listener.runOnUiThreadUnlessDestroyed(() -> onExceptionUi(exception)); listener.runOnUiThreadUnlessDestroyed(() -> onExceptionUi(exception));
} }

View File

@@ -17,7 +17,7 @@ public abstract class UiResultExceptionHandler<R, E extends Exception>
} }
@Override @Override
public void onResult(final R result) { public void onResult(R result) {
listener.runOnUiThreadUnlessDestroyed(() -> onResultUi(result)); listener.runOnUiThreadUnlessDestroyed(() -> onResultUi(result));
} }

View File

@@ -13,7 +13,7 @@ public abstract class UiResultHandler<R> implements ResultHandler<R> {
} }
@Override @Override
public void onResult(final R result) { public void onResult(R result) {
listener.runOnUiThreadUnlessDestroyed(() -> onResultUi(result)); listener.runOnUiThreadUnlessDestroyed(() -> onResultUi(result));
} }

View File

@@ -120,7 +120,7 @@ public class CreateForumActivity extends BriarActivity {
storeForum(nameEntry.getText().toString()); storeForum(nameEntry.getText().toString());
} }
private void storeForum(final String name) { private void storeForum(String name) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@@ -136,7 +136,7 @@ public class CreateForumActivity extends BriarActivity {
}); });
} }
private void displayForum(final Forum f) { private void displayForum(Forum f) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
Intent i = new Intent(CreateForumActivity.this, Intent i = new Intent(CreateForumActivity.this,
ForumActivity.class); ForumActivity.class);

View File

@@ -106,7 +106,7 @@ public class ForumActivity extends
} }
@Override @Override
public boolean onOptionsItemSelected(final MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items // Handle presses on the action bar items
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.action_forum_share: case R.id.action_forum_share:

View File

@@ -120,7 +120,7 @@ class ForumControllerImpl extends
@Override @Override
public void loadSharingContacts( public void loadSharingContacts(
final ResultExceptionHandler<Collection<ContactId>, DbException> handler) { ResultExceptionHandler<Collection<ContactId>, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
Collection<Contact> contacts = Collection<Contact> contacts =
@@ -137,9 +137,9 @@ class ForumControllerImpl extends
} }
@Override @Override
public void createAndStoreMessage(final String body, public void createAndStoreMessage(String body,
@Nullable final ForumItem parentItem, @Nullable ForumItem parentItem,
final ResultExceptionHandler<ForumItem, DbException> handler) { ResultExceptionHandler<ForumItem, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
LocalAuthor author = identityManager.getLocalAuthor(); LocalAuthor author = identityManager.getLocalAuthor();
@@ -156,9 +156,9 @@ class ForumControllerImpl extends
}); });
} }
private void createMessage(final String body, final long timestamp, private void createMessage(String body, long timestamp,
final @Nullable MessageId parentId, final LocalAuthor author, @Nullable MessageId parentId, LocalAuthor author,
final ResultExceptionHandler<ForumItem, DbException> handler) { ResultExceptionHandler<ForumItem, DbException> handler) {
cryptoExecutor.execute(() -> { cryptoExecutor.execute(() -> {
LOG.info("Creating forum post..."); LOG.info("Creating forum post...");
ForumPost msg = forumManager.createLocalPost(getGroupId(), body, ForumPost msg = forumManager.createLocalPost(getGroupId(), body,
@@ -184,17 +184,17 @@ class ForumControllerImpl extends
} }
private void onForumPostReceived(ForumPostHeader h, String body) { private void onForumPostReceived(ForumPostHeader h, String body) {
final ForumItem item = buildItem(h, body); ForumItem item = buildItem(h, body);
listener.runOnUiThreadUnlessDestroyed( listener.runOnUiThreadUnlessDestroyed(
() -> listener.onItemReceived(item)); () -> listener.onItemReceived(item));
} }
private void onForumInvitationAccepted(final ContactId c) { private void onForumInvitationAccepted(ContactId c) {
listener.runOnUiThreadUnlessDestroyed( listener.runOnUiThreadUnlessDestroyed(
() -> listener.onInvitationAccepted(c)); () -> listener.onInvitationAccepted(c));
} }
private void onForumLeft(final ContactId c) { private void onForumLeft(ContactId c) {
listener.runOnUiThreadUnlessDestroyed(() -> listener.onForumLeft(c)); listener.runOnUiThreadUnlessDestroyed(() -> listener.onForumLeft(c));
} }

View File

@@ -38,7 +38,7 @@ class ForumListAdapter
@Override @Override
public void onBindViewHolder(ForumViewHolder ui, int position) { public void onBindViewHolder(ForumViewHolder ui, int position) {
final ForumListItem item = getItemAt(position); ForumListItem item = getItemAt(position);
if (item == null) return; if (item == null) return;
// Avatar // Avatar

View File

@@ -140,7 +140,7 @@ public class ForumListFragment extends BaseEventFragment implements
} }
@Override @Override
public boolean onOptionsItemSelected(final MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items // Handle presses on the action bar items
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.action_create_forum: case R.id.action_create_forum:
@@ -154,7 +154,7 @@ public class ForumListFragment extends BaseEventFragment implements
} }
private void loadForums() { private void loadForums() {
final int revision = adapter.getRevision(); int revision = adapter.getRevision();
listener.runOnDbThread(() -> { listener.runOnDbThread(() -> {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@@ -178,8 +178,7 @@ public class ForumListFragment extends BaseEventFragment implements
}); });
} }
private void displayForums(final int revision, private void displayForums(int revision, Collection<ForumListItem> forums) {
final Collection<ForumListItem> forums) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
if (revision == adapter.getRevision()) { if (revision == adapter.getRevision()) {
adapter.incrementRevision(); adapter.incrementRevision();
@@ -207,7 +206,7 @@ public class ForumListFragment extends BaseEventFragment implements
}); });
} }
private void displayAvailableForums(final int availableCount) { private void displayAvailableForums(int availableCount) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
if (availableCount == 0) { if (availableCount == 0) {
snackbar.dismiss(); snackbar.dismiss();
@@ -247,7 +246,7 @@ public class ForumListFragment extends BaseEventFragment implements
} }
} }
private void updateItem(final GroupId g, final ForumPostHeader m) { private void updateItem(GroupId g, ForumPostHeader m) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
adapter.incrementRevision(); adapter.incrementRevision();
int position = adapter.findItemPosition(g); int position = adapter.findItemPosition(g);
@@ -259,7 +258,7 @@ public class ForumListFragment extends BaseEventFragment implements
}); });
} }
private void removeForum(final GroupId g) { private void removeForum(GroupId g) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
adapter.incrementRevision(); adapter.incrementRevision();
int position = adapter.findItemPosition(g); int position = adapter.findItemPosition(g);

View File

@@ -44,7 +44,7 @@ public abstract class BaseFragment extends Fragment
} }
@Override @Override
public boolean onOptionsItemSelected(final MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
listener.onBackPressed(); listener.onBackPressed();
@@ -79,8 +79,8 @@ public abstract class BaseFragment extends Fragment
@CallSuper @CallSuper
@Override @Override
public void runOnUiThreadUnlessDestroyed(final Runnable r) { public void runOnUiThreadUnlessDestroyed(Runnable r) {
final Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) { if (activity != null) {
activity.runOnUiThread(() -> { activity.runOnUiThread(() -> {
// Note that we don't have to check if the activity has // Note that we don't have to check if the activity has

View File

@@ -134,7 +134,7 @@ public class ContactChooserFragment extends BaseFragment {
}); });
} }
private void displayContacts(final List<ContactListItem> contacts) { private void displayContacts(List<ContactListItem> contacts) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
if (contacts.isEmpty()) list.showData(); if (contacts.isEmpty()) list.showData();
else adapter.addAll(contacts); else adapter.addAll(contacts);

View File

@@ -118,8 +118,7 @@ public class IntroductionMessageFragment extends BaseFragment
return TAG; return TAG;
} }
private void prepareToSetUpViews(final int contactId1, private void prepareToSetUpViews(int contactId1, int contactId2) {
final int contactId2) {
introductionActivity.runOnDbThread(() -> { introductionActivity.runOnDbThread(() -> {
try { try {
Contact c1 = contactManager.getContact( Contact c1 = contactManager.getContact(
@@ -133,7 +132,7 @@ public class IntroductionMessageFragment extends BaseFragment
}); });
} }
private void setUpViews(final Contact c1, final Contact c2) { private void setUpViews(Contact c1, Contact c2) {
introductionActivity.runOnUiThreadUnlessDestroyed(() -> { introductionActivity.runOnUiThreadUnlessDestroyed(() -> {
contact1 = c1; contact1 = c1;
contact2 = c2; contact2 = c2;
@@ -159,7 +158,7 @@ public class IntroductionMessageFragment extends BaseFragment
} }
@Override @Override
public boolean onOptionsItemSelected(final MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
introductionActivity.hideSoftKeyboard(ui.message); introductionActivity.hideSoftKeyboard(ui.message);
@@ -185,8 +184,7 @@ public class IntroductionMessageFragment extends BaseFragment
introductionActivity.supportFinishAfterTransition(); introductionActivity.supportFinishAfterTransition();
} }
private void makeIntroduction(final Contact c1, final Contact c2, private void makeIntroduction(Contact c1, Contact c2, String msg) {
final String msg) {
introductionActivity.runOnDbThread(() -> { introductionActivity.runOnDbThread(() -> {
// actually make the introduction // actually make the introduction
try { try {

View File

@@ -352,7 +352,7 @@ public class CameraView extends SurfaceView implements SurfaceHolder.Callback,
} }
@Override @Override
public void surfaceCreated(final SurfaceHolder holder) { public void surfaceCreated(SurfaceHolder holder) {
post(() -> { post(() -> {
try { try {
surfaceCreatedUi(holder); surfaceCreatedUi(holder);
@@ -375,8 +375,7 @@ public class CameraView extends SurfaceView implements SurfaceHolder.Callback,
} }
@Override @Override
public void surfaceChanged(final SurfaceHolder holder, int format, public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
final int w, final int h) {
post(() -> { post(() -> {
try { try {
surfaceChangedUi(holder, w, h); surfaceChangedUi(holder, w, h);
@@ -411,7 +410,7 @@ public class CameraView extends SurfaceView implements SurfaceHolder.Callback,
} }
@Override @Override
public void surfaceDestroyed(final SurfaceHolder holder) { public void surfaceDestroyed(SurfaceHolder holder) {
post(() -> surfaceDestroyedUi(holder)); post(() -> surfaceDestroyedUi(holder));
} }
@@ -427,7 +426,7 @@ public class CameraView extends SurfaceView implements SurfaceHolder.Callback,
} }
@Override @Override
public void onAutoFocus(boolean success, final Camera camera) { public void onAutoFocus(boolean success, Camera camera) {
LOG.info("Auto focus succeeded: " + success); LOG.info("Auto focus succeeded: " + success);
postDelayed(this::retryAutoFocus, AUTO_FOCUS_RETRY_DELAY); postDelayed(this::retryAutoFocus, AUTO_FOCUS_RETRY_DELAY);
} }

View File

@@ -99,7 +99,7 @@ public class KeyAgreementActivity extends BriarActivity implements
} }
@Override @Override
public boolean onOptionsItemSelected(final MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
onBackPressed(); onBackPressed();
@@ -204,11 +204,11 @@ public class KeyAgreementActivity extends BriarActivity implements
} }
} }
private void keyAgreementFinished(final KeyAgreementResult result) { private void keyAgreementFinished(KeyAgreementResult result) {
runOnUiThreadUnlessDestroyed(() -> startContactExchange(result)); runOnUiThreadUnlessDestroyed(() -> startContactExchange(result));
} }
private void startContactExchange(final KeyAgreementResult result) { private void startContactExchange(KeyAgreementResult result) {
runOnDbThread(() -> { runOnDbThread(() -> {
LocalAuthor localAuthor; LocalAuthor localAuthor;
// Load the local pseudonym // Load the local pseudonym
@@ -229,7 +229,7 @@ public class KeyAgreementActivity extends BriarActivity implements
} }
@Override @Override
public void contactExchangeSucceeded(final Author remoteAuthor) { public void contactExchangeSucceeded(Author remoteAuthor) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
String contactName = remoteAuthor.getName(); String contactName = remoteAuthor.getName();
String format = getString(string.contact_added_toast); String format = getString(string.contact_added_toast);
@@ -240,7 +240,7 @@ public class KeyAgreementActivity extends BriarActivity implements
} }
@Override @Override
public void duplicateContact(final Author remoteAuthor) { public void duplicateContact(Author remoteAuthor) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
String contactName = remoteAuthor.getName(); String contactName = remoteAuthor.getName();
String format = getString(string.contact_already_exists); String format = getString(string.contact_already_exists);

View File

@@ -30,8 +30,8 @@ class QrCodeUtils {
int smallestDimen = Math.min(dm.widthPixels, dm.heightPixels); int smallestDimen = Math.min(dm.widthPixels, dm.heightPixels);
try { try {
// Generate QR code // Generate QR code
final BitMatrix encoded = new QRCodeWriter().encode( BitMatrix encoded = new QRCodeWriter().encode(input, QR_CODE,
input, QR_CODE, smallestDimen, smallestDimen); smallestDimen, smallestDimen);
// Convert QR code to Bitmap // Convert QR code to Bitmap
int width = encoded.getWidth(); int width = encoded.getWidth();
int height = encoded.getHeight(); int height = encoded.getHeight();

View File

@@ -157,8 +157,7 @@ public class ShowQrCodeFragment extends BaseEventFragment
getActivity().registerReceiver(receiver, filter); getActivity().registerReceiver(receiver, filter);
// Enable BT adapter if it is not already on. // Enable BT adapter if it is not already on.
final BluetoothAdapter adapter = BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothAdapter.getDefaultAdapter();
if (adapter != null && !adapter.isEnabled()) { if (adapter != null && !adapter.isEnabled()) {
waitingForBluetooth = true; waitingForBluetooth = true;
eventBus.broadcast(new EnableBluetoothEvent()); eventBus.broadcast(new EnableBluetoothEvent());
@@ -189,8 +188,8 @@ public class ShowQrCodeFragment extends BaseEventFragment
@UiThread @UiThread
private void startListening() { private void startListening() {
final KeyAgreementTask oldTask = task; KeyAgreementTask oldTask = task;
final KeyAgreementTask newTask = keyAgreementTaskFactory.createTask(); KeyAgreementTask newTask = keyAgreementTaskFactory.createTask();
task = newTask; task = newTask;
ioExecutor.execute(() -> { ioExecutor.execute(() -> {
if (oldTask != null) oldTask.stopListening(); if (oldTask != null) oldTask.stopListening();
@@ -200,7 +199,7 @@ public class ShowQrCodeFragment extends BaseEventFragment
@UiThread @UiThread
private void stopListening() { private void stopListening() {
final KeyAgreementTask oldTask = task; KeyAgreementTask oldTask = task;
ioExecutor.execute(() -> { ioExecutor.execute(() -> {
if (oldTask != null) oldTask.stopListening(); if (oldTask != null) oldTask.stopListening();
}); });
@@ -257,11 +256,11 @@ public class ShowQrCodeFragment extends BaseEventFragment
} }
@UiThread @UiThread
private void generateBitmapQR(final Payload payload) { private void generateBitmapQR(Payload payload) {
// Get narrowest screen dimension // Get narrowest screen dimension
Context context = getContext(); Context context = getContext();
if (context == null) return; if (context == null) return;
final DisplayMetrics dm = context.getResources().getDisplayMetrics(); DisplayMetrics dm = context.getResources().getDisplayMetrics();
new AsyncTask<Void, Void, Bitmap>() { new AsyncTask<Void, Void, Bitmap>() {
@Override @Override
@@ -286,7 +285,7 @@ public class ShowQrCodeFragment extends BaseEventFragment
}.execute(); }.execute();
} }
private void setQrCode(final Payload localPayload) { private void setQrCode(Payload localPayload) {
runOnUiThreadUnlessDestroyed(() -> generateBitmapQR(localPayload)); runOnUiThreadUnlessDestroyed(() -> generateBitmapQR(localPayload));
} }
@@ -311,7 +310,7 @@ public class ShowQrCodeFragment extends BaseEventFragment
}); });
} }
private void keyAgreementAborted(final boolean remoteAborted) { private void keyAgreementAborted(boolean remoteAborted) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
reset(); reset();
mainProgressContainer.setVisibility(INVISIBLE); mainProgressContainer.setVisibility(INVISIBLE);
@@ -325,7 +324,7 @@ public class ShowQrCodeFragment extends BaseEventFragment
} }
@Override @Override
public void handleResult(final Result result) { public void handleResult(Result result) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
LOG.info("Got result from decoder"); LOG.info("Got result from decoder");
// Ignore results until the KeyAgreementTask is ready // Ignore results until the KeyAgreementTask is ready

View File

@@ -47,9 +47,9 @@ public class PasswordControllerImpl extends ConfigControllerImpl
} }
@Override @Override
public void validatePassword(final String password, public void validatePassword(String password,
final ResultHandler<Boolean> resultHandler) { ResultHandler<Boolean> resultHandler) {
final byte[] encrypted = getEncryptedKey(); byte[] encrypted = getEncryptedKey();
cryptoExecutor.execute(() -> { cryptoExecutor.execute(() -> {
byte[] key = crypto.decryptWithPassword(encrypted, password); byte[] key = crypto.decryptWithPassword(encrypted, password);
if (key == null) { if (key == null) {
@@ -62,9 +62,9 @@ public class PasswordControllerImpl extends ConfigControllerImpl
} }
@Override @Override
public void changePassword(final String password, final String newPassword, public void changePassword(String password, String newPassword,
final ResultHandler<Boolean> resultHandler) { ResultHandler<Boolean> resultHandler) {
final byte[] encrypted = getEncryptedKey(); byte[] encrypted = getEncryptedKey();
cryptoExecutor.execute(() -> { cryptoExecutor.execute(() -> {
byte[] key = crypto.decryptWithPassword(encrypted, password); byte[] key = crypto.decryptWithPassword(encrypted, password);
if (key == null) { if (key == null) {

View File

@@ -2,7 +2,6 @@ package org.briarproject.briar.android.navdrawer;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.annotation.TargetApi; import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.res.Configuration; import android.content.res.Configuration;
import android.os.Bundle; import android.os.Bundle;
@@ -283,8 +282,7 @@ public class NavDrawerActivity extends BriarActivity implements
if (daysUntilExpiry < 0) signOut(); if (daysUntilExpiry < 0) signOut();
// show expiry warning text // show expiry warning text
final ViewGroup ViewGroup expiryWarning = (ViewGroup) findViewById(R.id.expiryWarning);
expiryWarning = (ViewGroup) findViewById(R.id.expiryWarning);
TextView expiryWarningText = TextView expiryWarningText =
(TextView) expiryWarning.findViewById(R.id.expiryWarningText); (TextView) expiryWarning.findViewById(R.id.expiryWarningText);
// make close button functional // make close button functional
@@ -320,20 +318,16 @@ public class NavDrawerActivity extends BriarActivity implements
new AlertDialog.Builder(this, R.style.BriarDialogTheme) new AlertDialog.Builder(this, R.style.BriarDialogTheme)
.setMessage(R.string.setup_doze_intro) .setMessage(R.string.setup_doze_intro)
.setPositiveButton(R.string.ok, .setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() { (dialog, which) -> {
@Override Intent i = getDozeWhitelistingIntent(
public void onClick(DialogInterface dialog, NavDrawerActivity.this);
int which) { startActivityForResult(i,
Intent i = getDozeWhitelistingIntent( REQUEST_DOZE_WHITELISTING);
NavDrawerActivity.this);
startActivityForResult(i,
REQUEST_DOZE_WHITELISTING);
}
}) })
.show(); .show();
} }
private void initializeTransports(final LayoutInflater inflater) { private void initializeTransports(LayoutInflater inflater) {
transports = new ArrayList<>(3); transports = new ArrayList<>(3);
Transport tor = new Transport(); Transport tor = new Transport();
@@ -407,7 +401,7 @@ public class NavDrawerActivity extends BriarActivity implements
}; };
} }
private void setTransport(final TransportId id, final boolean enabled) { private void setTransport(TransportId id, boolean enabled) {
runOnUiThreadUnlessDestroyed(() -> { runOnUiThreadUnlessDestroyed(() -> {
if (transports == null || transportsAdapter == null) return; if (transports == null || transportsAdapter == null) return;
for (Transport t : transports) { for (Transport t : transports) {

View File

@@ -8,11 +8,11 @@ import org.briarproject.briar.android.controller.handler.ResultHandler;
@NotNullByDefault @NotNullByDefault
public interface NavDrawerController extends ActivityLifecycleController { public interface NavDrawerController extends ActivityLifecycleController {
enum ExpiryWarning { SHOW, NO, UPDATE }; enum ExpiryWarning { SHOW, NO, UPDATE }
boolean isTransportRunning(TransportId transportId); boolean isTransportRunning(TransportId transportId);
void showExpiryWarning(final ResultHandler<ExpiryWarning> handler); void showExpiryWarning(ResultHandler<ExpiryWarning> handler);
void expiryWarningDismissed(); void expiryWarningDismissed();

View File

@@ -96,14 +96,13 @@ public class NavDrawerControllerImpl extends DbControllerImpl
} }
} }
private void transportStateUpdate(final TransportId id, private void transportStateUpdate(TransportId id, boolean enabled) {
final boolean enabled) {
listener.runOnUiThreadUnlessDestroyed( listener.runOnUiThreadUnlessDestroyed(
() -> listener.stateUpdate(id, enabled)); () -> listener.stateUpdate(id, enabled));
} }
@Override @Override
public void showExpiryWarning(final ResultHandler<ExpiryWarning> handler) { public void showExpiryWarning(ResultHandler<ExpiryWarning> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
Settings settings = Settings settings =

View File

@@ -110,7 +110,7 @@ public class GroupActivity extends
} }
@Override @Override
protected void onNamedGroupLoaded(final PrivateGroup group) { protected void onNamedGroupLoaded(PrivateGroup group) {
setTitle(group.getName()); setTitle(group.getName());
controller.loadLocalAuthor( controller.loadLocalAuthor(
new UiResultExceptionHandler<LocalAuthor, DbException>(this) { new UiResultExceptionHandler<LocalAuthor, DbException>(this) {
@@ -144,7 +144,7 @@ public class GroupActivity extends
} }
@Override @Override
public boolean onOptionsItemSelected(final MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.action_group_member_list: case R.id.action_group_member_list:
Intent i1 = new Intent(this, GroupMemberListActivity.class); Intent i1 = new Intent(this, GroupMemberListActivity.class);

View File

@@ -83,13 +83,12 @@ class GroupControllerImpl extends
GroupMessageAddedEvent g = (GroupMessageAddedEvent) e; GroupMessageAddedEvent g = (GroupMessageAddedEvent) e;
if (!g.isLocal() && g.getGroupId().equals(getGroupId())) { if (!g.isLocal() && g.getGroupId().equals(getGroupId())) {
LOG.info("Group message received, adding..."); LOG.info("Group message received, adding...");
final GroupMessageItem item = GroupMessageItem item = buildItem(g.getHeader(), g.getBody());
buildItem(g.getHeader(), g.getBody());
listener.runOnUiThreadUnlessDestroyed( listener.runOnUiThreadUnlessDestroyed(
() -> listener.onItemReceived(item)); () -> listener.onItemReceived(item));
} }
} else if (e instanceof ContactRelationshipRevealedEvent) { } else if (e instanceof ContactRelationshipRevealedEvent) {
final ContactRelationshipRevealedEvent c = ContactRelationshipRevealedEvent c =
(ContactRelationshipRevealedEvent) e; (ContactRelationshipRevealedEvent) e;
if (getGroupId().equals(c.getGroupId())) { if (getGroupId().equals(c.getGroupId())) {
listener.runOnUiThreadUnlessDestroyed(() -> listener.runOnUiThreadUnlessDestroyed(() ->
@@ -99,7 +98,7 @@ class GroupControllerImpl extends
} else if (e instanceof GroupInvitationResponseReceivedEvent) { } else if (e instanceof GroupInvitationResponseReceivedEvent) {
GroupInvitationResponseReceivedEvent g = GroupInvitationResponseReceivedEvent g =
(GroupInvitationResponseReceivedEvent) e; (GroupInvitationResponseReceivedEvent) e;
final GroupInvitationResponse r = GroupInvitationResponse r =
(GroupInvitationResponse) g.getResponse(); (GroupInvitationResponse) g.getResponse();
if (getGroupId().equals(r.getShareableId()) && r.wasAccepted()) { if (getGroupId().equals(r.getShareableId()) && r.wasAccepted()) {
listener.runOnUiThreadUnlessDestroyed( listener.runOnUiThreadUnlessDestroyed(
@@ -141,7 +140,7 @@ class GroupControllerImpl extends
@Override @Override
public void loadSharingContacts( public void loadSharingContacts(
final ResultExceptionHandler<Collection<ContactId>, DbException> handler) { ResultExceptionHandler<Collection<ContactId>, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
Collection<GroupMember> members = Collection<GroupMember> members =
@@ -160,9 +159,9 @@ class GroupControllerImpl extends
} }
@Override @Override
public void createAndStoreMessage(final String body, public void createAndStoreMessage(String body,
@Nullable final GroupMessageItem parentItem, @Nullable GroupMessageItem parentItem,
final ResultExceptionHandler<GroupMessageItem, DbException> handler) { ResultExceptionHandler<GroupMessageItem, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
LocalAuthor author = identityManager.getLocalAuthor(); LocalAuthor author = identityManager.getLocalAuthor();
@@ -183,10 +182,10 @@ class GroupControllerImpl extends
}); });
} }
private void createMessage(final String body, final long timestamp, private void createMessage(String body, long timestamp,
final @Nullable MessageId parentId, final LocalAuthor author, @Nullable MessageId parentId, LocalAuthor author,
final MessageId previousMsgId, MessageId previousMsgId,
final ResultExceptionHandler<GroupMessageItem, DbException> handler) { ResultExceptionHandler<GroupMessageItem, DbException> handler) {
cryptoExecutor.execute(() -> { cryptoExecutor.execute(() -> {
LOG.info("Creating group message..."); LOG.info("Creating group message...");
GroupMessage msg = groupMessageFactory GroupMessage msg = groupMessageFactory
@@ -218,7 +217,7 @@ class GroupControllerImpl extends
@Override @Override
public void loadLocalAuthor( public void loadLocalAuthor(
final ResultExceptionHandler<LocalAuthor, DbException> handler) { ResultExceptionHandler<LocalAuthor, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
LocalAuthor author = identityManager.getLocalAuthor(); LocalAuthor author = identityManager.getLocalAuthor();

View File

@@ -32,7 +32,7 @@ class JoinMessageItemViewHolder
else bind((JoinMessageItem) item); else bind((JoinMessageItem) item);
} }
private void bindForCreator(final JoinMessageItem item) { private void bindForCreator(JoinMessageItem item) {
if (item.isInitial()) { if (item.isInitial()) {
textView.setText(R.string.groups_member_created_you); textView.setText(R.string.groups_member_created_you);
} else { } else {
@@ -42,8 +42,8 @@ class JoinMessageItemViewHolder
} }
} }
private void bind(final JoinMessageItem item) { private void bind(JoinMessageItem item) {
final Context ctx = getContext(); Context ctx = getContext();
if (item.isInitial()) { if (item.isInitial()) {
textView.setText(ctx.getString(R.string.groups_member_created, textView.setText(ctx.getString(R.string.groups_member_created,

View File

@@ -74,8 +74,8 @@ class CreateGroupControllerImpl extends ContactSelectorControllerImpl
} }
@Override @Override
public void createGroup(final String name, public void createGroup(String name,
final ResultExceptionHandler<GroupId, DbException> handler) { ResultExceptionHandler<GroupId, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
LocalAuthor author = identityManager.getLocalAuthor(); LocalAuthor author = identityManager.getLocalAuthor();
@@ -87,9 +87,8 @@ class CreateGroupControllerImpl extends ContactSelectorControllerImpl
}); });
} }
private void createGroupAndMessages(final LocalAuthor author, private void createGroupAndMessages(LocalAuthor author, String name,
final String name, ResultExceptionHandler<GroupId, DbException> handler) {
final ResultExceptionHandler<GroupId, DbException> handler) {
cryptoExecutor.execute(() -> { cryptoExecutor.execute(() -> {
LOG.info("Creating group..."); LOG.info("Creating group...");
PrivateGroup group = PrivateGroup group =
@@ -102,9 +101,8 @@ class CreateGroupControllerImpl extends ContactSelectorControllerImpl
}); });
} }
private void storeGroup(final PrivateGroup group, private void storeGroup(PrivateGroup group, GroupMessage joinMsg,
final GroupMessage joinMsg, ResultExceptionHandler<GroupId, DbException> handler) {
final ResultExceptionHandler<GroupId, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
LOG.info("Adding group to database..."); LOG.info("Adding group to database...");
try { try {
@@ -123,9 +121,8 @@ class CreateGroupControllerImpl extends ContactSelectorControllerImpl
} }
@Override @Override
public void sendInvitation(final GroupId g, public void sendInvitation(GroupId g, Collection<ContactId> contactIds,
final Collection<ContactId> contactIds, final String message, String message, ResultExceptionHandler<Void, DbException> handler) {
final ResultExceptionHandler<Void, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
LocalAuthor localAuthor = identityManager.getLocalAuthor(); LocalAuthor localAuthor = identityManager.getLocalAuthor();
@@ -145,9 +142,9 @@ class CreateGroupControllerImpl extends ContactSelectorControllerImpl
}); });
} }
private void signInvitations(final GroupId g, final LocalAuthor localAuthor, private void signInvitations(GroupId g, LocalAuthor localAuthor,
final Collection<Contact> contacts, final String message, Collection<Contact> contacts, String message,
final ResultExceptionHandler<Void, DbException> handler) { ResultExceptionHandler<Void, DbException> handler) {
cryptoExecutor.execute(() -> { cryptoExecutor.execute(() -> {
long timestamp = clock.currentTimeMillis(); long timestamp = clock.currentTimeMillis();
List<InvitationContext> contexts = new ArrayList<>(); List<InvitationContext> contexts = new ArrayList<>();
@@ -161,9 +158,9 @@ class CreateGroupControllerImpl extends ContactSelectorControllerImpl
}); });
} }
private void sendInvitations(final GroupId g, private void sendInvitations(GroupId g,
final Collection<InvitationContext> contexts, final String message, Collection<InvitationContext> contexts, String message,
final ResultExceptionHandler<Void, DbException> handler) { ResultExceptionHandler<Void, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
String msg = message.isEmpty() ? null : message; String msg = message.isEmpty() ? null : message;

View File

@@ -64,9 +64,8 @@ class GroupInvitationControllerImpl
} }
@Override @Override
public void respondToInvitation(final GroupInvitationItem item, public void respondToInvitation(GroupInvitationItem item, boolean accept,
final boolean accept, ExceptionHandler<DbException> handler) {
final ExceptionHandler<DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
PrivateGroup g = item.getShareable(); PrivateGroup g = item.getShareable();

View File

@@ -17,8 +17,8 @@ class GroupInvitationViewHolder
} }
@Override @Override
public void onBind(@Nullable final GroupInvitationItem item, public void onBind(@Nullable GroupInvitationItem item,
final InvitationClickListener<GroupInvitationItem> listener) { InvitationClickListener<GroupInvitationItem> listener) {
super.onBind(item, listener); super.onBind(item, listener);
if (item == null) return; if (item == null) return;

View File

@@ -119,7 +119,7 @@ class GroupListControllerImpl extends DbControllerImpl
} }
} }
private void onGroupMessageAdded(final GroupMessageHeader h) { private void onGroupMessageAdded(GroupMessageHeader h) {
listener.runOnUiThreadUnlessDestroyed( listener.runOnUiThreadUnlessDestroyed(
() -> listener.onGroupMessageAdded(h)); () -> listener.onGroupMessageAdded(h));
} }
@@ -129,22 +129,22 @@ class GroupListControllerImpl extends DbControllerImpl
() -> listener.onGroupInvitationReceived()); () -> listener.onGroupInvitationReceived());
} }
private void onGroupAdded(final GroupId g) { private void onGroupAdded(GroupId g) {
listener.runOnUiThreadUnlessDestroyed(() -> listener.onGroupAdded(g)); listener.runOnUiThreadUnlessDestroyed(() -> listener.onGroupAdded(g));
} }
private void onGroupRemoved(final GroupId g) { private void onGroupRemoved(GroupId g) {
listener.runOnUiThreadUnlessDestroyed(() -> listener.onGroupRemoved(g)); listener.runOnUiThreadUnlessDestroyed(() -> listener.onGroupRemoved(g));
} }
private void onGroupDissolved(final GroupId g) { private void onGroupDissolved(GroupId g) {
listener.runOnUiThreadUnlessDestroyed( listener.runOnUiThreadUnlessDestroyed(
() -> listener.onGroupDissolved(g)); () -> listener.onGroupDissolved(g));
} }
@Override @Override
public void loadGroups( public void loadGroups(
final ResultExceptionHandler<Collection<GroupItem>, DbException> handler) { ResultExceptionHandler<Collection<GroupItem>, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@@ -173,8 +173,7 @@ class GroupListControllerImpl extends DbControllerImpl
} }
@Override @Override
public void removeGroup(final GroupId g, public void removeGroup(GroupId g, ExceptionHandler<DbException> handler) {
final ExceptionHandler<DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@@ -191,7 +190,7 @@ class GroupListControllerImpl extends DbControllerImpl
@Override @Override
public void loadAvailableGroups( public void loadAvailableGroups(
final ResultExceptionHandler<Integer, DbException> handler) { ResultExceptionHandler<Integer, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
handler.onResult( handler.onResult(

View File

@@ -113,7 +113,7 @@ public class GroupListFragment extends BaseFragment implements
} }
@Override @Override
public boolean onOptionsItemSelected(final MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.action_add_group: case R.id.action_add_group:
Intent i = new Intent(getContext(), CreateGroupActivity.class); Intent i = new Intent(getContext(), CreateGroupActivity.class);
@@ -184,7 +184,7 @@ public class GroupListFragment extends BaseFragment implements
} }
private void loadGroups() { private void loadGroups() {
final int revision = adapter.getRevision(); int revision = adapter.getRevision();
controller.loadGroups( controller.loadGroups(
new UiResultExceptionHandler<Collection<GroupItem>, DbException>( new UiResultExceptionHandler<Collection<GroupItem>, DbException>(
this) { this) {

View File

@@ -50,8 +50,8 @@ class GroupViewHolder extends RecyclerView.ViewHolder {
remove = (Button) v.findViewById(R.id.removeButton); remove = (Button) v.findViewById(R.id.removeButton);
} }
void bindView(final Context ctx, final GroupItem group, void bindView(Context ctx, GroupItem group,
final OnGroupRemoveClickListener listener) { OnGroupRemoveClickListener listener) {
// Avatar // Avatar
avatar.setText(group.getName().substring(0, 1)); avatar.setText(group.getName().substring(0, 1));
avatar.setBackgroundBytes(group.getId().getBytes()); avatar.setBackgroundBytes(group.getId().getBytes());

View File

@@ -38,7 +38,7 @@ public class GroupMemberListActivity extends BriarActivity {
} }
@Override @Override
public void onCreate(@Nullable final Bundle state) { public void onCreate(@Nullable Bundle state) {
super.onCreate(state); super.onCreate(state);
setContentView(R.layout.activity_sharing_status); setContentView(R.layout.activity_sharing_status);

View File

@@ -40,7 +40,7 @@ class GroupMemberListControllerImpl extends DbControllerImpl
} }
@Override @Override
public void loadMembers(final GroupId groupId, final public void loadMembers(GroupId groupId,
ResultExceptionHandler<Collection<MemberListItem>, DbException> handler) { ResultExceptionHandler<Collection<MemberListItem>, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {

View File

@@ -59,9 +59,8 @@ class RevealContactsControllerImpl extends DbControllerImpl
} }
@Override @Override
public void loadContacts(final GroupId g, public void loadContacts(GroupId g, Collection<ContactId> selection,
final Collection<ContactId> selection, ResultExceptionHandler<Collection<RevealableContactItem>, DbException> handler) {
final ResultExceptionHandler<Collection<RevealableContactItem>, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
handler.onResult(getItems(g, selection)); handler.onResult(getItems(g, selection));
@@ -98,7 +97,7 @@ class RevealContactsControllerImpl extends DbControllerImpl
@Override @Override
public void isOnboardingNeeded( public void isOnboardingNeeded(
final ResultExceptionHandler<Boolean, DbException> handler) { ResultExceptionHandler<Boolean, DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
try { try {
Settings settings = Settings settings =
@@ -129,8 +128,8 @@ class RevealContactsControllerImpl extends DbControllerImpl
} }
@Override @Override
public void reveal(final GroupId g, final Collection<ContactId> contacts, public void reveal(GroupId g, Collection<ContactId> contacts,
final ExceptionHandler<DbException> handler) { ExceptionHandler<DbException> handler) {
runOnDbThread(() -> { runOnDbThread(() -> {
for (ContactId c : contacts) { for (ContactId c : contacts) {
try { try {

View File

@@ -93,7 +93,7 @@ public class DevReportActivity extends BaseCrashReportDialog
Toolbar tb = (Toolbar) findViewById(R.id.toolbar); Toolbar tb = (Toolbar) findViewById(R.id.toolbar);
getDelegate().setSupportActionBar(tb); getDelegate().setSupportActionBar(tb);
final View requestReport = findViewById(R.id.request_report); View requestReport = findViewById(R.id.request_report);
userCommentView = (EditText) findViewById(R.id.user_comment); userCommentView = (EditText) findViewById(R.id.user_comment);
userEmailView = (EditText) findViewById(R.id.user_email); userEmailView = (EditText) findViewById(R.id.user_email);
includeDebugReport = (CheckBox) findViewById(R.id.include_debug_report); includeDebugReport = (CheckBox) findViewById(R.id.include_debug_report);
@@ -170,7 +170,7 @@ public class DevReportActivity extends BaseCrashReportDialog
} }
@Override @Override
public boolean onOptionsItemSelected(final MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items // Handle presses on the action bar items
switch (item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
@@ -243,8 +243,7 @@ public class DevReportActivity extends BaseCrashReportDialog
protected CrashReportData doInBackground(Void... args) { protected CrashReportData doInBackground(Void... args) {
File reportFile = (File) getIntent().getSerializableExtra( File reportFile = (File) getIntent().getSerializableExtra(
EXTRA_REPORT_FILE); EXTRA_REPORT_FILE);
final CrashReportPersister persister = CrashReportPersister persister = new CrashReportPersister();
new CrashReportPersister();
try { try {
return persister.load(reportFile); return persister.load(reportFile);
} catch (IOException e) { } catch (IOException e) {
@@ -293,8 +292,7 @@ public class DevReportActivity extends BaseCrashReportDialog
userEmailView.setEnabled(false); userEmailView.setEnabled(false);
sendReport.setEnabled(false); sendReport.setEnabled(false);
progress.setVisibility(VISIBLE); progress.setVisibility(VISIBLE);
final boolean includeReport = boolean includeReport = !isFeedback() || includeDebugReport.isChecked();
!isFeedback() || includeDebugReport.isChecked();
new AsyncTask<Void, Void, Boolean>() { new AsyncTask<Void, Void, Boolean>() {
@Override @Override

Some files were not shown because too many files have changed in this diff Show More