Merge branch 'checkstyle-more' into 'master'

Checkstyle: require braces, consistent constant names



See merge request !207
This commit is contained in:
Peter Serwylo 2016-02-21 01:40:03 +00:00
commit 1bae2b0132
45 changed files with 397 additions and 257 deletions

View File

@ -468,13 +468,14 @@ public class AppDetails extends AppCompatActivity implements ProgressListener, A
new IntentFilter(Downloader.LOCAL_ACTION_PROGRESS)); new IntentFilter(Downloader.LOCAL_ACTION_PROGRESS));
downloadHandler.setProgressListener(this); downloadHandler.setProgressListener(this);
if (downloadHandler.getTotalBytes() == 0) if (downloadHandler.getTotalBytes() == 0) {
mHeaderFragment.startProgress(); mHeaderFragment.startProgress();
else } else {
mHeaderFragment.updateProgress(downloadHandler.getBytesRead(), downloadHandler.getTotalBytes()); mHeaderFragment.updateProgress(downloadHandler.getBytesRead(), downloadHandler.getTotalBytes());
} }
} }
} }
}
/** /**
* Remove progress listener, suppress progress bar, set downloadHandler to null. * Remove progress listener, suppress progress bar, set downloadHandler to null.
@ -523,10 +524,11 @@ public class AppDetails extends AppCompatActivity implements ProgressListener, A
private final BroadcastReceiver downloaderProgressReceiver = new BroadcastReceiver() { private final BroadcastReceiver downloaderProgressReceiver = new BroadcastReceiver() {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
if (mHeaderFragment != null) if (mHeaderFragment != null) {
mHeaderFragment.updateProgress(intent.getIntExtra(Downloader.EXTRA_BYTES_READ, -1), mHeaderFragment.updateProgress(intent.getIntExtra(Downloader.EXTRA_BYTES_READ, -1),
intent.getIntExtra(Downloader.EXTRA_TOTAL_BYTES, -1)); intent.getIntExtra(Downloader.EXTRA_TOTAL_BYTES, -1));
} }
}
}; };
private void onAppChanged() { private void onAppChanged() {
@ -618,8 +620,9 @@ public class AppDetails extends AppCompatActivity implements ProgressListener, A
public boolean onPrepareOptionsMenu(Menu menu) { public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu); super.onPrepareOptionsMenu(menu);
menu.clear(); menu.clear();
if (app == null) if (app == null) {
return true; return true;
}
if (mPm.getLaunchIntentForPackage(app.packageName) != null && app.canAndWantToUpdate()) { if (mPm.getLaunchIntentForPackage(app.packageName) != null && app.canAndWantToUpdate()) {
MenuItemCompat.setShowAsAction(menu.add( MenuItemCompat.setShowAsAction(menu.add(
@ -773,10 +776,11 @@ public class AppDetails extends AppCompatActivity implements ProgressListener, A
return true; return true;
case IGNORETHIS: case IGNORETHIS:
if (app.ignoreThisUpdate >= app.suggestedVercode) if (app.ignoreThisUpdate >= app.suggestedVercode) {
app.ignoreThisUpdate = 0; app.ignoreThisUpdate = 0;
else } else {
app.ignoreThisUpdate = app.suggestedVercode; app.ignoreThisUpdate = app.suggestedVercode;
}
item.setChecked(app.ignoreThisUpdate > 0); item.setChecked(app.ignoreThisUpdate > 0);
return true; return true;
@ -803,8 +807,9 @@ public class AppDetails extends AppCompatActivity implements ProgressListener, A
} }
// Ignore call if another download is running. // Ignore call if another download is running.
if (downloadHandler != null && !downloadHandler.isComplete()) if (downloadHandler != null && !downloadHandler.isComplete()) {
return; return;
}
final String repoaddress = getRepoAddress(apk); final String repoaddress = getRepoAddress(apk);
if (repoaddress == null) return; if (repoaddress == null) return;
@ -988,10 +993,11 @@ public class AppDetails extends AppCompatActivity implements ProgressListener, A
switch (event.type) { switch (event.type) {
case ApkDownloader.EVENT_ERROR: case ApkDownloader.EVENT_ERROR:
final int res; final int res;
if (event.getData().getInt(ApkDownloader.EVENT_DATA_ERROR_TYPE) == ApkDownloader.ERROR_HASH_MISMATCH) if (event.getData().getInt(ApkDownloader.EVENT_DATA_ERROR_TYPE) == ApkDownloader.ERROR_HASH_MISMATCH) {
res = R.string.corrupt_download; res = R.string.corrupt_download;
else } else {
res = R.string.details_notinstalled; res = R.string.details_notinstalled;
}
// this must be on the main UI thread // this must be on the main UI thread
Toast.makeText(this, res, Toast.LENGTH_LONG).show(); Toast.makeText(this, res, Toast.LENGTH_LONG).show();
cleanUpFinishedDownload(); cleanUpFinishedDownload();
@ -1004,8 +1010,9 @@ public class AppDetails extends AppCompatActivity implements ProgressListener, A
} }
if (finished) { if (finished) {
if (mHeaderFragment != null) if (mHeaderFragment != null) {
mHeaderFragment.removeProgress(); mHeaderFragment.removeProgress();
}
downloadHandler = null; downloadHandler = null;
} }
} }
@ -1215,10 +1222,11 @@ public class AppDetails extends AppCompatActivity implements ProgressListener, A
// App ID // App ID
final TextView packageNameView = (TextView) view.findViewById(R.id.package_name); final TextView packageNameView = (TextView) view.findViewById(R.id.package_name);
if (prefs.expertMode()) if (prefs.expertMode()) {
packageNameView.setText(app.packageName); packageNameView.setText(app.packageName);
else } else {
packageNameView.setVisibility(View.GONE); packageNameView.setVisibility(View.GONE);
}
// Summary // Summary
final TextView summaryView = (TextView) view.findViewById(R.id.summary); final TextView summaryView = (TextView) view.findViewById(R.id.summary);
@ -1232,73 +1240,83 @@ public class AppDetails extends AppCompatActivity implements ProgressListener, A
// Website button // Website button
View tv = view.findViewById(R.id.website); View tv = view.findViewById(R.id.website);
if (!TextUtils.isEmpty(app.webURL)) if (!TextUtils.isEmpty(app.webURL)) {
tv.setOnClickListener(mOnClickListener); tv.setOnClickListener(mOnClickListener);
else } else {
tv.setVisibility(View.GONE); tv.setVisibility(View.GONE);
}
// Email button // Email button
tv = view.findViewById(R.id.email); tv = view.findViewById(R.id.email);
if (!TextUtils.isEmpty(app.email)) if (!TextUtils.isEmpty(app.email)) {
tv.setOnClickListener(mOnClickListener); tv.setOnClickListener(mOnClickListener);
else } else {
tv.setVisibility(View.GONE); tv.setVisibility(View.GONE);
}
// Source button // Source button
tv = view.findViewById(R.id.source); tv = view.findViewById(R.id.source);
if (!TextUtils.isEmpty(app.sourceURL)) if (!TextUtils.isEmpty(app.sourceURL)) {
tv.setOnClickListener(mOnClickListener); tv.setOnClickListener(mOnClickListener);
else } else {
tv.setVisibility(View.GONE); tv.setVisibility(View.GONE);
}
// Issues button // Issues button
tv = view.findViewById(R.id.issues); tv = view.findViewById(R.id.issues);
if (!TextUtils.isEmpty(app.trackerURL)) if (!TextUtils.isEmpty(app.trackerURL)) {
tv.setOnClickListener(mOnClickListener); tv.setOnClickListener(mOnClickListener);
else } else {
tv.setVisibility(View.GONE); tv.setVisibility(View.GONE);
}
// Changelog button // Changelog button
tv = view.findViewById(R.id.changelog); tv = view.findViewById(R.id.changelog);
if (!TextUtils.isEmpty(app.changelogURL)) if (!TextUtils.isEmpty(app.changelogURL)) {
tv.setOnClickListener(mOnClickListener); tv.setOnClickListener(mOnClickListener);
else } else {
tv.setVisibility(View.GONE); tv.setVisibility(View.GONE);
}
// Donate button // Donate button
tv = view.findViewById(R.id.donate); tv = view.findViewById(R.id.donate);
if (!TextUtils.isEmpty(app.donateURL)) if (!TextUtils.isEmpty(app.donateURL)) {
tv.setOnClickListener(mOnClickListener); tv.setOnClickListener(mOnClickListener);
else } else {
tv.setVisibility(View.GONE); tv.setVisibility(View.GONE);
}
// Bitcoin // Bitcoin
tv = view.findViewById(R.id.bitcoin); tv = view.findViewById(R.id.bitcoin);
if (!TextUtils.isEmpty(app.bitcoinAddr)) if (!TextUtils.isEmpty(app.bitcoinAddr)) {
tv.setOnClickListener(mOnClickListener); tv.setOnClickListener(mOnClickListener);
else } else {
tv.setVisibility(View.GONE); tv.setVisibility(View.GONE);
}
// Litecoin // Litecoin
tv = view.findViewById(R.id.litecoin); tv = view.findViewById(R.id.litecoin);
if (!TextUtils.isEmpty(app.litecoinAddr)) if (!TextUtils.isEmpty(app.litecoinAddr)) {
tv.setOnClickListener(mOnClickListener); tv.setOnClickListener(mOnClickListener);
else } else {
tv.setVisibility(View.GONE); tv.setVisibility(View.GONE);
}
// Flattr // Flattr
tv = view.findViewById(R.id.flattr); tv = view.findViewById(R.id.flattr);
if (!TextUtils.isEmpty(app.flattrID)) if (!TextUtils.isEmpty(app.flattrID)) {
tv.setOnClickListener(mOnClickListener); tv.setOnClickListener(mOnClickListener);
else } else {
tv.setVisibility(View.GONE); tv.setVisibility(View.GONE);
}
// Categories TextView // Categories TextView
final TextView categories = (TextView) view.findViewById(R.id.categories); final TextView categories = (TextView) view.findViewById(R.id.categories);
if (prefs.expertMode() && app.categories != null) if (prefs.expertMode() && app.categories != null) {
categories.setText(app.categories.toString().replaceAll(",", ", ")); categories.setText(app.categories.toString().replaceAll(",", ", "));
else } else {
categories.setVisibility(View.GONE); categories.setVisibility(View.GONE);
}
Apk curApk = null; Apk curApk = null;
for (int i = 0; i < getApks().getCount(); i++) { for (int i = 0; i < getApks().getCount(); i++) {
@ -1544,8 +1562,9 @@ public class AppDetails extends AppCompatActivity implements ProgressListener, A
@Override @Override
public void onClick(View view) { public void onClick(View view) {
AppDetails activity = (AppDetails) getActivity(); AppDetails activity = (AppDetails) getActivity();
if (activity == null || activity.downloadHandler == null) if (activity == null || activity.downloadHandler == null) {
return; return;
}
activity.downloadHandler.cancel(true); activity.downloadHandler.cancel(true);
activity.cleanUpFinishedDownload(); activity.cleanUpFinishedDownload();

View File

@ -59,10 +59,11 @@ public class CompatibilityChecker extends Compatibility {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
boolean first = true; boolean first = true;
for (final String abi : cpuAbis) { for (final String abi : cpuAbis) {
if (first) if (first) {
first = false; first = false;
else } else {
builder.append(", "); builder.append(", ");
}
builder.append(abi); builder.append(abi);
} }
cpuAbisDesc = builder.toString(); cpuAbisDesc = builder.toString();

View File

@ -232,13 +232,15 @@ public class FDroid extends AppCompatActivity implements SearchView.OnQueryTextL
if (!TextUtils.isEmpty(query)) { if (!TextUtils.isEmpty(query)) {
// an old format for querying via packageName // an old format for querying via packageName
if (query.startsWith("pname:")) if (query.startsWith("pname:")) {
packageName = query.split(":")[1]; packageName = query.split(":")[1];
}
// sometimes, search URLs include pub: or other things before the query string // sometimes, search URLs include pub: or other things before the query string
if (query.contains(":")) if (query.contains(":")) {
query = query.split(":")[1]; query = query.split(":")[1];
} }
}
if (!TextUtils.isEmpty(packageName)) { if (!TextUtils.isEmpty(packageName)) {
Utils.debugLog(TAG, "FDroid launched via app link for '" + packageName + "'"); Utils.debugLog(TAG, "FDroid launched via app link for '" + packageName + "'");

View File

@ -81,16 +81,16 @@ public class FDroidApp extends Application {
public static SubnetUtils.SubnetInfo subnetInfo; public static SubnetUtils.SubnetInfo subnetInfo;
public static String ssid; public static String ssid;
public static String bssid; public static String bssid;
public static final Repo repo = new Repo(); public static final Repo REPO = new Repo();
// Leaving the fully qualified class name here to help clarify the difference between spongy/bouncy castle. // Leaving the fully qualified class name here to help clarify the difference between spongy/bouncy castle.
private static final org.spongycastle.jce.provider.BouncyCastleProvider spongyCastleProvider; private static final org.spongycastle.jce.provider.BouncyCastleProvider SPONGYCASTLE_PROVIDER;
@SuppressWarnings("unused") @SuppressWarnings("unused")
BluetoothAdapter bluetoothAdapter; BluetoothAdapter bluetoothAdapter;
static { static {
spongyCastleProvider = new org.spongycastle.jce.provider.BouncyCastleProvider(); SPONGYCASTLE_PROVIDER = new org.spongycastle.jce.provider.BouncyCastleProvider();
enableSpongyCastle(); enableSpongyCastle();
} }
@ -127,18 +127,18 @@ public class FDroidApp extends Application {
} }
public static void enableSpongyCastle() { public static void enableSpongyCastle() {
Security.addProvider(spongyCastleProvider); Security.addProvider(SPONGYCASTLE_PROVIDER);
} }
public static void enableSpongyCastleOnLollipop() { public static void enableSpongyCastleOnLollipop() {
if (Build.VERSION.SDK_INT == 21) { if (Build.VERSION.SDK_INT == 21) {
Security.addProvider(spongyCastleProvider); Security.addProvider(SPONGYCASTLE_PROVIDER);
} }
} }
public static void disableSpongyCastleOnLollipop() { public static void disableSpongyCastleOnLollipop() {
if (Build.VERSION.SDK_INT == 21) { if (Build.VERSION.SDK_INT == 21) {
Security.removeProvider(spongyCastleProvider.getName()); Security.removeProvider(SPONGYCASTLE_PROVIDER.getName());
} }
} }
@ -309,8 +309,9 @@ public class FDroidApp extends Application {
} }
public void sendViaBluetooth(Activity activity, int resultCode, String packageName) { public void sendViaBluetooth(Activity activity, int resultCode, String packageName) {
if (resultCode == Activity.RESULT_CANCELED) if (resultCode == Activity.RESULT_CANCELED) {
return; return;
}
String bluetoothPackageName = null; String bluetoothPackageName = null;
String className = null; String className = null;
boolean found = false; boolean found = false;

View File

@ -124,14 +124,15 @@ public class Hasher {
for (int i = 0; i < data.length(); i++) { for (int i = 0; i < data.length(); i++) {
char halfbyte = data.charAt(i); char halfbyte = data.charAt(i);
int value; int value;
if ('0' <= halfbyte && halfbyte <= '9') if ('0' <= halfbyte && halfbyte <= '9') {
value = halfbyte - '0'; value = halfbyte - '0';
else if ('a' <= halfbyte && halfbyte <= 'f') } else if ('a' <= halfbyte && halfbyte <= 'f') {
value = halfbyte - 'a' + 10; value = halfbyte - 'a' + 10;
else if ('A' <= halfbyte && halfbyte <= 'F') } else if ('A' <= halfbyte && halfbyte <= 'F') {
value = halfbyte - 'A' + 10; value = halfbyte - 'A' + 10;
else } else {
throw new IllegalArgumentException("Bad hex digit"); throw new IllegalArgumentException("Bad hex digit");
}
rawdata[i / 2] += (byte) (i % 2 == 0 ? value << 4 : value); rawdata[i / 2] += (byte) (i % 2 == 0 ? value << 4 : value);
} }
return rawdata; return rawdata;

View File

@ -18,8 +18,9 @@ public class NfcHelper {
@TargetApi(14) @TargetApi(14)
private static NfcAdapter getAdapter(Context context) { private static NfcAdapter getAdapter(Context context) {
if (Build.VERSION.SDK_INT < 14) if (Build.VERSION.SDK_INT < 14) {
return null; return null;
}
return NfcAdapter.getDefaultAdapter(context.getApplicationContext()); return NfcAdapter.getDefaultAdapter(context.getApplicationContext());
} }
@ -38,8 +39,9 @@ public class NfcHelper {
@TargetApi(16) @TargetApi(16)
static void setAndroidBeam(Activity activity, String packageName) { static void setAndroidBeam(Activity activity, String packageName) {
if (Build.VERSION.SDK_INT < 16) if (Build.VERSION.SDK_INT < 16) {
return; return;
}
PackageManager pm = activity.getPackageManager(); PackageManager pm = activity.getPackageManager();
NfcAdapter nfcAdapter = getAdapter(activity); NfcAdapter nfcAdapter = getAdapter(activity);
if (nfcAdapter != null) { if (nfcAdapter != null) {
@ -58,11 +60,13 @@ public class NfcHelper {
@TargetApi(16) @TargetApi(16)
static void disableAndroidBeam(Activity activity) { static void disableAndroidBeam(Activity activity) {
if (Build.VERSION.SDK_INT < 16) if (Build.VERSION.SDK_INT < 16) {
return; return;
}
NfcAdapter nfcAdapter = getAdapter(activity); NfcAdapter nfcAdapter = getAdapter(activity);
if (nfcAdapter != null) if (nfcAdapter != null) {
nfcAdapter.setBeamPushUris(null, activity); nfcAdapter.setBeamPushUris(null, activity);
} }
}
} }

View File

@ -24,11 +24,12 @@ public class NfcNotEnabledActivity extends ActionBarActivity {
if (nfcAdapter == null) { if (nfcAdapter == null) {
return; return;
} }
if (nfcAdapter.isEnabled()) if (nfcAdapter.isEnabled()) {
intent.setAction(Settings.ACTION_NFCSHARING_SETTINGS); intent.setAction(Settings.ACTION_NFCSHARING_SETTINGS);
else } else {
intent.setAction(Settings.ACTION_NFC_SETTINGS); intent.setAction(Settings.ACTION_NFC_SETTINGS);
} }
}
// this API was added in 4.0 aka Ice Cream Sandwich // this API was added in 4.0 aka Ice Cream Sandwich
@TargetApi(14) @TargetApi(14)

View File

@ -48,10 +48,11 @@ public class QrGenAsyncTask extends AsyncTask<String, Void, Void> {
x = display.getWidth(); x = display.getWidth();
y = display.getHeight(); y = display.getHeight();
} }
if (x < y) if (x < y) {
qrCodeDimension = x; qrCodeDimension = x;
else } else {
qrCodeDimension = y; qrCodeDimension = y;
}
Utils.debugLog(TAG, "generating QRCode Bitmap of " + qrCodeDimension + "x" + qrCodeDimension); Utils.debugLog(TAG, "generating QRCode Bitmap of " + qrCodeDimension + "x" + qrCodeDimension);
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrData, null, QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrData, null,
Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), qrCodeDimension); Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), qrCodeDimension);

View File

@ -164,8 +164,9 @@ public class RepoUpdater {
public void processDownloadedFile(File downloadedFile) throws UpdateException { public void processDownloadedFile(File downloadedFile) throws UpdateException {
InputStream indexInputStream = null; InputStream indexInputStream = null;
try { try {
if (downloadedFile == null || !downloadedFile.exists()) if (downloadedFile == null || !downloadedFile.exists()) {
throw new UpdateException(repo, downloadedFile + " does not exist!"); throw new UpdateException(repo, downloadedFile + " does not exist!");
}
// Due to a bug in Android 5.0 Lollipop, the inclusion of spongycastle causes // Due to a bug in Android 5.0 Lollipop, the inclusion of spongycastle causes
// breakage when verifying the signature of the downloaded .jar. For more // breakage when verifying the signature of the downloaded .jar. For more
@ -306,8 +307,9 @@ public class RepoUpdater {
*/ */
private void verifyAndStoreTOFUCerts(String certFromIndexXml, X509Certificate rawCertFromJar) private void verifyAndStoreTOFUCerts(String certFromIndexXml, X509Certificate rawCertFromJar)
throws SigningException { throws SigningException {
if (repo.pubkey != null) if (repo.pubkey != null) {
return; // there is a repo.pubkey already, nothing to TOFU return; // there is a repo.pubkey already, nothing to TOFU
}
/* The first time a repo is added, it can be added with the signing certificate's /* The first time a repo is added, it can be added with the signing certificate's
* fingerprint. In that case, check that fingerprint against what is * fingerprint. In that case, check that fingerprint against what is
@ -348,8 +350,9 @@ public class RepoUpdater {
// repo and repo.pubkey must be pre-loaded from the database // repo and repo.pubkey must be pre-loaded from the database
if (TextUtils.isEmpty(repo.pubkey) if (TextUtils.isEmpty(repo.pubkey)
|| TextUtils.isEmpty(certFromJar) || TextUtils.isEmpty(certFromJar)
|| TextUtils.isEmpty(certFromIndexXml)) || TextUtils.isEmpty(certFromIndexXml)) {
throw new SigningException(repo, "A empty repo or signing certificate is invalid!"); throw new SigningException(repo, "A empty repo or signing certificate is invalid!");
}
// though its called repo.pubkey, its actually a X509 certificate // though its called repo.pubkey, its actually a X509 certificate
if (repo.pubkey.equals(certFromJar) if (repo.pubkey.equals(certFromJar)

View File

@ -173,8 +173,9 @@ public class UpdateService extends IntentService implements ProgressListener {
protected static void sendStatus(Context context, int statusCode, String message, int progress) { protected static void sendStatus(Context context, int statusCode, String message, int progress) {
Intent intent = new Intent(LOCAL_ACTION_STATUS); Intent intent = new Intent(LOCAL_ACTION_STATUS);
intent.putExtra(EXTRA_STATUS_CODE, statusCode); intent.putExtra(EXTRA_STATUS_CODE, statusCode);
if (!TextUtils.isEmpty(message)) if (!TextUtils.isEmpty(message)) {
intent.putExtra(EXTRA_MESSAGE, message); intent.putExtra(EXTRA_MESSAGE, message);
}
intent.putExtra(EXTRA_PROGRESS, progress); intent.putExtra(EXTRA_PROGRESS, progress);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent); LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
} }
@ -190,11 +191,13 @@ public class UpdateService extends IntentService implements ProgressListener {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
String action = intent.getAction(); String action = intent.getAction();
if (TextUtils.isEmpty(action)) if (TextUtils.isEmpty(action)) {
return; return;
}
if (!action.equals(Downloader.LOCAL_ACTION_PROGRESS)) if (!action.equals(Downloader.LOCAL_ACTION_PROGRESS)) {
return; return;
}
String repoAddress = intent.getStringExtra(Downloader.EXTRA_ADDRESS); String repoAddress = intent.getStringExtra(Downloader.EXTRA_ADDRESS);
int downloadedSize = intent.getIntExtra(Downloader.EXTRA_BYTES_READ, -1); int downloadedSize = intent.getIntExtra(Downloader.EXTRA_BYTES_READ, -1);
@ -220,11 +223,13 @@ public class UpdateService extends IntentService implements ProgressListener {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
String action = intent.getAction(); String action = intent.getAction();
if (TextUtils.isEmpty(action)) if (TextUtils.isEmpty(action)) {
return; return;
}
if (!action.equals(LOCAL_ACTION_STATUS)) if (!action.equals(LOCAL_ACTION_STATUS)) {
return; return;
}
final String message = intent.getStringExtra(EXTRA_MESSAGE); final String message = intent.getStringExtra(EXTRA_MESSAGE);
int resultCode = intent.getIntExtra(EXTRA_STATUS_CODE, -1); int resultCode = intent.getIntExtra(EXTRA_STATUS_CODE, -1);
@ -317,8 +322,9 @@ public class UpdateService extends IntentService implements ProgressListener {
// this could be cellular or wifi // this could be cellular or wifi
NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork == null) if (activeNetwork == null) {
return false; return false;
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (activeNetwork.getType() != ConnectivityManager.TYPE_WIFI if (activeNetwork.getType() != ConnectivityManager.TYPE_WIFI

View File

@ -202,7 +202,7 @@ public final class Utils {
return String.format(FRIENDLY_SIZE_FORMAT[i], s); return String.format(FRIENDLY_SIZE_FORMAT[i], s);
} }
private static final String[] androidVersionNames = { private static final String[] ANDROID_VERSION_NAMES = {
"?", // 0, undefined "?", // 0, undefined
"1.0", // 1 "1.0", // 1
"1.1", // 2 "1.1", // 2
@ -231,12 +231,12 @@ public final class Utils {
public static String getAndroidVersionName(int sdkLevel) { public static String getAndroidVersionName(int sdkLevel) {
if (sdkLevel < 0) { if (sdkLevel < 0) {
return androidVersionNames[0]; return ANDROID_VERSION_NAMES[0];
} }
if (sdkLevel >= androidVersionNames.length) { if (sdkLevel >= ANDROID_VERSION_NAMES.length) {
return String.format(Locale.ENGLISH, "v%d", sdkLevel); return String.format(Locale.ENGLISH, "v%d", sdkLevel);
} }
return androidVersionNames[sdkLevel]; return ANDROID_VERSION_NAMES[sdkLevel];
} }
/* PackageManager doesn't give us the min and max sdk versions, so we have /* PackageManager doesn't give us the min and max sdk versions, so we have
@ -275,39 +275,45 @@ public final class Utils {
public static String formatFingerprint(Context context, String fingerprint) { public static String formatFingerprint(Context context, String fingerprint) {
if (TextUtils.isEmpty(fingerprint) if (TextUtils.isEmpty(fingerprint)
|| fingerprint.length() != 64 // SHA-256 is 64 hex chars || fingerprint.length() != 64 // SHA-256 is 64 hex chars
|| fingerprint.matches(".*[^0-9a-fA-F].*")) // its a hex string || fingerprint.matches(".*[^0-9a-fA-F].*")) { // its a hex string
return context.getString(R.string.bad_fingerprint); return context.getString(R.string.bad_fingerprint);
}
String displayFP = fingerprint.substring(0, 2); String displayFP = fingerprint.substring(0, 2);
for (int i = 2; i < fingerprint.length(); i = i + 2) for (int i = 2; i < fingerprint.length(); i = i + 2) {
displayFP += " " + fingerprint.substring(i, i + 2); displayFP += " " + fingerprint.substring(i, i + 2);
}
return displayFP; return displayFP;
} }
@NonNull @NonNull
public static Uri getLocalRepoUri(Repo repo) { public static Uri getLocalRepoUri(Repo repo) {
if (TextUtils.isEmpty(repo.address)) if (TextUtils.isEmpty(repo.address)) {
return Uri.parse("http://wifi-not-enabled"); return Uri.parse("http://wifi-not-enabled");
}
Uri uri = Uri.parse(repo.address); Uri uri = Uri.parse(repo.address);
Uri.Builder b = uri.buildUpon(); Uri.Builder b = uri.buildUpon();
if (!TextUtils.isEmpty(repo.fingerprint)) if (!TextUtils.isEmpty(repo.fingerprint)) {
b.appendQueryParameter("fingerprint", repo.fingerprint); b.appendQueryParameter("fingerprint", repo.fingerprint);
}
String scheme = Preferences.get().isLocalRepoHttpsEnabled() ? "https" : "http"; String scheme = Preferences.get().isLocalRepoHttpsEnabled() ? "https" : "http";
b.scheme(scheme); b.scheme(scheme);
return b.build(); return b.build();
} }
public static Uri getSharingUri(Repo repo) { public static Uri getSharingUri(Repo repo) {
if (TextUtils.isEmpty(repo.address)) if (TextUtils.isEmpty(repo.address)) {
return Uri.parse("http://wifi-not-enabled"); return Uri.parse("http://wifi-not-enabled");
}
Uri localRepoUri = getLocalRepoUri(repo); Uri localRepoUri = getLocalRepoUri(repo);
Uri.Builder b = localRepoUri.buildUpon(); Uri.Builder b = localRepoUri.buildUpon();
b.scheme(localRepoUri.getScheme().replaceFirst("http", "fdroidrepo")); b.scheme(localRepoUri.getScheme().replaceFirst("http", "fdroidrepo"));
b.appendQueryParameter("swap", "1"); b.appendQueryParameter("swap", "1");
if (!TextUtils.isEmpty(FDroidApp.bssid)) { if (!TextUtils.isEmpty(FDroidApp.bssid)) {
b.appendQueryParameter("bssid", FDroidApp.bssid); b.appendQueryParameter("bssid", FDroidApp.bssid);
if (!TextUtils.isEmpty(FDroidApp.ssid)) if (!TextUtils.isEmpty(FDroidApp.ssid)) {
b.appendQueryParameter("ssid", FDroidApp.ssid); b.appendQueryParameter("ssid", FDroidApp.ssid);
} }
}
return b.build(); return b.build();
} }
@ -350,8 +356,9 @@ public final class Utils {
} }
public static String calcFingerprint(Certificate cert) { public static String calcFingerprint(Certificate cert) {
if (cert == null) if (cert == null) {
return null; return null;
}
try { try {
return calcFingerprint(cert.getEncoded()); return calcFingerprint(cert.getEncoded());
} catch (CertificateEncodingException e) { } catch (CertificateEncodingException e) {
@ -360,8 +367,9 @@ public final class Utils {
} }
private static String calcFingerprint(byte[] key) { private static String calcFingerprint(byte[] key) {
if (key == null) if (key == null) {
return null; return null;
}
if (key.length < 256) { if (key.length < 256) {
Log.e(TAG, "key was shorter than 256 bytes (" + key.length + "), cannot be valid!"); Log.e(TAG, "key was shorter than 256 bytes (" + key.length + "), cannot be valid!");
return null; return null;
@ -426,8 +434,9 @@ public final class Utils {
} }
public static CommaSeparatedList make(List<String> list) { public static CommaSeparatedList make(List<String> list) {
if (list == null || list.isEmpty()) if (list == null || list.isEmpty()) {
return null; return null;
}
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) { for (int i = 0; i < list.size(); i++) {
if (i > 0) { if (i > 0) {
@ -439,8 +448,9 @@ public final class Utils {
} }
public static CommaSeparatedList make(String[] list) { public static CommaSeparatedList make(String[] list) {
if (list == null || list.length == 0) if (list == null || list.length == 0) {
return null; return null;
}
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.length; i++) { for (int i = 0; i < list.length; i++) {
if (i > 0) { if (i > 0) {
@ -453,8 +463,9 @@ public final class Utils {
@Nullable @Nullable
public static CommaSeparatedList make(@Nullable String list) { public static CommaSeparatedList make(@Nullable String list) {
if (TextUtils.isEmpty(list)) if (TextUtils.isEmpty(list)) {
return null; return null;
}
return new CommaSeparatedList(list); return new CommaSeparatedList(list);
} }
@ -480,9 +491,10 @@ public final class Utils {
public boolean contains(String v) { public boolean contains(String v) {
for (final String s : this) { for (final String s : this) {
if (s.equals(v)) if (s.equals(v)) {
return true; return true;
} }
}
return false; return false;
} }
} }
@ -522,8 +534,9 @@ public final class Utils {
byte[] dataBytes = new byte[524288]; byte[] dataBytes = new byte[524288];
int nread; int nread;
while ((nread = bis.read(dataBytes)) != -1) while ((nread = bis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread); md.update(dataBytes, 0, nread);
}
byte[] mdbytes = md.digest(); byte[] mdbytes = md.digest();
return toHexString(mdbytes); return toHexString(mdbytes);
@ -609,16 +622,18 @@ public final class Utils {
XMLReader reader) { XMLReader reader) {
switch (tag) { switch (tag) {
case "ul": case "ul":
if (opening) if (opening) {
listNum = -1; listNum = -1;
else } else {
output.append('\n'); output.append('\n');
}
break; break;
case "ol": case "ol":
if (opening) if (opening) {
listNum = 1; listNum = 1;
else } else {
output.append('\n'); output.append('\n');
}
break; break;
case "li": case "li":
if (opening) { if (opening) {

View File

@ -177,19 +177,19 @@ public final class PRNGFixes extends Compatibility {
* Linux PRNG. * Linux PRNG.
* *
* Concurrency: Read requests to the underlying Linux PRNG are * Concurrency: Read requests to the underlying Linux PRNG are
* serialized (on sLock) to ensure that multiple threads do not get * serialized (on S_LOCK) to ensure that multiple threads do not get
* duplicated PRNG output. * duplicated PRNG output.
*/ */
private static final File URANDOM_FILE = new File("/dev/urandom"); private static final File URANDOM_FILE = new File("/dev/urandom");
private static final Object sLock = new Object(); private static final Object S_LOCK = new Object();
/** /**
* Input stream for reading from Linux PRNG or {@code null} if not yet * Input stream for reading from Linux PRNG or {@code null} if not yet
* opened. * opened.
* *
* @GuardedBy("sLock") * @GuardedBy("S_LOCK")
*/ */
private static DataInputStream sUrandomIn; private static DataInputStream sUrandomIn;
@ -197,7 +197,7 @@ public final class PRNGFixes extends Compatibility {
* Output stream for writing to Linux PRNG or {@code null} if not yet * Output stream for writing to Linux PRNG or {@code null} if not yet
* opened. * opened.
* *
* @GuardedBy("sLock") * @GuardedBy("S_LOCK")
*/ */
private static OutputStream sUrandomOut; private static OutputStream sUrandomOut;
@ -212,7 +212,7 @@ public final class PRNGFixes extends Compatibility {
protected void engineSetSeed(byte[] bytes) { protected void engineSetSeed(byte[] bytes) {
try { try {
OutputStream out; OutputStream out;
synchronized (sLock) { synchronized (S_LOCK) {
out = getUrandomOutputStream(); out = getUrandomOutputStream();
} }
out.write(bytes); out.write(bytes);
@ -235,7 +235,7 @@ public final class PRNGFixes extends Compatibility {
try { try {
DataInputStream in; DataInputStream in;
synchronized (sLock) { synchronized (S_LOCK) {
in = getUrandomInputStream(); in = getUrandomInputStream();
} }
synchronized (in) { synchronized (in) {
@ -255,7 +255,7 @@ public final class PRNGFixes extends Compatibility {
} }
private DataInputStream getUrandomInputStream() { private DataInputStream getUrandomInputStream() {
synchronized (sLock) { synchronized (S_LOCK) {
if (sUrandomIn == null) { if (sUrandomIn == null) {
// NOTE: Consider inserting a BufferedInputStream between // NOTE: Consider inserting a BufferedInputStream between
// DataInputStream and FileInputStream if you need higher // DataInputStream and FileInputStream if you need higher
@ -274,7 +274,7 @@ public final class PRNGFixes extends Compatibility {
} }
private OutputStream getUrandomOutputStream() throws IOException { private OutputStream getUrandomOutputStream() throws IOException {
synchronized (sLock) { synchronized (S_LOCK) {
if (sUrandomOut == null) { if (sUrandomOut == null) {
sUrandomOut = new FileOutputStream(URANDOM_FILE); sUrandomOut = new FileOutputStream(URANDOM_FILE);
} }

View File

@ -56,9 +56,10 @@ public class TabManager {
FragmentTransaction ft) { FragmentTransaction ft) {
int pos = tab.getPosition(); int pos = tab.getPosition();
pager.setCurrentItem(pos); pager.setCurrentItem(pos);
if (pos == INDEX_CAN_UPDATE) if (pos == INDEX_CAN_UPDATE) {
removeNotification(1); removeNotification(1);
} }
}
@Override @Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
@ -78,9 +79,10 @@ public class TabManager {
if (actionBarSpinner != null) { if (actionBarSpinner != null) {
actionBarSpinner.setSelection(index); actionBarSpinner.setSelection(index);
} }
if (index == INDEX_CAN_UPDATE) if (index == INDEX_CAN_UPDATE) {
removeNotification(1); removeNotification(1);
} }
}
public void refreshTabLabel(int index) { public void refreshTabLabel(int index) {
CharSequence text = getLabel(index); CharSequence text = getLabel(index);

View File

@ -237,7 +237,7 @@ public class ApkProvider extends FDroidProvider {
private static final String PATH_REPO_APPS = "repo-apps"; private static final String PATH_REPO_APPS = "repo-apps";
protected static final String PATH_REPO_APK = "repo-apk"; protected static final String PATH_REPO_APK = "repo-apk";
private static final UriMatcher matcher = new UriMatcher(-1); private static final UriMatcher MATCHER = new UriMatcher(-1);
private static final Map<String, String> REPO_FIELDS = new HashMap<>(); private static final Map<String, String> REPO_FIELDS = new HashMap<>();
@ -245,13 +245,13 @@ public class ApkProvider extends FDroidProvider {
REPO_FIELDS.put(DataColumns.REPO_VERSION, RepoProvider.DataColumns.VERSION); REPO_FIELDS.put(DataColumns.REPO_VERSION, RepoProvider.DataColumns.VERSION);
REPO_FIELDS.put(DataColumns.REPO_ADDRESS, RepoProvider.DataColumns.ADDRESS); REPO_FIELDS.put(DataColumns.REPO_ADDRESS, RepoProvider.DataColumns.ADDRESS);
matcher.addURI(getAuthority(), PATH_REPO + "/#", CODE_REPO); MATCHER.addURI(getAuthority(), PATH_REPO + "/#", CODE_REPO);
matcher.addURI(getAuthority(), PATH_APK + "/#/*", CODE_SINGLE); MATCHER.addURI(getAuthority(), PATH_APK + "/#/*", CODE_SINGLE);
matcher.addURI(getAuthority(), PATH_APKS + "/*", CODE_APKS); MATCHER.addURI(getAuthority(), PATH_APKS + "/*", CODE_APKS);
matcher.addURI(getAuthority(), PATH_APP + "/*", CODE_APP); MATCHER.addURI(getAuthority(), PATH_APP + "/*", CODE_APP);
matcher.addURI(getAuthority(), PATH_REPO_APPS + "/#/*", CODE_REPO_APPS); MATCHER.addURI(getAuthority(), PATH_REPO_APPS + "/#/*", CODE_REPO_APPS);
matcher.addURI(getAuthority(), PATH_REPO_APK + "/#/*", CODE_REPO_APK); MATCHER.addURI(getAuthority(), PATH_REPO_APK + "/#/*", CODE_REPO_APK);
matcher.addURI(getAuthority(), null, CODE_LIST); MATCHER.addURI(getAuthority(), null, CODE_LIST);
} }
public static String getAuthority() { public static String getAuthority() {
@ -357,7 +357,7 @@ public class ApkProvider extends FDroidProvider {
@Override @Override
protected UriMatcher getMatcher() { protected UriMatcher getMatcher() {
return matcher; return MATCHER;
} }
private static class Query extends QueryBuilder { private static class Query extends QueryBuilder {
@ -449,7 +449,7 @@ public class ApkProvider extends FDroidProvider {
QuerySelection query = new QuerySelection(selection, selectionArgs); QuerySelection query = new QuerySelection(selection, selectionArgs);
switch (matcher.match(uri)) { switch (MATCHER.match(uri)) {
case CODE_LIST: case CODE_LIST:
break; break;
@ -522,7 +522,7 @@ public class ApkProvider extends FDroidProvider {
QuerySelection query = new QuerySelection(where, whereArgs); QuerySelection query = new QuerySelection(where, whereArgs);
switch (matcher.match(uri)) { switch (MATCHER.match(uri)) {
case CODE_REPO: case CODE_REPO:
query = query.add(queryRepo(Long.parseLong(uri.getLastPathSegment()))); query = query.add(queryRepo(Long.parseLong(uri.getLastPathSegment())));
@ -561,7 +561,7 @@ public class ApkProvider extends FDroidProvider {
@Override @Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
if (matcher.match(uri) != CODE_SINGLE) { if (MATCHER.match(uri) != CODE_SINGLE) {
throw new UnsupportedOperationException("Cannot update anything other than a single apk."); throw new UnsupportedOperationException("Cannot update anything other than a single apk.");
} }
return performUpdateUnchecked(uri, values, where, whereArgs); return performUpdateUnchecked(uri, values, where, whereArgs);

View File

@ -250,20 +250,23 @@ public class App extends ValueObject implements Comparable<App> {
Log.w(TAG, "Could not get app info: " + installerPackageName, e); Log.w(TAG, "Could not get app info: " + installerPackageName, e);
} }
} }
if (TextUtils.isEmpty(installerPackageLabel)) if (TextUtils.isEmpty(installerPackageLabel)) {
installerPackageLabel = installerPackageName; installerPackageLabel = installerPackageName;
}
final CharSequence appDescription = appInfo.loadDescription(pm); final CharSequence appDescription = appInfo.loadDescription(pm);
if (TextUtils.isEmpty(appDescription)) if (TextUtils.isEmpty(appDescription)) {
this.summary = "(installed by " + installerPackageLabel + ")"; this.summary = "(installed by " + installerPackageLabel + ")";
else } else {
this.summary = (String) appDescription.subSequence(0, 40); this.summary = (String) appDescription.subSequence(0, 40);
}
this.packageName = appInfo.packageName; this.packageName = appInfo.packageName;
this.added = new Date(packageInfo.firstInstallTime); this.added = new Date(packageInfo.firstInstallTime);
this.lastUpdated = new Date(packageInfo.lastUpdateTime); this.lastUpdated = new Date(packageInfo.lastUpdateTime);
this.description = "<p>"; this.description = "<p>";
if (!TextUtils.isEmpty(appDescription)) if (!TextUtils.isEmpty(appDescription)) {
this.description += appDescription + "\n"; this.description += appDescription + "\n";
}
this.description += "(installed by " + installerPackageLabel this.description += "(installed by " + installerPackageLabel
+ ", first installed on " + this.added + ", first installed on " + this.added
+ ", last updated on " + this.lastUpdated + ")</p>"; + ", last updated on " + this.lastUpdated + ")</p>";
@ -358,14 +361,17 @@ public class App extends ValueObject implements Comparable<App> {
public boolean isValid() { public boolean isValid() {
if (TextUtils.isEmpty(this.name) if (TextUtils.isEmpty(this.name)
|| TextUtils.isEmpty(this.packageName)) || TextUtils.isEmpty(this.packageName)) {
return false; return false;
}
if (this.installedApk == null) if (this.installedApk == null) {
return false; return false;
}
if (TextUtils.isEmpty(this.installedApk.sig)) if (TextUtils.isEmpty(this.installedApk.sig)) {
return false; return false;
}
final File apkFile = this.installedApk.installedFile; final File apkFile = this.installedApk.installedFile;
return !(apkFile == null || !apkFile.canRead()); return !(apkFile == null || !apkFile.canRead());

View File

@ -423,7 +423,7 @@ public class AppProvider extends FDroidProvider {
private static final String PROVIDER_NAME = "AppProvider"; private static final String PROVIDER_NAME = "AppProvider";
private static final UriMatcher matcher = new UriMatcher(-1); private static final UriMatcher MATCHER = new UriMatcher(-1);
private static final String PATH_INSTALLED = "installed"; private static final String PATH_INSTALLED = "installed";
private static final String PATH_CAN_UPDATE = "canUpdate"; private static final String PATH_CAN_UPDATE = "canUpdate";
@ -456,22 +456,22 @@ public class AppProvider extends FDroidProvider {
private static final int SEARCH_CAN_UPDATE = SEARCH_INSTALLED + 1; private static final int SEARCH_CAN_UPDATE = SEARCH_INSTALLED + 1;
static { static {
matcher.addURI(getAuthority(), null, CODE_LIST); MATCHER.addURI(getAuthority(), null, CODE_LIST);
matcher.addURI(getAuthority(), PATH_CALC_APP_DETAILS_FROM_INDEX, CALC_APP_DETAILS_FROM_INDEX); MATCHER.addURI(getAuthority(), PATH_CALC_APP_DETAILS_FROM_INDEX, CALC_APP_DETAILS_FROM_INDEX);
matcher.addURI(getAuthority(), PATH_IGNORED, IGNORED); MATCHER.addURI(getAuthority(), PATH_IGNORED, IGNORED);
matcher.addURI(getAuthority(), PATH_RECENTLY_UPDATED, RECENTLY_UPDATED); MATCHER.addURI(getAuthority(), PATH_RECENTLY_UPDATED, RECENTLY_UPDATED);
matcher.addURI(getAuthority(), PATH_NEWLY_ADDED, NEWLY_ADDED); MATCHER.addURI(getAuthority(), PATH_NEWLY_ADDED, NEWLY_ADDED);
matcher.addURI(getAuthority(), PATH_CATEGORY + "/*", CATEGORY); MATCHER.addURI(getAuthority(), PATH_CATEGORY + "/*", CATEGORY);
matcher.addURI(getAuthority(), PATH_SEARCH + "/*", SEARCH); MATCHER.addURI(getAuthority(), PATH_SEARCH + "/*", SEARCH);
matcher.addURI(getAuthority(), PATH_SEARCH_INSTALLED + "/*", SEARCH_INSTALLED); MATCHER.addURI(getAuthority(), PATH_SEARCH_INSTALLED + "/*", SEARCH_INSTALLED);
matcher.addURI(getAuthority(), PATH_SEARCH_CAN_UPDATE + "/*", SEARCH_CAN_UPDATE); MATCHER.addURI(getAuthority(), PATH_SEARCH_CAN_UPDATE + "/*", SEARCH_CAN_UPDATE);
matcher.addURI(getAuthority(), PATH_SEARCH_REPO + "/*/*", SEARCH_REPO); MATCHER.addURI(getAuthority(), PATH_SEARCH_REPO + "/*/*", SEARCH_REPO);
matcher.addURI(getAuthority(), PATH_REPO + "/#", REPO); MATCHER.addURI(getAuthority(), PATH_REPO + "/#", REPO);
matcher.addURI(getAuthority(), PATH_CAN_UPDATE, CAN_UPDATE); MATCHER.addURI(getAuthority(), PATH_CAN_UPDATE, CAN_UPDATE);
matcher.addURI(getAuthority(), PATH_INSTALLED, INSTALLED); MATCHER.addURI(getAuthority(), PATH_INSTALLED, INSTALLED);
matcher.addURI(getAuthority(), PATH_NO_APKS, NO_APKS); MATCHER.addURI(getAuthority(), PATH_NO_APKS, NO_APKS);
matcher.addURI(getAuthority(), PATH_APPS + "/*", APPS); MATCHER.addURI(getAuthority(), PATH_APPS + "/*", APPS);
matcher.addURI(getAuthority(), "*", CODE_SINGLE); MATCHER.addURI(getAuthority(), "*", CODE_SINGLE);
} }
public static Uri getContentUri() { public static Uri getContentUri() {
@ -597,7 +597,7 @@ public class AppProvider extends FDroidProvider {
@Override @Override
protected UriMatcher getMatcher() { protected UriMatcher getMatcher() {
return matcher; return MATCHER;
} }
private AppQuerySelection queryCanUpdate() { private AppQuerySelection queryCanUpdate() {
@ -742,7 +742,7 @@ public class AppProvider extends FDroidProvider {
// Queries which are for the main list of apps should not include swap apps. // Queries which are for the main list of apps should not include swap apps.
boolean includeSwap = true; boolean includeSwap = true;
switch (matcher.match(uri)) { switch (MATCHER.match(uri)) {
case CODE_LIST: case CODE_LIST:
includeSwap = false; includeSwap = false;
break; break;
@ -842,7 +842,7 @@ public class AppProvider extends FDroidProvider {
public int delete(Uri uri, String where, String[] whereArgs) { public int delete(Uri uri, String where, String[] whereArgs) {
QuerySelection query = new QuerySelection(where, whereArgs); QuerySelection query = new QuerySelection(where, whereArgs);
switch (matcher.match(uri)) { switch (MATCHER.match(uri)) {
case NO_APKS: case NO_APKS:
query = query.add(queryNoApks()); query = query.add(queryNoApks());
@ -870,7 +870,7 @@ public class AppProvider extends FDroidProvider {
@Override @Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
QuerySelection query = new QuerySelection(where, whereArgs); QuerySelection query = new QuerySelection(where, whereArgs);
switch (matcher.match(uri)) { switch (MATCHER.match(uri)) {
case CALC_APP_DETAILS_FROM_INDEX: case CALC_APP_DETAILS_FROM_INDEX:
updateAppDetails(); updateAppDetails();

View File

@ -350,10 +350,12 @@ public class DBHelper extends SQLiteOpenHelper {
boolean nameExists = columnExists(db, TABLE_REPO, "name"); boolean nameExists = columnExists(db, TABLE_REPO, "name");
boolean descriptionExists = columnExists(db, TABLE_REPO, "description"); boolean descriptionExists = columnExists(db, TABLE_REPO, "description");
if (oldVersion < 21 && !(nameExists && descriptionExists)) { if (oldVersion < 21 && !(nameExists && descriptionExists)) {
if (!nameExists) if (!nameExists) {
db.execSQL("alter table " + TABLE_REPO + " add column name text"); db.execSQL("alter table " + TABLE_REPO + " add column name text");
if (!descriptionExists) }
if (!descriptionExists) {
db.execSQL("alter table " + TABLE_REPO + " add column description text"); db.execSQL("alter table " + TABLE_REPO + " add column description text");
}
insertNameAndDescription(db, R.string.fdroid_repo_address, insertNameAndDescription(db, R.string.fdroid_repo_address,
R.string.fdroid_repo_name, R.string.fdroid_repo_description); R.string.fdroid_repo_name, R.string.fdroid_repo_description);
insertNameAndDescription(db, R.string.fdroid_archive_address, insertNameAndDescription(db, R.string.fdroid_archive_address,
@ -372,8 +374,9 @@ public class DBHelper extends SQLiteOpenHelper {
*/ */
private void addFingerprintToRepo(SQLiteDatabase db, int oldVersion) { private void addFingerprintToRepo(SQLiteDatabase db, int oldVersion) {
if (oldVersion < 44) { if (oldVersion < 44) {
if (!columnExists(db, TABLE_REPO, "fingerprint")) if (!columnExists(db, TABLE_REPO, "fingerprint")) {
db.execSQL("alter table " + TABLE_REPO + " add column fingerprint text"); db.execSQL("alter table " + TABLE_REPO + " add column fingerprint text");
}
List<Repo> oldrepos = new ArrayList<>(); List<Repo> oldrepos = new ArrayList<>();
Cursor cursor = db.query(TABLE_REPO, Cursor cursor = db.query(TABLE_REPO,
new String[] {"address", "pubkey"}, new String[] {"address", "pubkey"},

View File

@ -77,12 +77,12 @@ public class InstalledAppProvider extends FDroidProvider {
private static final String PATH_SEARCH = "search"; private static final String PATH_SEARCH = "search";
private static final int CODE_SEARCH = CODE_SINGLE + 1; private static final int CODE_SEARCH = CODE_SINGLE + 1;
private static final UriMatcher matcher = new UriMatcher(-1); private static final UriMatcher MATCHER = new UriMatcher(-1);
static { static {
matcher.addURI(getAuthority(), null, CODE_LIST); MATCHER.addURI(getAuthority(), null, CODE_LIST);
matcher.addURI(getAuthority(), PATH_SEARCH + "/*", CODE_SEARCH); MATCHER.addURI(getAuthority(), PATH_SEARCH + "/*", CODE_SEARCH);
matcher.addURI(getAuthority(), "*", CODE_SINGLE); MATCHER.addURI(getAuthority(), "*", CODE_SINGLE);
} }
public static Uri getContentUri() { public static Uri getContentUri() {
@ -143,7 +143,7 @@ public class InstalledAppProvider extends FDroidProvider {
@Override @Override
protected UriMatcher getMatcher() { protected UriMatcher getMatcher() {
return matcher; return MATCHER;
} }
private QuerySelection queryApp(String packageName) { private QuerySelection queryApp(String packageName) {
@ -162,7 +162,7 @@ public class InstalledAppProvider extends FDroidProvider {
} }
QuerySelection selection = new QuerySelection(customSelection, selectionArgs); QuerySelection selection = new QuerySelection(customSelection, selectionArgs);
switch (matcher.match(uri)) { switch (MATCHER.match(uri)) {
case CODE_LIST: case CODE_LIST:
break; break;
@ -188,7 +188,7 @@ public class InstalledAppProvider extends FDroidProvider {
@Override @Override
public int delete(Uri uri, String where, String[] whereArgs) { public int delete(Uri uri, String where, String[] whereArgs) {
if (matcher.match(uri) != CODE_SINGLE) { if (MATCHER.match(uri) != CODE_SINGLE) {
throw new UnsupportedOperationException("Delete not supported for " + uri + "."); throw new UnsupportedOperationException("Delete not supported for " + uri + ".");
} }
@ -205,7 +205,7 @@ public class InstalledAppProvider extends FDroidProvider {
@Override @Override
public Uri insert(Uri uri, ContentValues values) { public Uri insert(Uri uri, ContentValues values) {
if (matcher.match(uri) != CODE_LIST) { if (MATCHER.match(uri) != CODE_LIST) {
throw new UnsupportedOperationException("Insert not supported for " + uri + "."); throw new UnsupportedOperationException("Insert not supported for " + uri + ".");
} }

View File

@ -238,12 +238,12 @@ public class RepoProvider extends FDroidProvider {
private static final int CODE_ALL_EXCEPT_SWAP = CODE_SINGLE + 1; private static final int CODE_ALL_EXCEPT_SWAP = CODE_SINGLE + 1;
private static final UriMatcher matcher = new UriMatcher(-1); private static final UriMatcher MATCHER = new UriMatcher(-1);
static { static {
matcher.addURI(AUTHORITY + "." + PROVIDER_NAME, null, CODE_LIST); MATCHER.addURI(AUTHORITY + "." + PROVIDER_NAME, null, CODE_LIST);
matcher.addURI(AUTHORITY + "." + PROVIDER_NAME, PATH_ALL_EXCEPT_SWAP, CODE_ALL_EXCEPT_SWAP); MATCHER.addURI(AUTHORITY + "." + PROVIDER_NAME, PATH_ALL_EXCEPT_SWAP, CODE_ALL_EXCEPT_SWAP);
matcher.addURI(AUTHORITY + "." + PROVIDER_NAME, "#", CODE_SINGLE); MATCHER.addURI(AUTHORITY + "." + PROVIDER_NAME, "#", CODE_SINGLE);
} }
public static String getAuthority() { public static String getAuthority() {
@ -276,7 +276,7 @@ public class RepoProvider extends FDroidProvider {
@Override @Override
protected UriMatcher getMatcher() { protected UriMatcher getMatcher() {
return matcher; return MATCHER;
} }
@Override @Override
@ -286,7 +286,7 @@ public class RepoProvider extends FDroidProvider {
sortOrder = "_ID ASC"; sortOrder = "_ID ASC";
} }
switch (matcher.match(uri)) { switch (MATCHER.match(uri)) {
case CODE_LIST: case CODE_LIST:
// Do nothing (don't restrict query) // Do nothing (don't restrict query)
break; break;
@ -350,7 +350,7 @@ public class RepoProvider extends FDroidProvider {
@Override @Override
public int delete(Uri uri, String where, String[] whereArgs) { public int delete(Uri uri, String where, String[] whereArgs) {
switch (matcher.match(uri)) { switch (MATCHER.match(uri)) {
case CODE_LIST: case CODE_LIST:
// Don't support deleting of multiple repos. // Don't support deleting of multiple repos.
return 0; return 0;

View File

@ -24,12 +24,12 @@ public class TempApkProvider extends ApkProvider {
private static final int CODE_INIT = 10000; private static final int CODE_INIT = 10000;
private static final UriMatcher matcher = new UriMatcher(-1); private static final UriMatcher MATCHER = new UriMatcher(-1);
static { static {
matcher.addURI(getAuthority(), PATH_INIT, CODE_INIT); MATCHER.addURI(getAuthority(), PATH_INIT, CODE_INIT);
matcher.addURI(getAuthority(), PATH_APK + "/#/*", CODE_SINGLE); MATCHER.addURI(getAuthority(), PATH_APK + "/#/*", CODE_SINGLE);
matcher.addURI(getAuthority(), PATH_REPO_APK + "/#/*", CODE_REPO_APK); MATCHER.addURI(getAuthority(), PATH_REPO_APK + "/#/*", CODE_REPO_APK);
} }
@Override @Override
@ -78,7 +78,7 @@ public class TempApkProvider extends ApkProvider {
@Override @Override
public Uri insert(Uri uri, ContentValues values) { public Uri insert(Uri uri, ContentValues values) {
switch (matcher.match(uri)) { switch (MATCHER.match(uri)) {
case CODE_INIT: case CODE_INIT:
initTable(); initTable();
return null; return null;
@ -90,7 +90,7 @@ public class TempApkProvider extends ApkProvider {
@Override @Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
if (matcher.match(uri) != CODE_SINGLE) { if (MATCHER.match(uri) != CODE_SINGLE) {
throw new UnsupportedOperationException("Cannot update anything other than a single apk."); throw new UnsupportedOperationException("Cannot update anything other than a single apk.");
} }
@ -102,7 +102,7 @@ public class TempApkProvider extends ApkProvider {
QuerySelection query = new QuerySelection(where, whereArgs); QuerySelection query = new QuerySelection(where, whereArgs);
switch (matcher.match(uri)) { switch (MATCHER.match(uri)) {
case CODE_REPO_APK: case CODE_REPO_APK:
List<String> pathSegments = uri.getPathSegments(); List<String> pathSegments = uri.getPathSegments();
query = query.add(queryRepo(Long.parseLong(pathSegments.get(1)))).add(queryApks(pathSegments.get(2))); query = query.add(queryRepo(Long.parseLong(pathSegments.get(1)))).add(queryApks(pathSegments.get(2)));

View File

@ -26,12 +26,12 @@ public class TempAppProvider extends AppProvider {
private static final int CODE_INIT = 10000; private static final int CODE_INIT = 10000;
private static final int CODE_COMMIT = CODE_INIT + 1; private static final int CODE_COMMIT = CODE_INIT + 1;
private static final UriMatcher matcher = new UriMatcher(-1); private static final UriMatcher MATCHER = new UriMatcher(-1);
static { static {
matcher.addURI(getAuthority(), PATH_INIT, CODE_INIT); MATCHER.addURI(getAuthority(), PATH_INIT, CODE_INIT);
matcher.addURI(getAuthority(), PATH_COMMIT, CODE_COMMIT); MATCHER.addURI(getAuthority(), PATH_COMMIT, CODE_COMMIT);
matcher.addURI(getAuthority(), "*", CODE_SINGLE); MATCHER.addURI(getAuthority(), "*", CODE_SINGLE);
} }
@Override @Override
@ -79,7 +79,7 @@ public class TempAppProvider extends AppProvider {
@Override @Override
public Uri insert(Uri uri, ContentValues values) { public Uri insert(Uri uri, ContentValues values) {
switch (matcher.match(uri)) { switch (MATCHER.match(uri)) {
case CODE_INIT: case CODE_INIT:
initTable(); initTable();
return null; return null;
@ -95,7 +95,7 @@ public class TempAppProvider extends AppProvider {
@Override @Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
QuerySelection query = new QuerySelection(where, whereArgs); QuerySelection query = new QuerySelection(where, whereArgs);
switch (matcher.match(uri)) { switch (MATCHER.match(uri)) {
case CODE_SINGLE: case CODE_SINGLE:
query = query.add(querySingle(uri.getLastPathSegment())); query = query.add(querySingle(uri.getLastPathSegment()));
break; break;

View File

@ -73,8 +73,9 @@ public final class LocalRepoKeyStore {
private File keyStoreFile; private File keyStoreFile;
public static LocalRepoKeyStore get(Context context) throws InitException { public static LocalRepoKeyStore get(Context context) throws InitException {
if (localRepoKeyStore == null) if (localRepoKeyStore == null) {
localRepoKeyStore = new LocalRepoKeyStore(context); localRepoKeyStore = new LocalRepoKeyStore(context);
}
return localRepoKeyStore; return localRepoKeyStore;
} }
@ -240,8 +241,9 @@ public final class LocalRepoKeyStore {
public Certificate getCertificate() { public Certificate getCertificate() {
try { try {
Key key = keyStore.getKey(INDEX_CERT_ALIAS, "".toCharArray()); Key key = keyStore.getKey(INDEX_CERT_ALIAS, "".toCharArray());
if (key instanceof PrivateKey) if (key instanceof PrivateKey) {
return keyStore.getCertificate(INDEX_CERT_ALIAS); return keyStore.getCertificate(INDEX_CERT_ALIAS);
}
} catch (GeneralSecurityException e) { } catch (GeneralSecurityException e) {
Log.e(TAG, "Unable to get certificate for local repo", e); Log.e(TAG, "Unable to get certificate for local repo", e);
} }

View File

@ -96,8 +96,9 @@ public final class LocalRepoManager {
@NonNull @NonNull
public static LocalRepoManager get(Context context) { public static LocalRepoManager get(Context context) {
if (localRepoManager == null) if (localRepoManager == null) {
localRepoManager = new LocalRepoManager(context); localRepoManager = new LocalRepoManager(context);
}
return localRepoManager; return localRepoManager;
} }
@ -118,18 +119,24 @@ public final class LocalRepoManager {
xmlIndexJar = new SanitizedFile(repoDir, "index.jar"); xmlIndexJar = new SanitizedFile(repoDir, "index.jar");
xmlIndexJarUnsigned = new SanitizedFile(repoDir, "index.unsigned.jar"); xmlIndexJarUnsigned = new SanitizedFile(repoDir, "index.unsigned.jar");
if (!fdroidDir.exists()) if (!fdroidDir.exists()) {
if (!fdroidDir.mkdir()) if (!fdroidDir.mkdir()) {
Log.e(TAG, "Unable to create empty base: " + fdroidDir); Log.e(TAG, "Unable to create empty base: " + fdroidDir);
}
}
if (!repoDir.exists()) if (!repoDir.exists()) {
if (!repoDir.mkdir()) if (!repoDir.mkdir()) {
Log.e(TAG, "Unable to create empty repo: " + repoDir); Log.e(TAG, "Unable to create empty repo: " + repoDir);
}
}
if (!iconsDir.exists()) if (!iconsDir.exists()) {
if (!iconsDir.mkdir()) if (!iconsDir.mkdir()) {
Log.e(TAG, "Unable to create icons folder: " + iconsDir); Log.e(TAG, "Unable to create icons folder: " + iconsDir);
} }
}
}
private String writeFdroidApkToWebroot() { private String writeFdroidApkToWebroot() {
ApplicationInfo appInfo; ApplicationInfo appInfo;
@ -140,8 +147,9 @@ public final class LocalRepoManager {
SanitizedFile apkFile = SanitizedFile.knownSanitized(appInfo.publicSourceDir); SanitizedFile apkFile = SanitizedFile.knownSanitized(appInfo.publicSourceDir);
SanitizedFile fdroidApkLink = new SanitizedFile(webRoot, "fdroid.client.apk"); SanitizedFile fdroidApkLink = new SanitizedFile(webRoot, "fdroid.client.apk");
attemptToDelete(fdroidApkLink); attemptToDelete(fdroidApkLink);
if (Utils.symlinkOrCopyFileQuietly(apkFile, fdroidApkLink)) if (Utils.symlinkOrCopyFileQuietly(apkFile, fdroidApkLink)) {
fdroidClientURL = "/" + fdroidApkLink.getName(); fdroidClientURL = "/" + fdroidApkLink.getName();
}
} catch (PackageManager.NameNotFoundException e) { } catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "Could not set up F-Droid apk in the webroot", e); Log.e(TAG, "Could not set up F-Droid apk in the webroot", e);
} }
@ -249,9 +257,10 @@ public final class LocalRepoManager {
if (app.installedApk != null) { if (app.installedApk != null) {
SanitizedFile outFile = new SanitizedFile(repoDir, app.installedApk.apkName); SanitizedFile outFile = new SanitizedFile(repoDir, app.installedApk.apkName);
if (Utils.symlinkOrCopyFileQuietly(app.installedApk.installedFile, outFile)) if (Utils.symlinkOrCopyFileQuietly(app.installedApk.installedFile, outFile)) {
continue; continue;
} }
}
// if we got here, something went wrong // if we got here, something went wrong
throw new IllegalStateException("Unable to copy APK"); throw new IllegalStateException("Unable to copy APK");
} }
@ -261,8 +270,9 @@ public final class LocalRepoManager {
App app; App app;
try { try {
app = new App(context.getApplicationContext(), pm, packageName); app = new App(context.getApplicationContext(), pm, packageName);
if (!app.isValid()) if (!app.isValid()) {
return; return;
}
PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_META_DATA); PackageInfo packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_META_DATA);
app.icon = getIconFile(packageName, packageInfo.versionCode).getName(); app.icon = getIconFile(packageName, packageInfo.versionCode).getName();
} catch (PackageManager.NameNotFoundException | CertificateEncodingException | IOException e) { } catch (PackageManager.NameNotFoundException | CertificateEncodingException | IOException e) {
@ -464,16 +474,18 @@ public final class LocalRepoManager {
buff.append(','); buff.append(',');
} }
String out = buff.toString(); String out = buff.toString();
if (!TextUtils.isEmpty(out)) if (!TextUtils.isEmpty(out)) {
serializer.text(out.substring(0, out.length() - 1)); serializer.text(out.substring(0, out.length() - 1));
} }
}
serializer.endTag("", "permissions"); serializer.endTag("", "permissions");
} }
private void tagFeatures(App app) throws IOException { private void tagFeatures(App app) throws IOException {
serializer.startTag("", "features"); serializer.startTag("", "features");
if (app.installedApk.features != null) if (app.installedApk.features != null) {
serializer.text(Utils.CommaSeparatedList.str(app.installedApk.features)); serializer.text(Utils.CommaSeparatedList.str(app.installedApk.features));
}
serializer.endTag("", "features"); serializer.endTag("", "features");
} }

View File

@ -221,7 +221,7 @@ public class SwapService extends Service {
@Override @Override
protected Void doInBackground(Void... args) { protected Void doInBackground(Void... args) {
Uri repoUri = Uri.parse(address); Uri repoUri = Uri.parse(address);
String swapBackUri = Utils.getLocalRepoUri(FDroidApp.repo).toString(); String swapBackUri = Utils.getLocalRepoUri(FDroidApp.REPO).toString();
AndroidHttpClient client = AndroidHttpClient.newInstance("F-Droid", SwapService.this); AndroidHttpClient client = AndroidHttpClient.newInstance("F-Droid", SwapService.this);
HttpPost request = new HttpPost("/request-swap"); HttpPost request = new HttpPost("/request-swap");
@ -279,8 +279,9 @@ public class SwapService extends Service {
values.put(RepoProvider.DataColumns.ADDRESS, peer.getRepoAddress()); values.put(RepoProvider.DataColumns.ADDRESS, peer.getRepoAddress());
values.put(RepoProvider.DataColumns.DESCRIPTION, ""); values.put(RepoProvider.DataColumns.DESCRIPTION, "");
String fingerprint = peer.getFingerprint(); String fingerprint = peer.getFingerprint();
if (!TextUtils.isEmpty(fingerprint)) if (!TextUtils.isEmpty(fingerprint)) {
values.put(RepoProvider.DataColumns.FINGERPRINT, peer.getFingerprint()); values.put(RepoProvider.DataColumns.FINGERPRINT, peer.getFingerprint());
}
values.put(RepoProvider.DataColumns.IN_USE, true); values.put(RepoProvider.DataColumns.IN_USE, true);
values.put(RepoProvider.DataColumns.IS_SWAP, true); values.put(RepoProvider.DataColumns.IS_SWAP, true);
Uri uri = RepoProvider.Helper.insert(this, values); Uri uri = RepoProvider.Helper.insert(this, values);

View File

@ -130,7 +130,7 @@ class BonjourFinder extends PeerFinder implements ServiceListener {
final String type = serviceInfo.getPropertyString("type"); final String type = serviceInfo.getPropertyString("type");
final String fingerprint = serviceInfo.getPropertyString("fingerprint"); final String fingerprint = serviceInfo.getPropertyString("fingerprint");
final boolean isFDroid = type != null && type.startsWith("fdroidrepo"); final boolean isFDroid = type != null && type.startsWith("fdroidrepo");
final boolean isSelf = FDroidApp.repo != null && fingerprint != null && fingerprint.equalsIgnoreCase(FDroidApp.repo.fingerprint); final boolean isSelf = FDroidApp.REPO != null && fingerprint != null && fingerprint.equalsIgnoreCase(FDroidApp.REPO.fingerprint);
if (isFDroid && !isSelf) { if (isFDroid && !isSelf) {
Utils.debugLog(TAG, "Found F-Droid swap Bonjour service:\n" + serviceInfo); Utils.debugLog(TAG, "Found F-Droid swap Bonjour service:\n" + serviceInfo);
subscriber.onNext(new BonjourPeer(serviceInfo)); subscriber.onNext(new BonjourPeer(serviceInfo));
@ -152,8 +152,9 @@ class BonjourFinder extends PeerFinder implements ServiceListener {
isScanning = false; isScanning = false;
if (jmdns == null) if (jmdns == null) {
return; return;
}
jmdns.removeServiceListener(HTTP_SERVICE_TYPE, this); jmdns.removeServiceListener(HTTP_SERVICE_TYPE, this);
jmdns.removeServiceListener(HTTPS_SERVICE_TYPE, this); jmdns.removeServiceListener(HTTPS_SERVICE_TYPE, this);
jmdns = null; jmdns = null;

View File

@ -35,8 +35,9 @@ public final class BluetoothSwap extends SwapType {
if (adapter == null) { if (adapter == null) {
return new NoBluetoothType(context); return new NoBluetoothType(context);
} }
if (mInstance == null) if (mInstance == null) {
mInstance = new BluetoothSwap(context, adapter); mInstance = new BluetoothSwap(context, adapter);
}
return mInstance; return mInstance;
} }
@ -59,8 +60,9 @@ public final class BluetoothSwap extends SwapType {
@Override @Override
public synchronized void start() { public synchronized void start() {
if (isConnected()) if (isConnected()) {
return; return;
}
receiver = new BroadcastReceiver() { receiver = new BroadcastReceiver() {
@Override @Override
@ -90,8 +92,9 @@ public final class BluetoothSwap extends SwapType {
server = null; server = null;
}*/ }*/
if (server == null) if (server == null) {
server = new BluetoothServer(this, context.getFilesDir()); server = new BluetoothServer(this, context.getFilesDir());
}
sendBroadcast(SwapService.EXTRA_STARTING); sendBroadcast(SwapService.EXTRA_STARTING);
@ -100,8 +103,9 @@ public final class BluetoothSwap extends SwapType {
/* /*
Utils.debugLog(TAG, "Prefixing Bluetooth adapter name with " + BLUETOOTH_NAME_TAG + " to make it identifiable as a swap device."); Utils.debugLog(TAG, "Prefixing Bluetooth adapter name with " + BLUETOOTH_NAME_TAG + " to make it identifiable as a swap device.");
if (!deviceBluetoothName.startsWith(BLUETOOTH_NAME_TAG)) if (!deviceBluetoothName.startsWith(BLUETOOTH_NAME_TAG)) {
adapter.setName(BLUETOOTH_NAME_TAG + deviceBluetoothName); adapter.setName(BLUETOOTH_NAME_TAG + deviceBluetoothName);
}
if (!adapter.getName().startsWith(BLUETOOTH_NAME_TAG)) { if (!adapter.getName().startsWith(BLUETOOTH_NAME_TAG)) {
Log.e(TAG, "Couldn't change the name of the Bluetooth adapter, it will not get recognized by other swap clients."); Log.e(TAG, "Couldn't change the name of the Bluetooth adapter, it will not get recognized by other swap clients.");

View File

@ -40,13 +40,14 @@ public class BonjourBroadcast extends SwapType {
* of JmDNS, and there is only ever a single LocalHTTPD port to * of JmDNS, and there is only ever a single LocalHTTPD port to
* advertise anyway. * advertise anyway.
*/ */
if (pairService != null || jmdns != null) if (pairService != null || jmdns != null) {
clearCurrentMDNSService(); clearCurrentMDNSService();
}
String repoName = Preferences.get().getLocalRepoName(); String repoName = Preferences.get().getLocalRepoName();
HashMap<String, String> values = new HashMap<>(); HashMap<String, String> values = new HashMap<>();
values.put("path", "/fdroid/repo"); values.put("path", "/fdroid/repo");
values.put("name", repoName); values.put("name", repoName);
values.put("fingerprint", FDroidApp.repo.fingerprint); values.put("fingerprint", FDroidApp.REPO.fingerprint);
String type; String type;
if (Preferences.get().isLocalRepoHttpsEnabled()) { if (Preferences.get().isLocalRepoHttpsEnabled()) {
values.put("type", "fdroidrepos"); values.put("type", "fdroidrepos");

View File

@ -95,8 +95,9 @@ public class BluetoothDownloader extends Downloader {
@Override @Override
protected void close() { protected void close() {
if (connection != null) if (connection != null) {
connection.closeQuietly(); connection.closeQuietly();
} }
}
} }

View File

@ -89,8 +89,9 @@ public class HttpDownloader extends Downloader {
} }
protected void setupConnection() throws IOException { protected void setupConnection() throws IOException {
if (connection != null) if (connection != null) {
return; return;
}
Preferences prefs = Preferences.get(); Preferences prefs = Preferences.get();
if (prefs.isProxyEnabled() && !isSwapUrl()) { if (prefs.isProxyEnabled() && !isSwapUrl()) {
SocketAddress sa = new InetSocketAddress(prefs.getProxyHost(), prefs.getProxyPort()); SocketAddress sa = new InetSocketAddress(prefs.getProxyHost(), prefs.getProxyPort());

View File

@ -40,9 +40,10 @@ public class LocalHTTPD extends NanoHTTPD {
super(hostname, port); super(hostname, port);
this.webRoot = webRoot; this.webRoot = webRoot;
this.context = context.getApplicationContext(); this.context = context.getApplicationContext();
if (useHttps) if (useHttps) {
enableHTTPS(); enableHTTPS();
} }
}
/** /**
* URL-encodes everything between "/"-characters. Encodes spaces as '%20' * URL-encodes everything between "/"-characters. Encodes spaces as '%20'

View File

@ -80,8 +80,9 @@ public class WifiStateChangeService extends Service {
wifiState = wifiManager.getWifiState(); wifiState = wifiManager.getWifiState();
while (FDroidApp.ipAddressString == null) { while (FDroidApp.ipAddressString == null) {
if (isCancelled()) // can be canceled by a change via WifiStateChangeReceiver if (isCancelled()) { // can be canceled by a change via WifiStateChangeReceiver
return null; return null;
}
if (wifiState == WifiManager.WIFI_STATE_ENABLED) { if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
wifiInfo = wifiManager.getConnectionInfo(); wifiInfo = wifiManager.getConnectionInfo();
FDroidApp.ipAddressString = formatIpAddress(wifiInfo.getIpAddress()); FDroidApp.ipAddressString = formatIpAddress(wifiInfo.getIpAddress());
@ -90,14 +91,16 @@ public class WifiStateChangeService extends Service {
return null; return null;
} }
String netmask = formatIpAddress(dhcpInfo.netmask); String netmask = formatIpAddress(dhcpInfo.netmask);
if (!TextUtils.isEmpty(FDroidApp.ipAddressString) && netmask != null) if (!TextUtils.isEmpty(FDroidApp.ipAddressString) && netmask != null) {
FDroidApp.subnetInfo = new SubnetUtils(FDroidApp.ipAddressString, netmask).getInfo(); FDroidApp.subnetInfo = new SubnetUtils(FDroidApp.ipAddressString, netmask).getInfo();
}
} else if (wifiState == WifiManager.WIFI_STATE_DISABLED } else if (wifiState == WifiManager.WIFI_STATE_DISABLED
|| wifiState == WifiManager.WIFI_STATE_DISABLING) { || wifiState == WifiManager.WIFI_STATE_DISABLING) {
// try once to see if its a hotspot // try once to see if its a hotspot
setIpInfoFromNetworkInterface(); setIpInfoFromNetworkInterface();
if (FDroidApp.ipAddressString == null) if (FDroidApp.ipAddressString == null) {
return null; return null;
}
} else { // a hotspot can be active during WIFI_STATE_UNKNOWN } else { // a hotspot can be active during WIFI_STATE_UNKNOWN
setIpInfoFromNetworkInterface(); setIpInfoFromNetworkInterface();
} }
@ -107,8 +110,9 @@ public class WifiStateChangeService extends Service {
Utils.debugLog(TAG, "waiting for an IP address..."); Utils.debugLog(TAG, "waiting for an IP address...");
} }
} }
if (isCancelled()) // can be canceled by a change via WifiStateChangeReceiver if (isCancelled()) { // can be canceled by a change via WifiStateChangeReceiver
return null; return null;
}
if (wifiInfo != null) { if (wifiInfo != null) {
String ssid = wifiInfo.getSSID(); String ssid = wifiInfo.getSSID();
@ -124,28 +128,31 @@ public class WifiStateChangeService extends Service {
// TODO: Can this be moved to the swap service instead? // TODO: Can this be moved to the swap service instead?
String scheme; String scheme;
if (Preferences.get().isLocalRepoHttpsEnabled()) if (Preferences.get().isLocalRepoHttpsEnabled()) {
scheme = "https"; scheme = "https";
else } else {
scheme = "http"; scheme = "http";
FDroidApp.repo.name = Preferences.get().getLocalRepoName(); }
FDroidApp.repo.address = String.format(Locale.ENGLISH, "%s://%s:%d/fdroid/repo", FDroidApp.REPO.name = Preferences.get().getLocalRepoName();
FDroidApp.REPO.address = String.format(Locale.ENGLISH, "%s://%s:%d/fdroid/repo",
scheme, FDroidApp.ipAddressString, FDroidApp.port); scheme, FDroidApp.ipAddressString, FDroidApp.port);
if (isCancelled()) // can be canceled by a change via WifiStateChangeReceiver if (isCancelled()) { // can be canceled by a change via WifiStateChangeReceiver
return null; return null;
}
Context context = WifiStateChangeService.this.getApplicationContext(); Context context = WifiStateChangeService.this.getApplicationContext();
LocalRepoManager lrm = LocalRepoManager.get(context); LocalRepoManager lrm = LocalRepoManager.get(context);
lrm.writeIndexPage(Utils.getSharingUri(FDroidApp.repo).toString()); lrm.writeIndexPage(Utils.getSharingUri(FDroidApp.REPO).toString());
if (isCancelled()) // can be canceled by a change via WifiStateChangeReceiver if (isCancelled()) { // can be canceled by a change via WifiStateChangeReceiver
return null; return null;
}
// the fingerprint for the local repo's signing key // the fingerprint for the local repo's signing key
LocalRepoKeyStore localRepoKeyStore = LocalRepoKeyStore.get(context); LocalRepoKeyStore localRepoKeyStore = LocalRepoKeyStore.get(context);
Certificate localCert = localRepoKeyStore.getCertificate(); Certificate localCert = localRepoKeyStore.getCertificate();
FDroidApp.repo.fingerprint = Utils.calcFingerprint(localCert); FDroidApp.REPO.fingerprint = Utils.calcFingerprint(localCert);
/* /*
* Once the IP address is known we need to generate a self * Once the IP address is known we need to generate a self
@ -154,8 +161,9 @@ public class WifiStateChangeService extends Service {
* because if this is the first time the singleton is run, it * because if this is the first time the singleton is run, it
* can take a while to instantiate. * can take a while to instantiate.
*/ */
if (Preferences.get().isLocalRepoHttpsEnabled()) if (Preferences.get().isLocalRepoHttpsEnabled()) {
localRepoKeyStore.setupHTTPSCertificate(); localRepoKeyStore.setupHTTPSCertificate();
}
} catch (LocalRepoKeyStore.InitException | InterruptedException e) { } catch (LocalRepoKeyStore.InitException | InterruptedException e) {
Log.e(TAG, "Unable to configure a fingerprint or HTTPS for the local repo", e); Log.e(TAG, "Unable to configure a fingerprint or HTTPS for the local repo", e);
@ -204,8 +212,9 @@ public class WifiStateChangeService extends Service {
|| netIf.getDisplayName().contains("eth0") || netIf.getDisplayName().contains("eth0")
|| netIf.getDisplayName().contains("ap0")) { || netIf.getDisplayName().contains("ap0")) {
FDroidApp.ipAddressString = inetAddress.getHostAddress(); FDroidApp.ipAddressString = inetAddress.getHostAddress();
if (Build.VERSION.SDK_INT < 9) if (Build.VERSION.SDK_INT < 9) {
return; return;
}
// the following methods were not added until android-9/Gingerbread // the following methods were not added until android-9/Gingerbread
for (InterfaceAddress address : netIf.getInterfaceAddresses()) { for (InterfaceAddress address : netIf.getInterfaceAddresses()) {
if (inetAddress.equals(address.getAddress()) && !TextUtils.isEmpty(FDroidApp.ipAddressString)) { if (inetAddress.equals(address.getAddress()) && !TextUtils.isEmpty(FDroidApp.ipAddressString)) {

View File

@ -32,8 +32,9 @@ public class BluetoothClient {
return connection; return connection;
} catch (IOException e1) { } catch (IOException e1) {
if (connection != null) if (connection != null) {
connection.closeQuietly(); connection.closeQuietly();
}
throw e1; throw e1;

View File

@ -135,9 +135,10 @@ public class BluetoothServer extends Thread {
break; break;
} }
if (isInterrupted()) if (isInterrupted()) {
break; break;
} }
}
connection.closeQuietly(); connection.closeQuietly();
@ -183,8 +184,9 @@ public class BluetoothServer extends Thread {
Log.e(TAG, "error processing request; sending 500 response", e); Log.e(TAG, "error processing request; sending 500 response", e);
if (builder == null) if (builder == null) {
builder = new Response.Builder(); builder = new Response.Builder();
}
return builder return builder
.setStatusCode(500) .setStatusCode(500)

View File

@ -91,14 +91,16 @@ public final class Request {
String requestLine = readLine(); String requestLine = readLine();
if (requestLine == null || requestLine.trim().length() == 0) if (requestLine == null || requestLine.trim().length() == 0) {
return false; return false;
}
String[] parts = requestLine.split("\\s+"); String[] parts = requestLine.split("\\s+");
// First part is the method (GET/HEAD), second is the path (/fdroid/repo/index.jar) // First part is the method (GET/HEAD), second is the path (/fdroid/repo/index.jar)
if (parts.length < 2) if (parts.length < 2) {
return false; return false;
}
method = parts[0].toUpperCase(Locale.ENGLISH); method = parts[0].toUpperCase(Locale.ENGLISH);
path = parts[1]; path = parts[1];
@ -143,8 +145,9 @@ public final class Request {
int b = input.read(); int b = input.read();
if (((char) b) == '\n') { if (((char) b) == '\n') {
if (baos.size() > 0) if (baos.size() > 0) {
line = new String(baos.toByteArray()); line = new String(baos.toByteArray());
}
return line; return line;
} }
@ -180,10 +183,11 @@ public final class Request {
headers.put(header, value); headers.put(header, value);
} }
if (input.available() > 0) if (input.available() > 0) {
responseLine = readLine(); responseLine = readLine();
else } else {
break; break;
}
} }
return headers; return headers;

View File

@ -182,8 +182,9 @@ public class ManageReposActivity extends ActionBarActivity {
Uri uri = Uri.parse(text); Uri uri = Uri.parse(text);
fingerprint = uri.getQueryParameter("fingerprint"); fingerprint = uri.getQueryParameter("fingerprint");
// uri might contain a QR-style, all uppercase URL: // uri might contain a QR-style, all uppercase URL:
if (TextUtils.isEmpty(fingerprint)) if (TextUtils.isEmpty(fingerprint)) {
fingerprint = uri.getQueryParameter("FINGERPRINT"); fingerprint = uri.getQueryParameter("FINGERPRINT");
}
text = NewRepoConfig.sanitizeRepoUri(uri); text = NewRepoConfig.sanitizeRepoUri(uri);
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
text = null; text = null;
@ -683,8 +684,9 @@ public class ManageReposActivity extends ActionBarActivity {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo(); WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String bssid = wifiInfo.getBSSID(); String bssid = wifiInfo.getBSSID();
if (TextUtils.isEmpty(bssid)) /* not all devices have wifi */ if (TextUtils.isEmpty(bssid)) { /* not all devices have wifi */
return; return;
}
bssid = bssid.toLowerCase(Locale.ENGLISH); bssid = bssid.toLowerCase(Locale.ENGLISH);
String newRepoBssid = Uri.decode(newRepo.getBssid()).toLowerCase(Locale.ENGLISH); String newRepoBssid = Uri.decode(newRepo.getBssid()).toLowerCase(Locale.ENGLISH);
if (!bssid.equals(newRepoBssid)) { if (!bssid.equals(newRepoBssid)) {

View File

@ -156,8 +156,9 @@ public class RepoDetailsActivity extends ActionBarActivity {
@TargetApi(9) @TargetApi(9)
void processIntent(Intent i) { void processIntent(Intent i) {
if (Build.VERSION.SDK_INT < 9) if (Build.VERSION.SDK_INT < 9) {
return; return;
}
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(i.getAction())) { if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(i.getAction())) {
Parcelable[] rawMsgs = Parcelable[] rawMsgs =
i.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); i.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
@ -176,9 +177,10 @@ public class RepoDetailsActivity extends ActionBarActivity {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
int statusCode = intent.getIntExtra(UpdateService.EXTRA_STATUS_CODE, -1); int statusCode = intent.getIntExtra(UpdateService.EXTRA_STATUS_CODE, -1);
if (statusCode == UpdateService.STATUS_COMPLETE_WITH_CHANGES) if (statusCode == UpdateService.STATUS_COMPLETE_WITH_CHANGES) {
updateRepoView(); updateRepoView();
} }
}
}; };
@Override @Override

View File

@ -83,8 +83,9 @@ public class AvailableAppsFragment extends AppListFragment implements
// hierarchy can touch its views." // hierarchy can touch its views."
final Activity activity = getActivity(); final Activity activity = getActivity();
// this nullguard is temporary, this Fragment really needs to merged into the Activity // this nullguard is temporary, this Fragment really needs to merged into the Activity
if (activity == null) if (activity == null) {
return; return;
}
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -162,12 +163,15 @@ public class AvailableAppsFragment extends AppListFragment implements
@Override @Override
protected Uri getDataUri() { protected Uri getDataUri() {
if (currentCategory == null || currentCategory.equals(AppProvider.Helper.getCategoryAll(getActivity()))) if (currentCategory == null || currentCategory.equals(AppProvider.Helper.getCategoryAll(getActivity()))) {
return AppProvider.getContentUri(); return AppProvider.getContentUri();
if (currentCategory.equals(AppProvider.Helper.getCategoryRecentlyUpdated(getActivity()))) }
if (currentCategory.equals(AppProvider.Helper.getCategoryRecentlyUpdated(getActivity()))) {
return AppProvider.getRecentlyUpdatedUri(); return AppProvider.getRecentlyUpdatedUri();
if (currentCategory.equals(AppProvider.Helper.getCategoryWhatsNew(getActivity()))) }
if (currentCategory.equals(AppProvider.Helper.getCategoryWhatsNew(getActivity()))) {
return AppProvider.getNewlyAddedUri(); return AppProvider.getNewlyAddedUri();
}
return AppProvider.getCategoryUri(currentCategory); return AppProvider.getCategoryUri(currentCategory);
} }

View File

@ -24,7 +24,7 @@ import org.fdroid.fdroid.installer.PrivilegedInstaller;
public class PreferencesFragment extends PreferenceFragment public class PreferencesFragment extends PreferenceFragment
implements SharedPreferences.OnSharedPreferenceChangeListener { implements SharedPreferences.OnSharedPreferenceChangeListener {
private static final String[] summariesToUpdate = { private static final String[] SUMMARIES_TO_UPDATE = {
Preferences.PREF_UPD_INTERVAL, Preferences.PREF_UPD_INTERVAL,
Preferences.PREF_UPD_WIFI_ONLY, Preferences.PREF_UPD_WIFI_ONLY,
Preferences.PREF_UPD_NOTIFY, Preferences.PREF_UPD_NOTIFY,
@ -153,19 +153,21 @@ public class PreferencesFragment extends PreferenceFragment
case Preferences.PREF_PROXY_HOST: case Preferences.PREF_PROXY_HOST:
EditTextPreference textPref = (EditTextPreference) findPreference(key); EditTextPreference textPref = (EditTextPreference) findPreference(key);
String text = Preferences.get().getProxyHost(); String text = Preferences.get().getProxyHost();
if (TextUtils.isEmpty(text) || text.equals(Preferences.DEFAULT_PROXY_HOST)) if (TextUtils.isEmpty(text) || text.equals(Preferences.DEFAULT_PROXY_HOST)) {
textPref.setSummary(R.string.proxy_host_summary); textPref.setSummary(R.string.proxy_host_summary);
else } else {
textPref.setSummary(text); textPref.setSummary(text);
}
break; break;
case Preferences.PREF_PROXY_PORT: case Preferences.PREF_PROXY_PORT:
EditTextPreference textPref2 = (EditTextPreference) findPreference(key); EditTextPreference textPref2 = (EditTextPreference) findPreference(key);
int port = Preferences.get().getProxyPort(); int port = Preferences.get().getProxyPort();
if (port == Preferences.DEFAULT_PROXY_PORT) if (port == Preferences.DEFAULT_PROXY_PORT) {
textPref2.setSummary(R.string.proxy_port_summary); textPref2.setSummary(R.string.proxy_port_summary);
else } else {
textPref2.setSummary(String.valueOf(port)); textPref2.setSummary(String.valueOf(port));
}
break; break;
} }
@ -271,7 +273,7 @@ public class PreferencesFragment extends PreferenceFragment
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
for (final String key : summariesToUpdate) { for (final String key : SUMMARIES_TO_UPDATE) {
updateSummary(key, false); updateSummary(key, false);
} }

View File

@ -379,14 +379,16 @@ public class SwapAppsView extends ListView implements
private void resetView() { private void resetView() {
if (app == null) if (app == null) {
return; return;
}
progressView.setVisibility(View.GONE); progressView.setVisibility(View.GONE);
progressView.setIndeterminate(true); progressView.setIndeterminate(true);
if (app.name != null) if (app.name != null) {
nameView.setText(app.name); nameView.setText(app.name);
}
ImageLoader.getInstance().displayImage(app.iconUrl, iconView, displayImageOptions); ImageLoader.getInstance().displayImage(app.iconUrl, iconView, displayImageOptions);

View File

@ -500,7 +500,7 @@ public class SwapWorkflowActivity extends AppCompatActivity {
// Even if they opted to skip the message which says "Touch devices to swap", // Even if they opted to skip the message which says "Touch devices to swap",
// we still want to actually enable the feature, so that they could touch // we still want to actually enable the feature, so that they could touch
// during the wifi qr code being shown too. // during the wifi qr code being shown too.
boolean nfcMessageReady = NfcHelper.setPushMessage(this, Utils.getSharingUri(FDroidApp.repo)); boolean nfcMessageReady = NfcHelper.setPushMessage(this, Utils.getSharingUri(FDroidApp.REPO));
if (Preferences.get().showNfcDuringSwap() && nfcMessageReady) { if (Preferences.get().showNfcDuringSwap() && nfcMessageReady) {
inflateInnerView(R.layout.swap_nfc); inflateInnerView(R.layout.swap_nfc);
@ -603,7 +603,7 @@ public class SwapWorkflowActivity extends AppCompatActivity {
Utils.debugLog(TAG, "Initiating Bluetooth swap, will ensure the Bluetooth devices is enabled and discoverable before starting server."); Utils.debugLog(TAG, "Initiating Bluetooth swap, will ensure the Bluetooth devices is enabled and discoverable before starting server.");
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter != null) if (adapter != null) {
if (adapter.isEnabled()) { if (adapter.isEnabled()) {
Utils.debugLog(TAG, "Bluetooth enabled, will check if device is discoverable with device."); Utils.debugLog(TAG, "Bluetooth enabled, will check if device is discoverable with device.");
ensureBluetoothDiscoverableThenStart(); ensureBluetoothDiscoverableThenStart();
@ -613,6 +613,7 @@ public class SwapWorkflowActivity extends AppCompatActivity {
startActivityForResult(enableBtIntent, REQUEST_BLUETOOTH_ENABLE_FOR_SWAP); startActivityForResult(enableBtIntent, REQUEST_BLUETOOTH_ENABLE_FOR_SWAP);
} }
} }
}
private void ensureBluetoothDiscoverableThenStart() { private void ensureBluetoothDiscoverableThenStart() {
Utils.debugLog(TAG, "Ensuring Bluetooth is in discoverable mode."); Utils.debugLog(TAG, "Ensuring Bluetooth is in discoverable mode.");
@ -667,7 +668,7 @@ public class SwapWorkflowActivity extends AppCompatActivity {
PrepareSwapRepo(@NonNull Set<String> apps) { PrepareSwapRepo(@NonNull Set<String> apps) {
context = SwapWorkflowActivity.this; context = SwapWorkflowActivity.this;
selectedApps = apps; selectedApps = apps;
sharingUri = Utils.getSharingUri(FDroidApp.repo); sharingUri = Utils.getSharingUri(FDroidApp.REPO);
} }
private void broadcast(int type) { private void broadcast(int type) {

View File

@ -118,8 +118,9 @@ public class WifiQrView extends ScrollView implements SwapWorkflowActivity.Inner
private void setUIFromWifi() { private void setUIFromWifi() {
if (TextUtils.isEmpty(FDroidApp.repo.address)) if (TextUtils.isEmpty(FDroidApp.REPO.address)) {
return; return;
}
String scheme = Preferences.get().isLocalRepoHttpsEnabled() ? "https://" : "http://"; String scheme = Preferences.get().isLocalRepoHttpsEnabled() ? "https://" : "http://";
@ -135,7 +136,7 @@ public class WifiQrView extends ScrollView implements SwapWorkflowActivity.Inner
* wifi AP to join. Lots of QR Scanners are buggy and do not respect * wifi AP to join. Lots of QR Scanners are buggy and do not respect
* custom URI schemes, so we have to use http:// or https:// :-( * custom URI schemes, so we have to use http:// or https:// :-(
*/ */
Uri sharingUri = Utils.getSharingUri(FDroidApp.repo); Uri sharingUri = Utils.getSharingUri(FDroidApp.REPO);
String qrUriString = (scheme + sharingUri.getHost()).toUpperCase(Locale.ENGLISH); String qrUriString = (scheme + sharingUri.getHost()).toUpperCase(Locale.ENGLISH);
if (sharingUri.getPort() != 80) { if (sharingUri.getPort() != 80) {
qrUriString += ":" + sharingUri.getPort(); qrUriString += ":" + sharingUri.getPort();

View File

@ -17,14 +17,17 @@ public class ApkProviderHelperTest extends BaseApkProviderTest {
public void testKnownApks() { public void testKnownApks() {
for (int i = 0; i < 7; i++) for (int i = 0; i < 7; i++) {
TestUtils.insertApk(this, "org.fdroid.fdroid", i); TestUtils.insertApk(this, "org.fdroid.fdroid", i);
}
for (int i = 0; i < 9; i++) for (int i = 0; i < 9; i++) {
TestUtils.insertApk(this, "org.example", i); TestUtils.insertApk(this, "org.example", i);
}
for (int i = 0; i < 3; i++) for (int i = 0; i < 3; i++) {
TestUtils.insertApk(this, "com.example", i); TestUtils.insertApk(this, "com.example", i);
}
TestUtils.insertApk(this, "com.apk.thingo", 1); TestUtils.insertApk(this, "com.apk.thingo", 1);
@ -64,20 +67,24 @@ public class ApkProviderHelperTest extends BaseApkProviderTest {
assertResultCount(known.length, knownApks); assertResultCount(known.length, knownApks);
for (Apk knownApk : knownApks) for (Apk knownApk : knownApks) {
assertContains(knownApks, knownApk); assertContains(knownApks, knownApk);
} }
}
public void testFindByApp() { public void testFindByApp() {
for (int i = 0; i < 7; i++) for (int i = 0; i < 7; i++) {
TestUtils.insertApk(this, "org.fdroid.fdroid", i); TestUtils.insertApk(this, "org.fdroid.fdroid", i);
}
for (int i = 0; i < 9; i++) for (int i = 0; i < 9; i++) {
TestUtils.insertApk(this, "org.example", i); TestUtils.insertApk(this, "org.example", i);
}
for (int i = 0; i < 3; i++) for (int i = 0; i < 3; i++) {
TestUtils.insertApk(this, "com.example", i); TestUtils.insertApk(this, "com.example", i);
}
TestUtils.insertApk(this, "com.apk.thingo", 1); TestUtils.insertApk(this, "com.apk.thingo", 1);
@ -157,8 +164,9 @@ public class ApkProviderHelperTest extends BaseApkProviderTest {
// Insert some random apks either side of the "com.example", so that // Insert some random apks either side of the "com.example", so that
// the Helper.find() method doesn't stumble upon the app we are interested // the Helper.find() method doesn't stumble upon the app we are interested
// in by shear dumb luck... // in by shear dumb luck...
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++) {
TestUtils.insertApk(this, "org.fdroid.apk." + i, i); TestUtils.insertApk(this, "org.fdroid.apk." + i, i);
}
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(ApkProvider.DataColumns.VERSION, "v1.1"); values.put(ApkProvider.DataColumns.VERSION, "v1.1");
@ -167,8 +175,9 @@ public class ApkProviderHelperTest extends BaseApkProviderTest {
TestUtils.insertApk(this, "com.example", 11, values); TestUtils.insertApk(this, "com.example", 11, values);
// ...and a few more for good measure... // ...and a few more for good measure...
for (int i = 15; i < 20; i++) for (int i = 15; i < 20; i++) {
TestUtils.insertApk(this, "com.other.thing." + i, i); TestUtils.insertApk(this, "com.other.thing." + i, i);
}
Apk apk = ApkProvider.Helper.find(getMockContext(), "com.example", 11); Apk apk = ApkProvider.Helper.find(getMockContext(), "com.example", 11);

View File

@ -433,8 +433,9 @@ public class MultiRepoUpdaterTest extends InstrumentationTestCase {
} }
private boolean updateRepo(RepoUpdater updater, String indexJarPath) throws UpdateException { private boolean updateRepo(RepoUpdater updater, String indexJarPath) throws UpdateException {
if (!testFilesDir.canWrite()) if (!testFilesDir.canWrite()) {
return false; return false;
}
File indexJar = TestUtils.copyAssetToDir(context, indexJarPath, testFilesDir); File indexJar = TestUtils.copyAssetToDir(context, indexJarPath, testFilesDir);
updater.processDownloadedFile(indexJar); updater.processDownloadedFile(indexJar);

View File

@ -28,8 +28,9 @@ public class RepoUpdaterTest extends InstrumentationTestCase {
} }
public void testExtractIndexFromJar() { public void testExtractIndexFromJar() {
if (!testFilesDir.canWrite()) if (!testFilesDir.canWrite()) {
return; return;
}
File simpleIndexJar = TestUtils.copyAssetToDir(context, "simpleIndex.jar", testFilesDir); File simpleIndexJar = TestUtils.copyAssetToDir(context, "simpleIndex.jar", testFilesDir);
// these are supposed to succeed // these are supposed to succeed
@ -42,8 +43,9 @@ public class RepoUpdaterTest extends InstrumentationTestCase {
} }
public void testExtractIndexFromJarWithoutSignatureJar() { public void testExtractIndexFromJarWithoutSignatureJar() {
if (!testFilesDir.canWrite()) if (!testFilesDir.canWrite()) {
return; return;
}
// this is supposed to fail // this is supposed to fail
try { try {
File jarFile = TestUtils.copyAssetToDir(context, "simpleIndexWithoutSignature.jar", testFilesDir); File jarFile = TestUtils.copyAssetToDir(context, "simpleIndexWithoutSignature.jar", testFilesDir);
@ -55,8 +57,9 @@ public class RepoUpdaterTest extends InstrumentationTestCase {
} }
public void testExtractIndexFromJarWithCorruptedManifestJar() { public void testExtractIndexFromJarWithCorruptedManifestJar() {
if (!testFilesDir.canWrite()) if (!testFilesDir.canWrite()) {
return; return;
}
// this is supposed to fail // this is supposed to fail
try { try {
File jarFile = TestUtils.copyAssetToDir(context, "simpleIndexWithCorruptedManifest.jar", testFilesDir); File jarFile = TestUtils.copyAssetToDir(context, "simpleIndexWithCorruptedManifest.jar", testFilesDir);
@ -71,8 +74,9 @@ public class RepoUpdaterTest extends InstrumentationTestCase {
} }
public void testExtractIndexFromJarWithCorruptedSignature() { public void testExtractIndexFromJarWithCorruptedSignature() {
if (!testFilesDir.canWrite()) if (!testFilesDir.canWrite()) {
return; return;
}
// this is supposed to fail // this is supposed to fail
try { try {
File jarFile = TestUtils.copyAssetToDir(context, "simpleIndexWithCorruptedSignature.jar", testFilesDir); File jarFile = TestUtils.copyAssetToDir(context, "simpleIndexWithCorruptedSignature.jar", testFilesDir);
@ -87,8 +91,9 @@ public class RepoUpdaterTest extends InstrumentationTestCase {
} }
public void testExtractIndexFromJarWithCorruptedCertificate() { public void testExtractIndexFromJarWithCorruptedCertificate() {
if (!testFilesDir.canWrite()) if (!testFilesDir.canWrite()) {
return; return;
}
// this is supposed to fail // this is supposed to fail
try { try {
File jarFile = TestUtils.copyAssetToDir(context, "simpleIndexWithCorruptedCertificate.jar", testFilesDir); File jarFile = TestUtils.copyAssetToDir(context, "simpleIndexWithCorruptedCertificate.jar", testFilesDir);
@ -103,8 +108,9 @@ public class RepoUpdaterTest extends InstrumentationTestCase {
} }
public void testExtractIndexFromJarWithCorruptedEverything() { public void testExtractIndexFromJarWithCorruptedEverything() {
if (!testFilesDir.canWrite()) if (!testFilesDir.canWrite()) {
return; return;
}
// this is supposed to fail // this is supposed to fail
try { try {
File jarFile = TestUtils.copyAssetToDir(context, "simpleIndexWithCorruptedEverything.jar", testFilesDir); File jarFile = TestUtils.copyAssetToDir(context, "simpleIndexWithCorruptedEverything.jar", testFilesDir);
@ -119,8 +125,9 @@ public class RepoUpdaterTest extends InstrumentationTestCase {
} }
public void testExtractIndexFromMasterKeyIndexJar() { public void testExtractIndexFromMasterKeyIndexJar() {
if (!testFilesDir.canWrite()) if (!testFilesDir.canWrite()) {
return; return;
}
// this is supposed to fail // this is supposed to fail
try { try {
File jarFile = TestUtils.copyAssetToDir(context, "masterKeyIndex.jar", testFilesDir); File jarFile = TestUtils.copyAssetToDir(context, "masterKeyIndex.jar", testFilesDir);

View File

@ -15,7 +15,9 @@
<module name="TreeWalker"> <module name="TreeWalker">
<!--<module name="ConstantName" />--> <module name="ConstantName">
<property name="format" value="^[A-Z_][A-Z0-9]*(_[A-Z0-9]+)*$"/>
</module>
<module name="LocalFinalVariableName" /> <module name="LocalFinalVariableName" />
<module name="LocalVariableName" /> <module name="LocalVariableName" />
<module name="MemberName" /> <module name="MemberName" />
@ -86,7 +88,9 @@
<module name="LeftCurly"> <module name="LeftCurly">
<property name="maxLineLength" value="100"/> <property name="maxLineLength" value="100"/>
</module> </module>
<!--<module name="NeedBraces" />--> <module name="NeedBraces">
<property name="allowSingleLineStatement" value="true"/>
</module>
<module name="RightCurly"/> <module name="RightCurly"/>
<module name="RightCurly"> <module name="RightCurly">
<property name="option" value="alone"/> <property name="option" value="alone"/>