This commit is contained in:
akwizgran
2017-11-16 10:29:18 +00:00
committed by Torsten Grote
parent 27328afe3c
commit 5fa6b0ca1c
109 changed files with 2087 additions and 3450 deletions

View File

@@ -124,12 +124,7 @@ class DroidtoothPlugin implements DuplexPlugin, EventListener {
// with a message queue, so submit it to the AndroidExecutor // with a message queue, so submit it to the AndroidExecutor
try { try {
adapter = androidExecutor.runOnBackgroundThread( adapter = androidExecutor.runOnBackgroundThread(
new Callable<BluetoothAdapter>() { BluetoothAdapter::getDefaultAdapter).get();
@Override
public BluetoothAdapter call() throws Exception {
return BluetoothAdapter.getDefaultAdapter();
}
}).get();
} catch (InterruptedException e) { } catch (InterruptedException e) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
LOG.warning("Interrupted while getting BluetoothAdapter"); LOG.warning("Interrupted while getting BluetoothAdapter");
@@ -162,9 +157,7 @@ class DroidtoothPlugin implements DuplexPlugin, EventListener {
} }
private void bind() { private void bind() {
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
if (!isRunning()) return; if (!isRunning()) return;
String address = AndroidUtils.getBluetoothAddress(appContext, String address = AndroidUtils.getBluetoothAddress(appContext,
adapter); adapter);
@@ -182,8 +175,7 @@ class DroidtoothPlugin implements DuplexPlugin, EventListener {
ss = adapter.listenUsingInsecureRfcommWithServiceRecord( ss = adapter.listenUsingInsecureRfcommWithServiceRecord(
"RFCOMM", getUuid()); "RFCOMM", getUuid());
} catch (IOException e) { } catch (IOException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
return; return;
} }
if (!isRunning()) { if (!isRunning()) {
@@ -195,7 +187,6 @@ class DroidtoothPlugin implements DuplexPlugin, EventListener {
backoff.reset(); backoff.reset();
callback.transportEnabled(); callback.transportEnabled();
acceptContactConnections(); acceptContactConnections();
}
}); });
} }
@@ -300,16 +291,13 @@ class DroidtoothPlugin implements DuplexPlugin, EventListener {
if (StringUtils.isNullOrEmpty(address)) continue; if (StringUtils.isNullOrEmpty(address)) continue;
final String uuid = e.getValue().get(PROP_UUID); final String uuid = e.getValue().get(PROP_UUID);
if (StringUtils.isNullOrEmpty(uuid)) continue; if (StringUtils.isNullOrEmpty(uuid)) continue;
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
if (!running) return; if (!running) return;
BluetoothSocket s = connect(address, uuid); BluetoothSocket s = connect(address, uuid);
if (s != null) { if (s != null) {
backoff.reset(); backoff.reset();
callback.outgoingConnectionCreated(c, wrapSocket(s)); callback.outgoingConnectionCreated(c, wrapSocket(s));
} }
}
}); });
} }
} }
@@ -438,21 +426,11 @@ class DroidtoothPlugin implements DuplexPlugin, EventListener {
} }
private void enableAdapterAsync() { private void enableAdapterAsync() {
ioExecutor.execute(new Runnable() { ioExecutor.execute(this::enableAdapter);
@Override
public void run() {
enableAdapter();
}
});
} }
private void disableAdapterAsync() { private void disableAdapterAsync() {
ioExecutor.execute(new Runnable() { ioExecutor.execute(this::disableAdapter);
@Override
public void run() {
disableAdapter();
}
});
} }
private class BluetoothStateReceiver extends BroadcastReceiver { private class BluetoothStateReceiver extends BroadcastReceiver {
@@ -490,16 +468,13 @@ class DroidtoothPlugin implements DuplexPlugin, EventListener {
@Override @Override
public Callable<KeyAgreementConnection> listen() { public Callable<KeyAgreementConnection> listen() {
return new Callable<KeyAgreementConnection>() { return () -> {
@Override
public KeyAgreementConnection call() throws IOException {
BluetoothSocket s = ss.accept(); BluetoothSocket s = ss.accept();
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info(ID.getString() + ": Incoming connection"); LOG.info(ID.getString() + ": Incoming connection");
return new KeyAgreementConnection( return new KeyAgreementConnection(
new DroidtoothTransportConnection( new DroidtoothTransportConnection(
DroidtoothPlugin.this, s), ID); DroidtoothPlugin.this, s), ID);
}
}; };
} }

View File

@@ -370,20 +370,15 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
} }
private void sendDevReports() { private void sendDevReports() {
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
// TODO: Trigger this with a TransportEnabledEvent // TODO: Trigger this with a TransportEnabledEvent
File reportDir = AndroidUtils.getReportDir(appContext); File reportDir = AndroidUtils.getReportDir(appContext);
reporter.sendReports(reportDir); reporter.sendReports(reportDir);
}
}); });
} }
private void bind() { private void bind() {
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
// If there's already a port number stored in config, reuse it // If there's already a port number stored in config, reuse it
String portString = callback.getSettings().get(PREF_TOR_PORT); String portString = callback.getSettings().get(PREF_TOR_PORT);
int port; int port;
@@ -395,8 +390,7 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
ss = new ServerSocket(); ss = new ServerSocket();
ss.bind(new InetSocketAddress("127.0.0.1", port)); ss.bind(new InetSocketAddress("127.0.0.1", port));
} catch (IOException e) { } catch (IOException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
tryToClose(ss); tryToClose(ss);
return; return;
} }
@@ -411,16 +405,10 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
s.put(PREF_TOR_PORT, localPort); s.put(PREF_TOR_PORT, localPort);
callback.mergeSettings(s); callback.mergeSettings(s);
// Create a hidden service if necessary // Create a hidden service if necessary
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> publishHiddenService(localPort));
@Override
public void run() {
publishHiddenService(localPort);
}
});
backoff.reset(); backoff.reset();
// Accept incoming hidden service connections from Tor // Accept incoming hidden service connections from Tor
acceptContactConnections(ss); acceptContactConnections(ss);
}
}); });
} }
@@ -550,16 +538,13 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
private void connectAndCallBack(final ContactId c, private void connectAndCallBack(final ContactId c,
final TransportProperties p) { final TransportProperties p) {
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
if (!isRunning()) return; if (!isRunning()) return;
DuplexTransportConnection d = createConnection(p); DuplexTransportConnection d = createConnection(p);
if (d != null) { if (d != null) {
backoff.reset(); backoff.reset();
callback.outgoingConnectionCreated(c, d); callback.outgoingConnectionCreated(c, d);
} }
}
}); });
} }
@@ -691,9 +676,7 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
} }
private void updateConnectionStatus() { private void updateConnectionStatus() {
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
if (!running) return; if (!running) return;
Object o = appContext.getSystemService(CONNECTIVITY_SERVICE); Object o = appContext.getSystemService(CONNECTIVITY_SERVICE);
@@ -705,8 +688,7 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
boolean blocked = TorNetworkMetadata.isTorProbablyBlocked( boolean blocked = TorNetworkMetadata.isTorProbablyBlocked(
country); country);
Settings s = callback.getSettings(); Settings s = callback.getSettings();
int network = s.getInt(PREF_TOR_NETWORK, int network = s.getInt(PREF_TOR_NETWORK, PREF_TOR_NETWORK_ALWAYS);
PREF_TOR_NETWORK_ALWAYS);
if (LOG.isLoggable(INFO)) { if (LOG.isLoggable(INFO)) {
LOG.info("Online: " + online + ", wifi: " + wifi); LOG.info("Online: " + online + ", wifi: " + wifi);
@@ -730,9 +712,7 @@ class TorPlugin implements DuplexPlugin, EventHandler, EventListener {
enableNetwork(true); enableNetwork(true);
} }
} catch (IOException e) { } catch (IOException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }

View File

@@ -27,14 +27,11 @@ class AndroidExecutorImpl implements AndroidExecutor {
@Inject @Inject
AndroidExecutorImpl(Application app) { AndroidExecutorImpl(Application app) {
uiHandler = new Handler(app.getApplicationContext().getMainLooper()); uiHandler = new Handler(app.getApplicationContext().getMainLooper());
loop = new Runnable() { loop = () -> {
@Override
public void run() {
Looper.prepare(); Looper.prepare();
backgroundHandler = new Handler(); backgroundHandler = new Handler();
startLatch.countDown(); startLatch.countDown();
Looper.loop(); Looper.loop();
}
}; };
} }

View File

@@ -8,12 +8,9 @@ public abstract class BrambleTestCase {
public BrambleTestCase() { public BrambleTestCase() {
// Ensure exceptions thrown on worker threads cause tests to fail // Ensure exceptions thrown on worker threads cause tests to fail
UncaughtExceptionHandler fail = new UncaughtExceptionHandler() { UncaughtExceptionHandler fail = (thread, throwable) -> {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
throwable.printStackTrace(); throwable.printStackTrace();
fail(); fail();
}
}; };
Thread.setDefaultUncaughtExceptionHandler(fail); Thread.setDefaultUncaughtExceptionHandler(fail);
} }

View File

@@ -50,9 +50,7 @@ public class PoliteExecutor implements Executor {
@Override @Override
public void execute(final Runnable r) { public void execute(final Runnable r) {
final long submitted = System.currentTimeMillis(); final long submitted = System.currentTimeMillis();
Runnable wrapped = new Runnable() { Runnable wrapped = () -> {
@Override
public void run() {
if (log.isLoggable(LOG_LEVEL)) { if (log.isLoggable(LOG_LEVEL)) {
long queued = System.currentTimeMillis() - submitted; long queued = System.currentTimeMillis() - submitted;
log.log(LOG_LEVEL, "Queue time " + queued + " ms"); log.log(LOG_LEVEL, "Queue time " + queued + " ms");
@@ -62,7 +60,6 @@ public class PoliteExecutor implements Executor {
} finally { } finally {
scheduleNext(); scheduleNext();
} }
}
}; };
synchronized (lock) { synchronized (lock) {
if (concurrentTasks < maxConcurrentTasks) { if (concurrentTasks < maxConcurrentTasks) {

View File

@@ -31,16 +31,13 @@ public class TimeLoggingExecutor extends ThreadPoolExecutor {
public void execute(final Runnable r) { public void execute(final Runnable r) {
if (log.isLoggable(LOG_LEVEL)) { if (log.isLoggable(LOG_LEVEL)) {
final long submitted = System.currentTimeMillis(); final long submitted = System.currentTimeMillis();
super.execute(new Runnable() { super.execute(() -> {
@Override
public void run() {
long started = System.currentTimeMillis(); long started = System.currentTimeMillis();
long queued = started - submitted; long queued = started - submitted;
log.log(LOG_LEVEL, "Queue time " + queued + " ms"); log.log(LOG_LEVEL, "Queue time " + queued + " ms");
r.run(); r.run();
long executing = System.currentTimeMillis() - started; long executing = System.currentTimeMillis() - started;
log.log(LOG_LEVEL, "Execution time " + executing + " ms"); log.log(LOG_LEVEL, "Execution time " + executing + " ms");
}
}); });
} else { } else {
super.execute(r); super.execute(r);

View File

@@ -103,15 +103,11 @@ class DatabaseComponentImpl<T> implements DatabaseComponent {
@Override @Override
public boolean open() throws DbException { public boolean open() throws DbException {
Runnable shutdownHook = new Runnable() { Runnable shutdownHook = () -> {
@Override
public void run() {
try { try {
close(); close();
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}; };
boolean reopened = db.open(); boolean reopened = db.open();

View File

@@ -266,12 +266,7 @@ class ConnectionManagerImpl implements ConnectionManager {
contactId = ctx.getContactId(); contactId = ctx.getContactId();
connectionRegistry.registerConnection(contactId, transportId, true); connectionRegistry.registerConnection(contactId, transportId, true);
// Start the outgoing session on another thread // Start the outgoing session on another thread
ioExecutor.execute(new Runnable() { ioExecutor.execute(this::runOutgoingSession);
@Override
public void run() {
runOutgoingSession();
}
});
try { try {
// Create and run the incoming session // Create and run the incoming session
incomingSession = createIncomingSession(ctx, reader); incomingSession = createIncomingSession(ctx, reader);
@@ -368,12 +363,7 @@ class ConnectionManagerImpl implements ConnectionManager {
return; return;
} }
// Start the incoming session on another thread // Start the incoming session on another thread
ioExecutor.execute(new Runnable() { ioExecutor.execute(this::runIncomingSession);
@Override
public void run() {
runIncomingSession();
}
});
try { try {
// Create and run the outgoing session // Create and run the outgoing session
outgoingSession = createDuplexOutgoingSession(ctx, writer); outgoingSession = createDuplexOutgoingSession(ctx, writer);

View File

@@ -112,30 +112,24 @@ class Poller implements EventListener {
} }
private void connectToContact(final ContactId c, final SimplexPlugin p) { private void connectToContact(final ContactId c, final SimplexPlugin p) {
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
TransportId t = p.getId(); TransportId t = p.getId();
if (!connectionRegistry.isConnected(c, t)) { if (!connectionRegistry.isConnected(c, t)) {
TransportConnectionWriter w = p.createWriter(c); TransportConnectionWriter w = p.createWriter(c);
if (w != null) if (w != null)
connectionManager.manageOutgoingConnection(c, t, w); connectionManager.manageOutgoingConnection(c, t, w);
} }
}
}); });
} }
private void connectToContact(final ContactId c, final DuplexPlugin p) { private void connectToContact(final ContactId c, final DuplexPlugin p) {
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
TransportId t = p.getId(); TransportId t = p.getId();
if (!connectionRegistry.isConnected(c, t)) { if (!connectionRegistry.isConnected(c, t)) {
DuplexTransportConnection d = p.createConnection(c); DuplexTransportConnection d = p.createConnection(c);
if (d != null) if (d != null)
connectionManager.manageOutgoingConnection(c, t, d); connectionManager.manageOutgoingConnection(c, t, d);
} }
}
}); });
} }
@@ -161,12 +155,8 @@ class Poller implements EventListener {
if (scheduled == null || due < scheduled.due) { if (scheduled == null || due < scheduled.due) {
final PollTask task = new PollTask(p, due, randomiseNext); final PollTask task = new PollTask(p, due, randomiseNext);
tasks.put(t, task); tasks.put(t, task);
scheduler.schedule(new Runnable() { scheduler.schedule(
@Override () -> ioExecutor.execute(task), delay, MILLISECONDS);
public void run() {
ioExecutor.execute(task);
}
}, delay, MILLISECONDS);
} }
} finally { } finally {
lock.unlock(); lock.unlock();

View File

@@ -260,16 +260,12 @@ class LanTcpPlugin extends TcpPlugin {
@Override @Override
public Callable<KeyAgreementConnection> listen() { public Callable<KeyAgreementConnection> listen() {
return new Callable<KeyAgreementConnection>() { return () -> {
@Override
public KeyAgreementConnection call() throws IOException {
Socket s = ss.accept(); Socket s = ss.accept();
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info(ID.getString() + ": Incoming connection"); LOG.info(ID.getString() + ": Incoming connection");
return new KeyAgreementConnection( return new KeyAgreementConnection(
new TcpTransportConnection(LanTcpPlugin.this, s), new TcpTransportConnection(LanTcpPlugin.this, s), ID);
ID);
}
}; };
} }

View File

@@ -50,12 +50,7 @@ class PortMapperImpl implements PortMapper {
succeeded = gateway.addPortMapping(port, port, succeeded = gateway.addPortMapping(port, port,
getHostAddress(internal), "TCP", "TCP"); getHostAddress(internal), "TCP", "TCP");
if (succeeded) { if (succeeded) {
shutdownManager.addShutdownHook(new Runnable() { shutdownManager.addShutdownHook(() -> deleteMapping(port));
@Override
public void run() {
deleteMapping(port);
}
});
} }
String externalString = gateway.getExternalIPAddress(); String externalString = gateway.getExternalIPAddress();
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))

View File

@@ -110,9 +110,7 @@ abstract class TcpPlugin implements DuplexPlugin {
} }
protected void bind() { protected void bind() {
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
if (!running) return; if (!running) return;
ServerSocket ss = null; ServerSocket ss = null;
for (InetSocketAddress addr : getLocalSocketAddresses()) { for (InetSocketAddress addr : getLocalSocketAddresses()) {
@@ -122,8 +120,7 @@ abstract class TcpPlugin implements DuplexPlugin {
break; break;
} catch (IOException e) { } catch (IOException e) {
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Failed to bind " + LOG.info("Failed to bind " + scrubSocketAddress(addr));
scrubSocketAddress(addr));
tryToClose(ss); tryToClose(ss);
} }
} }
@@ -144,7 +141,6 @@ abstract class TcpPlugin implements DuplexPlugin {
LOG.info("Listening on " + scrubSocketAddress(local)); LOG.info("Listening on " + scrubSocketAddress(local));
callback.transportEnabled(); callback.transportEnabled();
acceptContactConnections(); acceptContactConnections();
}
}); });
} }
@@ -220,16 +216,13 @@ abstract class TcpPlugin implements DuplexPlugin {
private void connectAndCallBack(final ContactId c, private void connectAndCallBack(final ContactId c,
final TransportProperties p) { final TransportProperties p) {
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
if (!isRunning()) return; if (!isRunning()) return;
DuplexTransportConnection d = createConnection(p); DuplexTransportConnection d = createConnection(p);
if (d != null) { if (d != null) {
backoff.reset(); backoff.reset();
callback.outgoingConnectionCreated(c, d); callback.outgoingConnectionCreated(c, d);
} }
}
}); });
} }

View File

@@ -54,9 +54,7 @@ class ReliabilityLayerImpl implements ReliabilityLayer, WriteHandler {
inputStream = new ReceiverInputStream(receiver); inputStream = new ReceiverInputStream(receiver);
outputStream = new SenderOutputStream(sender); outputStream = new SenderOutputStream(sender);
running = true; running = true;
executor.execute(new Runnable() { executor.execute(() -> {
@Override
public void run() {
long now = clock.currentTimeMillis(); long now = clock.currentTimeMillis();
long next = now + TICK_INTERVAL; long next = now + TICK_INTERVAL;
try { try {
@@ -80,11 +78,9 @@ class ReliabilityLayerImpl implements ReliabilityLayer, WriteHandler {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
running = false; running = false;
} catch (IOException e) { } catch (IOException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
running = false; running = false;
} }
}
}); });
} }

View File

@@ -54,12 +54,7 @@ class DuplexOutgoingSession implements SyncSession, EventListener {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(DuplexOutgoingSession.class.getName()); Logger.getLogger(DuplexOutgoingSession.class.getName());
private static final ThrowingRunnable<IOException> CLOSE = private static final ThrowingRunnable<IOException> CLOSE = () -> {};
new ThrowingRunnable<IOException>() {
@Override
public void run() {
}
};
private final DatabaseComponent db; private final DatabaseComponent db;
private final Executor dbExecutor; private final Executor dbExecutor;

View File

@@ -43,12 +43,7 @@ class SimplexOutgoingSession implements SyncSession, EventListener {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(SimplexOutgoingSession.class.getName()); Logger.getLogger(SimplexOutgoingSession.class.getName());
private static final ThrowingRunnable<IOException> CLOSE = private static final ThrowingRunnable<IOException> CLOSE = () -> {};
new ThrowingRunnable<IOException>() {
@Override
public void run() {
}
};
private final DatabaseComponent db; private final DatabaseComponent db;
private final Executor dbExecutor; private final Executor dbExecutor;

View File

@@ -94,12 +94,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
} }
private void validateOutstandingMessagesAsync(final ClientId c) { private void validateOutstandingMessagesAsync(final ClientId c) {
dbExecutor.execute(new Runnable() { dbExecutor.execute(() -> validateOutstandingMessages(c));
@Override
public void run() {
validateOutstandingMessages(c);
}
});
} }
@DatabaseExecutor @DatabaseExecutor
@@ -121,12 +116,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
private void validateNextMessageAsync(final Queue<MessageId> unvalidated) { private void validateNextMessageAsync(final Queue<MessageId> unvalidated) {
if (unvalidated.isEmpty()) return; if (unvalidated.isEmpty()) return;
dbExecutor.execute(new Runnable() { dbExecutor.execute(() -> validateNextMessage(unvalidated));
@Override
public void run() {
validateNextMessage(unvalidated);
}
});
} }
@DatabaseExecutor @DatabaseExecutor
@@ -159,12 +149,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
} }
private void deliverOutstandingMessagesAsync(final ClientId c) { private void deliverOutstandingMessagesAsync(final ClientId c) {
dbExecutor.execute(new Runnable() { dbExecutor.execute(() -> deliverOutstandingMessages(c));
@Override
public void run() {
deliverOutstandingMessages(c);
}
});
} }
@DatabaseExecutor @DatabaseExecutor
@@ -187,12 +172,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
private void deliverNextPendingMessageAsync( private void deliverNextPendingMessageAsync(
final Queue<MessageId> pending) { final Queue<MessageId> pending) {
if (pending.isEmpty()) return; if (pending.isEmpty()) return;
dbExecutor.execute(new Runnable() { dbExecutor.execute(() -> deliverNextPendingMessage(pending));
@Override
public void run() {
deliverNextPendingMessage(pending);
}
});
} }
@DatabaseExecutor @DatabaseExecutor
@@ -255,12 +235,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
} }
private void validateMessageAsync(final Message m, final Group g) { private void validateMessageAsync(final Message m, final Group g) {
validationExecutor.execute(new Runnable() { validationExecutor.execute(() -> validateMessage(m, g));
@Override
public void run() {
validateMessage(m, g);
}
});
} }
@ValidationExecutor @ValidationExecutor
@@ -285,12 +260,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
private void storeMessageContextAsync(final Message m, final ClientId c, private void storeMessageContextAsync(final Message m, final ClientId c,
final MessageContext result) { final MessageContext result) {
dbExecutor.execute(new Runnable() { dbExecutor.execute(() -> storeMessageContext(m, c, result));
@Override
public void run() {
storeMessageContext(m, c, result);
}
});
} }
@DatabaseExecutor @DatabaseExecutor
@@ -385,12 +355,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
} }
private void shareOutstandingMessagesAsync(final ClientId c) { private void shareOutstandingMessagesAsync(final ClientId c) {
dbExecutor.execute(new Runnable() { dbExecutor.execute(() -> shareOutstandingMessages(c));
@Override
public void run() {
shareOutstandingMessages(c);
}
});
} }
@DatabaseExecutor @DatabaseExecutor
@@ -418,12 +383,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
*/ */
private void shareNextMessageAsync(final Queue<MessageId> toShare) { private void shareNextMessageAsync(final Queue<MessageId> toShare) {
if (toShare.isEmpty()) return; if (toShare.isEmpty()) return;
dbExecutor.execute(new Runnable() { dbExecutor.execute(() -> shareNextMessage(toShare));
@Override
public void run() {
shareNextMessage(toShare);
}
});
} }
@DatabaseExecutor @DatabaseExecutor
@@ -452,12 +412,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
private void invalidateNextMessageAsync(final Queue<MessageId> invalidate) { private void invalidateNextMessageAsync(final Queue<MessageId> invalidate) {
if (invalidate.isEmpty()) return; if (invalidate.isEmpty()) return;
dbExecutor.execute(new Runnable() { dbExecutor.execute(() -> invalidateNextMessage(invalidate));
@Override
public void run() {
invalidateNextMessage(invalidate);
}
});
} }
@DatabaseExecutor @DatabaseExecutor
@@ -513,12 +468,7 @@ class ValidationManagerImpl implements ValidationManager, Service,
} }
private void loadGroupAndValidateAsync(final Message m) { private void loadGroupAndValidateAsync(final Message m) {
dbExecutor.execute(new Runnable() { dbExecutor.execute(() -> loadGroupAndValidate(m));
@Override
public void run() {
loadGroupAndValidate(m);
}
});
} }
@DatabaseExecutor @DatabaseExecutor

View File

@@ -157,12 +157,8 @@ class KeyManagerImpl implements KeyManager, Service, EventListener {
private void removeContact(final ContactId c) { private void removeContact(final ContactId c) {
activeContacts.remove(c); activeContacts.remove(c);
dbExecutor.execute(new Runnable() { dbExecutor.execute(() -> {
@Override for (TransportKeyManager m : managers.values()) m.removeContact(c);
public void run() {
for (TransportKeyManager m : managers.values())
m.removeContact(c);
}
}); });
} }
} }

View File

@@ -134,20 +134,12 @@ class TransportKeyManagerImpl implements TransportKeyManager {
} }
private void scheduleKeyRotation(long now) { private void scheduleKeyRotation(long now) {
Runnable task = new Runnable() {
@Override
public void run() {
rotateKeys();
}
};
long delay = rotationPeriodLength - now % rotationPeriodLength; long delay = rotationPeriodLength - now % rotationPeriodLength;
scheduler.schedule(task, delay, MILLISECONDS); scheduler.schedule((Runnable) this::rotateKeys, delay, MILLISECONDS);
} }
private void rotateKeys() { private void rotateKeys() {
dbExecutor.execute(new Runnable() { dbExecutor.execute(() -> {
@Override
public void run() {
try { try {
Transaction txn = db.startTransaction(false); Transaction txn = db.startTransaction(false);
try { try {
@@ -157,9 +149,7 @@ class TransportKeyManagerImpl implements TransportKeyManager {
db.endTransaction(txn); db.endTransaction(txn);
} }
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }

View File

@@ -28,12 +28,9 @@ public class PoliteExecutorTest extends BrambleTestCase {
final CountDownLatch latch = new CountDownLatch(TASKS); final CountDownLatch latch = new CountDownLatch(TASKS);
for (int i = 0; i < TASKS; i++) { for (int i = 0; i < TASKS; i++) {
final int result = i; final int result = i;
polite.execute(new Runnable() { polite.execute(() -> {
@Override
public void run() {
list.add(result); list.add(result);
latch.countDown(); latch.countDown();
}
}); });
} }
// Wait for all the tasks to finish // Wait for all the tasks to finish
@@ -53,12 +50,9 @@ public class PoliteExecutorTest extends BrambleTestCase {
final CountDownLatch latch = new CountDownLatch(TASKS); final CountDownLatch latch = new CountDownLatch(TASKS);
for (int i = 0; i < TASKS; i++) { for (int i = 0; i < TASKS; i++) {
final int result = i; final int result = i;
polite.execute(new Runnable() { polite.execute(() -> {
@Override
public void run() {
list.add(result); list.add(result);
latch.countDown(); latch.countDown();
}
}); });
} }
// Wait for all the tasks to finish // Wait for all the tasks to finish
@@ -78,9 +72,7 @@ public class PoliteExecutorTest extends BrambleTestCase {
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; final int result = i;
polite.execute(new Runnable() { polite.execute(() -> {
@Override
public void run() {
try { try {
// Each task waits for the next task, if any, to finish // Each task waits for the next task, if any, to finish
if (result < TASKS - 1) latches[result + 1].await(); if (result < TASKS - 1) latches[result + 1].await();
@@ -89,7 +81,6 @@ public class PoliteExecutorTest extends BrambleTestCase {
fail(); fail();
} }
latches[result].countDown(); latches[result].countDown();
}
}); });
} }
// Wait for all the tasks to finish // Wait for all the tasks to finish
@@ -108,9 +99,7 @@ public class PoliteExecutorTest extends BrambleTestCase {
final CountDownLatch latch = new CountDownLatch(TASKS); final CountDownLatch latch = new CountDownLatch(TASKS);
for (int i = 0; i < TASKS; i++) { for (int i = 0; i < TASKS; i++) {
final int result = i; final int result = i;
polite.execute(new Runnable() { polite.execute(() -> {
@Override
public void run() {
try { try {
// Each task runs faster than the previous task // Each task runs faster than the previous task
Thread.sleep(TASKS - result); Thread.sleep(TASKS - result);
@@ -119,7 +108,6 @@ public class PoliteExecutorTest extends BrambleTestCase {
fail(); fail();
} }
latch.countDown(); latch.countDown();
}
}); });
} }
// Wait for all the tasks to finish // Wait for all the tasks to finish

View File

@@ -17,11 +17,7 @@ public class ShutdownManagerImplTest extends BrambleTestCase {
ShutdownManager s = createShutdownManager(); ShutdownManager s = createShutdownManager();
Set<Integer> handles = new HashSet<>(); Set<Integer> handles = new HashSet<>();
for (int i = 0; i < 100; i++) { for (int i = 0; i < 100; i++) {
int handle = s.addShutdownHook(new Runnable() { int handle = s.addShutdownHook(() -> {});
@Override
public void run() {
}
});
// The handles should all be distinct // The handles should all be distinct
assertTrue(handles.add(handle)); assertTrue(handles.add(handle));
} }

View File

@@ -113,17 +113,13 @@ class WindowsShutdownManagerImpl extends ShutdownManagerImpl {
final User32 user32 = (User32) Native.loadLibrary("user32", final 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 = new WindowProc() { WindowProc proc = (hwnd, msg, wp, lp) -> {
@Override
public LRESULT callback(HWND hwnd, int msg, WPARAM wp,
LPARAM lp) {
if (msg == WM_QUERYENDSESSION) { if (msg == WM_QUERYENDSESSION) {
// It's safe to delay returning from this message // It's safe to delay returning from this message
runShutdownHooks(); runShutdownHooks();
} }
// Pass the message to the default window procedure // Pass the message to the default window procedure
return user32.DefWindowProc(hwnd, msg, wp, lp); return user32.DefWindowProc(hwnd, msg, wp, lp);
}
}; };
// Create a native window // Create a native window
HWND hwnd = user32.CreateWindowEx(0, "STATIC", "", WS_MINIMIZE, HWND hwnd = user32.CreateWindowEx(0, "STATIC", "", WS_MINIMIZE,

View File

@@ -108,9 +108,7 @@ class BluetoothPlugin implements DuplexPlugin {
} }
private void bind() { private void bind() {
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
if (!running) return; if (!running) return;
// Advertise the Bluetooth address to contacts // Advertise the Bluetooth address to contacts
TransportProperties p = new TransportProperties(); TransportProperties p = new TransportProperties();
@@ -134,7 +132,6 @@ class BluetoothPlugin implements DuplexPlugin {
backoff.reset(); backoff.reset();
callback.transportEnabled(); callback.transportEnabled();
acceptContactConnections(ss); acceptContactConnections(ss);
}
}); });
} }
@@ -220,20 +217,18 @@ class BluetoothPlugin implements DuplexPlugin {
if (StringUtils.isNullOrEmpty(address)) continue; if (StringUtils.isNullOrEmpty(address)) continue;
final String uuid = e.getValue().get(PROP_UUID); final String uuid = e.getValue().get(PROP_UUID);
if (StringUtils.isNullOrEmpty(uuid)) continue; if (StringUtils.isNullOrEmpty(uuid)) continue;
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
if (!running) return; if (!running) return;
StreamConnection s = connect(makeUrl(address, uuid)); StreamConnection s = connect(makeUrl(address, uuid));
if (s != null) { if (s != null) {
backoff.reset(); backoff.reset();
callback.outgoingConnectionCreated(c, wrapSocket(s)); callback.outgoingConnectionCreated(c, wrapSocket(s));
} }
}
}); });
} }
} }
@Nullable
private StreamConnection connect(String url) { private StreamConnection connect(String url) {
if (LOG.isLoggable(INFO)) LOG.info("Connecting to " + url); if (LOG.isLoggable(INFO)) LOG.info("Connecting to " + url);
try { try {
@@ -341,16 +336,13 @@ class BluetoothPlugin implements DuplexPlugin {
@Override @Override
public Callable<KeyAgreementConnection> listen() { public Callable<KeyAgreementConnection> listen() {
return new Callable<KeyAgreementConnection>() { return () -> {
@Override
public KeyAgreementConnection call() throws Exception {
StreamConnection s = ss.acceptAndOpen(); StreamConnection s = ss.acceptAndOpen();
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info(ID.getString() + ": Incoming connection"); LOG.info(ID.getString() + ": Incoming connection");
return new KeyAgreementConnection( return new KeyAgreementConnection(
new BluetoothTransportConnection( new BluetoothTransportConnection(
BluetoothPlugin.this, s), ID); BluetoothPlugin.this, s), ID);
}
}; };
} }

View File

@@ -390,16 +390,13 @@ class ModemImpl implements Modem, WriteHandler, SerialPortEventListener {
lock.unlock(); lock.unlock();
} }
} else if (s.equals("RING")) { } else if (s.equals("RING")) {
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
try { try {
answer(); answer();
} catch (IOException e) { } catch (IOException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING))
LOG.log(WARNING, e.toString(), e); LOG.log(WARNING, e.toString(), e);
} }
}
}); });
} }
} else { } else {

View File

@@ -44,7 +44,6 @@ import org.briarproject.briar.api.sharing.event.InvitationResponseReceivedEvent;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.concurrent.Future; import java.util.concurrent.Future;
@@ -138,16 +137,13 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
@Override @Override
public void stopService() throws ServiceException { public void stopService() throws ServiceException {
// Clear all notifications // Clear all notifications
Future<Void> f = androidExecutor.runOnUiThread(new Callable<Void>() { Future<Void> f = androidExecutor.runOnUiThread(() -> {
@Override
public Void call() {
clearContactNotification(); clearContactNotification();
clearGroupMessageNotification(); clearGroupMessageNotification();
clearForumPostNotification(); clearForumPostNotification();
clearBlogPostNotification(); clearBlogPostNotification();
clearIntroductionSuccessNotification(); clearIntroductionSuccessNotification();
return null; return null;
}
}); });
try { try {
f.get(); f.get();
@@ -236,23 +232,18 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
} }
private void loadSettings() { private void loadSettings() {
dbExecutor.execute(new Runnable() { dbExecutor.execute(() -> {
@Override
public void run() {
try { try {
settings = settingsManager.getSettings(SETTINGS_NAMESPACE); settings = settingsManager.getSettings(SETTINGS_NAMESPACE);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING))
LOG.log(WARNING, e.toString(), e); LOG.log(WARNING, e.toString(), e);
} }
}
}); });
} }
private void showContactNotification(final ContactId c) { private void showContactNotification(final ContactId c) {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(() -> {
@Override
public void run() {
if (blockContacts) return; if (blockContacts) return;
if (c.equals(blockedContact)) return; if (c.equals(blockedContact)) return;
Integer count = contactCounts.get(c); Integer count = contactCounts.get(c);
@@ -260,20 +251,16 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
else contactCounts.put(c, count + 1); else contactCounts.put(c, count + 1);
contactTotal++; contactTotal++;
updateContactNotification(true); updateContactNotification(true);
}
}); });
} }
@Override @Override
public void clearContactNotification(final ContactId c) { public void clearContactNotification(final ContactId c) {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(() -> {
@Override
public void run() {
Integer count = contactCounts.remove(c); Integer count = contactCounts.remove(c);
if (count == null) return; // Already cleared if (count == null) return; // Already cleared
contactTotal -= count; contactTotal -= count;
updateContactNotification(false); updateContactNotification(false);
}
}); });
} }
@@ -358,19 +345,13 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
@Override @Override
public void clearAllContactNotifications() { public void clearAllContactNotifications() {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(
@Override (Runnable) this::clearContactNotification);
public void run() {
clearContactNotification();
}
});
} }
@UiThread @UiThread
private void showGroupMessageNotification(final GroupId g) { private void showGroupMessageNotification(final GroupId g) {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(() -> {
@Override
public void run() {
if (blockGroups) return; if (blockGroups) return;
if (g.equals(blockedGroup)) return; if (g.equals(blockedGroup)) return;
Integer count = groupCounts.get(g); Integer count = groupCounts.get(g);
@@ -378,20 +359,16 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
else groupCounts.put(g, count + 1); else groupCounts.put(g, count + 1);
groupTotal++; groupTotal++;
updateGroupMessageNotification(true); updateGroupMessageNotification(true);
}
}); });
} }
@Override @Override
public void clearGroupMessageNotification(final GroupId g) { public void clearGroupMessageNotification(final GroupId g) {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(() -> {
@Override
public void run() {
Integer count = groupCounts.remove(g); Integer count = groupCounts.remove(g);
if (count == null) return; // Already cleared if (count == null) return; // Already cleared
groupTotal -= count; groupTotal -= count;
updateGroupMessageNotification(false); updateGroupMessageNotification(false);
}
}); });
} }
@@ -445,19 +422,13 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
@Override @Override
public void clearAllGroupMessageNotifications() { public void clearAllGroupMessageNotifications() {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(
@Override (Runnable) this::clearGroupMessageNotification);
public void run() {
clearGroupMessageNotification();
}
});
} }
@UiThread @UiThread
private void showForumPostNotification(final GroupId g) { private void showForumPostNotification(final GroupId g) {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(() -> {
@Override
public void run() {
if (blockForums) return; if (blockForums) return;
if (g.equals(blockedGroup)) return; if (g.equals(blockedGroup)) return;
Integer count = forumCounts.get(g); Integer count = forumCounts.get(g);
@@ -465,20 +436,16 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
else forumCounts.put(g, count + 1); else forumCounts.put(g, count + 1);
forumTotal++; forumTotal++;
updateForumPostNotification(true); updateForumPostNotification(true);
}
}); });
} }
@Override @Override
public void clearForumPostNotification(final GroupId g) { public void clearForumPostNotification(final GroupId g) {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(() -> {
@Override
public void run() {
Integer count = forumCounts.remove(g); Integer count = forumCounts.remove(g);
if (count == null) return; // Already cleared if (count == null) return; // Already cleared
forumTotal -= count; forumTotal -= count;
updateForumPostNotification(false); updateForumPostNotification(false);
}
}); });
} }
@@ -532,19 +499,13 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
@Override @Override
public void clearAllForumPostNotifications() { public void clearAllForumPostNotifications() {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(
@Override (Runnable) this::clearForumPostNotification);
public void run() {
clearForumPostNotification();
}
});
} }
@UiThread @UiThread
private void showBlogPostNotification(final GroupId g) { private void showBlogPostNotification(final GroupId g) {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(() -> {
@Override
public void run() {
if (blockBlogs) return; if (blockBlogs) return;
if (g.equals(blockedGroup)) return; if (g.equals(blockedGroup)) return;
Integer count = blogCounts.get(g); Integer count = blogCounts.get(g);
@@ -552,20 +513,16 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
else blogCounts.put(g, count + 1); else blogCounts.put(g, count + 1);
blogTotal++; blogTotal++;
updateBlogPostNotification(true); updateBlogPostNotification(true);
}
}); });
} }
@Override @Override
public void clearBlogPostNotification(final GroupId g) { public void clearBlogPostNotification(final GroupId g) {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(() -> {
@Override
public void run() {
Integer count = blogCounts.remove(g); Integer count = blogCounts.remove(g);
if (count == null) return; // Already cleared if (count == null) return; // Already cleared
blogTotal -= count; blogTotal -= count;
updateBlogPostNotification(false); updateBlogPostNotification(false);
}
}); });
} }
@@ -606,22 +563,15 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
@Override @Override
public void clearAllBlogPostNotifications() { public void clearAllBlogPostNotifications() {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(
@Override (Runnable) this::clearBlogPostNotification);
public void run() {
clearBlogPostNotification();
}
});
} }
private void showIntroductionNotification() { private void showIntroductionNotification() {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(() -> {
@Override
public void run() {
if (blockIntroductions) return; if (blockIntroductions) return;
introductionTotal++; introductionTotal++;
updateIntroductionNotification(); updateIntroductionNotification();
}
}); });
} }
@@ -656,71 +606,41 @@ class AndroidNotificationManagerImpl implements AndroidNotificationManager,
@Override @Override
public void clearAllIntroductionNotifications() { public void clearAllIntroductionNotifications() {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(
@Override this::clearIntroductionSuccessNotification);
public void run() {
clearIntroductionSuccessNotification();
}
});
} }
@Override @Override
public void blockNotification(final GroupId g) { public void blockNotification(final GroupId g) {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread((Runnable) () -> blockedGroup = g);
@Override
public void run() {
blockedGroup = g;
}
});
} }
@Override @Override
public void unblockNotification(final GroupId g) { public void unblockNotification(final GroupId g) {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(() -> {
@Override
public void run() {
if (g.equals(blockedGroup)) blockedGroup = null; if (g.equals(blockedGroup)) blockedGroup = null;
}
}); });
} }
@Override @Override
public void blockContactNotification(final ContactId c) { public void blockContactNotification(final ContactId c) {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread((Runnable) () -> blockedContact = c);
@Override
public void run() {
blockedContact = c;
}
});
} }
@Override @Override
public void unblockContactNotification(final ContactId c) { public void unblockContactNotification(final ContactId c) {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(() -> {
@Override
public void run() {
if (c.equals(blockedContact)) blockedContact = null; if (c.equals(blockedContact)) blockedContact = null;
}
}); });
} }
@Override @Override
public void blockAllBlogPostNotifications() { public void blockAllBlogPostNotifications() {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread((Runnable) () -> blockBlogs = true);
@Override
public void run() {
blockBlogs = true;
}
});
} }
@Override @Override
public void unblockAllBlogPostNotifications() { public void unblockAllBlogPostNotifications() {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread((Runnable) () -> blockBlogs = false);
@Override
public void run() {
blockBlogs = false;
}
});
} }
} }

View File

@@ -112,9 +112,7 @@ public class BriarService extends Service {
} }
private void showStartupFailureNotification(final StartResult result) { private void showStartupFailureNotification(final StartResult result) {
androidExecutor.runOnUiThread(new Runnable() { androidExecutor.runOnUiThread(() -> {
@Override
public void run() {
NotificationCompat.Builder b = NotificationCompat.Builder b =
new NotificationCompat.Builder(BriarService.this); new NotificationCompat.Builder(BriarService.this);
b.setSmallIcon(android.R.drawable.stat_notify_error); b.setSmallIcon(android.R.drawable.stat_notify_error);
@@ -138,7 +136,6 @@ public class BriarService extends Service {
i.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TOP); i.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("briar.STARTUP_FAILED", true); i.putExtra("briar.STARTUP_FAILED", true);
startActivity(i); startActivity(i);
}
}); });
} }

View File

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

View File

@@ -13,7 +13,6 @@ import android.view.Window;
import org.briarproject.briar.R; import org.briarproject.briar.R;
import org.briarproject.briar.android.controller.BriarController; import org.briarproject.briar.android.controller.BriarController;
import org.briarproject.briar.android.controller.DbController; import org.briarproject.briar.android.controller.DbController;
import org.briarproject.briar.android.controller.handler.ResultHandler;
import org.briarproject.briar.android.login.PasswordActivity; import org.briarproject.briar.android.login.PasswordActivity;
import org.briarproject.briar.android.panic.ExitActivity; import org.briarproject.briar.android.panic.ExitActivity;
@@ -102,17 +101,8 @@ public abstract class BriarActivity extends BaseActivity {
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
briarController.signOut(new ResultHandler<Void>() { briarController.signOut(result -> runOnUiThread(
@Override () -> exit(removeFromRecentApps)));
public void onResult(Void result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
exit(removeFromRecentApps);
}
});
}
});
} else { } else {
exit(removeFromRecentApps); exit(removeFromRecentApps);
} }
@@ -146,11 +136,6 @@ public abstract class BriarActivity extends BaseActivity {
@Deprecated @Deprecated
protected void finishOnUiThread() { protected void finishOnUiThread() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(this::supportFinishAfterTransition);
@Override
public void run() {
supportFinishAfterTransition();
}
});
} }
} }

View File

@@ -85,30 +85,18 @@ abstract class BaseControllerImpl extends DbControllerImpl
} }
void onBlogPostAdded(final BlogPostHeader h, final boolean local) { void onBlogPostAdded(final BlogPostHeader h, final boolean local) {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(
@Override () -> listener.onBlogPostAdded(h, local));
public void run() {
listener.onBlogPostAdded(h, local);
}
});
} }
void onBlogRemoved() { void onBlogRemoved() {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(() -> listener.onBlogRemoved());
@Override
public void run() {
listener.onBlogRemoved();
} }
});
}
@Override @Override
public void loadBlogPosts(final GroupId groupId, public void loadBlogPosts(final GroupId groupId,
final ResultExceptionHandler<Collection<BlogPostItem>, DbException> handler) { final ResultExceptionHandler<Collection<BlogPostItem>, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
Collection<BlogPostItem> items = loadItems(groupId); Collection<BlogPostItem> items = loadItems(groupId);
handler.onResult(items); handler.onResult(items);
@@ -117,7 +105,6 @@ abstract class BaseControllerImpl extends DbControllerImpl
LOG.log(WARNING, e.toString(), e); LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@@ -151,9 +138,7 @@ abstract class BaseControllerImpl extends DbControllerImpl
handler.onResult(new BlogPostItem(header, body)); handler.onResult(new BlogPostItem(header, body));
return; return;
} }
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
BlogPostItem item = getItem(header); BlogPostItem item = getItem(header);
@@ -166,7 +151,6 @@ abstract class BaseControllerImpl extends DbControllerImpl
LOG.log(WARNING, e.toString(), e); LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@@ -180,13 +164,11 @@ abstract class BaseControllerImpl extends DbControllerImpl
loadBlogPost(header, handler); loadBlogPost(header, handler);
return; return;
} }
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
BlogPostHeader header = getPostHeader(g, m); BlogPostHeader header1 = getPostHeader(g, m);
BlogPostItem item = getItem(header); BlogPostItem item = getItem(header1);
long duration = System.currentTimeMillis() - now; long duration = System.currentTimeMillis() - now;
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Loading post took " + duration + " ms"); LOG.info("Loading post took " + duration + " ms");
@@ -196,7 +178,6 @@ abstract class BaseControllerImpl extends DbControllerImpl
LOG.log(WARNING, e.toString(), e); LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@@ -204,9 +185,7 @@ abstract class BaseControllerImpl extends DbControllerImpl
public void repeatPost(final BlogPostItem item, public void repeatPost(final BlogPostItem item,
final @Nullable String comment, final @Nullable String comment,
final ExceptionHandler<DbException> handler) { final ExceptionHandler<DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
LocalAuthor a = identityManager.getLocalAuthor(); LocalAuthor a = identityManager.getLocalAuthor();
Blog b = blogManager.getPersonalBlog(a); Blog b = blogManager.getPersonalBlog(a);
@@ -217,7 +196,6 @@ abstract class BaseControllerImpl extends DbControllerImpl
LOG.log(WARNING, e.toString(), e); LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }

View File

@@ -99,13 +99,10 @@ abstract class BasePostFragment extends BaseFragment {
} }
private void startPeriodicUpdate() { private void startPeriodicUpdate() {
refresher = new Runnable() { refresher = () -> {
@Override
public void run() {
LOG.info("Updating Content..."); LOG.info("Updating Content...");
ui.updateDate(post.getTimestamp()); ui.updateDate(post.getTimestamp());
handler.postDelayed(refresher, MIN_DATE_RESOLUTION); handler.postDelayed(refresher, MIN_DATE_RESOLUTION);
}
}; };
LOG.info("Adding Handler Callback"); LOG.info("Adding Handler Callback");
handler.postDelayed(refresher, MIN_DATE_RESOLUTION); handler.postDelayed(refresher, MIN_DATE_RESOLUTION);

View File

@@ -3,7 +3,6 @@ package org.briarproject.briar.android.blog;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.support.v7.widget.Toolbar; import android.support.v7.widget.Toolbar;
import android.view.View;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault; import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault; import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
@@ -41,15 +40,11 @@ public class BlogActivity extends BriarActivity
// Open Sharing Status on Toolbar click // Open Sharing Status on Toolbar click
if (toolbar != null) { if (toolbar != null) {
toolbar.setOnClickListener( toolbar.setOnClickListener(v -> {
new View.OnClickListener() { Intent i1 = new Intent(BlogActivity.this,
@Override
public void onClick(View v) {
Intent i = new Intent(BlogActivity.this,
BlogSharingStatusActivity.class); BlogSharingStatusActivity.class);
i.putExtra(GROUP_ID, groupId.getBytes()); i1.putExtra(GROUP_ID, groupId.getBytes());
startActivity(i); startActivity(i1);
}
}); });
} }

View File

@@ -126,21 +126,12 @@ class BlogControllerImpl extends BaseControllerImpl
} }
private void onBlogInvitationAccepted(final ContactId c) { private void onBlogInvitationAccepted(final ContactId c) {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(
@Override () -> listener.onBlogInvitationAccepted(c));
public void run() {
listener.onBlogInvitationAccepted(c);
}
});
} }
private void onBlogLeft(final ContactId c) { private void onBlogLeft(final ContactId c) {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(() -> listener.onBlogLeft(c));
@Override
public void run() {
listener.onBlogLeft(c);
}
});
} }
@Override @Override
@@ -161,9 +152,7 @@ class BlogControllerImpl extends BaseControllerImpl
public void loadBlog( public void loadBlog(
final ResultExceptionHandler<BlogItem, DbException> handler) { final ResultExceptionHandler<BlogItem, DbException> handler) {
if (groupId == null) throw new IllegalStateException(); if (groupId == null) throw new IllegalStateException();
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
LocalAuthor a = identityManager.getLocalAuthor(); LocalAuthor a = identityManager.getLocalAuthor();
@@ -180,7 +169,6 @@ class BlogControllerImpl extends BaseControllerImpl
LOG.log(WARNING, e.toString(), e); LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@@ -188,9 +176,7 @@ class BlogControllerImpl extends BaseControllerImpl
public void deleteBlog( public void deleteBlog(
final ResultExceptionHandler<Void, DbException> handler) { final ResultExceptionHandler<Void, DbException> handler) {
if (groupId == null) throw new IllegalStateException(); if (groupId == null) throw new IllegalStateException();
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
Blog b = blogManager.getBlog(groupId); Blog b = blogManager.getBlog(groupId);
@@ -204,7 +190,6 @@ class BlogControllerImpl extends BaseControllerImpl
LOG.log(WARNING, e.toString(), e); LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@@ -212,9 +197,7 @@ class BlogControllerImpl extends BaseControllerImpl
public void loadSharingContacts( public void loadSharingContacts(
final ResultExceptionHandler<Collection<ContactId>, DbException> handler) { final ResultExceptionHandler<Collection<ContactId>, DbException> handler) {
if (groupId == null) throw new IllegalStateException(); if (groupId == null) throw new IllegalStateException();
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
Collection<Contact> contacts = Collection<Contact> contacts =
blogSharingManager.getSharedWith(groupId); blogSharingManager.getSharedWith(groupId);
@@ -227,7 +210,6 @@ class BlogControllerImpl extends BaseControllerImpl
LOG.log(WARNING, e.toString(), e); LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }

View File

@@ -331,12 +331,7 @@ public class BlogFragment extends BaseFragment
Snackbar.make(list, stringId, Snackbar.LENGTH_LONG); Snackbar.make(list, stringId, Snackbar.LENGTH_LONG);
snackbar.getView().setBackgroundResource(R.color.briar_primary); snackbar.getView().setBackgroundResource(R.color.briar_primary);
if (scroll) { if (scroll) {
View.OnClickListener onClick = new View.OnClickListener() { View.OnClickListener onClick = v -> list.smoothScrollToPosition(0);
@Override
public void onClick(View v) {
list.smoothScrollToPosition(0);
}
};
snackbar.setActionTextColor(ContextCompat snackbar.setActionTextColor(ContextCompat
.getColor(getContext(), .getColor(getContext(),
R.color.briar_button_positive)); R.color.briar_button_positive));
@@ -347,12 +342,7 @@ public class BlogFragment extends BaseFragment
private void showDeleteDialog() { private void showDeleteDialog() {
DialogInterface.OnClickListener okListener = DialogInterface.OnClickListener okListener =
new DialogInterface.OnClickListener() { (dialog, which) -> deleteBlog();
@Override
public void onClick(DialogInterface dialog, int which) {
deleteBlog();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),
R.style.BriarDialogTheme); R.style.BriarDialogTheme);
builder.setTitle(getString(R.string.blogs_remove_blog)); builder.setTitle(getString(R.string.blogs_remove_blog));

View File

@@ -13,7 +13,6 @@ import android.support.v7.widget.RecyclerView;
import android.text.Spanned; import android.text.Spanned;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
@@ -95,12 +94,7 @@ class BlogPostViewHolder extends RecyclerView.ViewHolder {
setTransitionName(item.getId()); setTransitionName(item.getId());
if (!fullText) { if (!fullText) {
layout.setClickable(true); layout.setClickable(true);
layout.setOnClickListener(new OnClickListener() { layout.setOnClickListener(v -> listener.onBlogPostClick(item));
@Override
public void onClick(View v) {
listener.onBlogPostClick(item);
}
});
} }
// author and date // author and date
@@ -113,12 +107,7 @@ class BlogPostViewHolder extends RecyclerView.ViewHolder {
item.isRssFeed() ? AuthorView.RSS_FEED : AuthorView.NORMAL); item.isRssFeed() ? AuthorView.RSS_FEED : AuthorView.NORMAL);
// TODO make author clickable more often #624 // TODO make author clickable more often #624
if (!fullText && item.getHeader().getType() == POST) { if (!fullText && item.getHeader().getType() == POST) {
author.setAuthorClickable(new OnClickListener() { author.setAuthorClickable(v -> listener.onAuthorClick(item));
@Override
public void onClick(View v) {
listener.onAuthorClick(item);
}
});
} else { } else {
author.setAuthorNotClickable(); author.setAuthorNotClickable();
} }
@@ -137,9 +126,7 @@ class BlogPostViewHolder extends RecyclerView.ViewHolder {
} }
// reblog button // reblog button
reblogButton.setOnClickListener(new OnClickListener() { reblogButton.setOnClickListener(v -> {
@Override
public void onClick(View v) {
Intent i = new Intent(ctx, ReblogActivity.class); Intent i = new Intent(ctx, ReblogActivity.class);
i.putExtra(GROUP_ID, item.getGroupId().getBytes()); i.putExtra(GROUP_ID, item.getGroupId().getBytes());
i.putExtra(POST_ID, item.getId().getBytes()); i.putExtra(POST_ID, item.getId().getBytes());
@@ -154,7 +141,6 @@ class BlogPostViewHolder extends RecyclerView.ViewHolder {
// work-around for android bug #224270 // work-around for android bug #224270
ctx.startActivity(i); ctx.startActivity(i);
} }
}
}); });
// comments // comments
@@ -172,12 +158,7 @@ class BlogPostViewHolder extends RecyclerView.ViewHolder {
reblogger.setAuthorStatus(item.getAuthorStatus()); reblogger.setAuthorStatus(item.getAuthorStatus());
reblogger.setDate(item.getTimestamp()); reblogger.setDate(item.getTimestamp());
if (!fullText) { if (!fullText) {
reblogger.setAuthorClickable(new OnClickListener() { reblogger.setAuthorClickable(v -> listener.onAuthorClick(item));
@Override
public void onClick(View v) {
listener.onAuthorClick(item);
}
});
} }
reblogger.setVisibility(VISIBLE); reblogger.setVisibility(VISIBLE);
reblogger.setPersona(AuthorView.REBLOGGER); reblogger.setPersona(AuthorView.REBLOGGER);

View File

@@ -91,20 +91,13 @@ class FeedControllerImpl extends BaseControllerImpl
} }
private void onBlogAdded() { private void onBlogAdded() {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(() -> listener.onBlogAdded());
@Override
public void run() {
listener.onBlogAdded();
}
});
} }
@Override @Override
public void loadBlogPosts( public void loadBlogPosts(
final ResultExceptionHandler<Collection<BlogPostItem>, DbException> handler) { final ResultExceptionHandler<Collection<BlogPostItem>, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
Collection<BlogPostItem> posts = new ArrayList<>(); Collection<BlogPostItem> posts = new ArrayList<>();
@@ -121,20 +114,16 @@ class FeedControllerImpl extends BaseControllerImpl
LOG.info("Loading all posts took " + duration + " ms"); LOG.info("Loading all posts took " + duration + " ms");
handler.onResult(posts); handler.onResult(posts);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@Override @Override
public void loadPersonalBlog( public void loadPersonalBlog(
final ResultExceptionHandler<Blog, DbException> handler) { final ResultExceptionHandler<Blog, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
Author a = identityManager.getLocalAuthor(); Author a = identityManager.getLocalAuthor();
@@ -144,11 +133,9 @@ class FeedControllerImpl extends BaseControllerImpl
LOG.info("Loading blog took " + duration + " ms"); LOG.info("Loading blog took " + duration + " ms");
handler.onResult(b); handler.onResult(b);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }

View File

@@ -246,12 +246,7 @@ public class FeedFragment extends BaseFragment implements
Snackbar s = Snackbar.make(list, stringRes, LENGTH_LONG); Snackbar s = Snackbar.make(list, stringRes, LENGTH_LONG);
s.getView().setBackgroundResource(R.color.briar_primary); s.getView().setBackgroundResource(R.color.briar_primary);
if (scroll) { if (scroll) {
OnClickListener onClick = new OnClickListener() { OnClickListener onClick = v -> list.smoothScrollToPosition(0);
@Override
public void onClick(View v) {
list.smoothScrollToPosition(0);
}
};
s.setActionTextColor(ContextCompat s.setActionTextColor(ContextCompat
.getColor(getContext(), .getColor(getContext(),
R.color.briar_button_positive)); R.color.briar_button_positive));

View File

@@ -114,12 +114,7 @@ public class ReblogFragment extends BaseFragment implements TextInputListener {
ui.input.setListener(this); ui.input.setListener(this);
ui.input.setSendButtonEnabled(true); ui.input.setSendButtonEnabled(true);
ui.scrollView.post(new Runnable() { ui.scrollView.post(() -> ui.scrollView.fullScroll(FOCUS_DOWN));
@Override
public void run() {
ui.scrollView.fullScroll(FOCUS_DOWN);
}
});
} }
@Override @Override

View File

@@ -4,7 +4,6 @@ import android.content.Context;
import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.ImageButton; import android.widget.ImageButton;
import android.widget.TextView; import android.widget.TextView;
@@ -42,12 +41,7 @@ class RssFeedAdapter extends BriarAdapter<Feed, RssFeedAdapter.FeedViewHolder> {
ui.title.setText(item.getTitle()); ui.title.setText(item.getTitle());
// Delete Button // Delete Button
ui.delete.setOnClickListener(new OnClickListener() { ui.delete.setOnClickListener(v -> listener.onDeleteClick(item));
@Override
public void onClick(View v) {
listener.onDeleteClick(item);
}
});
// Author // Author
if (item.getAuthor() != null) { if (item.getAuthor() != null) {
@@ -72,12 +66,7 @@ class RssFeedAdapter extends BriarAdapter<Feed, RssFeedAdapter.FeedViewHolder> {
} }
// Open feed's blog when clicked // Open feed's blog when clicked
ui.layout.setOnClickListener(new OnClickListener() { ui.layout.setOnClickListener(v -> listener.onFeedClick(item));
@Override
public void onClick(View v) {
listener.onFeedClick(item);
}
});
} }
@Override @Override

View File

@@ -1,6 +1,5 @@
package org.briarproject.briar.android.blog; package org.briarproject.briar.android.blog;
import android.content.DialogInterface;
import android.os.Bundle; import android.os.Bundle;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.text.Editable; import android.text.Editable;
@@ -8,7 +7,6 @@ import android.text.TextWatcher;
import android.util.Patterns; import android.util.Patterns;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View;
import android.widget.Button; import android.widget.Button;
import android.widget.EditText; import android.widget.EditText;
import android.widget.ProgressBar; import android.widget.ProgressBar;
@@ -75,12 +73,7 @@ public class RssFeedImportActivity extends BriarActivity {
}); });
importButton = (Button) findViewById(R.id.importButton); importButton = (Button) findViewById(R.id.importButton);
importButton.setOnClickListener(new View.OnClickListener() { importButton.setOnClickListener(v -> publish());
@Override
public void onClick(View v) {
publish();
}
});
progressBar = (ProgressBar) findViewById(R.id.progressBar); progressBar = (ProgressBar) findViewById(R.id.progressBar);
} }
@@ -126,34 +119,23 @@ public class RssFeedImportActivity extends BriarActivity {
} }
private void importFeed(final String url) { private void importFeed(final String url) {
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
try { try {
feedManager.addFeed(url); feedManager.addFeed(url);
feedImported(); feedImported();
} catch (DbException | IOException e) { } catch (DbException | IOException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
importFailed(); importFailed();
} }
}
}); });
} }
private void feedImported() { private void feedImported() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(this::supportFinishAfterTransition);
@Override
public void run() {
supportFinishAfterTransition();
}
});
} }
private void importFailed() { private void importFailed() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
// hide progress bar, show publish button // hide progress bar, show publish button
progressBar.setVisibility(GONE); progressBar.setVisibility(GONE);
importButton.setVisibility(VISIBLE); importButton.setVisibility(VISIBLE);
@@ -165,15 +147,9 @@ public class RssFeedImportActivity extends BriarActivity {
builder.setMessage(R.string.blogs_rss_feeds_import_error); builder.setMessage(R.string.blogs_rss_feeds_import_error);
builder.setNegativeButton(R.string.cancel, null); builder.setNegativeButton(R.string.cancel, null);
builder.setPositiveButton(R.string.try_again_button, builder.setPositiveButton(R.string.try_again_button,
new DialogInterface.OnClickListener() { (dialog, which) -> publish());
@Override
public void onClick(DialogInterface dialog, int which) {
publish();
}
});
AlertDialog dialog = builder.create(); AlertDialog dialog = builder.create();
dialog.show(); dialog.show();
}
}); });
} }

View File

@@ -105,12 +105,7 @@ public class RssFeedManageActivity extends BriarActivity
@Override @Override
public void onDeleteClick(final Feed feed) { public void onDeleteClick(final Feed feed) {
DialogInterface.OnClickListener okListener = DialogInterface.OnClickListener okListener =
new DialogInterface.OnClickListener() { (dialog, which) -> deleteFeed(feed);
@Override
public void onClick(DialogInterface dialog, int which) {
deleteFeed(feed);
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog.Builder builder = new AlertDialog.Builder(this,
R.style.BriarDialogTheme); R.style.BriarDialogTheme);
builder.setTitle(getString(R.string.blogs_rss_remove_feed)); builder.setTitle(getString(R.string.blogs_rss_remove_feed));
@@ -124,24 +119,18 @@ public class RssFeedManageActivity extends BriarActivity
private void loadFeeds() { private void loadFeeds() {
final int revision = adapter.getRevision(); final int revision = adapter.getRevision();
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
displayFeeds(revision, feedManager.getFeeds()); displayFeeds(revision, feedManager.getFeeds());
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
onLoadError(); onLoadError();
} }
}
}); });
} }
private void displayFeeds(final int revision, final List<Feed> feeds) { private void displayFeeds(final int revision, final List<Feed> feeds) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
if (revision == adapter.getRevision()) { if (revision == adapter.getRevision()) {
adapter.incrementRevision(); adapter.incrementRevision();
if (feeds.isEmpty()) list.showData(); if (feeds.isEmpty()) list.showData();
@@ -150,55 +139,39 @@ public class RssFeedManageActivity extends BriarActivity
LOG.info("Concurrent update, reloading"); LOG.info("Concurrent update, reloading");
loadFeeds(); loadFeeds();
} }
}
}); });
} }
private void deleteFeed(final Feed feed) { private void deleteFeed(final Feed feed) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
feedManager.removeFeed(feed); feedManager.removeFeed(feed);
onFeedDeleted(feed); onFeedDeleted(feed);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
onDeleteError(); onDeleteError();
} }
}
}); });
} }
private void onLoadError() { private void onLoadError() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
list.setEmptyText(R.string.blogs_rss_feeds_manage_error); list.setEmptyText(R.string.blogs_rss_feeds_manage_error);
list.showData(); list.showData();
}
}); });
} }
private void onFeedDeleted(final Feed feed) { private void onFeedDeleted(final Feed feed) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
adapter.incrementRevision(); adapter.incrementRevision();
adapter.remove(feed); adapter.remove(feed);
}
}); });
} }
private void onDeleteError() { private void onDeleteError() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> Snackbar.make(list,
@Override
public void run() {
Snackbar.make(list,
R.string.blogs_rss_feeds_manage_delete_error, R.string.blogs_rss_feeds_manage_delete_error,
LENGTH_LONG).show(); LENGTH_LONG).show());
}
});
} }
} }

View File

@@ -141,9 +141,7 @@ public class WriteBlogPostActivity extends BriarActivity
} }
private void storePost(final String body) { private void storePost(final String body) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
try { try {
LocalAuthor author = identityManager.getLocalAuthor(); LocalAuthor author = identityManager.getLocalAuthor();
@@ -151,34 +149,27 @@ public class WriteBlogPostActivity extends BriarActivity
.createBlogPost(groupId, now, null, author, body); .createBlogPost(groupId, now, null, author, body);
blogManager.addLocalPost(p); blogManager.addLocalPost(p);
postPublished(); postPublished();
} catch (DbException | GeneralSecurityException | FormatException e) { } catch (DbException | GeneralSecurityException
if (LOG.isLoggable(WARNING)) | FormatException e) {
LOG.log(WARNING, e.toString(), e); if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
postFailedToPublish(); postFailedToPublish();
} }
}
}); });
} }
private void postPublished() { private void postPublished() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
setResult(RESULT_OK); setResult(RESULT_OK);
supportFinishAfterTransition(); supportFinishAfterTransition();
}
}); });
} }
private void postFailedToPublish() { private void postFailedToPublish() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
// hide progress bar, show publish button // hide progress bar, show publish button
progressBar.setVisibility(GONE); progressBar.setVisibility(GONE);
input.setVisibility(VISIBLE); input.setVisibility(VISIBLE);
// TODO show error // TODO show error
}
}); });
} }
} }

View File

@@ -54,11 +54,8 @@ public class ContactItemViewHolder<I extends ContactItem>
} }
} }
layout.setOnClickListener(new View.OnClickListener() { layout.setOnClickListener(v -> {
@Override
public void onClick(View v) {
if (listener != null) listener.onItemClick(avatar, item); if (listener != null) listener.onItemClick(avatar, item);
}
}); });
} }

View File

@@ -114,9 +114,7 @@ public class ContactListFragment extends BaseFragment implements EventListener {
View contentView = inflater.inflate(R.layout.list, container, false); View contentView = inflater.inflate(R.layout.list, container, false);
OnContactClickListener<ContactListItem> onContactClickListener = OnContactClickListener<ContactListItem> onContactClickListener =
new OnContactClickListener<ContactListItem>() { (view, item) -> {
@Override
public void onItemClick(View view, ContactListItem item) {
Intent i = new Intent(getActivity(), Intent i = new Intent(getActivity(),
ConversationActivity.class); ConversationActivity.class);
ContactId contactId = item.getContact().getId(); ContactId contactId = item.getContact().getId();
@@ -127,13 +125,12 @@ public class ContactListFragment extends BaseFragment implements EventListener {
(ContactListItemViewHolder) list (ContactListItemViewHolder) list
.getRecyclerView() .getRecyclerView()
.findViewHolderForAdapterPosition( .findViewHolderForAdapterPosition(
adapter.findItemPosition( adapter.findItemPosition(item));
item));
Pair<View, String> avatar = Pair<View, String> avatar =
Pair.create((View) holder.avatar, Pair.create(holder.avatar,
getTransitionName(holder.avatar)); getTransitionName(holder.avatar));
Pair<View, String> bulb = Pair<View, String> bulb =
Pair.create((View) holder.bulb, Pair.create(holder.bulb,
getTransitionName(holder.bulb)); getTransitionName(holder.bulb));
ActivityOptionsCompat options = ActivityOptionsCompat options =
makeSceneTransitionAnimation(getActivity(), makeSceneTransitionAnimation(getActivity(),
@@ -144,7 +141,6 @@ public class ContactListFragment extends BaseFragment implements EventListener {
// work-around for android bug #224270 // work-around for android bug #224270
startActivity(i); startActivity(i);
} }
}
}; };
adapter = new ContactListAdapter(getContext(), onContactClickListener); adapter = new ContactListAdapter(getContext(), onContactClickListener);
list = (BriarRecyclerView) contentView.findViewById(R.id.list); list = (BriarRecyclerView) contentView.findViewById(R.id.list);
@@ -196,9 +192,7 @@ public class ContactListFragment extends BaseFragment implements EventListener {
private void loadContacts() { private void loadContacts() {
final int revision = adapter.getRevision(); final int revision = adapter.getRevision();
listener.runOnDbThread(new Runnable() { listener.runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
List<ContactListItem> contacts = new ArrayList<>(); List<ContactListItem> contacts = new ArrayList<>();
@@ -209,8 +203,7 @@ public class ContactListFragment extends BaseFragment implements EventListener {
conversationManager.getGroupCount(id); conversationManager.getGroupCount(id);
boolean connected = boolean connected =
connectionRegistry.isConnected(c.getId()); connectionRegistry.isConnected(c.getId());
contacts.add(new ContactListItem(c, connected, contacts.add(new ContactListItem(c, connected, count));
count));
} catch (NoSuchContactException e) { } catch (NoSuchContactException e) {
// Continue // Continue
} }
@@ -220,18 +213,14 @@ public class ContactListFragment extends BaseFragment implements EventListener {
LOG.info("Full load took " + duration + " ms"); LOG.info("Full load took " + duration + " ms");
displayContacts(revision, contacts); displayContacts(revision, contacts);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
private void displayContacts(final int revision, private void displayContacts(final int revision,
final List<ContactListItem> contacts) { final List<ContactListItem> contacts) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
if (revision == adapter.getRevision()) { if (revision == adapter.getRevision()) {
adapter.incrementRevision(); adapter.incrementRevision();
if (contacts.isEmpty()) list.showData(); if (contacts.isEmpty()) list.showData();
@@ -240,7 +229,6 @@ public class ContactListFragment extends BaseFragment implements EventListener {
LOG.info("Concurrent update, reloading"); LOG.info("Concurrent update, reloading");
loadContacts(); loadContacts();
} }
}
}); });
} }
@@ -295,9 +283,7 @@ public class ContactListFragment extends BaseFragment implements EventListener {
} }
private void updateItem(final ContactId c, final BaseMessageHeader h) { private void updateItem(final ContactId c, final BaseMessageHeader h) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
adapter.incrementRevision(); adapter.incrementRevision();
int position = adapter.findItemPosition(c); int position = adapter.findItemPosition(c);
ContactListItem item = adapter.getItemAt(position); ContactListItem item = adapter.getItemAt(position);
@@ -306,26 +292,20 @@ public class ContactListFragment extends BaseFragment implements EventListener {
item.addMessage(i); item.addMessage(i);
adapter.updateItemAt(position, item); adapter.updateItemAt(position, item);
} }
}
}); });
} }
private void removeItem(final ContactId c) { private void removeItem(final ContactId c) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
adapter.incrementRevision(); adapter.incrementRevision();
int position = adapter.findItemPosition(c); int position = adapter.findItemPosition(c);
ContactListItem item = adapter.getItemAt(position); ContactListItem item = adapter.getItemAt(position);
if (item != null) adapter.remove(item); if (item != null) adapter.remove(item);
}
}); });
} }
private void setConnected(final ContactId c, final boolean connected) { private void setConnected(final ContactId c, final boolean connected) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
adapter.incrementRevision(); adapter.incrementRevision();
int position = adapter.findItemPosition(c); int position = adapter.findItemPosition(c);
ContactListItem item = adapter.getItemAt(position); ContactListItem item = adapter.getItemAt(position);
@@ -333,7 +313,6 @@ public class ContactListFragment extends BaseFragment implements EventListener {
item.setConnected(connected); item.setConnected(connected);
adapter.notifyItemChanged(position); adapter.notifyItemChanged(position);
} }
}
}); });
} }

View File

@@ -289,9 +289,7 @@ public class ConversationActivity extends BriarActivity
} }
private void loadContactDetailsAndMessages() { private void loadContactDetailsAndMessages() {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
if (contactName == null || contactAuthorId == null) { if (contactName == null || contactAuthorId == null) {
@@ -307,29 +305,22 @@ public class ConversationActivity extends BriarActivity
} catch (NoSuchContactException e) { } catch (NoSuchContactException e) {
finishOnUiThread(); finishOnUiThread();
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
private void displayContactDetails() { private void displayContactDetails() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
//noinspection ConstantConditions //noinspection ConstantConditions
toolbarAvatar.setImageDrawable( toolbarAvatar.setImageDrawable(
new IdenticonDrawable(contactAuthorId.getBytes())); new IdenticonDrawable(contactAuthorId.getBytes()));
toolbarTitle.setText(contactName); toolbarTitle.setText(contactName);
}
}); });
} }
private void displayContactOnlineStatus() { private void displayContactOnlineStatus() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
if (connectionRegistry.isConnected(contactId)) { if (connectionRegistry.isConnected(contactId)) {
toolbarStatus.setImageDrawable(ContextCompat toolbarStatus.setImageDrawable(ContextCompat
.getDrawable(ConversationActivity.this, .getDrawable(ConversationActivity.this,
@@ -343,31 +334,24 @@ public class ConversationActivity extends BriarActivity
toolbarStatus toolbarStatus
.setContentDescription(getString(R.string.offline)); .setContentDescription(getString(R.string.offline));
} }
}
}); });
} }
private void loadMessages() { private void loadMessages() {
final int revision = adapter.getRevision(); final int revision = adapter.getRevision();
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
Collection<PrivateMessageHeader> headers = Collection<PrivateMessageHeader> headers =
messagingManager.getMessageHeaders(contactId); messagingManager.getMessageHeaders(contactId);
Collection<IntroductionMessage> introductions = Collection<IntroductionMessage> introductions =
introductionManager introductionManager.getIntroductionMessages(contactId);
.getIntroductionMessages(contactId);
Collection<InvitationMessage> forumInvitations = Collection<InvitationMessage> forumInvitations =
forumSharingManager forumSharingManager.getInvitationMessages(contactId);
.getInvitationMessages(contactId);
Collection<InvitationMessage> blogInvitations = Collection<InvitationMessage> blogInvitations =
blogSharingManager blogSharingManager.getInvitationMessages(contactId);
.getInvitationMessages(contactId);
Collection<InvitationMessage> groupInvitations = Collection<InvitationMessage> groupInvitations =
groupInvitationManager groupInvitationManager.getInvitationMessages(contactId);
.getInvitationMessages(contactId);
List<InvitationMessage> invitations = new ArrayList<>( List<InvitationMessage> invitations = new ArrayList<>(
forumInvitations.size() + blogInvitations.size() + forumInvitations.size() + blogInvitations.size() +
groupInvitations.size()); groupInvitations.size());
@@ -377,14 +361,11 @@ public class ConversationActivity extends BriarActivity
long duration = System.currentTimeMillis() - now; long duration = System.currentTimeMillis() - now;
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Loading messages took " + duration + " ms"); LOG.info("Loading messages took " + duration + " ms");
displayMessages(revision, headers, introductions, displayMessages(revision, headers, introductions, invitations);
invitations);
} catch (NoSuchContactException e) { } catch (NoSuchContactException e) {
finishOnUiThread(); finishOnUiThread();
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
@@ -393,9 +374,7 @@ public class ConversationActivity extends BriarActivity
final Collection<PrivateMessageHeader> headers, final Collection<PrivateMessageHeader> headers,
final Collection<IntroductionMessage> introductions, final Collection<IntroductionMessage> introductions,
final Collection<InvitationMessage> invitations) { final Collection<InvitationMessage> invitations) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
if (revision == adapter.getRevision()) { if (revision == adapter.getRevision()) {
adapter.incrementRevision(); adapter.incrementRevision();
textInputView.setSendButtonEnabled(true); textInputView.setSendButtonEnabled(true);
@@ -409,7 +388,6 @@ public class ConversationActivity extends BriarActivity
LOG.info("Concurrent update, reloading"); LOG.info("Concurrent update, reloading");
loadMessages(); loadMessages();
} }
}
}); });
} }
@@ -459,9 +437,7 @@ public class ConversationActivity extends BriarActivity
} }
private void loadMessageBody(final MessageId m) { private void loadMessageBody(final MessageId m) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
String body = messagingManager.getMessageBody(m); String body = messagingManager.getMessageBody(m);
@@ -470,17 +446,13 @@ public class ConversationActivity extends BriarActivity
LOG.info("Loading body took " + duration + " ms"); LOG.info("Loading body took " + duration + " ms");
displayMessageBody(m, body); displayMessageBody(m, body);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
private void displayMessageBody(final MessageId m, final String body) { private void displayMessageBody(final MessageId m, final String body) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
bodyCache.put(m, body); bodyCache.put(m, body);
SparseArray<ConversationItem> messages = SparseArray<ConversationItem> messages =
adapter.getPrivateMessages(); adapter.getPrivateMessages();
@@ -493,7 +465,6 @@ public class ConversationActivity extends BriarActivity
return; return;
} }
} }
}
}); });
} }
@@ -573,14 +544,11 @@ public class ConversationActivity extends BriarActivity
} }
private void addConversationItem(final ConversationItem item) { private void addConversationItem(final ConversationItem item) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
adapter.incrementRevision(); adapter.incrementRevision();
adapter.add(item); adapter.add(item);
// Scroll to the bottom // Scroll to the bottom
list.scrollToPosition(adapter.getItemCount() - 1); list.scrollToPosition(adapter.getItemCount() - 1);
}
}); });
} }
@@ -588,24 +556,16 @@ public class ConversationActivity extends BriarActivity
getContactNameTask().addListener(new FutureTaskListener<String>() { getContactNameTask().addListener(new FutureTaskListener<String>() {
@Override @Override
public void onSuccess(final String contactName) { public void onSuccess(final String contactName) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
ConversationItem item = ConversationItem ConversationItem item = ConversationItem
.from(ConversationActivity.this, contactName, .from(ConversationActivity.this, contactName, m);
m);
addConversationItem(item); addConversationItem(item);
}
}); });
} }
@Override @Override
public void onFailure(final Throwable exception) { public void onFailure(final Throwable exception) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(
@Override () -> handleDbException((DbException) exception));
public void run() {
handleDbException((DbException) exception);
}
});
} }
}); });
} }
@@ -614,24 +574,16 @@ public class ConversationActivity extends BriarActivity
getContactNameTask().addListener(new FutureTaskListener<String>() { getContactNameTask().addListener(new FutureTaskListener<String>() {
@Override @Override
public void onSuccess(final String contactName) { public void onSuccess(final String contactName) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
ConversationItem item = ConversationItem ConversationItem item = ConversationItem
.from(ConversationActivity.this, contactName, .from(ConversationActivity.this, contactName, m);
m);
addConversationItem(item); addConversationItem(item);
}
}); });
} }
@Override @Override
public void onFailure(final Throwable exception) { public void onFailure(final Throwable exception) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(
@Override () -> handleDbException((DbException) exception));
public void run() {
handleDbException((DbException) exception);
}
});
} }
}); });
} }
@@ -640,24 +592,16 @@ public class ConversationActivity extends BriarActivity
getContactNameTask().addListener(new FutureTaskListener<String>() { getContactNameTask().addListener(new FutureTaskListener<String>() {
@Override @Override
public void onSuccess(final String contactName) { public void onSuccess(final String contactName) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
ConversationItem item = ConversationItem ConversationItem item = ConversationItem
.from(ConversationActivity.this, contactName, .from(ConversationActivity.this, contactName, m);
m);
addConversationItem(item); addConversationItem(item);
}
}); });
} }
@Override @Override
public void onFailure(final Throwable exception) { public void onFailure(final Throwable exception) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(
@Override () -> handleDbException((DbException) exception));
public void run() {
handleDbException((DbException) exception);
}
});
} }
}); });
} }
@@ -666,33 +610,23 @@ public class ConversationActivity extends BriarActivity
getContactNameTask().addListener(new FutureTaskListener<String>() { getContactNameTask().addListener(new FutureTaskListener<String>() {
@Override @Override
public void onSuccess(final String contactName) { public void onSuccess(final String contactName) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
ConversationItem item = ConversationItem ConversationItem item = ConversationItem
.from(ConversationActivity.this, contactName, .from(ConversationActivity.this, contactName, m);
m);
addConversationItem(item); addConversationItem(item);
}
}); });
} }
@Override @Override
public void onFailure(final Throwable exception) { public void onFailure(final Throwable exception) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(
@Override () -> handleDbException((DbException) exception));
public void run() {
handleDbException((DbException) exception);
}
});
} }
}); });
} }
private void markMessages(final Collection<MessageId> messageIds, private void markMessages(final Collection<MessageId> messageIds,
final boolean sent, final boolean seen) { final boolean sent, final boolean seen) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
adapter.incrementRevision(); adapter.incrementRevision();
Set<MessageId> messages = new HashSet<>(messageIds); Set<MessageId> messages = new HashSet<>(messageIds);
SparseArray<ConversationOutItem> list = SparseArray<ConversationOutItem> list =
@@ -705,7 +639,6 @@ public class ConversationActivity extends BriarActivity
adapter.notifyItemChanged(list.keyAt(i)); adapter.notifyItemChanged(list.keyAt(i));
} }
} }
}
}); });
} }
@@ -727,41 +660,31 @@ public class ConversationActivity extends BriarActivity
} }
private void loadGroupId(final String body, final long timestamp) { private void loadGroupId(final String body, final long timestamp) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
messagingGroupId = messagingGroupId =
messagingManager.getConversationId(contactId); messagingManager.getConversationId(contactId);
createMessage(body, timestamp); createMessage(body, timestamp);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
} }
}
}); });
} }
private void createMessage(final String body, final long timestamp) { private void createMessage(final String body, final long timestamp) {
cryptoExecutor.execute(new Runnable() { cryptoExecutor.execute(() -> {
@Override
public void run() {
try { try {
//noinspection ConstantConditions init in loadGroupId() //noinspection ConstantConditions init in loadGroupId()
storeMessage(privateMessageFactory.createPrivateMessage( storeMessage(privateMessageFactory.createPrivateMessage(
messagingGroupId, timestamp, body), body); messagingGroupId, timestamp, body), body);
} catch (FormatException e) { } catch (FormatException e) {throw new RuntimeException(e);
throw new RuntimeException(e);
}
} }
}); });
} }
private void storeMessage(final PrivateMessage m, final String body) { private void storeMessage(final PrivateMessage m, final String body) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
messagingManager.addLocalMessage(m); messagingManager.addLocalMessage(m);
@@ -777,21 +700,14 @@ public class ConversationActivity extends BriarActivity
bodyCache.put(message.getId(), body); bodyCache.put(message.getId(), body);
addConversationItem(item); addConversationItem(item);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
private void askToRemoveContact() { private void askToRemoveContact() {
DialogInterface.OnClickListener okListener = DialogInterface.OnClickListener okListener =
new DialogInterface.OnClickListener() { (dialog, which) -> removeContact();
@Override
public void onClick(DialogInterface dialog, int which) {
removeContact();
}
};
AlertDialog.Builder builder = AlertDialog.Builder builder =
new AlertDialog.Builder(ConversationActivity.this, new AlertDialog.Builder(ConversationActivity.this,
R.style.BriarDialogTheme); R.style.BriarDialogTheme);
@@ -803,37 +719,28 @@ public class ConversationActivity extends BriarActivity
} }
private void removeContact() { private void removeContact() {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
contactManager.removeContact(contactId); contactManager.removeContact(contactId);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
} finally { } finally {
finishAfterContactRemoved(); finishAfterContactRemoved();
} }
}
}); });
} }
private void finishAfterContactRemoved() { private void finishAfterContactRemoved() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
String deleted = getString(R.string.contact_deleted_toast); String deleted = getString(R.string.contact_deleted_toast);
Toast.makeText(ConversationActivity.this, deleted, LENGTH_SHORT) Toast.makeText(ConversationActivity.this, deleted, LENGTH_SHORT)
.show(); .show();
supportFinishAfterTransition(); supportFinishAfterTransition();
}
}); });
} }
private void enableIntroductionActionIfAvailable(final MenuItem item) { private void enableIntroductionActionIfAvailable(final MenuItem item) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
if (contactManager.getActiveContacts().size() > 1) { if (contactManager.getActiveContacts().size() > 1) {
enableIntroductionAction(item); enableIntroductionAction(item);
@@ -845,26 +752,17 @@ public class ConversationActivity extends BriarActivity
} }
} }
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
private void enableIntroductionAction(final MenuItem item) { private void enableIntroductionAction(final MenuItem item) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> item.setEnabled(true));
@Override
public void run() {
item.setEnabled(true);
}
});
} }
private void showIntroductionOnboarding() { private void showIntroductionOnboarding() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
// find view of overflow icon // find view of overflow icon
View target = null; View target = null;
for (int i = 0; i < toolbar.getChildCount(); i++) { for (int i = 0; i < toolbar.getChildCount(); i++) {
@@ -899,22 +797,17 @@ public class ConversationActivity extends BriarActivity
.setIcon(R.drawable.ic_more_vert_accent) .setIcon(R.drawable.ic_more_vert_accent)
.setOnHidePromptListener(listener) .setOnHidePromptListener(listener)
.show(); .show();
}
}); });
} }
private void introductionOnboardingSeen() { private void introductionOnboardingSeen() {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
Settings settings = new Settings(); Settings settings = new Settings();
settings.putBoolean(SHOW_ONBOARDING_INTRODUCTION, false); settings.putBoolean(SHOW_ONBOARDING_INTRODUCTION, false);
settingsManager.mergeSettings(settings, SETTINGS_NAMESPACE); settingsManager.mergeSettings(settings, SETTINGS_NAMESPACE);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
@@ -925,9 +818,7 @@ public class ConversationActivity extends BriarActivity
} }
private void markMessageRead(final GroupId g, final MessageId m) { private void markMessageRead(final GroupId g, final MessageId m) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
messagingManager.setReadFlag(g, m, true); messagingManager.setReadFlag(g, m, true);
@@ -935,9 +826,7 @@ public class ConversationActivity extends BriarActivity
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Marking read took " + duration + " ms"); LOG.info("Marking read took " + duration + " ms");
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
@@ -951,9 +840,7 @@ public class ConversationActivity extends BriarActivity
if (position != INVALID_POSITION) { if (position != INVALID_POSITION) {
adapter.notifyItemChanged(position, item); adapter.notifyItemChanged(position, item);
} }
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
long timestamp = System.currentTimeMillis(); long timestamp = System.currentTimeMillis();
timestamp = Math.max(timestamp, getMinTimestampForNewMessage()); timestamp = Math.max(timestamp, getMinTimestampForNewMessage());
try { try {
@@ -981,7 +868,6 @@ public class ConversationActivity extends BriarActivity
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING))
LOG.log(WARNING, e.toString(), e); LOG.log(WARNING, e.toString(), e);
} }
}
}); });
} }
@@ -1041,14 +927,10 @@ public class ConversationActivity extends BriarActivity
} }
private void introductionResponseError() { private void introductionResponseError() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() ->
@Override
public void run() {
Toast.makeText(ConversationActivity.this, Toast.makeText(ConversationActivity.this,
R.string.introduction_response_error, R.string.introduction_response_error,
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show());
}
});
} }
private ListenableFutureTask<String> getContactNameTask() { private ListenableFutureTask<String> getContactNameTask() {

View File

@@ -2,7 +2,6 @@ package org.briarproject.briar.android.contact;
import android.support.annotation.UiThread; import android.support.annotation.UiThread;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; import android.widget.Button;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
@@ -35,12 +34,8 @@ class ConversationRequestViewHolder extends ConversationNoticeInViewHolder {
if (item.wasAnswered() && item.canBeOpened()) { if (item.wasAnswered() && item.canBeOpened()) {
acceptButton.setVisibility(VISIBLE); acceptButton.setVisibility(VISIBLE);
acceptButton.setText(R.string.open); acceptButton.setText(R.string.open);
acceptButton.setOnClickListener(new OnClickListener() { acceptButton.setOnClickListener(
@Override v -> listener.openRequestedShareable(item));
public void onClick(View v) {
listener.openRequestedShareable(item);
}
});
declineButton.setVisibility(GONE); declineButton.setVisibility(GONE);
} else if (item.wasAnswered()) { } else if (item.wasAnswered()) {
acceptButton.setVisibility(GONE); acceptButton.setVisibility(GONE);
@@ -48,22 +43,16 @@ class ConversationRequestViewHolder extends ConversationNoticeInViewHolder {
} else { } else {
acceptButton.setVisibility(VISIBLE); acceptButton.setVisibility(VISIBLE);
acceptButton.setText(R.string.accept); acceptButton.setText(R.string.accept);
acceptButton.setOnClickListener(new OnClickListener() { acceptButton.setOnClickListener(v -> {
@Override
public void onClick(View v) {
acceptButton.setEnabled(false); acceptButton.setEnabled(false);
declineButton.setEnabled(false); declineButton.setEnabled(false);
listener.respondToRequest(item, true); listener.respondToRequest(item, true);
}
}); });
declineButton.setVisibility(VISIBLE); declineButton.setVisibility(VISIBLE);
declineButton.setOnClickListener(new OnClickListener() { declineButton.setOnClickListener(v -> {
@Override
public void onClick(View v) {
acceptButton.setEnabled(false); acceptButton.setEnabled(false);
declineButton.setEnabled(false); declineButton.setEnabled(false);
listener.respondToRequest(item, false); listener.respondToRequest(item, false);
}
}); });
} }
} }

View File

@@ -41,12 +41,9 @@ public abstract class ContactSelectorControllerImpl
public void loadContacts(final GroupId g, public void loadContacts(final GroupId g,
final Collection<ContactId> selection, final Collection<ContactId> selection,
final ResultExceptionHandler<Collection<SelectableContactItem>, DbException> handler) { final ResultExceptionHandler<Collection<SelectableContactItem>, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
Collection<SelectableContactItem> contacts = Collection<SelectableContactItem> contacts = new ArrayList<>();
new ArrayList<>();
for (Contact c : contactManager.getActiveContacts()) { for (Contact c : contactManager.getActiveContacts()) {
// was this contact already selected? // was this contact already selected?
boolean selected = selection.contains(c.getId()); boolean selected = selection.contains(c.getId());
@@ -57,11 +54,9 @@ public abstract class ContactSelectorControllerImpl
} }
handler.onResult(contacts); handler.onResult(contacts);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }

View File

@@ -29,9 +29,7 @@ public class DbControllerImpl implements DbController {
@Override @Override
public void runOnDbThread(final Runnable task) { public void runOnDbThread(final Runnable task) {
dbExecutor.execute(new Runnable() { dbExecutor.execute(() -> {
@Override
public void run() {
try { try {
lifecycleManager.waitForDatabase(); lifecycleManager.waitForDatabase();
task.run(); task.run();
@@ -39,7 +37,6 @@ public class DbControllerImpl implements DbController {
LOG.warning("Interrupted while waiting for database"); LOG.warning("Interrupted while waiting for database");
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
}
}); });
} }
} }

View File

@@ -60,14 +60,11 @@ public class SharingControllerImpl implements SharingController, EventListener {
private void setConnected(final ContactId c) { private void setConnected(final ContactId c) {
if (listener == null) return; if (listener == null) return;
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
if (contacts.contains(c)) { if (contacts.contains(c)) {
int online = getOnlineCount(); int online = getOnlineCount();
listener.onSharingInfoUpdated(contacts.size(), online); listener.onSharingInfoUpdated(contacts.size(), online);
} }
}
}); });
} }

View File

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

View File

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

View File

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

View File

@@ -5,14 +5,9 @@ import android.os.Bundle;
import android.support.design.widget.TextInputLayout; import android.support.design.widget.TextInputLayout;
import android.text.Editable; import android.text.Editable;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; import android.widget.Button;
import android.widget.EditText; import android.widget.EditText;
import android.widget.ProgressBar; import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast; import android.widget.Toast;
import org.briarproject.bramble.api.db.DbException; import org.briarproject.bramble.api.db.DbException;
@@ -79,22 +74,13 @@ public class CreateForumActivity extends BriarActivity {
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
} }
}); });
nameEntry.setOnEditorActionListener(new OnEditorActionListener() { nameEntry.setOnEditorActionListener((v, actionId, e) -> {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent e) {
createForum(); createForum();
return true; return true;
}
}); });
createForumButton = (Button) findViewById(R.id.createForumButton); createForumButton = (Button) findViewById(R.id.createForumButton);
createForumButton.setOnClickListener(new OnClickListener() { createForumButton.setOnClickListener(v -> createForum());
@Override
public void onClick(View v) {
createForum();
}
});
progress = (ProgressBar) findViewById(R.id.createForumProgressBar); progress = (ProgressBar) findViewById(R.id.createForumProgressBar);
} }
@@ -135,9 +121,7 @@ public class CreateForumActivity extends BriarActivity {
} }
private void storeForum(final String name) { private void storeForum(final String name) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
Forum f = forumManager.addForum(name); Forum f = forumManager.addForum(name);
@@ -146,18 +130,14 @@ public class CreateForumActivity extends BriarActivity {
LOG.info("Storing forum took " + duration + " ms"); LOG.info("Storing forum took " + duration + " ms");
displayForum(f); displayForum(f);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
finishOnUiThread(); finishOnUiThread();
} }
}
}); });
} }
private void displayForum(final Forum f) { private void displayForum(final Forum f) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
Intent i = new Intent(CreateForumActivity.this, Intent i = new Intent(CreateForumActivity.this,
ForumActivity.class); ForumActivity.class);
i.putExtra(GROUP_ID, f.getId().getBytes()); i.putExtra(GROUP_ID, f.getId().getBytes());
@@ -166,7 +146,6 @@ public class CreateForumActivity extends BriarActivity {
Toast.makeText(CreateForumActivity.this, Toast.makeText(CreateForumActivity.this,
R.string.forum_created_toast, LENGTH_LONG).show(); R.string.forum_created_toast, LENGTH_LONG).show();
supportFinishAfterTransition(); supportFinishAfterTransition();
}
}); });
} }
} }

View File

@@ -1,6 +1,5 @@
package org.briarproject.briar.android.forum; package org.briarproject.briar.android.forum;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnClickListener;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
@@ -11,7 +10,6 @@ import android.support.v7.widget.Toolbar;
import android.view.Menu; import android.view.Menu;
import android.view.MenuInflater; import android.view.MenuInflater;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View;
import android.widget.Toast; import android.widget.Toast;
import org.briarproject.bramble.api.contact.ContactId; import org.briarproject.bramble.api.contact.ContactId;
@@ -69,15 +67,11 @@ public class ForumActivity extends
// Open member list on Toolbar click // Open member list on Toolbar click
if (toolbar != null) { if (toolbar != null) {
toolbar.setOnClickListener( toolbar.setOnClickListener(v -> {
new View.OnClickListener() { Intent i1 = new Intent(ForumActivity.this,
@Override
public void onClick(View v) {
Intent i = new Intent(ForumActivity.this,
ForumSharingStatusActivity.class); ForumSharingStatusActivity.class);
i.putExtra(GROUP_ID, groupId.getBytes()); i1.putExtra(GROUP_ID, groupId.getBytes());
startActivity(i); startActivity(i1);
}
}); });
} }
} }
@@ -147,12 +141,7 @@ public class ForumActivity extends
} }
private void showUnsubscribeDialog() { private void showUnsubscribeDialog() {
OnClickListener okListener = new OnClickListener() { OnClickListener okListener = (dialog, which) -> deleteForum();
@Override
public void onClick(DialogInterface dialog, int which) {
deleteForum();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this, AlertDialog.Builder builder = new AlertDialog.Builder(this,
R.style.BriarDialogTheme); R.style.BriarDialogTheme);
builder.setTitle(getString(R.string.dialog_title_leave_forum)); builder.setTitle(getString(R.string.dialog_title_leave_forum));

View File

@@ -121,9 +121,7 @@ class ForumControllerImpl extends
@Override @Override
public void loadSharingContacts( public void loadSharingContacts(
final ResultExceptionHandler<Collection<ContactId>, DbException> handler) { final ResultExceptionHandler<Collection<ContactId>, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
Collection<Contact> contacts = Collection<Contact> contacts =
forumSharingManager.getSharedWith(getGroupId()); forumSharingManager.getSharedWith(getGroupId());
@@ -132,11 +130,9 @@ class ForumControllerImpl extends
for (Contact c : contacts) contactIds.add(c.getId()); for (Contact c : contacts) contactIds.add(c.getId());
handler.onResult(contactIds); handler.onResult(contactIds);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@@ -144,9 +140,7 @@ class ForumControllerImpl extends
public void createAndStoreMessage(final String body, public void createAndStoreMessage(final String body,
@Nullable final ForumItem parentItem, @Nullable final ForumItem parentItem,
final ResultExceptionHandler<ForumItem, DbException> handler) { final ResultExceptionHandler<ForumItem, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
LocalAuthor author = identityManager.getLocalAuthor(); LocalAuthor author = identityManager.getLocalAuthor();
GroupCount count = forumManager.getGroupCount(getGroupId()); GroupCount count = forumManager.getGroupCount(getGroupId());
@@ -156,26 +150,20 @@ class ForumControllerImpl extends
parentItem.getId() : null; parentItem.getId() : null;
createMessage(body, timestamp, parentId, author, handler); createMessage(body, timestamp, parentId, author, handler);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
private void createMessage(final String body, final long timestamp, private void createMessage(final String body, final long timestamp,
final @Nullable MessageId parentId, final LocalAuthor author, final @Nullable MessageId parentId, final LocalAuthor author,
final ResultExceptionHandler<ForumItem, DbException> handler) { final ResultExceptionHandler<ForumItem, DbException> handler) {
cryptoExecutor.execute(new Runnable() { cryptoExecutor.execute(() -> {
@Override
public void run() {
LOG.info("Creating forum post..."); LOG.info("Creating forum post...");
ForumPost msg = forumManager ForumPost msg = forumManager.createLocalPost(getGroupId(), body,
.createLocalPost(getGroupId(), body, timestamp, timestamp, parentId, author);
parentId, author);
storePost(msg, body, handler); storePost(msg, body, handler);
}
}); });
} }
@@ -197,30 +185,17 @@ class ForumControllerImpl extends
private void onForumPostReceived(ForumPostHeader h, String body) { private void onForumPostReceived(ForumPostHeader h, String body) {
final ForumItem item = buildItem(h, body); final ForumItem item = buildItem(h, body);
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(
@Override () -> listener.onItemReceived(item));
public void run() {
listener.onItemReceived(item);
}
});
} }
private void onForumInvitationAccepted(final ContactId c) { private void onForumInvitationAccepted(final ContactId c) {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(
@Override () -> listener.onInvitationAccepted(c));
public void run() {
listener.onInvitationAccepted(c);
}
});
} }
private void onForumLeft(final ContactId c) { private void onForumLeft(final ContactId c) {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(() -> listener.onForumLeft(c));
@Override
public void run() {
listener.onForumLeft(c);
}
});
} }
} }

View File

@@ -77,15 +77,12 @@ class ForumListAdapter
} }
// Open Forum on Click // Open Forum on Click
ui.layout.setOnClickListener(new View.OnClickListener() { ui.layout.setOnClickListener(v -> {
@Override
public void onClick(View v) {
Intent i = new Intent(ctx, ForumActivity.class); Intent i = new Intent(ctx, ForumActivity.class);
Forum f = item.getForum(); Forum f = item.getForum();
i.putExtra(GROUP_ID, f.getId().getBytes()); i.putExtra(GROUP_ID, f.getId().getBytes());
i.putExtra(GROUP_NAME, f.getName()); i.putExtra(GROUP_NAME, f.getName());
ctx.startActivity(i); ctx.startActivity(i);
}
}); });
} }

View File

@@ -155,9 +155,7 @@ public class ForumListFragment extends BaseEventFragment implements
private void loadForums() { private void loadForums() {
final int revision = adapter.getRevision(); final int revision = adapter.getRevision();
listener.runOnDbThread(new Runnable() { listener.runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
Collection<ForumListItem> forums = new ArrayList<>(); Collection<ForumListItem> forums = new ArrayList<>();
@@ -175,18 +173,14 @@ public class ForumListFragment extends BaseEventFragment implements
LOG.info("Full load took " + duration + " ms"); LOG.info("Full load took " + duration + " ms");
displayForums(revision, forums); displayForums(revision, forums);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
private void displayForums(final int revision, private void displayForums(final int revision,
final Collection<ForumListItem> forums) { final Collection<ForumListItem> forums) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
if (revision == adapter.getRevision()) { if (revision == adapter.getRevision()) {
adapter.incrementRevision(); adapter.incrementRevision();
if (forums.isEmpty()) list.showData(); if (forums.isEmpty()) list.showData();
@@ -195,34 +189,26 @@ public class ForumListFragment extends BaseEventFragment implements
LOG.info("Concurrent update, reloading"); LOG.info("Concurrent update, reloading");
loadForums(); loadForums();
} }
}
}); });
} }
private void loadAvailableForums() { private void loadAvailableForums() {
listener.runOnDbThread(new Runnable() { listener.runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
int available = int available = forumSharingManager.getInvitations().size();
forumSharingManager.getInvitations().size();
long duration = System.currentTimeMillis() - now; long duration = System.currentTimeMillis() - now;
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Loading available took " + duration + " ms"); LOG.info("Loading available took " + duration + " ms");
displayAvailableForums(available); displayAvailableForums(available);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
private void displayAvailableForums(final int availableCount) { private void displayAvailableForums(final int availableCount) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
if (availableCount == 0) { if (availableCount == 0) {
snackbar.dismiss(); snackbar.dismiss();
} else { } else {
@@ -231,7 +217,6 @@ public class ForumListFragment extends BaseEventFragment implements
availableCount)); availableCount));
if (!snackbar.isShownOrQueued()) snackbar.show(); if (!snackbar.isShownOrQueued()) snackbar.show();
} }
}
}); });
} }
@@ -263,9 +248,7 @@ public class ForumListFragment extends BaseEventFragment implements
} }
private void updateItem(final GroupId g, final ForumPostHeader m) { private void updateItem(final GroupId g, final ForumPostHeader m) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
adapter.incrementRevision(); adapter.incrementRevision();
int position = adapter.findItemPosition(g); int position = adapter.findItemPosition(g);
ForumListItem item = adapter.getItemAt(position); ForumListItem item = adapter.getItemAt(position);
@@ -273,19 +256,15 @@ public class ForumListFragment extends BaseEventFragment implements
item.addHeader(m); item.addHeader(m);
adapter.updateItemAt(position, item); adapter.updateItemAt(position, item);
} }
}
}); });
} }
private void removeForum(final GroupId g) { private void removeForum(final GroupId g) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
adapter.incrementRevision(); adapter.incrementRevision();
int position = adapter.findItemPosition(g); int position = adapter.findItemPosition(g);
ForumListItem item = adapter.getItemAt(position); ForumListItem item = adapter.getItemAt(position);
if (item != null) adapter.remove(item); if (item != null) adapter.remove(item);
}
}); });
} }

View File

@@ -82,15 +82,12 @@ public abstract class BaseFragment extends Fragment
public void runOnUiThreadUnlessDestroyed(final Runnable r) { public void runOnUiThreadUnlessDestroyed(final Runnable r) {
final Activity activity = getActivity(); final Activity activity = getActivity();
if (activity != null) { if (activity != null) {
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(() -> {
@Override
public void run() {
// Note that we don't have to check if the activity has // Note that we don't have to check if the activity has
// been destroyed as the Fragment has not been detached yet // been destroyed as the Fragment has not been detached yet
if (!isDetached() && !activity.isFinishing()) { if (!isDetached() && !activity.isFinishing()) {
r.run(); r.run();
} }
}
}); });
} }
} }

View File

@@ -1,7 +1,6 @@
package org.briarproject.briar.android.fragment; package org.briarproject.briar.android.fragment;
import android.app.Dialog; import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.app.DialogFragment; import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
@@ -35,12 +34,7 @@ public class ScreenFilterDialogFragment extends DialogFragment {
builder.setMessage(getString(R.string.screen_filter_body, builder.setMessage(getString(R.string.screen_filter_body,
TextUtils.join("\n", apps))); TextUtils.join("\n", apps)));
builder.setNeutralButton(R.string.continue_button, builder.setNeutralButton(R.string.continue_button,
new DialogInterface.OnClickListener() { (dialog, which) -> dialog.dismiss());
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create(); return builder.create();
} }
} }

View File

@@ -71,13 +71,10 @@ public class ContactChooserFragment extends BaseFragment {
View contentView = inflater.inflate(R.layout.list, container, false); View contentView = inflater.inflate(R.layout.list, container, false);
OnContactClickListener<ContactListItem> onContactClickListener = OnContactClickListener<ContactListItem> onContactClickListener =
new OnContactClickListener<ContactListItem>() { (view, item) -> {
@Override
public void onItemClick(View view, ContactListItem item) {
if (c1 == null) throw new IllegalStateException(); if (c1 == null) throw new IllegalStateException();
Contact c2 = item.getContact(); Contact c2 = item.getContact();
showMessageScreen(c1, c2); showMessageScreen(c1, c2);
}
}; };
adapter = new ContactListAdapter(getActivity(), onContactClickListener); adapter = new ContactListAdapter(getActivity(), onContactClickListener);
@@ -115,9 +112,7 @@ public class ContactChooserFragment extends BaseFragment {
} }
private void loadContacts() { private void loadContacts() {
listener.runOnDbThread(new Runnable() { listener.runOnDbThread(() -> {
@Override
public void run() {
try { try {
List<ContactListItem> contacts = new ArrayList<>(); List<ContactListItem> contacts = new ArrayList<>();
for (Contact c : contactManager.getActiveContacts()) { for (Contact c : contactManager.getActiveContacts()) {
@@ -129,26 +124,20 @@ public class ContactChooserFragment extends BaseFragment {
conversationManager.getGroupCount(id); conversationManager.getGroupCount(id);
boolean connected = boolean connected =
connectionRegistry.isConnected(c.getId()); connectionRegistry.isConnected(c.getId());
contacts.add(new ContactListItem(c, connected, contacts.add(new ContactListItem(c, connected, count));
count));
} }
} }
displayContacts(contacts); displayContacts(contacts);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
private void displayContacts(final List<ContactListItem> contacts) { private void displayContacts(final List<ContactListItem> contacts) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
if (contacts.isEmpty()) list.showData(); if (contacts.isEmpty()) list.showData();
else adapter.addAll(contacts); else adapter.addAll(contacts);
}
}); });
} }

View File

@@ -120,9 +120,7 @@ public class IntroductionMessageFragment extends BaseFragment
private void prepareToSetUpViews(final int contactId1, private void prepareToSetUpViews(final int contactId1,
final int contactId2) { final int contactId2) {
introductionActivity.runOnDbThread(new Runnable() { introductionActivity.runOnDbThread(() -> {
@Override
public void run() {
try { try {
Contact c1 = contactManager.getContact( Contact c1 = contactManager.getContact(
new ContactId(contactId1)); new ContactId(contactId1));
@@ -130,17 +128,13 @@ public class IntroductionMessageFragment extends BaseFragment
new ContactId(contactId2)); new ContactId(contactId2));
setUpViews(c1, c2); setUpViews(c1, c2);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
private void setUpViews(final Contact c1, final Contact c2) { private void setUpViews(final Contact c1, final Contact c2) {
introductionActivity.runOnUiThreadUnlessDestroyed(new Runnable() { introductionActivity.runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
contact1 = c1; contact1 = c1;
contact2 = c2; contact2 = c2;
@@ -161,7 +155,6 @@ public class IntroductionMessageFragment extends BaseFragment
ui.progressBar.setVisibility(GONE); ui.progressBar.setVisibility(GONE);
ui.message.setSendButtonEnabled(true); ui.message.setSendButtonEnabled(true);
ui.message.showSoftKeyboard(); ui.message.showSoftKeyboard();
}
}); });
} }
@@ -194,31 +187,22 @@ public class IntroductionMessageFragment extends BaseFragment
private void makeIntroduction(final Contact c1, final Contact c2, private void makeIntroduction(final Contact c1, final Contact c2,
final String msg) { final String msg) {
introductionActivity.runOnDbThread(new Runnable() { introductionActivity.runOnDbThread(() -> {
@Override
public void run() {
// actually make the introduction // actually make the introduction
try { try {
long timestamp = System.currentTimeMillis(); long timestamp = System.currentTimeMillis();
introductionManager.makeIntroduction(c1, c2, msg, introductionManager.makeIntroduction(c1, c2, msg, timestamp);
timestamp);
} catch (DbException | FormatException e) { } catch (DbException | FormatException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
introductionError(); introductionError();
} }
}
}); });
} }
private void introductionError() { private void introductionError() {
introductionActivity.runOnUiThreadUnlessDestroyed(new Runnable() { introductionActivity.runOnUiThreadUnlessDestroyed(
@Override () -> Toast.makeText(introductionActivity,
public void run() { R.string.introduction_error, LENGTH_SHORT).show());
Toast.makeText(introductionActivity,
R.string.introduction_error, LENGTH_SHORT).show();
}
});
} }
private static class ViewHolder { private static class ViewHolder {

View File

@@ -353,15 +353,11 @@ public class CameraView extends SurfaceView implements SurfaceHolder.Callback,
@Override @Override
public void surfaceCreated(final SurfaceHolder holder) { public void surfaceCreated(final SurfaceHolder holder) {
post(new Runnable() { post(() -> {
@Override
public void run() {
try { try {
surfaceCreatedUi(holder); surfaceCreatedUi(holder);
} catch (CameraException e) { } catch (CameraException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
@@ -381,15 +377,11 @@ public class CameraView extends SurfaceView implements SurfaceHolder.Callback,
@Override @Override
public void surfaceChanged(final SurfaceHolder holder, int format, public void surfaceChanged(final SurfaceHolder holder, int format,
final int w, final int h) { final int w, final int h) {
post(new Runnable() { post(() -> {
@Override
public void run() {
try { try {
surfaceChangedUi(holder, w, h); surfaceChangedUi(holder, w, h);
} catch (CameraException e) { } catch (CameraException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
@@ -420,12 +412,7 @@ public class CameraView extends SurfaceView implements SurfaceHolder.Callback,
@Override @Override
public void surfaceDestroyed(final SurfaceHolder holder) { public void surfaceDestroyed(final SurfaceHolder holder) {
post(new Runnable() { post(() -> surfaceDestroyedUi(holder));
@Override
public void run() {
surfaceDestroyedUi(holder);
}
});
} }
@UiThread @UiThread
@@ -442,12 +429,7 @@ public class CameraView extends SurfaceView implements SurfaceHolder.Callback,
@Override @Override
public void onAutoFocus(boolean success, final Camera camera) { public void onAutoFocus(boolean success, final Camera camera) {
LOG.info("Auto focus succeeded: " + success); LOG.info("Auto focus succeeded: " + success);
postDelayed(new Runnable() { postDelayed(this::retryAutoFocus, AUTO_FOCUS_RETRY_DELAY);
@Override
public void run() {
retryAutoFocus();
}
}, AUTO_FOCUS_RETRY_DELAY);
} }
@UiThread @UiThread

View File

@@ -4,7 +4,6 @@ import android.content.Context;
import android.os.Bundle; import android.os.Bundle;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.ScrollView; import android.widget.ScrollView;
@@ -66,24 +65,14 @@ public class IntroFragment extends BaseFragment {
false); false);
scrollView = (ScrollView) v.findViewById(R.id.scrollView); scrollView = (ScrollView) v.findViewById(R.id.scrollView);
View button = v.findViewById(R.id.continueButton); View button = v.findViewById(R.id.continueButton);
button.setOnClickListener(new OnClickListener() { button.setOnClickListener(view -> screenSeenListener.showNextScreen());
@Override
public void onClick(View view) {
screenSeenListener.showNextScreen();
}
});
return v; return v;
} }
@Override @Override
public void onStart() { public void onStart() {
super.onStart(); super.onStart();
scrollView.post(new Runnable() { scrollView.post(() -> scrollView.fullScroll(FOCUS_DOWN));
@Override
public void run() {
scrollView.fullScroll(FOCUS_DOWN);
}
});
} }
} }

View File

@@ -1,6 +1,5 @@
package org.briarproject.briar.android.keyagreement; package org.briarproject.briar.android.keyagreement;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnClickListener;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.UiThread; import android.support.annotation.UiThread;
@@ -144,12 +143,8 @@ public class KeyAgreementActivity extends BriarActivity implements
// Should we show an explanation? // Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this, if (ActivityCompat.shouldShowRequestPermissionRationale(this,
CAMERA)) { CAMERA)) {
OnClickListener continueListener = new OnClickListener() { OnClickListener continueListener =
@Override (dialog, which) -> requestPermission();
public void onClick(DialogInterface dialog, int which) {
requestPermission();
}
};
Builder builder = new Builder(this, style.BriarDialogTheme); Builder builder = new Builder(this, style.BriarDialogTheme);
builder.setTitle(string.permission_camera_title); builder.setTitle(string.permission_camera_title);
builder.setMessage(string.permission_camera_request_body); builder.setMessage(string.permission_camera_request_body);
@@ -183,12 +178,8 @@ public class KeyAgreementActivity extends BriarActivity implements
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
CAMERA)) { CAMERA)) {
// The user has permanently denied the request // The user has permanently denied the request
OnClickListener cancelListener = new OnClickListener() { OnClickListener cancelListener =
@Override (dialog, which) -> supportFinishAfterTransition();
public void onClick(DialogInterface dialog, int which) {
supportFinishAfterTransition();
}
};
Builder builder = new Builder(this, style.BriarDialogTheme); Builder builder = new Builder(this, style.BriarDialogTheme);
builder.setTitle(string.permission_camera_title); builder.setTitle(string.permission_camera_title);
builder.setMessage(string.permission_camera_denied_body); builder.setMessage(string.permission_camera_denied_body);
@@ -214,25 +205,17 @@ public class KeyAgreementActivity extends BriarActivity implements
} }
private void keyAgreementFinished(final KeyAgreementResult result) { private void keyAgreementFinished(final KeyAgreementResult result) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> startContactExchange(result));
@Override
public void run() {
startContactExchange(result);
}
});
} }
private void startContactExchange(final KeyAgreementResult result) { private void startContactExchange(final KeyAgreementResult result) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
LocalAuthor localAuthor; LocalAuthor localAuthor;
// Load the local pseudonym // Load the local pseudonym
try { try {
localAuthor = identityManager.getLocalAuthor(); localAuthor = identityManager.getLocalAuthor();
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
contactExchangeFailed(); contactExchangeFailed();
return; return;
} }
@@ -242,49 +225,37 @@ public class KeyAgreementActivity extends BriarActivity implements
localAuthor, result.getMasterKey(), localAuthor, result.getMasterKey(),
result.getConnection(), result.getTransportId(), result.getConnection(), result.getTransportId(),
result.wasAlice()); result.wasAlice());
}
}); });
} }
@Override @Override
public void contactExchangeSucceeded(final Author remoteAuthor) { public void contactExchangeSucceeded(final Author remoteAuthor) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
String contactName = remoteAuthor.getName(); String contactName = remoteAuthor.getName();
String format = getString(R.string.contact_added_toast); String format = getString(string.contact_added_toast);
String text = String.format(format, contactName); String text = String.format(format, contactName);
Toast.makeText(KeyAgreementActivity.this, text, LENGTH_LONG) Toast.makeText(KeyAgreementActivity.this, text, LENGTH_LONG).show();
.show();
supportFinishAfterTransition(); supportFinishAfterTransition();
}
}); });
} }
@Override @Override
public void duplicateContact(final Author remoteAuthor) { public void duplicateContact(final Author remoteAuthor) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
String contactName = remoteAuthor.getName(); String contactName = remoteAuthor.getName();
String format = getString(R.string.contact_already_exists); String format = getString(string.contact_already_exists);
String text = String.format(format, contactName); String text = String.format(format, contactName);
Toast.makeText(KeyAgreementActivity.this, text, LENGTH_LONG) Toast.makeText(KeyAgreementActivity.this, text, LENGTH_LONG).show();
.show();
finish(); finish();
}
}); });
} }
@Override @Override
public void contactExchangeFailed() { public void contactExchangeFailed() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
Toast.makeText(KeyAgreementActivity.this, Toast.makeText(KeyAgreementActivity.this,
R.string.contact_exchange_failed, LENGTH_LONG).show(); string.contact_exchange_failed, LENGTH_LONG).show();
finish(); finish();
}
}); });
} }
} }

View File

@@ -192,23 +192,17 @@ public class ShowQrCodeFragment extends BaseEventFragment
final KeyAgreementTask oldTask = task; final KeyAgreementTask oldTask = task;
final KeyAgreementTask newTask = keyAgreementTaskFactory.createTask(); final KeyAgreementTask newTask = keyAgreementTaskFactory.createTask();
task = newTask; task = newTask;
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
if (oldTask != null) oldTask.stopListening(); if (oldTask != null) oldTask.stopListening();
newTask.listen(); newTask.listen();
}
}); });
} }
@UiThread @UiThread
private void stopListening() { private void stopListening() {
final KeyAgreementTask oldTask = task; final KeyAgreementTask oldTask = task;
ioExecutor.execute(new Runnable() { ioExecutor.execute(() -> {
@Override
public void run() {
if (oldTask != null) oldTask.stopListening(); if (oldTask != null) oldTask.stopListening();
}
}); });
} }
@@ -255,13 +249,9 @@ public class ShowQrCodeFragment extends BaseEventFragment
KeyAgreementAbortedEvent event = (KeyAgreementAbortedEvent) e; KeyAgreementAbortedEvent event = (KeyAgreementAbortedEvent) e;
keyAgreementAborted(event.didRemoteAbort()); keyAgreementAborted(event.didRemoteAbort());
} else if (e instanceof KeyAgreementFinishedEvent) { } else if (e instanceof KeyAgreementFinishedEvent) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
mainProgressContainer.setVisibility(VISIBLE); mainProgressContainer.setVisibility(VISIBLE);
mainProgressTitle.setText( mainProgressTitle.setText(R.string.exchanging_contact_details);
R.string.exchanging_contact_details);
}
}); });
} }
} }
@@ -297,49 +287,32 @@ public class ShowQrCodeFragment extends BaseEventFragment
} }
private void setQrCode(final Payload localPayload) { private void setQrCode(final Payload localPayload) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> generateBitmapQR(localPayload));
@Override
public void run() {
generateBitmapQR(localPayload);
}
});
} }
private void keyAgreementFailed() { private void keyAgreementFailed() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
reset(); reset();
// TODO show failure somewhere persistent? // TODO show failure somewhere persistent?
Toast.makeText(getActivity(), R.string.connection_failed, Toast.makeText(getActivity(), R.string.connection_failed,
LENGTH_LONG).show(); LENGTH_LONG).show();
}
}); });
} }
private void keyAgreementWaiting() { private void keyAgreementWaiting() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(
@Override () -> status.setText(R.string.waiting_for_contact_to_scan));
public void run() {
status.setText(R.string.waiting_for_contact_to_scan);
}
});
} }
private void keyAgreementStarted() { private void keyAgreementStarted() {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
mainProgressContainer.setVisibility(VISIBLE); mainProgressContainer.setVisibility(VISIBLE);
mainProgressTitle.setText(R.string.authenticating_with_device); mainProgressTitle.setText(R.string.authenticating_with_device);
}
}); });
} }
private void keyAgreementAborted(final boolean remoteAborted) { private void keyAgreementAborted(final boolean remoteAborted) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
reset(); reset();
mainProgressContainer.setVisibility(INVISIBLE); mainProgressContainer.setVisibility(INVISIBLE);
mainProgressTitle.setText(""); mainProgressTitle.setText("");
@@ -348,15 +321,12 @@ public class ShowQrCodeFragment extends BaseEventFragment
remoteAborted ? R.string.connection_aborted_remote : remoteAborted ? R.string.connection_aborted_remote :
R.string.connection_aborted_local, LENGTH_LONG) R.string.connection_aborted_local, LENGTH_LONG)
.show(); .show();
}
}); });
} }
@Override @Override
public void handleResult(final Result result) { public void handleResult(final Result result) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
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
if (!gotLocalPayload) { if (!gotLocalPayload) {
@@ -366,7 +336,6 @@ public class ShowQrCodeFragment extends BaseEventFragment
gotRemotePayload = true; gotRemotePayload = true;
qrCodeScanned(result.getText()); qrCodeScanned(result.getText());
} }
}
}); });
} }

View File

@@ -1,6 +1,5 @@
package org.briarproject.briar.android.login; package org.briarproject.briar.android.login;
import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
@@ -8,13 +7,10 @@ import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.text.Editable; import android.text.Editable;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View; import android.view.View;
import android.widget.Button; import android.widget.Button;
import android.widget.EditText; import android.widget.EditText;
import android.widget.ProgressBar; import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import org.briarproject.briar.R; import org.briarproject.briar.R;
import org.briarproject.briar.android.activity.ActivityComponent; import org.briarproject.briar.android.activity.ActivityComponent;
@@ -61,13 +57,9 @@ public class PasswordActivity extends BaseActivity {
progress = (ProgressBar) findViewById(R.id.progress_wheel); progress = (ProgressBar) findViewById(R.id.progress_wheel);
input = (TextInputLayout) findViewById(R.id.password_layout); input = (TextInputLayout) findViewById(R.id.password_layout);
password = (EditText) findViewById(R.id.edit_password); password = (EditText) findViewById(R.id.edit_password);
password.setOnEditorActionListener(new OnEditorActionListener() { password.setOnEditorActionListener((v, actionId, event) -> {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
validatePassword(); validatePassword();
return true; return true;
}
}); });
password.addTextChangedListener(new TextWatcher() { password.addTextChangedListener(new TextWatcher() {
@@ -131,12 +123,7 @@ public class PasswordActivity extends BaseActivity {
builder.setMessage(R.string.dialog_message_lost_password); builder.setMessage(R.string.dialog_message_lost_password);
builder.setPositiveButton(R.string.cancel, null); builder.setPositiveButton(R.string.cancel, null);
builder.setNegativeButton(R.string.delete, builder.setNegativeButton(R.string.delete,
new DialogInterface.OnClickListener() { (dialog, which) -> deleteAccount());
@Override
public void onClick(DialogInterface dialog, int which) {
deleteAccount();
}
});
AlertDialog dialog = builder.create(); AlertDialog dialog = builder.create();
dialog.show(); dialog.show();
} }

View File

@@ -50,9 +50,7 @@ public class PasswordControllerImpl extends ConfigControllerImpl
public void validatePassword(final String password, public void validatePassword(final String password,
final ResultHandler<Boolean> resultHandler) { final ResultHandler<Boolean> resultHandler) {
final byte[] encrypted = getEncryptedKey(); final byte[] encrypted = getEncryptedKey();
cryptoExecutor.execute(new Runnable() { cryptoExecutor.execute(() -> {
@Override
public void run() {
byte[] key = crypto.decryptWithPassword(encrypted, password); byte[] key = crypto.decryptWithPassword(encrypted, password);
if (key == null) { if (key == null) {
resultHandler.onResult(false); resultHandler.onResult(false);
@@ -60,7 +58,6 @@ public class PasswordControllerImpl extends ConfigControllerImpl
databaseConfig.setEncryptionKey(new SecretKey(key)); databaseConfig.setEncryptionKey(new SecretKey(key));
resultHandler.onResult(true); resultHandler.onResult(true);
} }
}
}); });
} }
@@ -68,9 +65,7 @@ public class PasswordControllerImpl extends ConfigControllerImpl
public void changePassword(final String password, final String newPassword, public void changePassword(final String password, final String newPassword,
final ResultHandler<Boolean> resultHandler) { final ResultHandler<Boolean> resultHandler) {
final byte[] encrypted = getEncryptedKey(); final byte[] encrypted = getEncryptedKey();
cryptoExecutor.execute(new Runnable() { cryptoExecutor.execute(() -> {
@Override
public void run() {
byte[] key = crypto.decryptWithPassword(encrypted, password); byte[] key = crypto.decryptWithPassword(encrypted, password);
if (key == null) { if (key == null) {
resultHandler.onResult(false); resultHandler.onResult(false);
@@ -80,7 +75,6 @@ public class PasswordControllerImpl extends ConfigControllerImpl
storeEncryptedDatabaseKey(hex); storeEncryptedDatabaseKey(hex);
resultHandler.onResult(true); resultHandler.onResult(true);
} }
}
}); });
} }

View File

@@ -86,16 +86,13 @@ public class SetupControllerImpl extends PasswordControllerImpl
public void createAccount(final ResultHandler<Void> resultHandler) { public void createAccount(final ResultHandler<Void> resultHandler) {
if (authorName == null || password == null) if (authorName == null || password == null)
throw new IllegalStateException(); throw new IllegalStateException();
cryptoExecutor.execute(new Runnable() { cryptoExecutor.execute(() -> {
@Override
public void run() {
databaseConfig.setLocalAuthorName(authorName); databaseConfig.setLocalAuthorName(authorName);
SecretKey key = crypto.generateSecretKey(); SecretKey key = crypto.generateSecretKey();
databaseConfig.setEncryptionKey(key); databaseConfig.setEncryptionKey(key);
String hex = encryptDatabaseKey(key, password); String hex = encryptDatabaseKey(key, password);
storeEncryptedDatabaseKey(hex); storeEncryptedDatabaseKey(hex);
resultHandler.onResult(null); resultHandler.onResult(null);
}
}); });
} }

View File

@@ -307,12 +307,9 @@ public class NavDrawerActivity extends BriarActivity implements
daysUntilExpiry, daysUntilExpiry)); daysUntilExpiry, daysUntilExpiry));
} }
expiryWarningClose.setOnClickListener(new View.OnClickListener() { expiryWarningClose.setOnClickListener(v -> {
@Override
public void onClick(View v) {
controller.expiryWarningDismissed(); controller.expiryWarningDismissed();
expiryWarning.setVisibility(GONE); expiryWarning.setVisibility(GONE);
}
}); });
expiryWarning.setVisibility(VISIBLE); expiryWarning.setVisibility(VISIBLE);
@@ -411,9 +408,7 @@ public class NavDrawerActivity extends BriarActivity implements
} }
private void setTransport(final TransportId id, final boolean enabled) { private void setTransport(final TransportId id, final boolean enabled) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
if (transports == null || transportsAdapter == null) return; if (transports == null || transportsAdapter == null) return;
for (Transport t : transports) { for (Transport t : transports) {
if (t.id.equals(id)) { if (t.id.equals(id)) {
@@ -422,7 +417,6 @@ public class NavDrawerActivity extends BriarActivity implements
break; break;
} }
} }
}
}); });
} }

View File

@@ -98,19 +98,13 @@ public class NavDrawerControllerImpl extends DbControllerImpl
private void transportStateUpdate(final TransportId id, private void transportStateUpdate(final TransportId id,
final boolean enabled) { final boolean enabled) {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(
@Override () -> listener.stateUpdate(id, enabled));
public void run() {
listener.stateUpdate(id, enabled);
}
});
} }
@Override @Override
public void showExpiryWarning(final ResultHandler<ExpiryWarning> handler) { public void showExpiryWarning(final ResultHandler<ExpiryWarning> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
Settings settings = Settings settings =
settingsManager.getSettings(SETTINGS_NAMESPACE); settingsManager.getSettings(SETTINGS_NAMESPACE);
@@ -141,18 +135,14 @@ public class NavDrawerControllerImpl extends DbControllerImpl
} }
} }
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
@Override @Override
public void expiryWarningDismissed() { public void expiryWarningDismissed() {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
Settings settings = new Settings(); Settings settings = new Settings();
int date = (int) (System.currentTimeMillis() / 1000L); int date = (int) (System.currentTimeMillis() / 1000L);
@@ -160,9 +150,7 @@ public class NavDrawerControllerImpl extends DbControllerImpl
settings.putBoolean(EXPIRY_SHOW_UPDATE, false); settings.putBoolean(EXPIRY_SHOW_UPDATE, false);
settingsManager.mergeSettings(settings, SETTINGS_NAMESPACE); settingsManager.mergeSettings(settings, SETTINGS_NAMESPACE);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }

View File

@@ -12,7 +12,6 @@ import android.os.Bundle;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.support.v7.preference.CheckBoxPreference; import android.support.v7.preference.CheckBoxPreference;
import android.support.v7.preference.ListPreference; import android.support.v7.preference.ListPreference;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat; import android.support.v7.preference.PreferenceFragmentCompat;
import android.text.TextUtils; import android.text.TextUtils;
@@ -92,14 +91,9 @@ public class PanicPreferencesFragment extends PreferenceFragmentCompat
entryValues.toArray(new CharSequence[entryValues.size()])); entryValues.toArray(new CharSequence[entryValues.size()]));
panicAppPref.setDefaultValue(Panic.PACKAGE_NAME_NONE); panicAppPref.setDefaultValue(Panic.PACKAGE_NAME_NONE);
panicAppPref.setOnPreferenceChangeListener( panicAppPref.setOnPreferenceChangeListener((preference, newValue) -> {
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
String packageName = (String) newValue; String packageName = (String) newValue;
PanicResponder.setTriggerPackageName(getActivity(), PanicResponder.setTriggerPackageName(getActivity(), packageName);
packageName);
showPanicApp(packageName); showPanicApp(packageName);
if (packageName.equals(Panic.PACKAGE_NAME_NONE)) { if (packageName.equals(Panic.PACKAGE_NAME_NONE)) {
@@ -116,26 +110,19 @@ public class PanicPreferencesFragment extends PreferenceFragmentCompat
} }
return true; return true;
}
}); });
if (entries.size() <= 1) { if (entries.size() <= 1) {
panicAppPref.setOnPreferenceClickListener( panicAppPref.setOnPreferenceClickListener(preference -> {
new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(
Preference preference) {
Intent intent = new Intent(Intent.ACTION_VIEW); Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse( intent.setData(Uri.parse(
"market://details?id=info.guardianproject.ripple")); "market://details?id=info.guardianproject.ripple"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (intent.resolveActivity( if (intent.resolveActivity(getActivity().getPackageManager())
getActivity().getPackageManager()) != != null) {
null) {
startActivity(intent); startActivity(intent);
} }
return true; return true;
}
}); });
} }
} }
@@ -219,25 +206,14 @@ public class PanicPreferencesFragment extends PreferenceFragmentCompat
} }
private void showOptInDialog() { private void showOptInDialog() {
DialogInterface.OnClickListener okListener = DialogInterface.OnClickListener okListener = (dialog, which) -> {
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
PanicResponder.setTriggerPackageName(getActivity()); PanicResponder.setTriggerPackageName(getActivity());
showPanicApp(PanicResponder showPanicApp(PanicResponder.getTriggerPackageName(getActivity()));
.getTriggerPackageName(getActivity()));
getActivity().setResult(Activity.RESULT_OK); getActivity().setResult(Activity.RESULT_OK);
}
}; };
DialogInterface.OnClickListener cancelListener = DialogInterface.OnClickListener cancelListener = (dialog, which) -> {
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
getActivity().setResult(Activity.RESULT_CANCELED); getActivity().setResult(Activity.RESULT_CANCELED);
getActivity().finish(); getActivity().finish();
}
}; };
AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), AlertDialog.Builder builder = new AlertDialog.Builder(getContext(),

View File

@@ -93,9 +93,7 @@ public class PanicResponderActivity extends BriarActivity {
} }
private void deleteAllData() { private void deleteAllData() {
androidExecutor.runOnBackgroundThread(new Runnable() { androidExecutor.runOnBackgroundThread(() -> {
@Override
public void run() {
configController.deleteAccount(PanicResponderActivity.this); configController.deleteAccount(PanicResponderActivity.this);
// TODO somehow delete/shred the database more thoroughly // TODO somehow delete/shred the database more thoroughly
PanicResponder.deleteAllAppData(PanicResponderActivity.this); PanicResponder.deleteAllAppData(PanicResponderActivity.this);
@@ -104,7 +102,6 @@ public class PanicResponderActivity extends BriarActivity {
// so still sign out // so still sign out
LOG.info("Signing out..."); LOG.info("Signing out...");
signOut(true); signOut(true);
}
}); });
} }
} }

View File

@@ -11,7 +11,6 @@ import android.support.v7.widget.Toolbar;
import android.view.Menu; import android.view.Menu;
import android.view.MenuInflater; import android.view.MenuInflater;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View;
import org.briarproject.bramble.api.contact.ContactId; import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.db.DbException; import org.briarproject.bramble.api.db.DbException;
@@ -76,15 +75,11 @@ public class GroupActivity extends
// Open member list on Toolbar click // Open member list on Toolbar click
if (toolbar != null) { if (toolbar != null) {
toolbar.setOnClickListener( toolbar.setOnClickListener(v -> {
new View.OnClickListener() { Intent i1 = new Intent(GroupActivity.this,
@Override
public void onClick(View v) {
Intent i = new Intent(GroupActivity.this,
GroupMemberListActivity.class); GroupMemberListActivity.class);
i.putExtra(GROUP_ID, groupId.getBytes()); i1.putExtra(GROUP_ID, groupId.getBytes());
startActivity(i); startActivity(i1);
}
}); });
} }

View File

@@ -85,24 +85,16 @@ class GroupControllerImpl extends
LOG.info("Group message received, adding..."); LOG.info("Group message received, adding...");
final GroupMessageItem item = final GroupMessageItem item =
buildItem(g.getHeader(), g.getBody()); buildItem(g.getHeader(), g.getBody());
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(
@Override () -> listener.onItemReceived(item));
public void run() {
listener.onItemReceived(item);
}
});
} }
} else if (e instanceof ContactRelationshipRevealedEvent) { } else if (e instanceof ContactRelationshipRevealedEvent) {
final ContactRelationshipRevealedEvent c = final ContactRelationshipRevealedEvent c =
(ContactRelationshipRevealedEvent) e; (ContactRelationshipRevealedEvent) e;
if (getGroupId().equals(c.getGroupId())) { if (getGroupId().equals(c.getGroupId())) {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(() ->
@Override
public void run() {
listener.onContactRelationshipRevealed(c.getMemberId(), listener.onContactRelationshipRevealed(c.getMemberId(),
c.getContactId(), c.getVisibility()); c.getContactId(), c.getVisibility()));
}
});
} }
} else if (e instanceof GroupInvitationResponseReceivedEvent) { } else if (e instanceof GroupInvitationResponseReceivedEvent) {
GroupInvitationResponseReceivedEvent g = GroupInvitationResponseReceivedEvent g =
@@ -110,22 +102,14 @@ class GroupControllerImpl extends
final GroupInvitationResponse r = final GroupInvitationResponse r =
(GroupInvitationResponse) g.getResponse(); (GroupInvitationResponse) g.getResponse();
if (getGroupId().equals(r.getShareableId()) && r.wasAccepted()) { if (getGroupId().equals(r.getShareableId()) && r.wasAccepted()) {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(
@Override () -> listener.onInvitationAccepted(r.getContactId()));
public void run() {
listener.onInvitationAccepted(r.getContactId());
}
});
} }
} else if (e instanceof GroupDissolvedEvent) { } else if (e instanceof GroupDissolvedEvent) {
GroupDissolvedEvent g = (GroupDissolvedEvent) e; GroupDissolvedEvent g = (GroupDissolvedEvent) e;
if (getGroupId().equals(g.getGroupId())) { if (getGroupId().equals(g.getGroupId())) {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(
@Override () -> listener.onGroupDissolved());
public void run() {
listener.onGroupDissolved();
}
});
} }
} }
} }
@@ -158,9 +142,7 @@ class GroupControllerImpl extends
@Override @Override
public void loadSharingContacts( public void loadSharingContacts(
final ResultExceptionHandler<Collection<ContactId>, DbException> handler) { final ResultExceptionHandler<Collection<ContactId>, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
Collection<GroupMember> members = Collection<GroupMember> members =
privateGroupManager.getMembers(getGroupId()); privateGroupManager.getMembers(getGroupId());
@@ -171,11 +153,9 @@ class GroupControllerImpl extends
} }
handler.onResult(contactIds); handler.onResult(contactIds);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@@ -183,9 +163,7 @@ class GroupControllerImpl extends
public void createAndStoreMessage(final String body, public void createAndStoreMessage(final String body,
@Nullable final GroupMessageItem parentItem, @Nullable final GroupMessageItem parentItem,
final ResultExceptionHandler<GroupMessageItem, DbException> handler) { final ResultExceptionHandler<GroupMessageItem, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
LocalAuthor author = identityManager.getLocalAuthor(); LocalAuthor author = identityManager.getLocalAuthor();
MessageId parentId = null; MessageId parentId = null;
@@ -196,14 +174,12 @@ class GroupControllerImpl extends
long timestamp = count.getLatestMsgTime(); long timestamp = count.getLatestMsgTime();
if (parentItem != null) parentId = parentItem.getId(); if (parentItem != null) parentId = parentItem.getId();
timestamp = max(clock.currentTimeMillis(), timestamp + 1); timestamp = max(clock.currentTimeMillis(), timestamp + 1);
createMessage(body, timestamp, parentId, author, createMessage(body, timestamp, parentId, author, previousMsgId,
previousMsgId, handler); handler);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@@ -211,15 +187,12 @@ class GroupControllerImpl extends
final @Nullable MessageId parentId, final LocalAuthor author, final @Nullable MessageId parentId, final LocalAuthor author,
final MessageId previousMsgId, final MessageId previousMsgId,
final ResultExceptionHandler<GroupMessageItem, DbException> handler) { final ResultExceptionHandler<GroupMessageItem, DbException> handler) {
cryptoExecutor.execute(new Runnable() { cryptoExecutor.execute(() -> {
@Override
public void run() {
LOG.info("Creating group message..."); LOG.info("Creating group message...");
GroupMessage msg = groupMessageFactory GroupMessage msg = groupMessageFactory
.createGroupMessage(getGroupId(), timestamp, .createGroupMessage(getGroupId(), timestamp,
parentId, author, body, previousMsgId); parentId, author, body, previousMsgId);
storePost(msg, body, handler); storePost(msg, body, handler);
}
}); });
} }
@@ -246,37 +219,29 @@ class GroupControllerImpl extends
@Override @Override
public void loadLocalAuthor( public void loadLocalAuthor(
final ResultExceptionHandler<LocalAuthor, DbException> handler) { final ResultExceptionHandler<LocalAuthor, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
LocalAuthor author = identityManager.getLocalAuthor(); LocalAuthor author = identityManager.getLocalAuthor();
handler.onResult(author); handler.onResult(author);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@Override @Override
public void isDissolved(final public void isDissolved(final
ResultExceptionHandler<Boolean, DbException> handler) { ResultExceptionHandler<Boolean, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
boolean isDissolved = boolean isDissolved =
privateGroupManager.isDissolved(getGroupId()); privateGroupManager.isDissolved(getGroupId());
handler.onResult(isDissolved); handler.onResult(isDissolved);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }

View File

@@ -76,55 +76,44 @@ class CreateGroupControllerImpl extends ContactSelectorControllerImpl
@Override @Override
public void createGroup(final String name, public void createGroup(final String name,
final ResultExceptionHandler<GroupId, DbException> handler) { final ResultExceptionHandler<GroupId, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
LocalAuthor author = identityManager.getLocalAuthor(); LocalAuthor author = identityManager.getLocalAuthor();
createGroupAndMessages(author, name, handler); createGroupAndMessages(author, name, handler);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
private void createGroupAndMessages(final LocalAuthor author, private void createGroupAndMessages(final LocalAuthor author,
final String name, final String name,
final ResultExceptionHandler<GroupId, DbException> handler) { final ResultExceptionHandler<GroupId, DbException> handler) {
cryptoExecutor.execute(new Runnable() { cryptoExecutor.execute(() -> {
@Override
public void run() {
LOG.info("Creating group..."); LOG.info("Creating group...");
PrivateGroup group = PrivateGroup group =
groupFactory.createPrivateGroup(name, author); groupFactory.createPrivateGroup(name, author);
LOG.info("Creating new join announcement..."); LOG.info("Creating new join announcement...");
GroupMessage joinMsg = groupMessageFactory GroupMessage joinMsg =
.createJoinMessage(group.getId(), groupMessageFactory.createJoinMessage(group.getId(),
clock.currentTimeMillis(), author); clock.currentTimeMillis(), author);
storeGroup(group, joinMsg, handler); storeGroup(group, joinMsg, handler);
}
}); });
} }
private void storeGroup(final PrivateGroup group, private void storeGroup(final PrivateGroup group,
final GroupMessage joinMsg, final GroupMessage joinMsg,
final ResultExceptionHandler<GroupId, DbException> handler) { final ResultExceptionHandler<GroupId, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
LOG.info("Adding group to database..."); LOG.info("Adding group to database...");
try { try {
groupManager.addPrivateGroup(group, joinMsg, true); groupManager.addPrivateGroup(group, joinMsg, true);
handler.onResult(group.getId()); handler.onResult(group.getId());
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@@ -137,9 +126,7 @@ class CreateGroupControllerImpl extends ContactSelectorControllerImpl
public void sendInvitation(final GroupId g, public void sendInvitation(final GroupId g,
final Collection<ContactId> contactIds, final String message, final Collection<ContactId> contactIds, final String message,
final ResultExceptionHandler<Void, DbException> handler) { final ResultExceptionHandler<Void, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
LocalAuthor localAuthor = identityManager.getLocalAuthor(); LocalAuthor localAuthor = identityManager.getLocalAuthor();
List<Contact> contacts = new ArrayList<>(); List<Contact> contacts = new ArrayList<>();
@@ -152,39 +139,32 @@ class CreateGroupControllerImpl extends ContactSelectorControllerImpl
} }
signInvitations(g, localAuthor, contacts, message, handler); signInvitations(g, localAuthor, contacts, message, handler);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
private void signInvitations(final GroupId g, final LocalAuthor localAuthor, private void signInvitations(final GroupId g, final LocalAuthor localAuthor,
final Collection<Contact> contacts, final String message, final Collection<Contact> contacts, final String message,
final ResultExceptionHandler<Void, DbException> handler) { final ResultExceptionHandler<Void, DbException> handler) {
cryptoExecutor.execute(new Runnable() { cryptoExecutor.execute(() -> {
@Override
public void run() {
long timestamp = clock.currentTimeMillis(); long timestamp = clock.currentTimeMillis();
List<InvitationContext> contexts = new ArrayList<>(); List<InvitationContext> contexts = new ArrayList<>();
for (Contact c : contacts) { for (Contact c : contacts) {
byte[] signature = groupInvitationFactory.signInvitation(c, byte[] signature = groupInvitationFactory.signInvitation(c, g,
g, timestamp, localAuthor.getPrivateKey()); timestamp, localAuthor.getPrivateKey());
contexts.add(new InvitationContext(c.getId(), timestamp, contexts.add(new InvitationContext(c.getId(), timestamp,
signature)); signature));
} }
sendInvitations(g, contexts, message, handler); sendInvitations(g, contexts, message, handler);
}
}); });
} }
private void sendInvitations(final GroupId g, private void sendInvitations(final GroupId g,
final Collection<InvitationContext> contexts, final String message, final Collection<InvitationContext> contexts, final String message,
final ResultExceptionHandler<Void, DbException> handler) { final ResultExceptionHandler<Void, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
String msg = message.isEmpty() ? null : message; String msg = message.isEmpty() ? null : message;
for (InvitationContext context : contexts) { for (InvitationContext context : contexts) {
@@ -199,11 +179,9 @@ class CreateGroupControllerImpl extends ContactSelectorControllerImpl
//noinspection ConstantConditions //noinspection ConstantConditions
handler.onResult(null); handler.onResult(null);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }

View File

@@ -5,16 +5,12 @@ import android.os.Bundle;
import android.support.design.widget.TextInputLayout; import android.support.design.widget.TextInputLayout;
import android.text.Editable; import android.text.Editable;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.Button; import android.widget.Button;
import android.widget.EditText; import android.widget.EditText;
import android.widget.ProgressBar; import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import org.briarproject.bramble.util.StringUtils; import org.briarproject.bramble.util.StringUtils;
import org.briarproject.briar.R; import org.briarproject.briar.R;
@@ -65,24 +61,15 @@ public class CreateGroupFragment extends BaseFragment {
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
} }
}); });
nameEntry.setOnEditorActionListener(new OnEditorActionListener() { nameEntry.setOnEditorActionListener((v1, actionId, e) -> {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent e) {
createGroup(); createGroup();
return true; return true;
}
}); });
nameLayout = (TextInputLayout) v.findViewById(R.id.nameLayout); nameLayout = (TextInputLayout) v.findViewById(R.id.nameLayout);
createGroupButton = (Button) v.findViewById(R.id.button); createGroupButton = (Button) v.findViewById(R.id.button);
createGroupButton.setOnClickListener(new OnClickListener() { createGroupButton.setOnClickListener(v1 -> createGroup());
@Override
public void onClick(View v) {
createGroup();
}
});
progress = (ProgressBar) v.findViewById(R.id.progressBar); progress = (ProgressBar) v.findViewById(R.id.progressBar);

View File

@@ -67,19 +67,15 @@ class GroupInvitationControllerImpl
public void respondToInvitation(final GroupInvitationItem item, public void respondToInvitation(final GroupInvitationItem item,
final boolean accept, final boolean accept,
final ExceptionHandler<DbException> handler) { final ExceptionHandler<DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
PrivateGroup g = item.getShareable(); PrivateGroup g = item.getShareable();
ContactId c = item.getCreator().getId(); ContactId c = item.getCreator().getId();
groupInvitationManager.respondToInvitation(c, g, accept); groupInvitationManager.respondToInvitation(c, g, accept);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }

View File

@@ -120,56 +120,32 @@ class GroupListControllerImpl extends DbControllerImpl
} }
private void onGroupMessageAdded(final GroupMessageHeader h) { private void onGroupMessageAdded(final GroupMessageHeader h) {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(
@Override () -> listener.onGroupMessageAdded(h));
public void run() {
listener.onGroupMessageAdded(h);
}
});
} }
private void onGroupInvitationReceived() { private void onGroupInvitationReceived() {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(
@Override () -> listener.onGroupInvitationReceived());
public void run() {
listener.onGroupInvitationReceived();
}
});
} }
private void onGroupAdded(final GroupId g) { private void onGroupAdded(final GroupId g) {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(() -> listener.onGroupAdded(g));
@Override
public void run() {
listener.onGroupAdded(g);
}
});
} }
private void onGroupRemoved(final GroupId g) { private void onGroupRemoved(final GroupId g) {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(() -> listener.onGroupRemoved(g));
@Override
public void run() {
listener.onGroupRemoved(g);
}
});
} }
private void onGroupDissolved(final GroupId g) { private void onGroupDissolved(final GroupId g) {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(
@Override () -> listener.onGroupDissolved(g));
public void run() {
listener.onGroupDissolved(g);
}
});
} }
@Override @Override
public void loadGroups( public void loadGroups(
final ResultExceptionHandler<Collection<GroupItem>, DbException> handler) { final ResultExceptionHandler<Collection<GroupItem>, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
Collection<PrivateGroup> groups = Collection<PrivateGroup> groups =
@@ -190,20 +166,16 @@ class GroupListControllerImpl extends DbControllerImpl
LOG.info("Loading groups took " + duration + " ms"); LOG.info("Loading groups took " + duration + " ms");
handler.onResult(items); handler.onResult(items);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@Override @Override
public void removeGroup(final GroupId g, public void removeGroup(final GroupId g,
final ExceptionHandler<DbException> handler) { final ExceptionHandler<DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
groupManager.removePrivateGroup(g); groupManager.removePrivateGroup(g);
@@ -211,29 +183,23 @@ class GroupListControllerImpl extends DbControllerImpl
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Removing group took " + duration + " ms"); LOG.info("Removing group took " + duration + " ms");
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@Override @Override
public void loadAvailableGroups( public void loadAvailableGroups(
final ResultExceptionHandler<Integer, DbException> handler) { final ResultExceptionHandler<Integer, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
handler.onResult( handler.onResult(
groupInvitationManager.getInvitations().size()); groupInvitationManager.getInvitations().size());
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }

View File

@@ -4,7 +4,6 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.Button; import android.widget.Button;
import android.widget.TextView; import android.widget.TextView;
@@ -107,25 +106,17 @@ class GroupViewHolder extends RecyclerView.ViewHolder {
status status
.setText(ctx.getString(R.string.groups_group_is_dissolved)); .setText(ctx.getString(R.string.groups_group_is_dissolved));
status.setVisibility(VISIBLE); status.setVisibility(VISIBLE);
remove.setOnClickListener(new OnClickListener() { remove.setOnClickListener(v -> listener.onGroupRemoveClick(group));
@Override
public void onClick(View v) {
listener.onGroupRemoveClick(group);
}
});
remove.setVisibility(VISIBLE); remove.setVisibility(VISIBLE);
} }
// Open Group on Click // Open Group on Click
layout.setOnClickListener(new OnClickListener() { layout.setOnClickListener(v -> {
@Override
public void onClick(View v) {
Intent i = new Intent(ctx, GroupActivity.class); Intent i = new Intent(ctx, GroupActivity.class);
GroupId id = group.getId(); GroupId id = group.getId();
i.putExtra(GROUP_ID, id.getBytes()); i.putExtra(GROUP_ID, id.getBytes());
i.putExtra(GROUP_NAME, group.getName()); i.putExtra(GROUP_NAME, group.getName());
ctx.startActivity(i); ctx.startActivity(i);
}
}); });
} }

View File

@@ -42,9 +42,7 @@ class GroupMemberListControllerImpl extends DbControllerImpl
@Override @Override
public void loadMembers(final GroupId groupId, final public void loadMembers(final GroupId groupId, final
ResultExceptionHandler<Collection<MemberListItem>, DbException> handler) { ResultExceptionHandler<Collection<MemberListItem>, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
Collection<MemberListItem> items = new ArrayList<>(); Collection<MemberListItem> items = new ArrayList<>();
Collection<GroupMember> members = Collection<GroupMember> members =
@@ -58,11 +56,9 @@ class GroupMemberListControllerImpl extends DbControllerImpl
} }
handler.onResult(items); handler.onResult(items);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }

View File

@@ -1,6 +1,5 @@
package org.briarproject.briar.android.privategroup.reveal; package org.briarproject.briar.android.privategroup.reveal;
import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.LayoutRes; import android.support.annotation.LayoutRes;
@@ -110,19 +109,8 @@ public class RevealContactsActivity extends ContactSelectorActivity
new AlertDialog.Builder(this, R.style.OnboardingDialogTheme) new AlertDialog.Builder(this, R.style.OnboardingDialogTheme)
.setMessage(getString(R.string.groups_reveal_dialog_message)) .setMessage(getString(R.string.groups_reveal_dialog_message))
.setNeutralButton(R.string.got_it, .setNeutralButton(R.string.got_it,
new DialogInterface.OnClickListener() { (dialog, which) -> dialog.cancel())
@Override .setOnCancelListener(dialog -> onboardingShown())
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
onboardingShown();
}
})
.show(); .show();
} }

View File

@@ -62,19 +62,13 @@ class RevealContactsControllerImpl extends DbControllerImpl
public void loadContacts(final GroupId g, public void loadContacts(final GroupId g,
final Collection<ContactId> selection, final Collection<ContactId> selection,
final ResultExceptionHandler<Collection<RevealableContactItem>, DbException> handler) { final ResultExceptionHandler<Collection<RevealableContactItem>, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
Collection<RevealableContactItem> items = handler.onResult(getItems(g, selection));
getItems(g, selection);
handler.onResult(items);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@@ -105,9 +99,7 @@ class RevealContactsControllerImpl extends DbControllerImpl
@Override @Override
public void isOnboardingNeeded( public void isOnboardingNeeded(
final ResultExceptionHandler<Boolean, DbException> handler) { final ResultExceptionHandler<Boolean, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
Settings settings = Settings settings =
settingsManager.getSettings(SETTINGS_NAMESPACE); settingsManager.getSettings(SETTINGS_NAMESPACE);
@@ -115,20 +107,16 @@ class RevealContactsControllerImpl extends DbControllerImpl
settings.getBoolean(SHOW_ONBOARDING_REVEAL_CONTACTS, settings.getBoolean(SHOW_ONBOARDING_REVEAL_CONTACTS,
true)); true));
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@Override @Override
public void onboardingShown(ExceptionHandler<DbException> handler) { public void onboardingShown(ExceptionHandler<DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
Settings settings = new Settings(); Settings settings = new Settings();
settings.putBoolean(SHOW_ONBOARDING_REVEAL_CONTACTS, false); settings.putBoolean(SHOW_ONBOARDING_REVEAL_CONTACTS, false);
@@ -137,16 +125,13 @@ class RevealContactsControllerImpl extends DbControllerImpl
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING))
LOG.log(WARNING, e.toString(), e); LOG.log(WARNING, e.toString(), e);
} }
}
}); });
} }
@Override @Override
public void reveal(final GroupId g, final Collection<ContactId> contacts, public void reveal(final GroupId g, final Collection<ContactId> contacts,
final ExceptionHandler<DbException> handler) { final ExceptionHandler<DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
for (ContactId c : contacts) { for (ContactId c : contacts) {
try { try {
groupInvitationManager.revealRelationship(c, g); groupInvitationManager.revealRelationship(c, g);
@@ -161,7 +146,6 @@ class RevealContactsControllerImpl extends DbControllerImpl
break; break;
} }
} }
}
}); });
} }

View File

@@ -256,12 +256,9 @@ public class BriarReportPrimer implements ReportPrimer {
Looper.prepare(); Looper.prepare();
Handler handler = new Handler(); Handler handler = new Handler();
handler.post(runnable); handler.post(runnable);
handler.post(new Runnable() { handler.post(() -> {
@Override
public void run() {
Looper looper = Looper.myLooper(); Looper looper = Looper.myLooper();
if (looper != null) looper.quit(); if (looper != null) looper.quit();
}
}); });
Looper.loop(); Looper.loop();
} }

View File

@@ -1,6 +1,5 @@
package org.briarproject.briar.android.reporting; package org.briarproject.briar.android.reporting;
import android.content.Context;
import android.content.res.Configuration; import android.content.res.Configuration;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
@@ -37,6 +36,7 @@ import java.util.logging.Logger;
import static android.view.View.GONE; import static android.view.View.GONE;
import static android.view.View.INVISIBLE; import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE; import static android.view.View.VISIBLE;
import static android.view.inputmethod.InputMethodManager.SHOW_FORCED;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static org.acra.ACRAConstants.EXTRA_REPORT_FILE; import static org.acra.ACRAConstants.EXTRA_REPORT_FILE;
import static org.acra.ReportField.ANDROID_VERSION; import static org.acra.ReportField.ANDROID_VERSION;
@@ -115,28 +115,14 @@ public class DevReportActivity extends BaseCrashReportDialog
includeDebugReport.setChecked(true); includeDebugReport.setChecked(true);
} }
findViewById(R.id.acceptButton).setOnClickListener( findViewById(R.id.acceptButton).setOnClickListener(v -> {
new View.OnClickListener() {
@Override
public void onClick(View v) {
reviewing = true; reviewing = true;
requestReport.setVisibility(GONE); requestReport.setVisibility(GONE);
((InputMethodManager) getSystemService( ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
Context.INPUT_METHOD_SERVICE)) .showSoftInput(userCommentView, SHOW_FORCED);
.showSoftInput(userCommentView,
InputMethodManager.SHOW_FORCED);
}
}); });
findViewById(R.id.declineButton).setOnClickListener( findViewById(R.id.declineButton).setOnClickListener(v -> closeReport());
new View.OnClickListener() { chevron.setOnClickListener(v -> {
@Override
public void onClick(View v) {
closeReport();
}
});
chevron.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean show = boolean show =
chevron.getText().equals(getString(R.string.show)); chevron.getText().equals(getString(R.string.show));
if (show) { if (show) {
@@ -146,7 +132,6 @@ public class DevReportActivity extends BaseCrashReportDialog
chevron.setText(R.string.show); chevron.setText(R.string.show);
report.setVisibility(GONE); report.setVisibility(GONE);
} }
}
}); });
if (state != null) if (state != null)

View File

@@ -141,22 +141,16 @@ public class SettingsFragment extends PreferenceFragmentCompat
notifyLockscreen.setVisible(true); notifyLockscreen.setVisible(true);
notifyLockscreen.setOnPreferenceChangeListener(this); notifyLockscreen.setOnPreferenceChangeListener(this);
} }
notifySound.setOnPreferenceClickListener( notifySound.setOnPreferenceClickListener(preference -> {
new Preference.OnPreferenceClickListener() { String title = getString(R.string.choose_ringtone_title);
@Override
public boolean onPreferenceClick(Preference preference) {
String title =
getString(R.string.choose_ringtone_title);
Intent i = new Intent(ACTION_RINGTONE_PICKER); Intent i = new Intent(ACTION_RINGTONE_PICKER);
i.putExtra(EXTRA_RINGTONE_TYPE, TYPE_NOTIFICATION); i.putExtra(EXTRA_RINGTONE_TYPE, TYPE_NOTIFICATION);
i.putExtra(EXTRA_RINGTONE_TITLE, title); i.putExtra(EXTRA_RINGTONE_TITLE, title);
i.putExtra(EXTRA_RINGTONE_DEFAULT_URI, i.putExtra(EXTRA_RINGTONE_DEFAULT_URI, DEFAULT_NOTIFICATION_URI);
DEFAULT_NOTIFICATION_URI);
i.putExtra(EXTRA_RINGTONE_SHOW_SILENT, true); i.putExtra(EXTRA_RINGTONE_SHOW_SILENT, true);
if (settings.getBoolean(PREF_NOTIFY_SOUND, true)) { if (settings.getBoolean(PREF_NOTIFY_SOUND, true)) {
Uri uri; Uri uri;
String ringtoneUri = String ringtoneUri = settings.get(PREF_NOTIFY_RINGTONE_URI);
settings.get(PREF_NOTIFY_RINGTONE_URI);
if (StringUtils.isNullOrEmpty(ringtoneUri)) if (StringUtils.isNullOrEmpty(ringtoneUri))
uri = DEFAULT_NOTIFICATION_URI; uri = DEFAULT_NOTIFICATION_URI;
else uri = Uri.parse(ringtoneUri); else uri = Uri.parse(ringtoneUri);
@@ -164,30 +158,21 @@ public class SettingsFragment extends PreferenceFragmentCompat
} }
startActivityForResult(i, REQUEST_RINGTONE); startActivityForResult(i, REQUEST_RINGTONE);
return true; return true;
}
}); });
findPreference("pref_key_send_feedback").setOnPreferenceClickListener( findPreference("pref_key_send_feedback").setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() { preference -> {
@Override
public boolean onPreferenceClick(Preference preference) {
triggerFeedback(); triggerFeedback();
return true; return true;
}
}); });
Preference testData = findPreference("pref_key_test_data"); Preference testData = findPreference("pref_key_test_data");
if (IS_DEBUG_BUILD) { if (IS_DEBUG_BUILD) {
testData.setOnPreferenceClickListener( testData.setOnPreferenceClickListener(preference -> {
new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(
Preference preference) {
LOG.info("Creating test data"); LOG.info("Creating test data");
testDataCreator.createTestData(); testDataCreator.createTestData();
getActivity().finish(); getActivity().finish();
return true; return true;
}
}); });
} else { } else {
testData.setVisible(false); testData.setVisible(false);
@@ -209,14 +194,11 @@ public class SettingsFragment extends PreferenceFragmentCompat
} }
private void loadSettings() { private void loadSettings() {
listener.runOnDbThread(new Runnable() { listener.runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
settings = settingsManager.getSettings(SETTINGS_NAMESPACE); settings = settingsManager.getSettings(SETTINGS_NAMESPACE);
Settings btSettings = Settings btSettings = settingsManager.getSettings(BT_NAMESPACE);
settingsManager.getSettings(BT_NAMESPACE);
Settings torSettings = Settings torSettings =
settingsManager.getSettings(TOR_NAMESPACE); settingsManager.getSettings(TOR_NAMESPACE);
long duration = System.currentTimeMillis() - now; long duration = System.currentTimeMillis() - now;
@@ -228,18 +210,14 @@ public class SettingsFragment extends PreferenceFragmentCompat
PREF_TOR_NETWORK_ALWAYS); PREF_TOR_NETWORK_ALWAYS);
displaySettings(btSetting, torSetting); displaySettings(btSetting, torSetting);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
private void displaySettings(final boolean btSetting, private void displaySettings(final boolean btSetting,
final int torSetting) { final int torSetting) {
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
enableBluetooth.setValue(Boolean.toString(btSetting)); enableBluetooth.setValue(Boolean.toString(btSetting));
torNetwork.setValue(Integer.toString(torSetting)); torNetwork.setValue(Integer.toString(torSetting));
@@ -263,8 +241,7 @@ public class SettingsFragment extends PreferenceFragmentCompat
String text; String text;
if (settings.getBoolean(PREF_NOTIFY_SOUND, true)) { if (settings.getBoolean(PREF_NOTIFY_SOUND, true)) {
String ringtoneName = String ringtoneName = settings.get(PREF_NOTIFY_RINGTONE_NAME);
settings.get(PREF_NOTIFY_RINGTONE_NAME);
if (StringUtils.isNullOrEmpty(ringtoneName)) { if (StringUtils.isNullOrEmpty(ringtoneName)) {
text = getString(R.string.notify_sound_setting_default); text = getString(R.string.notify_sound_setting_default);
} else { } else {
@@ -274,18 +251,12 @@ public class SettingsFragment extends PreferenceFragmentCompat
text = getString(R.string.notify_sound_setting_disabled); text = getString(R.string.notify_sound_setting_disabled);
} }
notifySound.setSummary(text); notifySound.setSummary(text);
}
}); });
} }
private void triggerFeedback() { private void triggerFeedback() {
androidExecutor.runOnBackgroundThread(new Runnable() { androidExecutor.runOnBackgroundThread(() -> ACRA.getErrorReporter()
@Override .handleException(new UserFeedback(), false));
public void run() {
ACRA.getErrorReporter().handleException(new UserFeedback(),
false);
}
});
} }
@Override @Override
@@ -331,9 +302,7 @@ public class SettingsFragment extends PreferenceFragmentCompat
} }
private void storeTorSettings(final int torSetting) { private void storeTorSettings(final int torSetting) {
listener.runOnDbThread(new Runnable() { listener.runOnDbThread(() -> {
@Override
public void run() {
try { try {
Settings s = new Settings(); Settings s = new Settings();
s.putInt(PREF_TOR_NETWORK, torSetting); s.putInt(PREF_TOR_NETWORK, torSetting);
@@ -343,17 +312,13 @@ public class SettingsFragment extends PreferenceFragmentCompat
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Merging settings took " + duration + " ms"); LOG.info("Merging settings took " + duration + " ms");
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
private void storeBluetoothSettings(final boolean btSetting) { private void storeBluetoothSettings(final boolean btSetting) {
listener.runOnDbThread(new Runnable() { listener.runOnDbThread(() -> {
@Override
public void run() {
try { try {
Settings s = new Settings(); Settings s = new Settings();
s.putBoolean(PREF_BT_ENABLE, btSetting); s.putBoolean(PREF_BT_ENABLE, btSetting);
@@ -363,17 +328,13 @@ public class SettingsFragment extends PreferenceFragmentCompat
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Merging settings took " + duration + " ms"); LOG.info("Merging settings took " + duration + " ms");
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
private void storeSettings(final Settings settings) { private void storeSettings(final Settings settings) {
listener.runOnDbThread(new Runnable() { listener.runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
settingsManager.mergeSettings(settings, SETTINGS_NAMESPACE); settingsManager.mergeSettings(settings, SETTINGS_NAMESPACE);
@@ -381,9 +342,7 @@ public class SettingsFragment extends PreferenceFragmentCompat
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Merging settings took " + duration + " ms"); LOG.info("Merging settings took " + duration + " ms");
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }

View File

@@ -61,9 +61,7 @@ class BlogInvitationControllerImpl
public void respondToInvitation(final SharingInvitationItem item, public void respondToInvitation(final SharingInvitationItem item,
final boolean accept, final boolean accept,
final ExceptionHandler<DbException> handler) { final ExceptionHandler<DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
Blog f = (Blog) item.getShareable(); Blog f = (Blog) item.getShareable();
for (Contact c : item.getNewSharers()) { for (Contact c : item.getNewSharers()) {
@@ -71,11 +69,9 @@ class BlogInvitationControllerImpl
blogSharingManager.respondToInvitation(f, c, accept); blogSharingManager.respondToInvitation(f, c, accept);
} }
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }

View File

@@ -62,9 +62,7 @@ class ForumInvitationControllerImpl
public void respondToInvitation(final SharingInvitationItem item, public void respondToInvitation(final SharingInvitationItem item,
final boolean accept, final boolean accept,
final ExceptionHandler<DbException> handler) { final ExceptionHandler<DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
Forum f = (Forum) item.getShareable(); Forum f = (Forum) item.getShareable();
for (Contact c : item.getNewSharers()) { for (Contact c : item.getNewSharers()) {
@@ -72,11 +70,9 @@ class ForumInvitationControllerImpl
forumSharingManager.respondToInvitation(f, c, accept); forumSharingManager.respondToInvitation(f, c, accept);
} }
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }

View File

@@ -123,9 +123,7 @@ public abstract class InvitationActivity<I extends InvitationItem>
protected void displayInvitations(final int revision, protected void displayInvitations(final int revision,
final Collection<I> invitations, final boolean clear) { final Collection<I> invitations, final boolean clear) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
if (invitations.isEmpty()) { if (invitations.isEmpty()) {
LOG.info("No more invitations available, finishing"); LOG.info("No more invitations available, finishing");
supportFinishAfterTransition(); supportFinishAfterTransition();
@@ -137,7 +135,6 @@ public abstract class InvitationActivity<I extends InvitationItem>
LOG.info("Concurrent update, reloading"); LOG.info("Concurrent update, reloading");
loadInvitations(clear); loadInvitations(clear);
} }
}
}); });
} }

View File

@@ -93,24 +93,19 @@ public abstract class InvitationControllerImpl<I extends InvitationItem>
@Override @Override
public void loadInvitations(final boolean clear, public void loadInvitations(final boolean clear,
final ResultExceptionHandler<Collection<I>, DbException> handler) { final ResultExceptionHandler<Collection<I>, DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
Collection<I> invitations = new ArrayList<>(); Collection<I> invitations = new ArrayList<>();
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
invitations.addAll(getInvitations()); invitations.addAll(getInvitations());
long duration = System.currentTimeMillis() - now; long duration = System.currentTimeMillis() - now;
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info( LOG.info("Loading invitations took " + duration + " ms");
"Loading invitations took " + duration + " ms");
handler.onResult(invitations); handler.onResult(invitations);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }

View File

@@ -53,18 +53,8 @@ public class InvitationViewHolder<I extends InvitationItem>
subscribed.setVisibility(GONE); subscribed.setVisibility(GONE);
} }
accept.setOnClickListener(new View.OnClickListener() { accept.setOnClickListener(v -> listener.onItemClick(item, true));
@Override decline.setOnClickListener(v -> listener.onItemClick(item, false));
public void onClick(View v) {
listener.onItemClick(item, true);
}
});
decline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
listener.onItemClick(item, false);
}
});
} }
} }

View File

@@ -58,9 +58,7 @@ class ShareBlogControllerImpl extends ContactSelectorControllerImpl
public void share(final GroupId g, final Collection<ContactId> contacts, public void share(final GroupId g, final Collection<ContactId> contacts,
final String message, final String message,
final ExceptionHandler<DbException> handler) { final ExceptionHandler<DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
String msg = isNullOrEmpty(message) ? null : message; String msg = isNullOrEmpty(message) ? null : message;
for (ContactId c : contacts) { for (ContactId c : contacts) {
@@ -75,11 +73,9 @@ class ShareBlogControllerImpl extends ContactSelectorControllerImpl
} }
} }
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }

View File

@@ -58,9 +58,7 @@ class ShareForumControllerImpl extends ContactSelectorControllerImpl
public void share(final GroupId g, final Collection<ContactId> contacts, public void share(final GroupId g, final Collection<ContactId> contacts,
final String message, final String message,
final ExceptionHandler<DbException> handler) { final ExceptionHandler<DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
String msg = isNullOrEmpty(message) ? null : message; String msg = isNullOrEmpty(message) ? null : message;
for (ContactId c : contacts) { for (ContactId c : contacts) {
@@ -75,11 +73,9 @@ class ShareForumControllerImpl extends ContactSelectorControllerImpl
} }
} }
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }

View File

@@ -100,33 +100,25 @@ abstract class SharingStatusActivity extends BriarActivity {
} }
private void loadSharedWith() { private void loadSharedWith() {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
List<ContactItem> contactItems = new ArrayList<>(); List<ContactItem> contactItems = new ArrayList<>();
for (Contact c : getSharedWith()) { for (Contact c : getSharedWith()) {
boolean online = boolean online = connectionRegistry.isConnected(c.getId());
connectionRegistry.isConnected(c.getId());
ContactItem item = new ContactItem(c, online); ContactItem item = new ContactItem(c, online);
contactItems.add(item); contactItems.add(item);
} }
displaySharedWith(contactItems); displaySharedWith(contactItems);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
private void displaySharedWith(final List<ContactItem> contacts) { private void displaySharedWith(final List<ContactItem> contacts) {
runOnUiThreadUnlessDestroyed(new Runnable() { runOnUiThreadUnlessDestroyed(() -> {
@Override
public void run() {
if (contacts.isEmpty()) list.showData(); if (contacts.isEmpty()) list.showData();
else adapter.addAll(contacts); else adapter.addAll(contacts);
}
}); });
} }

View File

@@ -43,12 +43,9 @@ public class SplashScreenActivity extends BaseActivity {
setContentView(R.layout.splash); setContentView(R.layout.splash);
new Handler().postDelayed(new Runnable() { new Handler().postDelayed(() -> {
@Override
public void run() {
startNextActivity(); startNextActivity();
supportFinishAfterTransition(); supportFinishAfterTransition();
}
}, 500); }, 500);
} }
@@ -72,12 +69,8 @@ public class SplashScreenActivity extends BaseActivity {
} }
private void setPreferencesDefaults() { private void setPreferencesDefaults() {
androidExecutor.runOnBackgroundThread(new Runnable() { androidExecutor.runOnBackgroundThread(() ->
@Override
public void run() {
PreferenceManager.setDefaultValues(SplashScreenActivity.this, PreferenceManager.setDefaultValues(SplashScreenActivity.this,
R.xml.panic_preferences, false); R.xml.panic_preferences, false));
}
});
} }
} }

View File

@@ -85,13 +85,8 @@ public abstract class BaseThreadItemViewHolder<I extends ThreadItem>
public void onAnimationRepeat(Animator animation) { public void onAnimationRepeat(Animator animation) {
} }
}); });
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { anim.addUpdateListener(valueAnimator -> layout.setBackgroundColor(
@Override (Integer) valueAnimator.getAnimatedValue()));
public void onAnimationUpdate(ValueAnimator valueAnimator) {
layout.setBackgroundColor(
(Integer) valueAnimator.getAnimatedValue());
}
});
anim.setDuration(ANIMATION_DURATION); anim.setDuration(ANIMATION_DURATION);
anim.start(); anim.start();
} }

View File

@@ -10,7 +10,6 @@ import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View;
import org.briarproject.bramble.api.contact.ContactId; import org.briarproject.bramble.api.contact.ContactId;
import org.briarproject.bramble.api.db.DbException; import org.briarproject.bramble.api.db.DbException;
@@ -117,23 +116,17 @@ public abstract class ThreadListActivity<G extends NamedGroup, I extends ThreadI
}); });
upButton = (UnreadMessageButton) findViewById(R.id.upButton); upButton = (UnreadMessageButton) findViewById(R.id.upButton);
downButton = (UnreadMessageButton) findViewById(R.id.downButton); downButton = (UnreadMessageButton) findViewById(R.id.downButton);
upButton.setOnClickListener(new View.OnClickListener() { upButton.setOnClickListener(v -> {
@Override
public void onClick(View v) {
int position = adapter.getVisibleUnreadPosTop(); int position = adapter.getVisibleUnreadPosTop();
if (position != NO_POSITION) { if (position != NO_POSITION) {
list.getRecyclerView().scrollToPosition(position); list.getRecyclerView().scrollToPosition(position);
} }
}
}); });
downButton.setOnClickListener(new View.OnClickListener() { downButton.setOnClickListener(v -> {
@Override
public void onClick(View v) {
int position = adapter.getVisibleUnreadPosBottom(); int position = adapter.getVisibleUnreadPosBottom();
if (position != NO_POSITION) { if (position != NO_POSITION) {
list.getRecyclerView().scrollToPosition(position); list.getRecyclerView().scrollToPosition(position);
} }
}
}); });
if (state != null) { if (state != null) {

View File

@@ -101,17 +101,13 @@ public abstract class ThreadListControllerImpl<G extends NamedGroup, I extends T
public void onActivityDestroy() { public void onActivityDestroy() {
final MessageId messageId = listener.getFirstVisibleMessageId(); final MessageId messageId = listener.getFirstVisibleMessageId();
if (messageId != null) { if (messageId != null) {
dbExecutor.execute(new Runnable() { dbExecutor.execute(() -> {
@Override
public void run() {
try { try {
messageTracker messageTracker.storeMessageId(groupId, messageId);
.storeMessageId(groupId, messageId);
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING))
LOG.log(WARNING, e.toString(), e); LOG.log(WARNING, e.toString(), e);
} }
}
}); });
} }
} }
@@ -123,12 +119,8 @@ public abstract class ThreadListControllerImpl<G extends NamedGroup, I extends T
GroupRemovedEvent s = (GroupRemovedEvent) e; GroupRemovedEvent s = (GroupRemovedEvent) e;
if (s.getGroup().getId().equals(getGroupId())) { if (s.getGroup().getId().equals(getGroupId())) {
LOG.info("Group removed"); LOG.info("Group removed");
listener.runOnUiThreadUnlessDestroyed(new Runnable() { listener.runOnUiThreadUnlessDestroyed(
@Override () -> listener.onGroupRemoved());
public void run() {
listener.onGroupRemoved();
}
});
} }
} }
} }
@@ -137,9 +129,7 @@ public abstract class ThreadListControllerImpl<G extends NamedGroup, I extends T
public void loadNamedGroup( public void loadNamedGroup(
final ResultExceptionHandler<G, DbException> handler) { final ResultExceptionHandler<G, DbException> handler) {
checkGroupId(); checkGroupId();
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
G groupItem = loadNamedGroup(); G groupItem = loadNamedGroup();
@@ -152,7 +142,6 @@ public abstract class ThreadListControllerImpl<G extends NamedGroup, I extends T
LOG.log(WARNING, e.toString(), e); LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@@ -163,9 +152,7 @@ public abstract class ThreadListControllerImpl<G extends NamedGroup, I extends T
public void loadItems( public void loadItems(
final ResultExceptionHandler<ThreadItemList<I>, DbException> handler) { final ResultExceptionHandler<ThreadItemList<I>, DbException> handler) {
checkGroupId(); checkGroupId();
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
// Load headers // Load headers
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@@ -189,11 +176,9 @@ public abstract class ThreadListControllerImpl<G extends NamedGroup, I extends T
// Build and hand over items // Build and hand over items
handler.onResult(buildItems(headers)); handler.onResult(buildItems(headers));
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }
@@ -210,9 +195,7 @@ public abstract class ThreadListControllerImpl<G extends NamedGroup, I extends T
@Override @Override
public void markItemsRead(final Collection<I> items) { public void markItemsRead(final Collection<I> items) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
for (I i : items) { for (I i : items) {
@@ -222,9 +205,7 @@ public abstract class ThreadListControllerImpl<G extends NamedGroup, I extends T
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Marking read took " + duration + " ms"); LOG.info("Marking read took " + duration + " ms");
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
}
} }
}); });
} }
@@ -234,9 +215,7 @@ public abstract class ThreadListControllerImpl<G extends NamedGroup, I extends T
protected void storePost(final M msg, final String body, protected void storePost(final M msg, final String body,
final ResultExceptionHandler<I, DbException> resultHandler) { final ResultExceptionHandler<I, DbException> resultHandler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
H header = addLocalMessage(msg); H header = addLocalMessage(msg);
@@ -246,11 +225,9 @@ public abstract class ThreadListControllerImpl<G extends NamedGroup, I extends T
LOG.info("Storing message took " + duration + " ms"); LOG.info("Storing message took " + duration + " ms");
resultHandler.onResult(buildItem(header, body)); resultHandler.onResult(buildItem(header, body));
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
resultHandler.onException(e); resultHandler.onException(e);
} }
}
}); });
} }
@@ -259,9 +236,7 @@ public abstract class ThreadListControllerImpl<G extends NamedGroup, I extends T
@Override @Override
public void deleteNamedGroup(final ExceptionHandler<DbException> handler) { public void deleteNamedGroup(final ExceptionHandler<DbException> handler) {
runOnDbThread(new Runnable() { runOnDbThread(() -> {
@Override
public void run() {
try { try {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
G groupItem = loadNamedGroup(); G groupItem = loadNamedGroup();
@@ -270,11 +245,9 @@ public abstract class ThreadListControllerImpl<G extends NamedGroup, I extends T
if (LOG.isLoggable(INFO)) if (LOG.isLoggable(INFO))
LOG.info("Removing group took " + duration + " ms"); LOG.info("Removing group took " + duration + " ms");
} catch (DbException e) { } catch (DbException e) {
if (LOG.isLoggable(WARNING)) if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
LOG.log(WARNING, e.toString(), e);
handler.onException(e); handler.onException(e);
} }
}
}); });
} }

View File

@@ -50,12 +50,7 @@ public class ThreadPostViewHolder<I extends ThreadItem>
lvlText.setVisibility(GONE); lvlText.setVisibility(GONE);
} }
replyButton.setOnClickListener(new View.OnClickListener() { replyButton.setOnClickListener(v -> listener.onReplyClick(item));
@Override
public void onClick(View v) {
listener.onReplyClick(item);
}
});
} }
} }

View File

@@ -3,7 +3,6 @@ package org.briarproject.briar.android.util;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.annotation.TargetApi; import android.annotation.TargetApi;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnClickListener;
import android.content.Intent; import android.content.Intent;
import android.net.Uri; import android.net.Uri;
@@ -143,16 +142,13 @@ public class UiUtils {
public static OnClickListener getGoToSettingsListener( public static OnClickListener getGoToSettingsListener(
final Context context) { final Context context) {
return new OnClickListener() { return (dialog, which) -> {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(); Intent i = new Intent();
i.setAction("android.settings.APPLICATION_DETAILS_SETTINGS"); i.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
i.addCategory(CATEGORY_DEFAULT); i.addCategory(CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + APPLICATION_ID)); i.setData(Uri.parse("package:" + APPLICATION_ID));
i.addFlags(FLAG_ACTIVITY_NEW_TASK); i.addFlags(FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i); context.startActivity(i);
}
}; };
} }
@@ -160,13 +156,7 @@ public class UiUtils {
new AlertDialog.Builder(ctx, R.style.OnboardingDialogTheme) new AlertDialog.Builder(ctx, R.style.OnboardingDialogTheme)
.setMessage(text) .setMessage(text)
.setNeutralButton(R.string.got_it, .setNeutralButton(R.string.got_it,
new DialogInterface.OnClickListener() { (dialog, which) -> dialog.cancel())
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
})
.show(); .show();
} }

View File

@@ -94,22 +94,11 @@ public class BriarRecyclerView extends FrameLayout {
} }
private void addLayoutChangeListener() { private void addLayoutChangeListener() {
recyclerView.addOnLayoutChangeListener( recyclerView.addOnLayoutChangeListener((v, left, top, right, bottom,
new OnLayoutChangeListener() { oldLeft, oldTop, oldRight, oldBottom) -> {
@Override
public void onLayoutChange(View v, int left, int top,
int right, int bottom, int oldLeft, int oldTop,
int oldRight, int oldBottom) {
if (bottom < oldBottom) { if (bottom < oldBottom) {
recyclerView.postDelayed(new Runnable() { recyclerView.postDelayed(() -> scrollToPosition(
@Override recyclerView.getAdapter().getItemCount() - 1), 100);
public void run() {
scrollToPosition(
recyclerView.getAdapter()
.getItemCount() - 1);
}
}, 100);
}
} }
}); });
} }
@@ -191,14 +180,11 @@ public class BriarRecyclerView extends FrameLayout {
if (recyclerView == null || recyclerView.getAdapter() == null) { if (recyclerView == null || recyclerView.getAdapter() == null) {
throw new IllegalStateException("Need to call setAdapter() first!"); throw new IllegalStateException("Need to call setAdapter() first!");
} }
refresher = new Runnable() { refresher = () -> {
@Override
public void run() {
LOG.info("Updating Content..."); LOG.info("Updating Content...");
Adapter adapter = recyclerView.getAdapter(); Adapter adapter = recyclerView.getAdapter();
adapter.notifyItemRangeChanged(0, adapter.getItemCount()); adapter.notifyItemRangeChanged(0, adapter.getItemCount());
handler.postDelayed(refresher, MIN_DATE_RESOLUTION); handler.postDelayed(refresher, MIN_DATE_RESOLUTION);
}
}; };
LOG.info("Adding Handler Callback"); LOG.info("Adding Handler Callback");
handler.postDelayed(refresher, MIN_DATE_RESOLUTION); handler.postDelayed(refresher, MIN_DATE_RESOLUTION);

View File

@@ -75,35 +75,19 @@ public class TextInputView extends KeyboardAwareLinearLayout
} }
ui.emojiToggle.attach(ui.emojiDrawer); ui.emojiToggle.attach(ui.emojiDrawer);
ui.emojiToggle.setOnClickListener(new OnClickListener() { ui.emojiToggle.setOnClickListener(v -> onEmojiToggleClicked());
@Override ui.editText.setOnClickListener(v -> showSoftKeyboard());
public void onClick(View v) { ui.editText.setOnKeyListener((v, keyCode, event) -> {
onEmojiToggleClicked();
}
});
ui.editText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showSoftKeyboard();
}
});
ui.editText.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KEYCODE_BACK && isEmojiDrawerOpen()) { if (keyCode == KEYCODE_BACK && isEmojiDrawerOpen()) {
hideEmojiDrawer(); hideEmojiDrawer();
return true; return true;
} }
return false; return false;
}
}); });
ui.sendButton.setOnClickListener(new OnClickListener() { ui.sendButton.setOnClickListener(v -> {
@Override
public void onClick(View v) {
if (listener != null) { if (listener != null) {
listener.onSendClick(ui.editText.getText().toString()); listener.onSendClick(ui.editText.getText().toString());
} }
}
}); });
ui.emojiDrawer.setEmojiEventListener(this); ui.emojiDrawer.setEmojiEventListener(this);
} }
@@ -167,22 +151,13 @@ public class TextInputView extends KeyboardAwareLinearLayout
if (isKeyboardOpen()) return; if (isKeyboardOpen()) return;
if (ui.emojiDrawer.isShowing()) { if (ui.emojiDrawer.isShowing()) {
postOnKeyboardOpen(new Runnable() { postOnKeyboardOpen(this::hideEmojiDrawer);
@Override
public void run() {
hideEmojiDrawer();
} }
}); ui.editText.post(() -> {
}
ui.editText.post(new Runnable() {
@Override
public void run() {
ui.editText.requestFocus(); ui.editText.requestFocus();
InputMethodManager imm = InputMethodManager imm = (InputMethodManager)
(InputMethodManager) getContext() getContext().getSystemService(INPUT_METHOD_SERVICE);
.getSystemService(INPUT_METHOD_SERVICE);
imm.showSoftInput(ui.editText, SHOW_IMPLICIT); imm.showSoftInput(ui.editText, SHOW_IMPLICIT);
}
}); });
} }
@@ -194,11 +169,7 @@ public class TextInputView extends KeyboardAwareLinearLayout
public void showEmojiDrawer() { public void showEmojiDrawer() {
if (isKeyboardOpen()) { if (isKeyboardOpen()) {
postOnKeyboardClose(new Runnable() { postOnKeyboardClose(() -> ui.emojiDrawer.show(getKeyboardHeight()));
@Override public void run() {
ui.emojiDrawer.show(getKeyboardHeight());
}
});
hideSoftKeyboard(); hideSoftKeyboard();
} else { } else {
ui.emojiDrawer.show(getKeyboardHeight()); ui.emojiDrawer.show(getKeyboardHeight());

View File

@@ -8,7 +8,6 @@ import android.os.Bundle;
import android.support.v4.app.DialogFragment; import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.Button; import android.widget.Button;
import android.widget.TextView; import android.widget.TextView;
@@ -62,21 +61,13 @@ public class LinkDialogFragment extends DialogFragment {
getString(R.string.link_warning_open_link)) : i; getString(R.string.link_warning_open_link)) : i;
Button openButton = (Button) v.findViewById(R.id.openButton); Button openButton = (Button) v.findViewById(R.id.openButton);
openButton.setOnClickListener(new OnClickListener() { openButton.setOnClickListener(v1 -> {
@Override
public void onClick(View v) {
startActivity(intent); startActivity(intent);
getDialog().dismiss(); getDialog().dismiss();
}
}); });
Button cancelButton = (Button) v.findViewById(R.id.cancelButton); Button cancelButton = (Button) v.findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new OnClickListener() { cancelButton.setOnClickListener(v1 -> getDialog().cancel());
@Override
public void onClick(View v) {
getDialog().cancel();
}
});
return v; return v;
} }

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