...
 
Commits (8)
...@@ -9,19 +9,22 @@ import org.briarproject.bramble.api.account.AccountManager; ...@@ -9,19 +9,22 @@ import org.briarproject.bramble.api.account.AccountManager;
import org.briarproject.bramble.api.crypto.CryptoComponent; import org.briarproject.bramble.api.crypto.CryptoComponent;
import org.briarproject.bramble.api.db.DatabaseConfig; import org.briarproject.bramble.api.db.DatabaseConfig;
import org.briarproject.bramble.api.identity.IdentityManager; import org.briarproject.bramble.api.identity.IdentityManager;
import org.briarproject.bramble.util.IoUtils;
import java.io.File; import java.io.File;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.inject.Inject; import javax.inject.Inject;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.IoUtils.deleteFileOrDir;
class AndroidAccountManager extends AccountManagerImpl class AndroidAccountManager extends AccountManagerImpl
implements AccountManager { implements AccountManager {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(AndroidAccountManager.class.getName()); getLogger(AndroidAccountManager.class.getName());
private static final String PREF_DB_KEY = "key"; private static final String PREF_DB_KEY = "key";
...@@ -37,7 +40,7 @@ class AndroidAccountManager extends AccountManagerImpl ...@@ -37,7 +40,7 @@ class AndroidAccountManager extends AccountManagerImpl
appContext = app.getApplicationContext(); appContext = app.getApplicationContext();
} }
// Locking: stateChangeLock @GuardedBy("stateChangeLock")
@Override @Override
@Nullable @Nullable
protected String loadEncryptedDatabaseKey() { protected String loadEncryptedDatabaseKey() {
...@@ -47,7 +50,7 @@ class AndroidAccountManager extends AccountManagerImpl ...@@ -47,7 +50,7 @@ class AndroidAccountManager extends AccountManagerImpl
return key; return key;
} }
// Locking: stateChangeLock @GuardedBy("stateChangeLock")
@Nullable @Nullable
private String getDatabaseKeyFromPreferences() { private String getDatabaseKeyFromPreferences() {
String key = prefs.getString(PREF_DB_KEY, null); String key = prefs.getString(PREF_DB_KEY, null);
...@@ -56,7 +59,7 @@ class AndroidAccountManager extends AccountManagerImpl ...@@ -56,7 +59,7 @@ class AndroidAccountManager extends AccountManagerImpl
return key; return key;
} }
// Locking: stateChangeLock @GuardedBy("stateChangeLock")
private void migrateDatabaseKeyToFile(String key) { private void migrateDatabaseKeyToFile(String key) {
if (storeEncryptedDatabaseKey(key)) { if (storeEncryptedDatabaseKey(key)) {
if (prefs.edit().remove(PREF_DB_KEY).commit()) if (prefs.edit().remove(PREF_DB_KEY).commit())
...@@ -81,7 +84,7 @@ class AndroidAccountManager extends AccountManagerImpl ...@@ -81,7 +84,7 @@ class AndroidAccountManager extends AccountManagerImpl
return PreferenceManager.getDefaultSharedPreferences(appContext); return PreferenceManager.getDefaultSharedPreferences(appContext);
} }
// Locking: stateChangeLock @GuardedBy("stateChangeLock")
private void deleteAppData(SharedPreferences... clear) { private void deleteAppData(SharedPreferences... clear) {
// Clear and commit shared preferences // Clear and commit shared preferences
for (SharedPreferences prefs : clear) { for (SharedPreferences prefs : clear) {
...@@ -97,7 +100,7 @@ class AndroidAccountManager extends AccountManagerImpl ...@@ -97,7 +100,7 @@ class AndroidAccountManager extends AccountManagerImpl
for (File child : children) { for (File child : children) {
String name = child.getName(); String name = child.getName();
if (!name.equals("lib") && !name.equals("shared_prefs")) { if (!name.equals("lib") && !name.equals("shared_prefs")) {
IoUtils.deleteFileOrDir(child); deleteFileOrDir(child);
} }
} }
} }
......
...@@ -13,8 +13,7 @@ import org.briarproject.bramble.api.lifecycle.Service; ...@@ -13,8 +13,7 @@ import org.briarproject.bramble.api.lifecycle.Service;
import org.briarproject.bramble.api.network.NetworkManager; import org.briarproject.bramble.api.network.NetworkManager;
import org.briarproject.bramble.api.network.NetworkStatus; import org.briarproject.bramble.api.network.NetworkStatus;
import org.briarproject.bramble.api.network.event.NetworkStatusEvent; import org.briarproject.bramble.api.network.event.NetworkStatusEvent;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.bramble.api.system.Scheduler; import org.briarproject.bramble.api.system.Scheduler;
import java.util.concurrent.Future; import java.util.concurrent.Future;
...@@ -34,16 +33,17 @@ import static android.net.ConnectivityManager.CONNECTIVITY_ACTION; ...@@ -34,16 +33,17 @@ import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
import static android.net.ConnectivityManager.TYPE_WIFI; import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION.SDK_INT;
import static android.os.PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED; 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.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Logger.getLogger;
@MethodsNotNullByDefault @NotNullByDefault
@ParametersNotNullByDefault
class AndroidNetworkManager implements NetworkManager, Service { class AndroidNetworkManager implements NetworkManager, Service {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(AndroidNetworkManager.class.getName()); getLogger(AndroidNetworkManager.class.getName());
// See android.net.wifi.WifiManager // See android.net.wifi.WifiManager
private static final String WIFI_AP_STATE_CHANGED_ACTION = private static final String WIFI_AP_STATE_CHANGED_ACTION =
...@@ -56,6 +56,7 @@ class AndroidNetworkManager implements NetworkManager, Service { ...@@ -56,6 +56,7 @@ class AndroidNetworkManager implements NetworkManager, Service {
new AtomicReference<>(); new AtomicReference<>();
private final AtomicBoolean used = new AtomicBoolean(false); private final AtomicBoolean used = new AtomicBoolean(false);
@Nullable
private volatile BroadcastReceiver networkStateReceiver = null; private volatile BroadcastReceiver networkStateReceiver = null;
@Inject @Inject
...@@ -89,9 +90,8 @@ class AndroidNetworkManager implements NetworkManager, Service { ...@@ -89,9 +90,8 @@ class AndroidNetworkManager implements NetworkManager, Service {
@Override @Override
public NetworkStatus getNetworkStatus() { public NetworkStatus getNetworkStatus() {
ConnectivityManager cm = (ConnectivityManager) ConnectivityManager cm = (ConnectivityManager) requireNonNull(
appContext.getSystemService(CONNECTIVITY_SERVICE); appContext.getSystemService(CONNECTIVITY_SERVICE));
if (cm == null) throw new AssertionError();
NetworkInfo net = cm.getActiveNetworkInfo(); NetworkInfo net = cm.getActiveNetworkInfo();
boolean connected = net != null && net.isConnected(); boolean connected = net != null && net.isConnected();
boolean wifi = connected && net.getType() == TYPE_WIFI; boolean wifi = connected && net.getType() == TYPE_WIFI;
......
...@@ -24,7 +24,6 @@ import java.io.IOException; ...@@ -24,7 +24,6 @@ import java.io.IOException;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
...@@ -48,9 +47,11 @@ import static android.bluetooth.BluetoothAdapter.STATE_OFF; ...@@ -48,9 +47,11 @@ import static android.bluetooth.BluetoothAdapter.STATE_OFF;
import static android.bluetooth.BluetoothAdapter.STATE_ON; import static android.bluetooth.BluetoothAdapter.STATE_ON;
import static android.bluetooth.BluetoothDevice.ACTION_FOUND; import static android.bluetooth.BluetoothDevice.ACTION_FOUND;
import static android.bluetooth.BluetoothDevice.EXTRA_DEVICE; import static android.bluetooth.BluetoothDevice.EXTRA_DEVICE;
import static java.util.Collections.shuffle;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.PrivacyUtils.scrubMacAddress; import static org.briarproject.bramble.util.PrivacyUtils.scrubMacAddress;
@MethodsNotNullByDefault @MethodsNotNullByDefault
...@@ -58,7 +59,7 @@ import static org.briarproject.bramble.util.PrivacyUtils.scrubMacAddress; ...@@ -58,7 +59,7 @@ import static org.briarproject.bramble.util.PrivacyUtils.scrubMacAddress;
class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> { class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(AndroidBluetoothPlugin.class.getName()); getLogger(AndroidBluetoothPlugin.class.getName());
private static final int MAX_DISCOVERY_MS = 10_000; private static final int MAX_DISCOVERY_MS = 10_000;
...@@ -259,7 +260,7 @@ class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> { ...@@ -259,7 +260,7 @@ class AndroidBluetoothPlugin extends BluetoothPlugin<BluetoothServerSocket> {
appContext.unregisterReceiver(receiver); appContext.unregisterReceiver(receiver);
} }
// Shuffle the addresses so we don't always try the same one first // Shuffle the addresses so we don't always try the same one first
Collections.shuffle(addresses); shuffle(addresses);
return addresses; return addresses;
} }
......
...@@ -32,17 +32,19 @@ import static android.net.ConnectivityManager.TYPE_WIFI; ...@@ -32,17 +32,19 @@ import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION.SDK_INT;
import static java.util.Collections.emptyList; import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList; import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
import static java.util.logging.Logger.getLogger;
@NotNullByDefault @NotNullByDefault
class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener { class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener {
private static final Logger LOG =
getLogger(AndroidLanTcpPlugin.class.getName());
private static final byte[] WIFI_AP_ADDRESS_BYTES = private static final byte[] WIFI_AP_ADDRESS_BYTES =
{(byte) 192, (byte) 168, 43, 1}; {(byte) 192, (byte) 168, 43, 1};
private static final InetAddress WIFI_AP_ADDRESS; private static final InetAddress WIFI_AP_ADDRESS;
private static final Logger LOG =
Logger.getLogger(AndroidLanTcpPlugin.class.getName());
static { static {
try { try {
WIFI_AP_ADDRESS = InetAddress.getByAddress(WIFI_AP_ADDRESS_BYTES); WIFI_AP_ADDRESS = InetAddress.getByAddress(WIFI_AP_ADDRESS_BYTES);
...@@ -66,10 +68,8 @@ class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener { ...@@ -66,10 +68,8 @@ class AndroidLanTcpPlugin extends LanTcpPlugin implements EventListener {
// Don't execute more than one connection status check at a time // Don't execute more than one connection status check at a time
connectionStatusExecutor = connectionStatusExecutor =
new PoliteExecutor("AndroidLanTcpPlugin", ioExecutor, 1); new PoliteExecutor("AndroidLanTcpPlugin", ioExecutor, 1);
ConnectivityManager connectivityManager = (ConnectivityManager) connectivityManager = (ConnectivityManager) requireNonNull(
appContext.getSystemService(CONNECTIVITY_SERVICE); appContext.getSystemService(CONNECTIVITY_SERVICE));
if (connectivityManager == null) throw new AssertionError();
this.connectivityManager = connectivityManager;
wifiManager = (WifiManager) appContext.getApplicationContext() wifiManager = (WifiManager) appContext.getApplicationContext()
.getSystemService(WIFI_SERVICE); .getSystemService(WIFI_SERVICE);
socketFactory = SocketFactory.getDefault(); socketFactory = SocketFactory.getDefault();
......
...@@ -8,8 +8,7 @@ import android.os.PowerManager; ...@@ -8,8 +8,7 @@ import android.os.PowerManager;
import org.briarproject.bramble.api.battery.BatteryManager; import org.briarproject.bramble.api.battery.BatteryManager;
import org.briarproject.bramble.api.network.NetworkManager; import org.briarproject.bramble.api.network.NetworkManager;
import org.briarproject.bramble.api.nullsafety.MethodsNotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.nullsafety.ParametersNotNullByDefault;
import org.briarproject.bramble.api.plugin.Backoff; import org.briarproject.bramble.api.plugin.Backoff;
import org.briarproject.bramble.api.plugin.duplex.DuplexPluginCallback; import org.briarproject.bramble.api.plugin.duplex.DuplexPluginCallback;
import org.briarproject.bramble.api.system.Clock; import org.briarproject.bramble.api.system.Clock;
...@@ -26,10 +25,10 @@ import javax.net.SocketFactory; ...@@ -26,10 +25,10 @@ import javax.net.SocketFactory;
import static android.content.Context.MODE_PRIVATE; import static android.content.Context.MODE_PRIVATE;
import static android.content.Context.POWER_SERVICE; import static android.content.Context.POWER_SERVICE;
import static android.os.PowerManager.PARTIAL_WAKE_LOCK; import static android.os.PowerManager.PARTIAL_WAKE_LOCK;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.MINUTES;
@MethodsNotNullByDefault @NotNullByDefault
@ParametersNotNullByDefault
class AndroidTorPlugin extends TorPlugin { class AndroidTorPlugin extends TorPlugin {
// This tag may prevent Huawei's power manager from killing us // This tag may prevent Huawei's power manager from killing us
...@@ -52,8 +51,7 @@ class AndroidTorPlugin extends TorPlugin { ...@@ -52,8 +51,7 @@ class AndroidTorPlugin extends TorPlugin {
appContext.getDir("tor", MODE_PRIVATE)); appContext.getDir("tor", MODE_PRIVATE));
this.appContext = appContext; this.appContext = appContext;
PowerManager pm = (PowerManager) PowerManager pm = (PowerManager)
appContext.getSystemService(POWER_SERVICE); requireNonNull(appContext.getSystemService(POWER_SERVICE));
if (pm == null) throw new AssertionError();
wakeLock = new RenewableWakeLock(pm, scheduler, PARTIAL_WAKE_LOCK, wakeLock = new RenewableWakeLock(pm, scheduler, PARTIAL_WAKE_LOCK,
WAKE_LOCK_TAG, 1, MINUTES); WAKE_LOCK_TAG, 1, MINUTES);
} }
......
package org.briarproject.bramble.plugin.tor; package org.briarproject.bramble.plugin.tor;
import android.content.Context; import android.content.Context;
import android.os.Build;
import org.briarproject.bramble.api.battery.BatteryManager; import org.briarproject.bramble.api.battery.BatteryManager;
import org.briarproject.bramble.api.event.EventBus; import org.briarproject.bramble.api.event.EventBus;
...@@ -26,12 +25,15 @@ import java.util.logging.Logger; ...@@ -26,12 +25,15 @@ import java.util.logging.Logger;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
import javax.net.SocketFactory; import javax.net.SocketFactory;
import static android.os.Build.VERSION.SDK_INT;
import static java.util.logging.Logger.getLogger;
@Immutable @Immutable
@NotNullByDefault @NotNullByDefault
public class AndroidTorPluginFactory implements DuplexPluginFactory { public class AndroidTorPluginFactory implements DuplexPluginFactory {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(AndroidTorPluginFactory.class.getName()); getLogger(AndroidTorPluginFactory.class.getName());
private static final int MAX_LATENCY = 30 * 1000; // 30 seconds private static final int MAX_LATENCY = 30 * 1000; // 30 seconds
private static final int MAX_IDLE_TIME = 30 * 1000; // 30 seconds private static final int MAX_IDLE_TIME = 30 * 1000; // 30 seconds
...@@ -102,7 +104,7 @@ public class AndroidTorPluginFactory implements DuplexPluginFactory { ...@@ -102,7 +104,7 @@ public class AndroidTorPluginFactory implements DuplexPluginFactory {
return null; return null;
} }
// Use position-independent executable for SDK >= 16 // Use position-independent executable for SDK >= 16
if (Build.VERSION.SDK_INT >= 16) architecture += "_pie"; if (SDK_INT >= 16) architecture += "_pie";
Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL, Backoff backoff = backoffFactory.createBackoff(MIN_POLLING_INTERVAL,
MAX_POLLING_INTERVAL, BACKOFF_BASE); MAX_POLLING_INTERVAL, BACKOFF_BASE);
......
...@@ -15,12 +15,13 @@ import java.util.logging.Logger; ...@@ -15,12 +15,13 @@ import java.util.logging.Logger;
import javax.inject.Inject; import javax.inject.Inject;
import static android.content.Context.TELEPHONY_SERVICE; import static android.content.Context.TELEPHONY_SERVICE;
import static java.util.logging.Logger.getLogger;
@NotNullByDefault @NotNullByDefault
class AndroidLocationUtils implements LocationUtils { class AndroidLocationUtils implements LocationUtils {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(AndroidLocationUtils.class.getName()); getLogger(AndroidLocationUtils.class.getName());
private final Context appContext; private final Context appContext;
...@@ -59,14 +60,14 @@ class AndroidLocationUtils implements LocationUtils { ...@@ -59,14 +60,14 @@ class AndroidLocationUtils implements LocationUtils {
} }
private String getCountryFromPhoneNetwork() { private String getCountryFromPhoneNetwork() {
Object o = appContext.getSystemService(TELEPHONY_SERVICE); TelephonyManager tm = (TelephonyManager)
TelephonyManager tm = (TelephonyManager) o; appContext.getSystemService(TELEPHONY_SERVICE);
return tm.getNetworkCountryIso(); return tm == null ? "" : tm.getNetworkCountryIso();
} }
private String getCountryFromSimCard() { private String getCountryFromSimCard() {
Object o = appContext.getSystemService(TELEPHONY_SERVICE); TelephonyManager tm = (TelephonyManager)
TelephonyManager tm = (TelephonyManager) o; appContext.getSystemService(TELEPHONY_SERVICE);
return tm.getSimCountryIso(); return tm == null ? "" : tm.getSimCountryIso();
} }
} }
...@@ -8,7 +8,6 @@ import android.content.ContentResolver; ...@@ -8,7 +8,6 @@ import android.content.ContentResolver;
import android.content.Context; import android.content.Context;
import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager; import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Parcel; import android.os.Parcel;
import android.os.StrictMode; import android.os.StrictMode;
import android.provider.Settings; import android.provider.Settings;
...@@ -23,6 +22,9 @@ import javax.annotation.concurrent.Immutable; ...@@ -23,6 +22,9 @@ import javax.annotation.concurrent.Immutable;
import javax.inject.Inject; import javax.inject.Inject;
import static android.content.Context.WIFI_SERVICE; import static android.content.Context.WIFI_SERVICE;
import static android.os.Build.FINGERPRINT;
import static android.os.Build.SERIAL;
import static android.os.Build.VERSION.SDK_INT;
import static android.provider.Settings.Secure.ANDROID_ID; import static android.provider.Settings.Secure.ANDROID_ID;
@Immutable @Immutable
...@@ -45,8 +47,8 @@ class AndroidSecureRandomProvider extends UnixSecureRandomProvider { ...@@ -45,8 +47,8 @@ class AndroidSecureRandomProvider extends UnixSecureRandomProvider {
out.writeInt(android.os.Process.myPid()); out.writeInt(android.os.Process.myPid());
out.writeInt(android.os.Process.myTid()); out.writeInt(android.os.Process.myTid());
out.writeInt(android.os.Process.myUid()); out.writeInt(android.os.Process.myUid());
if (Build.FINGERPRINT != null) out.writeUTF(Build.FINGERPRINT); if (FINGERPRINT != null) out.writeUTF(FINGERPRINT);
if (Build.SERIAL != null) out.writeUTF(Build.SERIAL); if (SERIAL != null) out.writeUTF(SERIAL);
ContentResolver contentResolver = appContext.getContentResolver(); ContentResolver contentResolver = appContext.getContentResolver();
String id = Settings.Secure.getString(contentResolver, ANDROID_ID); String id = Settings.Secure.getString(contentResolver, ANDROID_ID);
if (id != null) out.writeUTF(id); if (id != null) out.writeUTF(id);
...@@ -74,15 +76,13 @@ class AndroidSecureRandomProvider extends UnixSecureRandomProvider { ...@@ -74,15 +76,13 @@ class AndroidSecureRandomProvider extends UnixSecureRandomProvider {
// Silence strict mode // Silence strict mode
StrictMode.ThreadPolicy tp = StrictMode.allowThreadDiskWrites(); StrictMode.ThreadPolicy tp = StrictMode.allowThreadDiskWrites();
super.writeSeed(); super.writeSeed();
if (Build.VERSION.SDK_INT >= 16 && Build.VERSION.SDK_INT <= 18) if (SDK_INT >= 16 && SDK_INT <= 18) applyOpenSslFix();
applyOpenSslFix();
StrictMode.setThreadPolicy(tp); StrictMode.setThreadPolicy(tp);
} }
// Based on https://android-developers.googleblog.com/2013/08/some-securerandom-thoughts.html // Based on https://android-developers.googleblog.com/2013/08/some-securerandom-thoughts.html
private void applyOpenSslFix() { private void applyOpenSslFix() {
byte[] seed = new UnixSecureRandomSpi().engineGenerateSeed( byte[] seed = new UnixSecureRandomSpi().engineGenerateSeed(SEED_LENGTH);
SEED_LENGTH);
try { try {
// Seed the OpenSSL PRNG // Seed the OpenSSL PRNG
Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto") Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto")
......
...@@ -3,17 +3,20 @@ package org.briarproject.bramble.util; ...@@ -3,17 +3,20 @@ package org.briarproject.bramble.util;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothAdapter;
import android.content.Context; import android.content.Context;
import android.os.Build;
import android.provider.Settings; import android.provider.Settings;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import static android.content.Context.MODE_PRIVATE; import static android.content.Context.MODE_PRIVATE;
import static android.os.Build.CPU_ABI;
import static android.os.Build.CPU_ABI2;
import static android.os.Build.SUPPORTED_ABIS;
import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION.SDK_INT;
import static java.util.Arrays.asList;
import static org.briarproject.bramble.util.StringUtils.isNullOrEmpty;
public class AndroidUtils { public class AndroidUtils {
...@@ -22,14 +25,13 @@ public class AndroidUtils { ...@@ -22,14 +25,13 @@ public class AndroidUtils {
private static final String STORED_REPORTS = "dev-reports"; private static final String STORED_REPORTS = "dev-reports";
@SuppressWarnings("deprecation")
public static Collection<String> getSupportedArchitectures() { public static Collection<String> getSupportedArchitectures() {
List<String> abis = new ArrayList<>(); List<String> abis = new ArrayList<>();
if (SDK_INT >= 21) { if (SDK_INT >= 21) {
abis.addAll(Arrays.asList(Build.SUPPORTED_ABIS)); abis.addAll(asList(SUPPORTED_ABIS));
} else { } else {
abis.add(Build.CPU_ABI); abis.add(CPU_ABI);
if (Build.CPU_ABI2 != null) abis.add(Build.CPU_ABI2); if (CPU_ABI2 != null) abis.add(CPU_ABI2);
} }
return abis; return abis;
} }
...@@ -49,7 +51,7 @@ public class AndroidUtils { ...@@ -49,7 +51,7 @@ public class AndroidUtils {
} }
private static boolean isValidBluetoothAddress(String address) { private static boolean isValidBluetoothAddress(String address) {
return !StringUtils.isNullOrEmpty(address) return !isNullOrEmpty(address)
&& BluetoothAdapter.checkBluetoothAddress(address) && BluetoothAdapter.checkBluetoothAddress(address)
&& !address.equals(FAKE_BLUETOOTH_ADDRESS); && !address.equals(FAKE_BLUETOOTH_ADDRESS);
} }
......
...@@ -10,17 +10,19 @@ import java.util.concurrent.TimeUnit; ...@@ -10,17 +10,19 @@ import java.util.concurrent.TimeUnit;
import java.util.logging.Logger; import java.util.logging.Logger;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe; import javax.annotation.concurrent.ThreadSafe;
import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.logging.Level.INFO; import static java.util.logging.Level.INFO;
import static java.util.logging.Logger.getLogger;
@ThreadSafe @ThreadSafe
@NotNullByDefault @NotNullByDefault
public class RenewableWakeLock { public class RenewableWakeLock {
private static final Logger LOG = private static final Logger LOG =
Logger.getLogger(RenewableWakeLock.class.getName()); getLogger(RenewableWakeLock.class.getName());
/** /**
* Automatically release the lock this many milliseconds after it's due * Automatically release the lock this many milliseconds after it's due
...@@ -36,10 +38,12 @@ public class RenewableWakeLock { ...@@ -36,10 +38,12 @@ public class RenewableWakeLock {
private final Runnable renewTask; private final Runnable renewTask;
private final Object lock = new Object(); private final Object lock = new Object();
@GuardedBy("lock")
@Nullable @Nullable
private PowerManager.WakeLock wakeLock; // Locking: lock private PowerManager.WakeLock wakeLock;
@GuardedBy("lock")
@Nullable @Nullable
private ScheduledFuture future; // Locking: lock private ScheduledFuture future;
public RenewableWakeLock(PowerManager powerManager, public RenewableWakeLock(PowerManager powerManager,
ScheduledExecutorService scheduler, int levelAndFlags, String tag, ScheduledExecutorService scheduler, int levelAndFlags, String tag,
......
package org.briarproject.bramble.api; package org.briarproject.bramble.api;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.StringUtils;
import java.util.Arrays; import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import javax.annotation.concurrent.ThreadSafe; import javax.annotation.concurrent.ThreadSafe;
import static org.briarproject.bramble.util.StringUtils.toHexString;
/** /**
* A wrapper around a byte array, to allow it to be stored in maps etc. * A wrapper around a byte array, to allow it to be stored in maps etc.
*/ */
...@@ -56,8 +57,7 @@ public class Bytes implements Comparable<Bytes> { ...@@ -56,8 +57,7 @@ public class Bytes implements Comparable<Bytes> {
@Override @Override
public String toString() { public String toString() {
return getClass().getSimpleName() + return getClass().getSimpleName() + "(" + toHexString(getBytes()) + ")";
"(" + StringUtils.toHexString(getBytes()) + ")";
} }
public static class BytesComparator implements Comparator<Bytes> { public static class BytesComparator implements Comparator<Bytes> {
......
...@@ -2,7 +2,6 @@ package org.briarproject.bramble.api; ...@@ -2,7 +2,6 @@ package org.briarproject.bramble.api;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
...@@ -10,6 +9,8 @@ import java.util.Set; ...@@ -10,6 +9,8 @@ import java.util.Set;
import javax.annotation.concurrent.NotThreadSafe; import javax.annotation.concurrent.NotThreadSafe;
import static java.util.Collections.unmodifiableSet;
@NotThreadSafe @NotThreadSafe
@NotNullByDefault @NotNullByDefault
public class Multiset<T> { public class Multiset<T> {
...@@ -96,6 +97,6 @@ public class Multiset<T> { ...@@ -96,6 +97,6 @@ public class Multiset<T> {
* is unmodifiable. * is unmodifiable.
*/ */
public Set<T> keySet() { public Set<T> keySet() {
return Collections.unmodifiableSet(map.keySet()); return unmodifiableSet(map.keySet());
} }
} }
...@@ -5,10 +5,11 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault; ...@@ -5,10 +5,11 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.api.sync.MessageId; import org.briarproject.bramble.api.sync.MessageId;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
import static java.util.Collections.emptyList;
@Immutable @Immutable
@NotNullByDefault @NotNullByDefault
public class BdfMessageContext { public class BdfMessageContext {
...@@ -23,7 +24,7 @@ public class BdfMessageContext { ...@@ -23,7 +24,7 @@ public class BdfMessageContext {
} }
public BdfMessageContext(BdfDictionary dictionary) { public BdfMessageContext(BdfDictionary dictionary) {
this(dictionary, Collections.emptyList()); this(dictionary, emptyList());
} }
public BdfDictionary getDictionary() { public BdfDictionary getDictionary() {
......
...@@ -16,6 +16,7 @@ import java.util.logging.Logger; ...@@ -16,6 +16,7 @@ import java.util.logging.Logger;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.api.transport.TransportConstants.MAX_CLOCK_DIFFERENCE; import static org.briarproject.bramble.api.transport.TransportConstants.MAX_CLOCK_DIFFERENCE;
@Immutable @Immutable
...@@ -23,7 +24,7 @@ import static org.briarproject.bramble.api.transport.TransportConstants.MAX_CLOC ...@@ -23,7 +24,7 @@ import static org.briarproject.bramble.api.transport.TransportConstants.MAX_CLOC
public abstract class BdfMessageValidator implements MessageValidator { public abstract class BdfMessageValidator implements MessageValidator {
protected static final Logger LOG = protected static final Logger LOG =
Logger.getLogger(BdfMessageValidator.class.getName()); getLogger(BdfMessageValidator.class.getName());
protected final ClientHelper clientHelper; protected final ClientHelper clientHelper;
protected final MetadataEncoder metadataEncoder; protected final MetadataEncoder metadataEncoder;
......
...@@ -4,7 +4,6 @@ import org.briarproject.bramble.api.Bytes; ...@@ -4,7 +4,6 @@ import org.briarproject.bramble.api.Bytes;
import org.briarproject.bramble.api.FormatException; import org.briarproject.bramble.api.FormatException;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap; import java.util.TreeMap;
import javax.annotation.Nullable; import javax.annotation.Nullable;
...@@ -24,9 +23,9 @@ public class BdfDictionary extends TreeMap<String, Object> { ...@@ -24,9 +23,9 @@ public class BdfDictionary extends TreeMap<String, Object> {
* ); * );
* </pre> * </pre>
*/ */
public static BdfDictionary of(Entry<String, ?>... entries) { public static BdfDictionary of(BdfEntry... entries) {
BdfDictionary d = new BdfDictionary(); 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; return d;
} }
......
...@@ -4,12 +4,12 @@ import org.briarproject.bramble.api.Bytes; ...@@ -4,12 +4,12 @@ import org.briarproject.bramble.api.Bytes;
import org.briarproject.bramble.api.FormatException; import org.briarproject.bramble.api.FormatException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe; import javax.annotation.concurrent.NotThreadSafe;
import static java.util.Arrays.asList;
import static org.briarproject.bramble.api.data.BdfDictionary.NULL_VALUE; import static org.briarproject.bramble.api.data.BdfDictionary.NULL_VALUE;
@NotThreadSafe @NotThreadSafe
...@@ -22,7 +22,7 @@ public class BdfList extends ArrayList<Object> { ...@@ -22,7 +22,7 @@ public class BdfList extends ArrayList<Object> {
* </pre> * </pre>
*/ */
public static BdfList of(Object... items) { public static BdfList of(Object... items) {
return new BdfList(Arrays.asList(items)); return new BdfList(asList(items));
} }
public BdfList() { public BdfList() {
...@@ -33,6 +33,7 @@ public class BdfList extends ArrayList<Object> { ...@@ -33,6 +33,7 @@ public class BdfList extends ArrayList<Object> {
super(items); super(items);
} }
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean isInRange(int index) { private boolean isInRange(int index) {
return index >= 0 && index < size(); return index >= 0 && index < size();
} }
......
...@@ -3,11 +3,12 @@ package org.briarproject.bramble.api.db; ...@@ -3,11 +3,12 @@ package org.briarproject.bramble.api.db;
import org.briarproject.bramble.api.event.Event; import org.briarproject.bramble.api.event.Event;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import javax.annotation.concurrent.NotThreadSafe; import javax.annotation.concurrent.NotThreadSafe;
import static java.util.Collections.emptyList;
/** /**
* A wrapper around a database transaction. Transactions are not thread-safe. * A wrapper around a database transaction. Transactions are not thread-safe.
*/ */
...@@ -53,7 +54,7 @@ public class Transaction { ...@@ -53,7 +54,7 @@ public class Transaction {
* Returns any events attached to the transaction. * Returns any events attached to the transaction.
*/ */
public List<Event> getEvents() { public List<Event> getEvents() {
if (events == null) return Collections.emptyList(); if (events == null) return emptyList();
return events; return events;
} }
......
...@@ -2,12 +2,12 @@ package org.briarproject.bramble.api.identity; ...@@ -2,12 +2,12 @@ package org.briarproject.bramble.api.identity;
import org.briarproject.bramble.api.Nameable; import org.briarproject.bramble.api.Nameable;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.StringUtils;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_AUTHOR_NAME_LENGTH; import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_AUTHOR_NAME_LENGTH;
import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_PUBLIC_KEY_LENGTH; import static org.briarproject.bramble.api.identity.AuthorConstants.MAX_PUBLIC_KEY_LENGTH;
import static org.briarproject.bramble.util.StringUtils.toUtf8;
/** /**
* A pseudonym for a user. * A pseudonym for a user.
...@@ -28,7 +28,7 @@ public class Author implements Nameable { ...@@ -28,7 +28,7 @@ public class Author implements Nameable {
public Author(AuthorId id, int formatVersion, String name, public Author(AuthorId id, int formatVersion, String name,
byte[] publicKey) { byte[] publicKey) {
int nameLength = StringUtils.toUtf8(name).length; int nameLength = toUtf8(name).length;
if (nameLength == 0 || nameLength > MAX_AUTHOR_NAME_LENGTH) if (nameLength == 0 || nameLength > MAX_AUTHOR_NAME_LENGTH)
throw new IllegalArgumentException(); throw new IllegalArgumentException();
if (publicKey.length == 0 || publicKey.length > MAX_PUBLIC_KEY_LENGTH) if (publicKey.length == 0 || publicKey.length > MAX_PUBLIC_KEY_LENGTH)
......
package org.briarproject.bramble.api.plugin; package org.briarproject.bramble.api.plugin;
import org.briarproject.bramble.util.StringUtils; import static org.briarproject.bramble.util.StringUtils.toUtf8;
/** /**
* Type-safe wrapper for a namespaced string that uniquely identifies a * Type-safe wrapper for a namespaced string that uniquely identifies a
...@@ -11,12 +11,12 @@ public class TransportId { ...@@ -11,12 +11,12 @@ public class TransportId {
/** /**
* The maximum length of a transport identifier in UTF-8 bytes. * 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; private final String id;
public TransportId(String id) { public TransportId(String id) {
int length = StringUtils.toUtf8(id).length; int length = toUtf8(id).length;
if (length == 0 || length > MAX_TRANSPORT_ID_LENGTH) if (length == 0 || length > MAX_TRANSPORT_ID_LENGTH)
throw new IllegalArgumentException(); throw new IllegalArgumentException();
this.id = id; this.id = id;
......
package org.briarproject.bramble.api.sync; package org.briarproject.bramble.api.sync;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import org.briarproject.bramble.util.StringUtils;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
import static org.briarproject.bramble.util.StringUtils.toUtf8;
/** /**
* Type-safe wrapper for a namespaced string that uniquely identifies a sync * Type-safe wrapper for a namespaced string that uniquely identifies a sync
* client. * client.
...@@ -16,12 +17,12 @@ public class ClientId implements Comparable<ClientId> { ...@@ -16,12 +17,12 @@ public class ClientId implements Comparable<ClientId> {
/** /**
* The maximum length of a client identifier in UTF-8 bytes. * 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; private final String id;
public ClientId(String id) { public ClientId(String id) {
int length = StringUtils.toUtf8(id).length; int length = toUtf8(id).length;
if (length == 0 || length > MAX_CLIENT_ID_LENGTH) if (length == 0 || length > MAX_CLIENT_ID_LENGTH)
throw new IllegalArgumentException(); throw new IllegalArgumentException();
this.id = id; this.id = id;
......
...@@ -4,10 +4,11 @@ import org.briarproject.bramble.api.db.Metadata; ...@@ -4,10 +4,11 @@ import org.briarproject.bramble.api.db.Metadata;
import org.briarproject.bramble.api.nullsafety.NotNullByDefault; import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.Immutable;
import static java.util.Collections.emptyList;
@Immutable @Immutable
@NotNullByDefault @NotNullByDefault
public class MessageContext { public class MessageContext {
...@@ -22,7 +23,7 @@ public class MessageContext { ...@@ -22,7 +23,7 @@ public class MessageContext {
} }
public MessageContext(Metadata metadata) { public MessageContext(Metadata metadata) {
this(metadata, Collections.emptyList()); this(metadata, emptyList());
} }
public Metadata getMetadata() { public Metadata getMetadata() {
......
...@@ -16,12 +16,13 @@ import java.util.logging.Logger; ...@@ -16,12 +16,13 @@ import java.util.logging.Logger;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import static java.util.logging.Level.WARNING; import static java.util.logging.Level.WARNING;
import static java.util.logging.Logger.getLogger;
import static org.briarproject.bramble.util.LogUtils.logException; import static org.briarproject.bramble.util.LogUtils.logException;
@NotNullByDefault @NotNullByDefault
public class IoUtils { public class IoUtils {
private static final Logger LOG = Logger.getLogger(IoUtils.class.getName()); private static final Logger LOG = getLogger(IoUtils.class.getName());
public static void deleteFileOrDir(File f) { public static void deleteFileOrDir(File f) {
if (f.isFile()) { if (f.isFile()) {
......
...@@ -7,13 +7,15 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault; ...@@ -7,13 +7,15 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import static org.briarproject.bramble.util.StringUtils.toUtf8;
@NotNullByDefault @NotNullByDefault
public class ValidationUtils { public class ValidationUtils {
public static void checkLength(@Nullable String s, int minLength, public static void checkLength(@Nullable String s, int minLength,
int maxLength) throws FormatException { int maxLength) throws FormatException {
if (s != null) { if (s != null) {
int length = StringUtils.toUtf8(s).length; int length = toUtf8(s).length;
if (length < minLength) throw new FormatException(); if (length < minLength) throw new FormatException();
if (length > maxLength) throw new FormatException(); if (length > maxLength) throw new FormatException();
} }
...@@ -21,7 +23,7 @@ public class ValidationUtils { ...@@ -21,7 +23,7 @@ public class ValidationUtils {
public static void checkLength(@Nullable String s, int length) public static void checkLength(@Nullable String s, int length)
throws FormatException { throws FormatException {
if (s != null && StringUtils.toUtf8(s).length != length) if (s != null && toUtf8(s).length != length)
throw new FormatException(); throw new FormatException();
} }
......
...@@ -8,6 +8,7 @@ import java.util.Collections; ...@@ -8,6 +8,7 @@ import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map.Entry; import java.util.Map.Entry;
import static java.util.Collections.singletonMap;
import static org.briarproject.bramble.api.data.BdfDictionary.NULL_VALUE; import static org.briarproject.bramble.api.data.BdfDictionary.NULL_VALUE;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
...@@ -19,15 +20,15 @@ public class BdfDictionaryTest extends BrambleTestCase { ...@@ -19,15 +20,15 @@ public class BdfDictionaryTest extends BrambleTestCase {
public void testConstructors() { public void testConstructors() {
assertEquals(Collections.<String, Object>emptyMap(), assertEquals(Collections.<String, Object>emptyMap(),
new BdfDictionary()); new BdfDictionary());
assertEquals(Collections.singletonMap("foo", NULL_VALUE), assertEquals(singletonMap("foo", NULL_VALUE),
new BdfDictionary(Collections.singletonMap("foo", NULL_VALUE))); new BdfDictionary(singletonMap("foo", NULL_VALUE)));
} }
@Test @Test
public void testFactoryMethod() { public void testFactoryMethod() {
assertEquals(Collections.<String, Object>emptyMap(), assertEquals(Collections.<String, Object>emptyMap(),
BdfDictionary.of()); BdfDictionary.of());
assertEquals(Collections.singletonMap("foo", NULL_VALUE), assertEquals(singletonMap("foo", NULL_VALUE),
BdfDictionary.of(new BdfEntry("foo", NULL_VALUE))); BdfDictionary.of(new BdfEntry("foo", NULL_VALUE)));
} }
...@@ -67,7 +68,7 @@ public class BdfDictionaryTest extends BrambleTestCase { ...@@ -67,7 +68,7 @@ public class BdfDictionaryTest extends BrambleTestCase {
} }
@Test @Test
public void testKeySetIteratorIsOrderedByKeys() throws Exception { public void testKeySetIteratorIsOrderedByKeys() {
BdfDictionary d = new BdfDictionary(); BdfDictionary d = new BdfDictionary();
d.put("a", 1); d.put("a", 1);
d.put("d", 4); d.put("d", 4);
...@@ -86,7 +87,7 @@ public class BdfDictionaryTest extends BrambleTestCase { ...@@ -86,7 +87,7 @@ public class BdfDictionaryTest extends BrambleTestCase {
} }
@Test @Test
public void testValuesIteratorIsOrderedByKeys() throws Exception { public void testValuesIteratorIsOrderedByKeys() {
BdfDictionary d = new BdfDictionary(); BdfDictionary d = new BdfDictionary();
d.put("a", 1); d.put("a", 1);
d.put("d", 4); d.put("d", 4);
...@@ -105,7 +106,7 @@ public class BdfDictionaryTest extends BrambleTestCase { ...@@ -105,7 +106,7 @@ public class BdfDictionaryTest extends BrambleTestCase {
} }
@Test @Test
public void testEntrySetIteratorIsOrderedByKeys() throws Exception { public void testEntrySetIteratorIsOrderedByKeys() {
BdfDictionary d = new BdfDictionary(); BdfDictionary d = new BdfDictionary();
d.put("a", 1); d.put("a", 1);
d.put("d", 4); d.put("d", 4);
......
...@@ -5,26 +5,31 @@ import org.briarproject.bramble.api.FormatException; ...@@ -5,26 +5,31 @@ import org.briarproject.bramble.api.FormatException;
import org.briarproject.bramble.test.BrambleTestCase; import org.briarproject.bramble.test.BrambleTestCase;
import org.junit.Test; import org.junit.Test;
import java.util.Arrays; import java.util.Random;
import java.util.Collections;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.briarproject.bramble.api.data.BdfDictionary.NULL_VALUE; import static org.briarproject.bramble.api.data.BdfDictionary.NULL_VALUE;
import static org.briarproject.bramble.test.TestUtils.getRandomBytes;
import static org.briarproject.bramble.util.StringUtils.getRandomString;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
public class BdfListTest extends BrambleTestCase { public class BdfListTest extends BrambleTestCase {
private final Random random = new Random();
@Test @Test
public void testConstructors() { public void testConstructors() {
assertEquals(Collections.emptyList(), new BdfList()); assertEquals(emptyList(), new BdfList());
assertEquals(Arrays.asList(1, 2, NULL_VALUE), assertEquals(asList(1, 2, NULL_VALUE),
new BdfList(Arrays.asList(1, 2, NULL_VALUE))); new BdfList(asList(1, 2, NULL_VALUE)));
} }
@Test @Test
public void testFactoryMethod() { public void testFactoryMethod() {
assertEquals(Collections.emptyList(), BdfList.of()); assertEquals(emptyList(), BdfList.of());
assertEquals(Arrays.asList(1, 2, NULL_VALUE), assertEquals(asList(1, 2, NULL_VALUE),
BdfList.of(1, 2, NULL_VALUE)); BdfList.of(1, 2, NULL_VALUE));
} }
...@@ -64,22 +69,21 @@ public class BdfListTest extends BrambleTestCase { ...@@ -64,22 +69,21 @@ public class BdfListTest extends BrambleTestCase {
} }
@Test @Test
@SuppressWarnings("ConstantConditions") public void testIndexOutOfBoundsReturnsDefaultValue() {
public void testIndexOutOfBoundsReturnsDefaultValue() throws Exception {
BdfList list = BdfList.of(1, 2, 3); BdfList list = BdfList.of(1, 2, 3);
boolean defaultBoolean = true; boolean defaultBoolean = random.nextBoolean();
assertEquals(defaultBoolean, list.getBoolean(-1, defaultBoolean)); assertEquals(defaultBoolean, list.getBoolean(-1, defaultBoolean));
assertEquals(defaultBoolean, list.getBoolean(3, defaultBoolean)); assertEquals(defaultBoolean, list.getBoolean(3, defaultBoolean));
Long defaultLong = 123L; Long defaultLong = random.nextLong();
assertEquals(defaultLong, list.getLong(-1, defaultLong)); assertEquals(defaultLong, list.getLong(-1, defaultLong));
assertEquals(defaultLong, list.getLong(3, defaultLong)); assertEquals(defaultLong, list.getLong(3, defaultLong));
Double defaultDouble = 1.23; Double defaultDouble = random.nextDouble();
assertEquals(defaultDouble, list.getDouble(-1, defaultDouble)); assertEquals(defaultDouble, list.getDouble(-1, defaultDouble));
assertEquals(defaultDouble, list.getDouble(3, defaultDouble)); assertEquals(defaultDouble, list.getDouble(3, defaultDouble));
String defaultString = "123"; String defaultString = getRandomString(123);
assertEquals(defaultString, list.getString(-1, defaultString)); assertEquals(defaultString, list.getString(-1, defaultString));
assertEquals(defaultString, list.getString(3, defaultString)); assertEquals(defaultString, list.getString(3, defaultString));
byte[] defaultBytes = new byte[] {1, 2, 3}; byte[] defaultBytes = getRandomBytes(123);
assertArrayEquals(defaultBytes, list.getRaw(-1, defaultBytes)); assertArrayEquals(defaultBytes, list.getRaw(-1, defaultBytes));
assertArrayEquals(defaultBytes, list.getRaw(3, defaultBytes)); assertArrayEquals(defaultBytes, list.getRaw(3, defaultBytes));
BdfList defaultList = BdfList.of(1, 2, 3); BdfList defaultList = BdfList.of(1, 2, 3);
...@@ -95,18 +99,17 @@ public class BdfListTest extends BrambleTestCase { ...@@ -95,18 +99,17 @@ public class BdfListTest extends BrambleTestCase {
}