Fixing codacy issues. Reduced reported count from 550 to 518.

This commit is contained in:
poojithakr 2017-10-04 00:28:11 -07:00
parent 9b8d8e9b7c
commit fc9cd0a3b7
13 changed files with 51 additions and 41 deletions

View file

@ -147,10 +147,10 @@ public class CommonsApplication extends Application {
* @return Account|null * @return Account|null
*/ */
public Account getCurrentAccount() { public Account getCurrentAccount() {
if(currentAccount == null) { if (currentAccount == null) {
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
Account[] allAccounts = accountManager.getAccountsByType(AccountUtil.accountType()); Account[] allAccounts = accountManager.getAccountsByType(AccountUtil.accountType());
if(allAccounts.length != 0) { if (allAccounts.length != 0) {
currentAccount = allAccounts[0]; currentAccount = allAccounts[0];
} }
} }
@ -161,7 +161,7 @@ public class CommonsApplication extends Application {
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
Account curAccount = getCurrentAccount(); Account curAccount = getCurrentAccount();
if(curAccount == null) { if (curAccount == null) {
return false; // This should never happen return false; // This should never happen
} }
@ -224,11 +224,13 @@ public class CommonsApplication extends Application {
if (getIndex() == allAccounts.length) { if (getIndex() == allAccounts.length) {
Timber.d("All accounts have been removed"); Timber.d("All accounts have been removed");
//TODO: fix preference manager //TODO: fix preference manager
PreferenceManager.getDefaultSharedPreferences(getInstance()).edit().clear().commit(); PreferenceManager.getDefaultSharedPreferences(getInstance())
.edit().clear().commit();
SharedPreferences preferences = context SharedPreferences preferences = context
.getSharedPreferences("fr.free.nrw.commons", MODE_PRIVATE); .getSharedPreferences("fr.free.nrw.commons", MODE_PRIVATE);
preferences.edit().clear().commit(); preferences.edit().clear().commit();
context.getSharedPreferences("prefs", Context.MODE_PRIVATE).edit().clear().commit(); context.getSharedPreferences("prefs", Context.MODE_PRIVATE)
.edit().clear().commit();
preferences.edit().putBoolean("firstrun", false).apply(); preferences.edit().putBoolean("firstrun", false).apply();
updateAllDatabases(); updateAllDatabases();
currentAccount = null; currentAccount = null;

View file

@ -3,10 +3,10 @@ package fr.free.nrw.commons;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
public class License { public class License {
String key; private String key;
String template; private String template;
String url; private String url;
String name; private String name;
public License(String key, String template, String url, String name) { public License(String key, String template, String url, String name) {
if (key == null) { if (key == null) {

View file

@ -242,9 +242,9 @@ public class Utils {
public static boolean xmlFastForward(XmlPullParser parser, String namespace, String element) { public static boolean xmlFastForward(XmlPullParser parser, String namespace, String element) {
try { try {
while (parser.next() != XmlPullParser.END_DOCUMENT) { while (parser.next() != XmlPullParser.END_DOCUMENT) {
if (parser.getEventType() == XmlPullParser.START_TAG && if (parser.getEventType() == XmlPullParser.START_TAG
parser.getNamespace().equals(namespace) && && parser.getNamespace().equals(namespace)
parser.getName().equals(element)) { && parser.getName().equals(element)) {
// We found it! // We found it!
return true; return true;
} }
@ -267,7 +267,8 @@ public class Utils {
extension = "jpg"; extension = "jpg";
} }
title = jpegPattern.matcher(title).replaceFirst(".jpg"); title = jpegPattern.matcher(title).replaceFirst(".jpg");
if (extension != null && !title.toLowerCase(Locale.getDefault()).endsWith("." + extension.toLowerCase(Locale.ENGLISH))) { if (extension != null && !title.toLowerCase(Locale.getDefault())
.endsWith("." + extension.toLowerCase(Locale.ENGLISH))) {
title += "." + extension; title += "." + extension;
} }
return title; return title;

View file

@ -14,7 +14,7 @@ import timber.log.Timber;
public abstract class AuthenticatedActivity extends NavigationBaseActivity { public abstract class AuthenticatedActivity extends NavigationBaseActivity {
String accountType; private String accountType;
CommonsApplication app; CommonsApplication app;
private String authCookie; private String authCookie;

View file

@ -25,7 +25,8 @@ public class SignupActivity extends BaseActivity {
webView.setWebViewClient(new MyWebViewClient()); webView.setWebViewClient(new MyWebViewClient());
WebSettings webSettings = webView.getSettings(); WebSettings webSettings = webView.getSettings();
//Needed to refresh Captcha. Might introduce XSS vulnerabilities, but we can trust Wikimedia's site... right? /*Needed to refresh Captcha. Might introduce XSS vulnerabilities, but we can
trust Wikimedia's site... right?*/
webSettings.setJavaScriptEnabled(true); webSettings.setJavaScriptEnabled(true);
webView.loadUrl(BuildConfig.SIGNUP_LANDING_URL); webView.loadUrl(BuildConfig.SIGNUP_LANDING_URL);

View file

@ -32,7 +32,7 @@ public class CacheController {
public void cacheCategory() { public void cacheCategory() {
List<String> pointCatList = new ArrayList<>(); List<String> pointCatList = new ArrayList<>();
if (MwVolleyApi.GpsCatExists.getGpsCatExists()) { if (MwVolleyApi.GpsCatExists.getGpsCatExists()) {
pointCatList.addAll(MwVolleyApi.getGpsCat()); pointCatList.addAll(MwVolleyApi.getGpsCat());
Timber.d("Categories being cached: %s", pointCatList); Timber.d("Categories being cached: %s", pointCatList);
} else { } else {
Timber.d("No categories found, so no categories cached"); Timber.d("No categories found, so no categories cached");

View file

@ -197,7 +197,7 @@ public class CategorizationFragment extends Fragment {
.concatWith( .concatWith(
searchAll(filter) searchAll(filter)
.mergeWith(searchCategories(filter)) .mergeWith(searchCategories(filter))
.concatWith( TextUtils.isEmpty(filter) .concatWith(TextUtils.isEmpty(filter)
? defaultCategories() : Observable.empty()) ? defaultCategories() : Observable.empty())
) )
.filter(categoryItem -> !containsYear(categoryItem.getName())) .filter(categoryItem -> !containsYear(categoryItem.getName()))

View file

@ -142,11 +142,13 @@ public class CategoryContentProvider extends ContentProvider {
public int update(@NonNull Uri uri, ContentValues contentValues, String selection, public int update(@NonNull Uri uri, ContentValues contentValues, String selection,
String[] selectionArgs) { String[] selectionArgs) {
/* /*
SQL Injection warnings: First, note that we're not exposing this to the outside world (exported="false") SQL Injection warnings: First, note that we're not exposing this to the
Even then, we should make sure to sanitize all user input appropriately. Input that passes through ContentValues outside world (exported="false"). Even then, we should make sure to sanitize
all user input appropriately. Input that passes through ContentValues
should be fine. So only issues are those that pass in via concating. should be fine. So only issues are those that pass in via concating.
In here, the only concat created argument is for id. It is cast to an int, and will error out otherwise. In here, the only concat created argument is for id. It is cast to an int,
and will error out otherwise.
*/ */
int uriType = uriMatcher.match(uri); int uriType = uriMatcher.match(uri);
SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase(); SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase();

View file

@ -154,10 +154,12 @@ public class ContributionsContentProvider extends ContentProvider {
public int update(@NonNull Uri uri, ContentValues contentValues, String selection, String[] selectionArgs) { public int update(@NonNull Uri uri, ContentValues contentValues, String selection, String[] selectionArgs) {
/* /*
SQL Injection warnings: First, note that we're not exposing this to the outside world (exported="false") SQL Injection warnings: First, note that we're not exposing this to the outside world (exported="false")
Even then, we should make sure to sanitize all user input appropriately. Input that passes through ContentValues Even then, we should make sure to sanitize all user input appropriately.
should be fine. So only issues are those that pass in via concating. Input that passes through ContentValuesshould be fine. So only issues are those that pass
in via concating.
In here, the only concat created argument is for id. It is cast to an int, and will error out otherwise. In here, the only concat created argument is for id. It is cast to an int, and will
error out otherwise.
*/ */
int uriType = uriMatcher.match(uri); int uriType = uriMatcher.match(uri);
CommonsApplication app = (CommonsApplication) getContext().getApplicationContext(); CommonsApplication app = (CommonsApplication) getContext().getApplicationContext();

View file

@ -27,7 +27,7 @@ public class ModifierSequence {
public ModifierSequence(Uri mediaUri, JSONObject data) { public ModifierSequence(Uri mediaUri, JSONObject data) {
this(mediaUri); this(mediaUri);
JSONArray modifiersJSON = data.optJSONArray("modifiers"); JSONArray modifiersJSON = data.optJSONArray("modifiers");
for(int i=0; i< modifiersJSON.length(); i++) { for (int i=0; i< modifiersJSON.length(); i++) {
modifiers.add(PageModifier.fromJSON(modifiersJSON.optJSONObject(i))); modifiers.add(PageModifier.fromJSON(modifiersJSON.optJSONObject(i)));
} }
} }
@ -41,7 +41,7 @@ public class ModifierSequence {
} }
public String executeModifications(String pageName, String pageContents) { public String executeModifications(String pageName, String pageContents) {
for(PageModifier modifier: modifiers) { for (PageModifier modifier: modifiers) {
pageContents = modifier.doModification(pageName, pageContents); pageContents = modifier.doModification(pageName, pageContents);
} }
return pageContents; return pageContents;
@ -60,7 +60,7 @@ public class ModifierSequence {
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
try { try {
JSONArray modifiersJSON = new JSONArray(); JSONArray modifiersJSON = new JSONArray();
for(PageModifier modifier: modifiers) { for (PageModifier modifier: modifiers) {
modifiersJSON.put(modifier.toJSON()); modifiersJSON.put(modifier.toJSON());
} }
data.put("modifiers", modifiersJSON); data.put("modifiers", modifiersJSON);
@ -81,7 +81,8 @@ public class ModifierSequence {
// Hardcoding column positions! // Hardcoding column positions!
ModifierSequence ms = null; ModifierSequence ms = null;
try { try {
ms = new ModifierSequence(Uri.parse(cursor.getString(1)), new JSONObject(cursor.getString(2))); ms = new ModifierSequence(Uri.parse(cursor.getString(1)),
new JSONObject(cursor.getString(2)));
} catch (JSONException e) { } catch (JSONException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }

View file

@ -390,7 +390,7 @@ public class ApacheHttpClientMediaWikiApi implements MediaWikiApi {
public UploadResult uploadFile(String filename, InputStream file, long dataLength, String pageContents, String editSummary, final ProgressListener progressListener) throws IOException { public UploadResult uploadFile(String filename, InputStream file, long dataLength, String pageContents, String editSummary, final ProgressListener progressListener) throws IOException {
ApiResult result = api.upload(filename, file, dataLength, pageContents, editSummary, progressListener::onProgress); ApiResult result = api.upload(filename, file, dataLength, pageContents, editSummary, progressListener::onProgress);
Log.e("WTF", "Result: "+result.toString()); Log.e("WTF", "Result: " +result.toString());
String resultStatus = result.getString("/api/upload/@result"); String resultStatus = result.getString("/api/upload/@result");
if (!resultStatus.equals("Success")) { if (!resultStatus.equals("Success")) {

View file

@ -63,7 +63,7 @@ public class MultipleShareActivity
@Override @Override
public int getTotalMediaCount() { public int getTotalMediaCount() {
if(photosList == null) { if (photosList == null) {
return 0; return 0;
} }
return photosList.size(); return photosList.size();
@ -71,7 +71,7 @@ public class MultipleShareActivity
@Override @Override
public void notifyDatasetChanged() { public void notifyDatasetChanged() {
if(uploadsList != null) { if (uploadsList != null) {
uploadsList.notifyDatasetChanged(); uploadsList.notifyDatasetChanged();
} }
} }
@ -145,7 +145,7 @@ public class MultipleShareActivity
uploadsList.setImageOnlyMode(true); uploadsList.setImageOnlyMode(true);
categorizationFragment = (CategorizationFragment) getSupportFragmentManager().findFragmentByTag("categorization"); categorizationFragment = (CategorizationFragment) getSupportFragmentManager().findFragmentByTag("categorization");
if(categorizationFragment == null) { if (categorizationFragment == null) {
categorizationFragment = new CategorizationFragment(); categorizationFragment = new CategorizationFragment();
} }
// FIXME: Stops the keyboard from being shown 'stale' while moving out of this fragment into the next // FIXME: Stops the keyboard from being shown 'stale' while moving out of this fragment into the next
@ -162,7 +162,7 @@ public class MultipleShareActivity
@Override @Override
public void onCategoriesSave(List<String> categories) { public void onCategoriesSave(List<String> categories) {
if(categories.size() > 0) { if (categories.size() > 0) {
ContentProviderClient client = getContentResolver().acquireContentProviderClient(ModificationsContentProvider.AUTHORITY); ContentProviderClient client = getContentResolver().acquireContentProviderClient(ModificationsContentProvider.AUTHORITY);
for(Contribution contribution: photosList) { for(Contribution contribution: photosList) {
ModifierSequence categoriesSequence = new ModifierSequence(contribution.getContentUri()); ModifierSequence categoriesSequence = new ModifierSequence(contribution.getContentUri());
@ -191,7 +191,7 @@ public class MultipleShareActivity
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) { switch(item.getItemId()) {
case android.R.id.home: case android.R.id.home:
if(mediaDetails.isVisible()) { if (mediaDetails.isVisible()) {
getSupportFragmentManager().popBackStack(); getSupportFragmentManager().popBackStack();
} }
return true; return true;
@ -209,7 +209,7 @@ public class MultipleShareActivity
ButterKnife.bind(this); ButterKnife.bind(this);
initDrawer(); initDrawer();
if(savedInstanceState != null) { if (savedInstanceState != null) {
photosList = savedInstanceState.getParcelableArrayList("uploadsList"); photosList = savedInstanceState.getParcelableArrayList("uploadsList");
} }
@ -225,7 +225,7 @@ public class MultipleShareActivity
} }
private void showDetail(int i) { private void showDetail(int i) {
if(mediaDetails == null ||!mediaDetails.isVisible()) { if (mediaDetails == null ||!mediaDetails.isVisible()) {
mediaDetails = new MediaDetailPagerFragment(true); mediaDetails = new MediaDetailPagerFragment(true);
getSupportFragmentManager() getSupportFragmentManager()
.beginTransaction() .beginTransaction()
@ -248,8 +248,8 @@ public class MultipleShareActivity
app.getMWApi().setAuthCookie(authCookie); app.getMWApi().setAuthCookie(authCookie);
Intent intent = getIntent(); Intent intent = getIntent();
if(intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) { if (intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
if(photosList == null) { if (photosList == null) {
photosList = new ArrayList<>(); photosList = new ArrayList<>();
ArrayList<Uri> urisList = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); ArrayList<Uri> urisList = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
for(int i=0; i < urisList.size(); i++) { for(int i=0; i < urisList.size(); i++) {
@ -265,7 +265,7 @@ public class MultipleShareActivity
} }
uploadsList = (MultipleUploadListFragment) getSupportFragmentManager().findFragmentByTag("uploadsList"); uploadsList = (MultipleUploadListFragment) getSupportFragmentManager().findFragmentByTag("uploadsList");
if(uploadsList == null) { if (uploadsList == null) {
uploadsList = new MultipleUploadListFragment(); uploadsList = new MultipleUploadListFragment();
getSupportFragmentManager() getSupportFragmentManager()
.beginTransaction() .beginTransaction()
@ -287,7 +287,7 @@ public class MultipleShareActivity
@Override @Override
public void onBackPressed() { public void onBackPressed() {
super.onBackPressed(); super.onBackPressed();
if(categorizationFragment != null && categorizationFragment.isVisible()) { if (categorizationFragment != null && categorizationFragment.isVisible()) {
EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT) EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT)
.param("username", app.getCurrentAccount().name) .param("username", app.getCurrentAccount().name)
.param("categories-count", categorizationFragment.getCurrentSelectedCount()) .param("categories-count", categorizationFragment.getCurrentSelectedCount())
@ -307,7 +307,7 @@ public class MultipleShareActivity
@Override @Override
public void onBackStackChanged() { public void onBackStackChanged() {
if(mediaDetails != null && mediaDetails.isVisible()) { if (mediaDetails != null && mediaDetails.isVisible()) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else { } else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(false);

View file

@ -86,7 +86,8 @@ public class SingleUploadFragment extends Fragment {
} }
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_single_upload, container, false); View rootView = inflater.inflate(R.layout.fragment_single_upload, container, false);
ButterKnife.bind(this, rootView); ButterKnife.bind(this, rootView);