Miscellaneous code cleanups.

parent c59ef29c
......@@ -13,8 +13,7 @@ import org.briarproject.bramble.api.lifecycle.Service;
import org.briarproject.bramble.api.network.NetworkManager;
import org.briarproject.bramble.api.network.NetworkStatus;
import org.briarproject.bramble.api.network.event.NetworkStatusEvent;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.system.Scheduler;
import java.util.concurrent.Future;
......@@ -34,13 +33,13 @@ import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.logging.Level.INFO;
import static java.util.logging.Logger.getLogger;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
@NotNullByDefault
class AndroidNetworkManager implements NetworkManager, Service {
private static final Logger LOG =
......@@ -57,6 +56,7 @@ class AndroidNetworkManager implements NetworkManager, Service {
new AtomicReference<>();
private final AtomicBoolean used = new AtomicBoolean(false);
@Nullable
private volatile BroadcastReceiver networkStateReceiver = null;
@Inject
......@@ -90,9 +90,8 @@ class AndroidNetworkManager implements NetworkManager, Service {
@Override
public NetworkStatus getNetworkStatus() {
ConnectivityManager cm = (ConnectivityManager)
appContext.getSystemService(CONNECTIVITY_SERVICE);
if (cm == null) throw new AssertionError();
ConnectivityManager cm = (ConnectivityManager) requireNonNull(
appContext.getSystemService(CONNECTIVITY_SERVICE));
NetworkInfo net = cm.getActiveNetworkInfo();
boolean connected = net != null && net.isConnected();
boolean wifi = connected && net.getType() == TYPE_WIFI;
......
......@@ -32,6 +32,7 @@ import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.os.Build.VERSION.SDK_INT;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
import static java.util.logging.Logger.getLogger;
@NotNullByDefault
......@@ -67,10 +68,8 @@ class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener {
// Don't execute more than one connection status check at a time
connectionStatusExecutor =
new PoliteExecutor("AndroidLanTcpPlugin", ioExecutor, 1);
ConnectivityManager connectivityManager = (ConnectivityManager)
appContext.getSystemService(CONNECTIVITY_SERVICE);
if (connectivityManager == null) throw new AssertionError();
this.connectivityManager = connectivityManager;
connectivityManager = (ConnectivityManager) requireNonNull(
appContext.getSystemService(CONNECTIVITY_SERVICE));
wifiManager = (WifiManager) appContext.getApplicationContext()
.getSystemService(WIFI_SERVICE);
socketFactory = SocketFactory.getDefault();
......
......@@ -8,8 +8,7 @@ import android.os.PowerManager;
import org.briarproject.bramble.api.battery.BatteryManager;
import org.briarproject.bramble.api.network.NetworkManager;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.plugin.Backoff;
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginCallback;
import org.briarproject.bramble.api.system.Clock;
......@@ -26,10 +25,10 @@ import javax.net.SocketFactory;
import static android.content.Context.MODE_PRIVATE;
import static android.content.Context.POWER_SERVICE;
import static android.os.PowerManager.PARTIAL_WAKE_LOCK;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MINUTES;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
@NotNullByDefault
class AndroidTorPlugin extends TorPlugin {
// This tag may prevent Huawei's power manager from killing us
......@@ -52,8 +51,7 @@ class AndroidTorPlugin extends TorPlugin {
appContext.getDir("tor", MODE_PRIVATE));
this.appContext = appContext;
PowerManager pm = (PowerManager)
appContext.getSystemService(POWER_SERVICE);
if (pm == null) throw new AssertionError();
requireNonNull(appContext.getSystemService(POWER_SERVICE));
wakeLock = new RenewableWakeLock(pm, scheduler, PARTIAL_WAKE_LOCK,
WAKE_LOCK_TAG, 1, MINUTES);
}
......
......@@ -60,14 +60,14 @@ class AndroidLocationUtils implements LocationUtils {
}
private String getCountryFromPhoneNetwork() {
Object o = appContext.getSystemService(TELEPHONY_SERVICE);
TelephonyManager tm = (TelephonyManager) o;
return tm.getNetworkCountryIso();
TelephonyManager tm = (TelephonyManager)
appContext.getSystemService(TELEPHONY_SERVICE);
return tm == null ? "" : tm.getNetworkCountryIso();
}
private String getCountryFromSimCard() {
Object o = appContext.getSystemService(TELEPHONY_SERVICE);
TelephonyManager tm = (TelephonyManager) o;
return tm.getSimCountryIso();
TelephonyManager tm = (TelephonyManager)
appContext.getSystemService(TELEPHONY_SERVICE);
return tm == null ? "" : tm.getSimCountryIso();
}
}
......@@ -4,7 +4,6 @@ import org.briarproject.bramble.api.Bytes;
import org.briarproject.bramble.api.FormatException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import javax.annotation.Nullable;
......@@ -24,9 +23,9 @@ public class BdfDictionary extends TreeMap<String, Object> {
* );
* </pre>
*/
public static BdfDictionary of(Entry<String, ?>... entries) {
public static BdfDictionary of(BdfEntry... entries) {
BdfDictionary d = new BdfDictionary();
for (Entry<String, ?> e : entries) d.put(e.getKey(), e.getValue());
for (BdfEntry e : entries) d.put(e.getKey(), e.getValue());
return d;
}
......
......@@ -33,6 +33,7 @@ public class BdfList extends ArrayList<Object> {
super(items);
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean isInRange(int index) {
return index >= 0 && index < size();
}
......
......@@ -11,7 +11,7 @@ public class TransportId {
/**
* The maximum length of a transport identifier in UTF-8 bytes.
*/
public static int MAX_TRANSPORT_ID_LENGTH = 100;
public static final int MAX_TRANSPORT_ID_LENGTH = 100;
private final String id;
......
......@@ -17,7 +17,7 @@ public class ClientId implements Comparable<ClientId> {
/**
* The maximum length of a client identifier in UTF-8 bytes.
*/
public static int MAX_CLIENT_ID_LENGTH = 100;
public static final int MAX_CLIENT_ID_LENGTH = 100;
private final String id;
......
......@@ -68,7 +68,7 @@ public class BdfDictionaryTest extends BrambleTestCase {
}
@Test
public void testKeySetIteratorIsOrderedByKeys() throws Exception {
public void testKeySetIteratorIsOrderedByKeys() {
BdfDictionary d = new BdfDictionary();
d.put("a", 1);
d.put("d", 4);
......@@ -87,7 +87,7 @@ public class BdfDictionaryTest extends BrambleTestCase {
}
@Test
public void testValuesIteratorIsOrderedByKeys() throws Exception {
public void testValuesIteratorIsOrderedByKeys() {
BdfDictionary d = new BdfDictionary();
d.put("a", 1);
d.put("d", 4);
......@@ -106,7 +106,7 @@ public class BdfDictionaryTest extends BrambleTestCase {
}
@Test
public void testEntrySetIteratorIsOrderedByKeys() throws Exception {
public void testEntrySetIteratorIsOrderedByKeys() {
BdfDictionary d = new BdfDictionary();
d.put("a", 1);
d.put("d", 4);
......
......@@ -6,8 +6,7 @@ import org.briarproject.bramble.api.crypto.SecretKey;
import org.briarproject.bramble.api.db.DatabaseConfig;
import org.briarproject.bramble.api.identity.IdentityManager;
import org.briarproject.bramble.api.identity.LocalAuthor;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import java.io.BufferedReader;
import java.io.File;
......@@ -27,8 +26,7 @@ import static org.briarproject.bramble.util.LogUtils.logException;
import static org.briarproject.bramble.util.StringUtils.fromHexString;
import static org.briarproject.bramble.util.StringUtils.toHexString;
@MethodsNotNullByDefault
@ParametersNotNullByDefault
@NotNullByDefault
class AccountManagerImpl implements AccountManager {
private static final Logger LOG =
......@@ -104,7 +102,7 @@ class AccountManagerImpl implements AccountManager {
}
// Locking: stateChangeLock
protected boolean storeEncryptedDatabaseKey(String hex) {
boolean storeEncryptedDatabaseKey(String hex) {
LOG.info("Storing database key in file");
// Create the directory if necessary
if (databaseConfig.getDatabaseKeyDirectory().mkdirs())
......
......@@ -191,6 +191,7 @@ class ContactExchangeTaskImpl extends Thread implements ContactExchangeTask {
streamWriter.sendEndOfStream();
// Skip any remaining records from the incoming stream
try {
//noinspection InfiniteLoopStatement
while (true) recordReader.readRecord();
} catch (EOFException expected) {
LOG.info("End of stream");
......
......@@ -15,7 +15,7 @@ class AsciiArmour {
int length = wrapped.length();
for (int i = 0; i < length; i += lineLength) {
int end = Math.min(i + lineLength, length);
s.append(wrapped.substring(i, end));
s.append(wrapped, i, end);
s.append("\r\n");
}
return s.toString();
......
......@@ -159,6 +159,7 @@ public class MessageEncrypter {
printUsage();
System.exit(1);
}
//noinspection IfCanBeSwitch
if (args[0].equals("generate")) {
if (args.length != 3) {
printUsage();
......
......@@ -242,7 +242,7 @@ interface Database<T> {
* bytes. This is based on the minimum of the space available on the device
* where the database is stored and the database's configured size.
*/
long getFreeSpace() throws DbException;
long getFreeSpace();
/**
* Returns the group with the given ID.
......
......@@ -339,6 +339,7 @@ abstract class JdbcDatabase implements Database<Connection> {
this.clock = clock;
}
@SuppressWarnings("unused")
protected void open(String driverClass, boolean reopen, SecretKey key,
@Nullable MigrationListener listener) throws DbException {
// Load the JDBC driver
......@@ -768,7 +769,7 @@ abstract class JdbcDatabase implements Database<Connection> {
for (Entry<ContactId, Boolean> e : visibility.entrySet()) {
ContactId c = e.getKey();
boolean offered = removeOfferedMessage(txn, c, m.getId());
boolean seen = offered || (sender != null && c.equals(sender));
boolean seen = offered || c.equals(sender);
addStatus(txn, m.getId(), c, m.getGroupId(), m.getTimestamp(),
raw.length, state, e.getValue(), messageShared,
false, seen);
......
......@@ -17,7 +17,7 @@ class Migration40_41 implements Migration<Connection> {
private final DatabaseTypes dbTypes;
public Migration40_41(DatabaseTypes databaseTypes) {
Migration40_41(DatabaseTypes databaseTypes) {
this.dbTypes = databaseTypes;
}
......
......@@ -2,7 +2,7 @@ package org.briarproject.bramble.keyagreement;
class AbortException extends Exception {
boolean receivedAbort;
final boolean receivedAbort;
AbortException() {
this(false);
......
......@@ -20,6 +20,7 @@ interface BluetoothConnectionLimiter {
* Returns true if a contact connection can be opened. This method does not
* need to be called for key agreement connections.
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
boolean canOpenContactConnection();
/**
......
......@@ -80,6 +80,7 @@ class LanTcpPlugin extends TcpPlugin {
locals.add(new InetSocketAddress(local, 0));
}
}
//noinspection Java8ListSort
sort(locals, ADDRESS_COMPARATOR);
return locals;
}
......
......@@ -85,6 +85,7 @@ abstract class TcpPlugin implements DuplexPlugin {
/**
* Returns true if connections to the given address can be attempted.
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
protected abstract boolean isConnectable(InetSocketAddress remote);
TcpPlugin(Executor ioExecutor, Backoff backoff,
......
......@@ -13,7 +13,7 @@ abstract class Frame {
static final byte ACK_FLAG = (byte) 128, FIN_FLAG = 64;
protected final byte[] buf;
final byte[] buf;
Frame(byte[] buf) {
this.buf = buf;
......
......@@ -101,6 +101,7 @@ class Receiver implements ReadHandler {
}
}
@SuppressWarnings("StatementWithEmptyBody")
private void handleData(byte[] b) throws IOException {
windowLock.lock();
try {
......@@ -124,6 +125,7 @@ class Receiver implements ReadHandler {
finalSequenceNumber = sequenceNumber;
// Remove any data frames with higher sequence numbers
Iterator<Data> it = dataFrames.iterator();
//noinspection Java8CollectionRemoveIf
while (it.hasNext()) {
Data d1 = it.next();
if (d1.getSequenceNumber() >= finalSequenceNumber)
......@@ -148,6 +150,7 @@ class Receiver implements ReadHandler {
private static class SequenceNumberComparator implements Comparator<Data> {
@SuppressWarnings("UseCompareMethod")
@Override
public int compare(Data d1, Data d2) {
long s1 = d1.getSequenceNumber(), s2 = d2.getSequenceNumber();
......
......@@ -52,6 +52,7 @@ class ReceiverInputStream extends InputStream {
return len;
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean receive() throws IOException {
if (length != 0) throw new AssertionError();
if (data != null && data.isLastFrame()) {
......
......@@ -16,6 +16,7 @@ import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.concurrent.ThreadSafe;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireNonNull;
@ThreadSafe
@NotNullByDefault
......@@ -96,7 +97,7 @@ class Sender {
}
// If any older data frames are outstanding, retransmit the oldest
if (foundIndex > 0) {
fastRetransmit = outstanding.poll();
fastRetransmit = requireNonNull(outstanding.poll());
fastRetransmit.lastTransmitted = now;
fastRetransmit.retransmitted = true;
outstanding.add(fastRetransmit);
......@@ -191,7 +192,7 @@ class Sender {
writeHandler.handleWrite(d.getBuffer());
}
void flush() throws IOException, InterruptedException {
void flush() throws InterruptedException {
windowLock.lock();
try {
while (dataWaiting || !outstanding.isEmpty())
......
......@@ -44,6 +44,7 @@ public class DevReportServer {
TokenBucket bucket = new TokenBucket();
bucket.start();
try {
//noinspection InfiniteLoopStatement
while (true) {
Socket s = ss.accept();
System.out.println("Incoming connection");
......@@ -103,6 +104,7 @@ public class DevReportServer {
@Override
public void run() {
try {
//noinspection InfiniteLoopStatement
while (true) {
// If the bucket isn't full, add a token
if (semaphore.availablePermits() < MAX_TOKENS) {
......@@ -134,6 +136,8 @@ public class DevReportServer {
try {
socket.setSoTimeout(SOCKET_TIMEOUT_MS);
in = getInputStream(socket);
// Directory may already exist
//noinspection ResultOfMethodCallIgnored
reportDir.mkdirs();
reportFile = createTempFile(FILE_PREFIX, FILE_SUFFIX,
reportDir);
......@@ -153,7 +157,8 @@ public class DevReportServer {
System.out.println("Saved " + length + " bytes");
} catch (IOException e) {
e.printStackTrace();
if (reportFile != null) reportFile.delete();
if (reportFile != null && !reportFile.delete())
System.err.println("Failed to delete report");
} finally {
tryToClose(in);
tryToClose(out);
......
......@@ -111,17 +111,15 @@ class DevReporterImpl implements DevReporter, EventListener {
LOG.info("Sending reports to developers");
for (File f : reports) {
OutputStream out = null;
InputStream in = null;
try {
Socket s = connectToDevelopers();
out = getOutputStream(s);
in = new FileInputStream(f);
InputStream in = new FileInputStream(f);
copyAndClose(in, out);
f.delete();
if (!f.delete()) LOG.warning("Failed to delete report");
} catch (IOException e) {
LOG.log(WARNING, "Failed to send reports", e);
tryToClose(out, LOG, WARNING);
tryToClose(in, LOG, WARNING);
return;
}
}
......
......@@ -28,6 +28,7 @@ class SocksSocket extends Socket {
"Address type not supported"
};
@SuppressWarnings("MismatchedReadAndWriteOfArray")
private static final byte[] UNSPECIFIED_ADDRESS = new byte[4];
private final SocketAddress proxy;
......
......@@ -45,7 +45,7 @@ class SocksSocketFactory extends SocketFactory {
@Override
public Socket createSocket(InetAddress address, int port,
InetAddress localAddress, int localPort) throws IOException {
InetAddress localAddress, int localPort) {
throw new UnsupportedOperationException();
}
}
......@@ -14,6 +14,7 @@ import javax.annotation.concurrent.Immutable;
import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.IoUtils.tryToClose;
import static org.briarproject.bramble.util.LogUtils.logException;
@Immutable
......@@ -43,15 +44,16 @@ class UnixSecureRandomProvider extends AbstractSecureRandomProvider {
}
protected void writeSeed() {
DataOutputStream out = null;
try {
DataOutputStream out = new DataOutputStream(
new FileOutputStream(outputDevice));
out = new DataOutputStream(new FileOutputStream(outputDevice));
writeToEntropyPool(out);
out.flush();
out.close();
} catch (IOException e) {
// On some devices /dev/urandom isn't writable - this isn't fatal
logException(LOG, WARNING, e);
} finally {
tryToClose(out, LOG, WARNING);
}
}
......
......@@ -11,6 +11,7 @@ import java.util.logging.Logger;
import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.IoUtils.tryToClose;
import static org.briarproject.bramble.util.LogUtils.logException;
public class UnixSecureRandomSpi extends SecureRandomSpi {
......@@ -34,15 +35,16 @@ public class UnixSecureRandomSpi extends SecureRandomSpi {
@Override
protected void engineSetSeed(byte[] seed) {
DataOutputStream out = null;
try {
DataOutputStream out = new DataOutputStream(
new FileOutputStream(outputDevice));
out = new DataOutputStream(new FileOutputStream(outputDevice));
out.write(seed);
out.flush();
out.close();
} catch (IOException e) {
// On some devices /dev/urandom isn't writable - this isn't fatal
logException(LOG, WARNING, e);
} finally {
tryToClose(out, LOG, WARNING);
}
}
......
......@@ -23,7 +23,7 @@ import static org.junit.Assert.assertEquals;
public class EllipticCurveMultiplicationTest extends BrambleTestCase {
@Test
public void testMultiplierProducesSameResultsAsDefault() throws Exception {
public void testMultiplierProducesSameResultsAsDefault() {
// Instantiate the default implementation of the curve
X9ECParameters defaultX9Parameters =
TeleTrusTNamedCurves.getByName("brainpoolp256r1");
......
......@@ -64,7 +64,7 @@ public class KeyAgreementTest extends BrambleTestCase {
}
@Test
public void testRfc7748TestVector() throws Exception {
public void testRfc7748TestVector() {
// Private keys need to be clamped because curve25519-java does the
// clamping at key generation time, not multiplication time
byte[] aPriv = Curve25519KeyParser.clamp(fromHexString(ALICE_PRIVATE));
......
......@@ -23,7 +23,7 @@ public class KeyEncodingAndParsingTest extends BrambleTestCase {
new CryptoComponentImpl(new TestSecureRandomProvider(), null);
@Test
public void testAgreementPublicKeyLength() throws Exception {
public void testAgreementPublicKeyLength() {
// Generate 10 agreement key pairs
for (int i = 0; i < 10; i++) {
KeyPair keyPair = crypto.generateAgreementKeyPair();
......@@ -70,7 +70,7 @@ public class KeyEncodingAndParsingTest extends BrambleTestCase {
}
@Test
public void testAgreementKeyParserByFuzzing() throws Exception {
public void testAgreementKeyParserByFuzzing() {
KeyParser parser = crypto.getAgreementKeyParser();
// Generate a key pair to get the proper public key length
KeyPair p = crypto.generateAgreementKeyPair();
......@@ -92,7 +92,7 @@ public class KeyEncodingAndParsingTest extends BrambleTestCase {
}
@Test
public void testSignaturePublicKeyLength() throws Exception {
public void testSignaturePublicKeyLength() {
// Generate 10 signature key pairs
for (int i = 0; i < 10; i++) {
KeyPair keyPair = crypto.generateSignatureKeyPair();
......@@ -159,7 +159,7 @@ public class KeyEncodingAndParsingTest extends BrambleTestCase {
}
@Test
public void testSignatureKeyParserByFuzzing() throws Exception {
public void testSignatureKeyParserByFuzzing() {
KeyParser parser = crypto.getSignatureKeyParser();
// Generate a key pair to get the proper public key length
KeyPair p = crypto.generateSignatureKeyPair();
......
......@@ -19,7 +19,7 @@ import static org.junit.Assert.assertEquals;
public class ScryptKdfTest extends BrambleTestCase {
@Test
public void testPasswordAffectsKey() throws Exception {
public void testPasswordAffectsKey() {
PasswordBasedKdf kdf = new ScryptKdf(new SystemClock());
byte[] salt = getRandomBytes(32);
Set<Bytes> keys = new HashSet<>();
......@@ -31,7 +31,7 @@ public class ScryptKdfTest extends BrambleTestCase {
}
@Test
public void testSaltAffectsKey() throws Exception {
public void testSaltAffectsKey() {
PasswordBasedKdf kdf = new ScryptKdf(new SystemClock());
String password = getRandomString(16);
Set<Bytes> keys = new HashSet<>();
......@@ -43,7 +43,7 @@ public class ScryptKdfTest extends BrambleTestCase {
}
@Test
public void testCostParameterAffectsKey() throws Exception {
public void testCostParameterAffectsKey() {
PasswordBasedKdf kdf = new ScryptKdf(new SystemClock());
String password = getRandomString(16);
byte[] salt = getRandomBytes(32);
......@@ -55,7 +55,7 @@ public class ScryptKdfTest extends BrambleTestCase {
}
@Test
public void testCalibration() throws Exception {
public void testCalibration() {
Clock clock = new ArrayClock(