From c64a64c905f615cdb96299307245b5011b688d32 Mon Sep 17 00:00:00 2001 From: misaochan Date: Wed, 21 Oct 2015 19:29:08 +1300 Subject: [PATCH] Removed dead code behind Campaigns feature - Removed entire Campaigns folder and associated classes - Removed associated code in other classes (mostly that test for campaign == null). I am assuming we want to keep the behaviour where campaign == null (ie campaigns are disabled) and discard the behaviour where campaign != null - Refactored code to fix spacing --- .../free/nrw/commons/CommonsApplication.java | 22 +- .../java/fr/free/nrw/commons/EventLog.java | 14 +- .../fr/free/nrw/commons/HandlerService.java | 3 +- .../main/java/fr/free/nrw/commons/Media.java | 17 +- .../free/nrw/commons/MediaDataExtractor.java | 9 +- .../free/nrw/commons/MediaWikiImageView.java | 38 ++-- .../fr/free/nrw/commons/SettingsActivity.java | 5 +- .../main/java/fr/free/nrw/commons/Utils.java | 33 ++- .../fr/free/nrw/commons/WelcomeActivity.java | 10 +- .../commons/auth/AuthenticatedActivity.java | 46 ++-- .../free/nrw/commons/auth/LoginActivity.java | 28 +-- .../auth/WikiAccountAuthenticator.java | 4 +- .../auth/WikiAccountAuthenticatorService.java | 8 +- .../free/nrw/commons/campaigns/Campaign.java | 190 ---------------- .../commons/campaigns/CampaignActivity.java | 59 ----- .../campaigns/CampaignContribution.java | 49 ----- .../campaigns/CampaignsContentProvider.java | 206 ------------------ .../campaigns/CampaignsListAdapter.java | 38 ---- .../campaigns/CampaignsSyncAdapter.java | 90 -------- .../campaigns/CampaignsSyncService.java | 26 --- .../category/CategorizationFragment.java | 35 +-- .../free/nrw/commons/category/Category.java | 16 +- .../category/CategoryContentProvider.java | 12 +- .../commons/contributions/Contribution.java | 48 ++-- .../contributions/ContributionController.java | 21 +- .../contributions/ContributionViewHolder.java | 8 +- .../contributions/ContributionsActivity.java | 88 +++----- .../ContributionsContentProvider.java | 18 +- .../ContributionsListAdapter.java | 25 ++- .../ContributionsListFragment.java | 38 ++-- .../ContributionsSyncAdapter.java | 22 +- .../contributions/MediaListAdapter.java | 13 +- .../free/nrw/commons/data/DBOpenHelper.java | 5 +- .../commons/media/CategoryImagesLoader.java | 4 +- .../commons/media/MediaDetailFragment.java | 20 +- .../media/MediaDetailPagerFragment.java | 45 ++-- .../modifications/CategoryModifier.java | 4 +- .../ModificationsContentProvider.java | 16 +- .../ModificationsSyncAdapter.java | 14 +- .../modifications/ModifierSequence.java | 14 +- .../commons/modifications/PageModifier.java | 4 +- .../modifications/TemplateRemoveModifier.java | 10 +- .../commons/upload/MultipleShareActivity.java | 52 ++--- .../upload/MultipleUploadListFragment.java | 38 ++-- .../nrw/commons/upload/ShareActivity.java | 50 ++--- .../commons/upload/SingleUploadFragment.java | 16 +- .../nrw/commons/upload/UploadController.java | 44 ++-- .../nrw/commons/upload/UploadService.java | 24 +- 48 files changed, 462 insertions(+), 1137 deletions(-) delete mode 100644 commons/src/main/java/fr/free/nrw/commons/campaigns/Campaign.java delete mode 100644 commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignActivity.java delete mode 100644 commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignContribution.java delete mode 100644 commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsContentProvider.java delete mode 100644 commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsListAdapter.java delete mode 100644 commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsSyncAdapter.java delete mode 100644 commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsSyncService.java diff --git a/commons/src/main/java/fr/free/nrw/commons/CommonsApplication.java b/commons/src/main/java/fr/free/nrw/commons/CommonsApplication.java index ea8f0c210..7ce3f2671 100644 --- a/commons/src/main/java/fr/free/nrw/commons/CommonsApplication.java +++ b/commons/src/main/java/fr/free/nrw/commons/CommonsApplication.java @@ -58,7 +58,7 @@ public class CommonsApplication extends Application { public static final Object[] EVENT_LOGIN_ATTEMPT = {"MobileAppLoginAttempts", 5257721L}; public static final Object[] EVENT_SHARE_ATTEMPT = {"MobileAppShareAttempts", 5346170L}; public static final Object[] EVENT_CATEGORIZATION_ATTEMPT = {"MobileAppCategorizationAttempts", 5359208L}; - + public static final String DEFAULT_EDIT_SUMMARY = "Uploaded using Android Commons app"; @@ -85,7 +85,7 @@ public class CommonsApplication extends Application { public DBOpenHelper getDbOpenHelper() { - if(dbOpenHelper == null) { + if (dbOpenHelper == null) { dbOpenHelper = new DBOpenHelper(this); } return dbOpenHelper; @@ -154,7 +154,7 @@ public class CommonsApplication extends Application { private LruCache imageCache; public com.android.volley.toolbox.ImageLoader getImageLoader() { - if(imageLoader == null) { + if (imageLoader == null) { imageLoader = new com.android.volley.toolbox.ImageLoader(volleyQueue, new com.android.volley.toolbox.ImageLoader.ImageCache() { public Bitmap getBitmap(String key) { return imageCache.get(key); @@ -168,30 +168,30 @@ public class CommonsApplication extends Application { } return imageLoader; } - + public MWApi getApi() { return api; } - + public Account getCurrentAccount() { - if(currentAccount == null) { + if (currentAccount == null) { AccountManager accountManager = AccountManager.get(this); Account[] allAccounts = accountManager.getAccountsByType(WikiAccountAuthenticator.COMMONS_ACCOUNT_TYPE); - if(allAccounts.length != 0) { + if (allAccounts.length != 0) { currentAccount = allAccounts[0]; } } return currentAccount; } - + public Boolean revalidateAuthToken() { AccountManager accountManager = AccountManager.get(this); Account curAccount = getCurrentAccount(); - - if(curAccount == null) { + + if (curAccount == null) { return false; // This should never happen } - + accountManager.invalidateAuthToken(WikiAccountAuthenticator.COMMONS_ACCOUNT_TYPE, api.getAuthCookie()); try { String authCookie = accountManager.blockingGetAuthToken(curAccount, "", false); diff --git a/commons/src/main/java/fr/free/nrw/commons/EventLog.java b/commons/src/main/java/fr/free/nrw/commons/EventLog.java index a860f4878..876437dd2 100644 --- a/commons/src/main/java/fr/free/nrw/commons/EventLog.java +++ b/commons/src/main/java/fr/free/nrw/commons/EventLog.java @@ -7,6 +7,7 @@ import android.util.*; import in.yuvi.http.fluent.Http; import org.apache.http.HttpResponse; import org.json.*; + import java.io.IOException; import java.net.*; @@ -19,16 +20,16 @@ public class EventLog { @Override protected Boolean doInBackground(LogBuilder... logBuilders) { - boolean allSuccess = true; + boolean allSuccess = true; // Not using the default URL connection, since that seems to have different behavior than the rest of the code - for(LogBuilder logBuilder: logBuilders) { + for (LogBuilder logBuilder : logBuilders) { HttpURLConnection conn; try { URL url = logBuilder.toUrl(); HttpResponse response = Http.get(url.toString()).use(CommonsApplication.createHttpClient()).asResponse(); - if(response.getStatusLine().getStatusCode() != 204) { + if (response.getStatusLine().getStatusCode() != 204) { allSuccess = false; } Log.d("Commons", "EventLog hit " + url.toString()); @@ -45,6 +46,7 @@ public class EventLog { } private static final String DEVICE; + static { if (Build.MODEL.startsWith(Build.MANUFACTURER)) { DEVICE = Utils.capitalize(Build.MODEL); @@ -100,7 +102,7 @@ public class EventLog { // Attempting to use anywhere else will cause kitten explosions public void log(boolean force) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(app); - if(!settings.getBoolean(Prefs.TRACKING_ENABLED, true) && !force) { + if (!settings.getBoolean(Prefs.TRACKING_ENABLED, true) && !force) { return; // User has disabled tracking } LogTask logTask = new LogTask(); @@ -118,9 +120,9 @@ public class EventLog { } public static LogBuilder schema(Object[] scid) { - if(scid.length != 2) { + if (scid.length != 2) { throw new IllegalArgumentException("Needs an object array with schema as first param and revision as second"); } - return schema((String)scid[0], (Long)scid[1]); + return schema((String) scid[0], (Long) scid[1]); } } diff --git a/commons/src/main/java/fr/free/nrw/commons/HandlerService.java b/commons/src/main/java/fr/free/nrw/commons/HandlerService.java index f2e30ffec..108b3c800 100644 --- a/commons/src/main/java/fr/free/nrw/commons/HandlerService.java +++ b/commons/src/main/java/fr/free/nrw/commons/HandlerService.java @@ -16,7 +16,7 @@ public abstract class HandlerService extends Service { @Override public void handleMessage(Message msg) { - handle(msg.what, (T)msg.obj); + handle(msg.what, (T) msg.obj); stopSelf(msg.arg1); } } @@ -35,6 +35,7 @@ public abstract class HandlerService extends Service { } private final IBinder localBinder = new HandlerServiceLocalBinder(); + @Override public IBinder onBind(Intent intent) { return localBinder; diff --git a/commons/src/main/java/fr/free/nrw/commons/Media.java b/commons/src/main/java/fr/free/nrw/commons/Media.java index ba0053442..7d442da28 100644 --- a/commons/src/main/java/fr/free/nrw/commons/Media.java +++ b/commons/src/main/java/fr/free/nrw/commons/Media.java @@ -34,14 +34,15 @@ public class Media implements Parcelable { } public static Pattern displayTitlePattern = Pattern.compile("(.*)(\\.\\w+)", Pattern.CASE_INSENSITIVE); - public String getDisplayTitle() { - if(filename == null) { + + public String getDisplayTitle() { + if (filename == null) { return ""; } // FIXME: Gross hack bercause my regex skills suck maybe or I am too lazy who knows String title = filename.replaceFirst("^File:", ""); Matcher matcher = displayTitlePattern.matcher(title); - if(matcher.matches()) { + if (matcher.matches()) { return matcher.group(1); } else { return title; @@ -58,7 +59,7 @@ public class Media implements Parcelable { } public String getImageUrl() { - if(imageUrl == null) { + if (imageUrl == null) { imageUrl = Utils.makeThumbBaseUrl(this.getFilename()); } return imageUrl; @@ -151,7 +152,7 @@ public class Media implements Parcelable { protected Map descriptions; // multilingual descriptions as loaded public ArrayList getCategories() { - return (ArrayList)categories.clone(); // feels dirty + return (ArrayList) categories.clone(); // feels dirty } public void setCategories(List categories) { @@ -159,7 +160,7 @@ public class Media implements Parcelable { this.categories.addAll(categories); } - public void setDescriptions(Map descriptions) { + public void setDescriptions(Map descriptions) { for (String key : this.descriptions.keySet()) { this.descriptions.remove(key); } @@ -223,7 +224,7 @@ public class Media implements Parcelable { } public Media(Parcel in) { - localUri = (Uri)in.readParcelable(Uri.class.getClassLoader()); + localUri = (Uri) in.readParcelable(Uri.class.getClassLoader()); imageUrl = in.readString(); filename = in.readString(); description = in.readString(); @@ -231,7 +232,7 @@ public class Media implements Parcelable { dateCreated = (Date) in.readSerializable(); dateUploaded = (Date) in.readSerializable(); creator = in.readString(); - tags = (HashMap)in.readSerializable(); + tags = (HashMap) in.readSerializable(); width = in.readInt(); height = in.readInt(); license = in.readString(); diff --git a/commons/src/main/java/fr/free/nrw/commons/MediaDataExtractor.java b/commons/src/main/java/fr/free/nrw/commons/MediaDataExtractor.java index 2e8a17094..c87d46ebc 100644 --- a/commons/src/main/java/fr/free/nrw/commons/MediaDataExtractor.java +++ b/commons/src/main/java/fr/free/nrw/commons/MediaDataExtractor.java @@ -20,7 +20,7 @@ import java.util.regex.Pattern; /** * Fetch additional media data from the network that we don't store locally. - * + *

* This includes things like category lists and multilingual descriptions, * which are not intrinsic to the media and may change due to editing. */ @@ -51,7 +51,7 @@ public class MediaDataExtractor { /** * Actually fetch the data over the network. * todo: use local caching? - * + *

* Warning: synchronous i/o, call on a background thread */ public void fetch() throws IOException { @@ -156,7 +156,7 @@ public class MediaDataExtractor { } private Node findTemplate(Element parentNode, String title) throws IOException { - String ucTitle= Utils.capitalize(title); + String ucTitle = Utils.capitalize(title); NodeList nodes = parentNode.getChildNodes(); for (int i = 0, length = nodes.getLength(); i < length; i++) { Node node = nodes.item(i); @@ -200,7 +200,7 @@ public class MediaDataExtractor { return findTemplateParameter(templateNode, new TemplateChildNodeComparator() { @Override public boolean match(Node node) { - Element el = (Element)node; + Element el = (Element) node; if (el.getTextContent().trim().equals(theIndex)) { return true; } else if (el.getAttribute("index") != null && el.getAttribute("index").trim().equals(theIndex)) { @@ -278,6 +278,7 @@ public class MediaDataExtractor { /** * Take our metadata and inject it into a live Media object. * Media object might contain stale or cached data, or emptiness. + * * @param media */ public void fill(Media media) { diff --git a/commons/src/main/java/fr/free/nrw/commons/MediaWikiImageView.java b/commons/src/main/java/fr/free/nrw/commons/MediaWikiImageView.java index f733edcf3..c8726b0d3 100644 --- a/commons/src/main/java/fr/free/nrw/commons/MediaWikiImageView.java +++ b/commons/src/main/java/fr/free/nrw/commons/MediaWikiImageView.java @@ -1,12 +1,12 @@ /** * Copyright (C) 2013 The Android Open Source Project - * + *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -85,29 +85,29 @@ public class MediaWikiImageView extends ImageView { return; } - if(mMedia == null) { + if (mMedia == null) { return; } // Do not count for density when loading thumbnails. // FIXME: Use another 'algorithm' that doesn't punish low res devices - if(isThumbnail) { - float dpFactor = Math.max(getResources().getDisplayMetrics().density, 1.0f); + if (isThumbnail) { + float dpFactor = Math.max(getResources().getDisplayMetrics().density, 1.0f); width = (int) (width / dpFactor); height = (int) (height / dpFactor); } - final String mUrl; - if(tryOriginal) { + final String mUrl; + if (tryOriginal) { mUrl = mMedia.getImageUrl(); } else { // Round it to the nearest 320 // Possible a similar size image has already been generated. // Reduces Server cache fragmentation, also increases chance of cache hit // If width is less than 320, we round up to 320 - int bucketedWidth = width <= 320 ? 320 : Math.round((float)width / 320.0f) * 320; - if(mMedia.getWidth() != 0 && mMedia.getWidth() < bucketedWidth) { + int bucketedWidth = width <= 320 ? 320 : Math.round((float) width / 320.0f) * 320; + if (mMedia.getWidth() != 0 && mMedia.getWidth() < bucketedWidth) { // If we know that the width of the image is lesser than the required width // We don't even try to load the thumbnai, go directly to the source loadImageIfNecessary(isInLayoutPass, true); @@ -137,10 +137,10 @@ public class MediaWikiImageView extends ImageView { } else { // if there is a pre-existing request, cancel it if it's fetching a different URL. mImageContainer.cancelRequest(); - BitmapDrawable actualDrawable = (BitmapDrawable)getDrawable(); - if(actualDrawable != null && actualDrawable.getBitmap() != null) { + BitmapDrawable actualDrawable = (BitmapDrawable) getDrawable(); + if (actualDrawable != null && actualDrawable.getBitmap() != null) { setImageBitmap(null); - if(loadingView != null) { + if (loadingView != null) { loadingView.setVisibility(View.VISIBLE); } } @@ -153,7 +153,7 @@ public class MediaWikiImageView extends ImageView { new ImageListener() { @Override public void onErrorResponse(final VolleyError error) { - if(!tryOriginal) { + if (!tryOriginal) { post(new Runnable() { public void run() { loadImageIfNecessary(false, true); @@ -181,14 +181,14 @@ public class MediaWikiImageView extends ImageView { if (response.getBitmap() != null) { setImageBitmap(response.getBitmap()); - if(tryOriginal && mMedia instanceof Contribution && (response.getBitmap().getWidth() > mMedia.getWidth() || response.getBitmap().getHeight() > mMedia.getHeight())) { + if (tryOriginal && mMedia instanceof Contribution && (response.getBitmap().getWidth() > mMedia.getWidth() || response.getBitmap().getHeight() > mMedia.getHeight())) { // If there is no width information for this image, save it. This speeds up image loading massively for smaller images mMedia.setHeight(response.getBitmap().getHeight()); mMedia.setWidth(response.getBitmap().getWidth()); - ((Contribution)mMedia).setContentProviderClient(MediaWikiImageView.this.getContext().getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY)); - ((Contribution)mMedia).save(); + ((Contribution) mMedia).setContentProviderClient(MediaWikiImageView.this.getContext().getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY)); + ((Contribution) mMedia).save(); } - if(loadingView != null) { + if (loadingView != null) { loadingView.setVisibility(View.GONE); } } else { diff --git a/commons/src/main/java/fr/free/nrw/commons/SettingsActivity.java b/commons/src/main/java/fr/free/nrw/commons/SettingsActivity.java index e8b3146c1..df9547237 100644 --- a/commons/src/main/java/fr/free/nrw/commons/SettingsActivity.java +++ b/commons/src/main/java/fr/free/nrw/commons/SettingsActivity.java @@ -9,6 +9,7 @@ import com.actionbarsherlock.app.SherlockPreferenceActivity; public class SettingsActivity extends SherlockPreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { CommonsApplication app; + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -29,12 +30,12 @@ public class SettingsActivity extends SherlockPreferenceActivity implements Shar licensePreference.setSummary(getString(Utils.licenseNameFor(licensePreference.getValue()))); licensePreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { - preference.setSummary(getString(Utils.licenseNameFor((String)newValue))); + preference.setSummary(getString(Utils.licenseNameFor((String) newValue))); return true; } }); - app = (CommonsApplication)getApplicationContext(); + app = (CommonsApplication) getApplicationContext(); } @Override diff --git a/commons/src/main/java/fr/free/nrw/commons/Utils.java b/commons/src/main/java/fr/free/nrw/commons/Utils.java index c3e3e7d9f..19e344ead 100644 --- a/commons/src/main/java/fr/free/nrw/commons/Utils.java +++ b/commons/src/main/java/fr/free/nrw/commons/Utils.java @@ -72,8 +72,7 @@ public class Utils { T... params) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); - } - else { + } else { task.execute(params); } } @@ -83,16 +82,16 @@ public class Utils { // FIXME: We're simply ignoring the executor on older androids if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { task.executeOnExecutor(executor, params); - } - else { + } else { task.execute(params); } } private static DisplayImageOptions.Builder defaultImageOptionsBuilder; + public static DisplayImageOptions.Builder getGenericDisplayOptions() { - if(defaultImageOptionsBuilder == null) { + if (defaultImageOptionsBuilder == null) { defaultImageOptionsBuilder = new DisplayImageOptions.Builder().cacheInMemory() .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { @@ -122,7 +121,7 @@ public class Utils { public static long countBytes(InputStream stream) throws IOException { long count = 0; BufferedInputStream bis = new BufferedInputStream(stream); - while(bis.read() != -1) { + while (bis.read() != -1) { count++; } return count; @@ -132,7 +131,7 @@ public class Utils { // Ugly Hack! // Update: OH DEAR GOD WHAT A HORRIBLE HACK I AM SO SORRY String thumbUrl = imageUrl.replaceFirst("test/", "test/thumb/").replace("commons/", "commons/thumb/") + "/" + width + "px-" + filename.replaceAll("File:", "").replaceAll(" ", "_"); - if(thumbUrl.endsWith("jpg") || thumbUrl.endsWith("png") || thumbUrl.endsWith("jpeg")) { + if (thumbUrl.endsWith("jpg") || thumbUrl.endsWith("png") || thumbUrl.endsWith("jpeg")) { return thumbUrl; } else { return thumbUrl + ".png"; @@ -140,37 +139,37 @@ public class Utils { } public static String capitalize(String string) { - return string.substring(0,1).toUpperCase() + string.substring(1); + return string.substring(0, 1).toUpperCase() + string.substring(1); } public static String licenseTemplateFor(String license) { - if(license.equals(Prefs.Licenses.CC_BY)) { + if (license.equals(Prefs.Licenses.CC_BY)) { return "{{self|cc-by-3.0}}"; - } else if(license.equals(Prefs.Licenses.CC_BY_SA)) { + } else if (license.equals(Prefs.Licenses.CC_BY_SA)) { return "{{self|cc-by-sa-3.0}}"; - } else if(license.equals(Prefs.Licenses.CC0)) { + } else if (license.equals(Prefs.Licenses.CC0)) { return "{{self|cc-zero}}"; } throw new RuntimeException("Unrecognized license value"); } public static int licenseNameFor(String license) { - if(license.equals(Prefs.Licenses.CC_BY)) { + if (license.equals(Prefs.Licenses.CC_BY)) { return R.string.license_name_cc_by; - } else if(license.equals(Prefs.Licenses.CC_BY_SA)) { + } else if (license.equals(Prefs.Licenses.CC_BY_SA)) { return R.string.license_name_cc_by_sa; - } else if(license.equals(Prefs.Licenses.CC0)) { + } else if (license.equals(Prefs.Licenses.CC0)) { return R.string.license_name_cc0; } throw new RuntimeException("Unrecognized license value"); } public static String licenseUrlFor(String license) { - if(license.equals(Prefs.Licenses.CC_BY)) { + if (license.equals(Prefs.Licenses.CC_BY)) { return "https://creativecommons.org/licenses/by/3.0/"; - } else if(license.equals(Prefs.Licenses.CC_BY_SA)) { + } else if (license.equals(Prefs.Licenses.CC_BY_SA)) { return "https://creativecommons.org/licenses/by-sa/3.0/"; - } else if(license.equals(Prefs.Licenses.CC0)) { + } else if (license.equals(Prefs.Licenses.CC0)) { return "https://creativecommons.org/publicdomain/zero/1.0/"; } throw new RuntimeException("Unrecognized license value"); diff --git a/commons/src/main/java/fr/free/nrw/commons/WelcomeActivity.java b/commons/src/main/java/fr/free/nrw/commons/WelcomeActivity.java index da05dfd08..34822d934 100644 --- a/commons/src/main/java/fr/free/nrw/commons/WelcomeActivity.java +++ b/commons/src/main/java/fr/free/nrw/commons/WelcomeActivity.java @@ -14,7 +14,7 @@ public class WelcomeActivity extends Activity { static final int PAGE_WIKIPEDIA = 0, PAGE_COPYRIGHT = 1, PAGE_FINAL = 2; - static final int[] pageLayouts = new int[] { + static final int[] pageLayouts = new int[]{ R.layout.welcome_wikipedia, R.layout.welcome_copyright, R.layout.welcome_final @@ -28,7 +28,7 @@ public class WelcomeActivity extends Activity { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); - pager = (ViewPager)findViewById(R.id.welcomePager); + pager = (ViewPager) findViewById(R.id.welcomePager); pager.setAdapter(new PagerAdapter() { @Override public int getCount() { @@ -45,7 +45,7 @@ public class WelcomeActivity extends Activity { View view = getLayoutInflater().inflate(pageLayouts[position], null); container.addView(view); if (position == PAGE_FINAL) { - yesButton = (Button)view.findViewById(R.id.welcomeYesButton); + yesButton = (Button) view.findViewById(R.id.welcomeYesButton); yesButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { finish(); @@ -58,11 +58,11 @@ public class WelcomeActivity extends Activity { @Override public void destroyItem(ViewGroup container, int position, Object obj) { yesButton = null; - container.removeView((View)obj); + container.removeView((View) obj); } }); - CirclePageIndicator indicator = (CirclePageIndicator)findViewById(R.id.welcomePagerIndicator); + CirclePageIndicator indicator = (CirclePageIndicator) findViewById(R.id.welcomePagerIndicator); indicator.setViewPager(pager); } } diff --git a/commons/src/main/java/fr/free/nrw/commons/auth/AuthenticatedActivity.java b/commons/src/main/java/fr/free/nrw/commons/auth/AuthenticatedActivity.java index a7579e54e..26251cf13 100644 --- a/commons/src/main/java/fr/free/nrw/commons/auth/AuthenticatedActivity.java +++ b/commons/src/main/java/fr/free/nrw/commons/auth/AuthenticatedActivity.java @@ -12,30 +12,31 @@ import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.Utils; public class AuthenticatedActivity extends SherlockFragmentActivity { - - + + String accountType; CommonsApplication app; private String authCookie; - + public AuthenticatedActivity(String accountType) { - this.accountType = accountType; + this.accountType = accountType; } - + private class GetAuthCookieTask extends AsyncTask { private Account account; private AccountManager accountManager; + public GetAuthCookieTask(Account account, AccountManager accountManager) { this.account = account; this.accountManager = accountManager; } - + @Override protected void onPostExecute(String result) { super.onPostExecute(result); - if(result != null) { + if (result != null) { authCookie = result; onAuthCookieAcquired(result); } else { @@ -59,19 +60,20 @@ public class AuthenticatedActivity extends SherlockFragmentActivity { } } } - - + + private class AddAccountTask extends AsyncTask { private AccountManager accountManager; + public AddAccountTask(AccountManager accountManager) { this.accountManager = accountManager; } - + @Override protected void onPostExecute(String result) { super.onPostExecute(result); - if(result != null) { - Account[] allAccounts =accountManager.getAccountsByType(accountType); + if (result != null) { + Account[] allAccounts = accountManager.getAccountsByType(accountType); Account curAccount = allAccounts[0]; GetAuthCookieTask getCookieTask = new GetAuthCookieTask(curAccount, accountManager); getCookieTask.execute(); @@ -98,22 +100,23 @@ public class AuthenticatedActivity extends SherlockFragmentActivity { e.printStackTrace(); return null; } - if(result.containsKey(AccountManager.KEY_ACCOUNT_NAME)) { + if (result.containsKey(AccountManager.KEY_ACCOUNT_NAME)) { return result.getString(AccountManager.KEY_ACCOUNT_NAME); } else { return null; } - + } } + protected void requestAuthToken() { - if(authCookie != null) { + if (authCookie != null) { onAuthCookieAcquired(authCookie); return; } AccountManager accountManager = AccountManager.get(this); Account curAccount = app.getCurrentAccount(); - if(curAccount == null) { + if (curAccount == null) { AddAccountTask addAccountTask = new AddAccountTask(accountManager); // This AsyncTask blocks until the Login Activity returns // And since in Android 4.x+ only one background thread runs all AsyncTasks @@ -127,12 +130,12 @@ public class AuthenticatedActivity extends SherlockFragmentActivity { task.execute(); } } - + @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - app = (CommonsApplication)this.getApplicationContext(); - if(savedInstanceState != null) { + app = (CommonsApplication) this.getApplicationContext(); + if (savedInstanceState != null) { authCookie = savedInstanceState.getString("authCookie"); } } @@ -144,9 +147,10 @@ public class AuthenticatedActivity extends SherlockFragmentActivity { } protected void onAuthCookieAcquired(String authCookie) { - + } + protected void onAuthFailure() { - + } } diff --git a/commons/src/main/java/fr/free/nrw/commons/auth/LoginActivity.java b/commons/src/main/java/fr/free/nrw/commons/auth/LoginActivity.java index 521895285..8cbdc2cea 100644 --- a/commons/src/main/java/fr/free/nrw/commons/auth/LoginActivity.java +++ b/commons/src/main/java/fr/free/nrw/commons/auth/LoginActivity.java @@ -17,7 +17,6 @@ import android.support.v4.app.NavUtils; import fr.free.nrw.commons.*; import fr.free.nrw.commons.WelcomeActivity; -import fr.free.nrw.commons.campaigns.CampaignsContentProvider; import fr.free.nrw.commons.modifications.ModificationsContentProvider; import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.EventLog; @@ -72,21 +71,20 @@ public class LoginActivity extends AccountAuthenticatorActivity { // FIXME: If the user turns it off, it shouldn't be auto turned back on ContentResolver.setSyncAutomatically(account, ContributionsContentProvider.AUTHORITY, true); // Enable sync by default! ContentResolver.setSyncAutomatically(account, ModificationsContentProvider.AUTHORITY, true); // Enable sync by default! - ContentResolver.setSyncAutomatically(account, CampaignsContentProvider.AUTHORITY, true); // Enable sync by default! context.finish(); } else { int response; - if(result.equals("NetworkFailure")) { + if (result.equals("NetworkFailure")) { response = R.string.login_failed_network; - } else if(result.equals("NotExists") || result.equals("Illegal") || result.equals("NotExists")) { + } else if (result.equals("NotExists") || result.equals("Illegal") || result.equals("NotExists")) { response = R.string.login_failed_username; passwordEdit.setText(""); - } else if(result.equals("EmptyPass") || result.equals("WrongPass")) { + } else if (result.equals("EmptyPass") || result.equals("WrongPass")) { response = R.string.login_failed_password; passwordEdit.setText(""); - } else if(result.equals("Throttled")) { + } else if (result.equals("Throttled")) { response = R.string.login_failed_throttled; - } else if(result.equals("Blocked")) { + } else if (result.equals("Blocked")) { response = R.string.login_failed_blocked; } else { // Should never really happen @@ -139,12 +137,14 @@ public class LoginActivity extends AccountAuthenticatorActivity { final LoginActivity that = this; TextWatcher loginEnabler = new TextWatcher() { - public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) { } + public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) { + } - public void onTextChanged(CharSequence charSequence, int start, int count, int after) { } + public void onTextChanged(CharSequence charSequence, int start, int count, int after) { + } public void afterTextChanged(Editable editable) { - if(usernameEdit.getText().length() != 0 && passwordEdit.getText().length() != 0) { + if (usernameEdit.getText().length() != 0 && passwordEdit.getText().length() != 0) { loginButton.setEnabled(true); } else { loginButton.setEnabled(false); @@ -190,7 +190,7 @@ public class LoginActivity extends AccountAuthenticatorActivity { private void performLogin() { String username = usernameEdit.getText().toString(); // Because Mediawiki is upercase-first-char-then-case-sensitive :) - String canonicalUsername = username.substring(0,1).toUpperCase() + username.substring(1); + String canonicalUsername = username.substring(0, 1).toUpperCase() + username.substring(1); String password = passwordEdit.getText().toString(); @@ -208,9 +208,9 @@ public class LoginActivity extends AccountAuthenticatorActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { - case android.R.id.home: - NavUtils.navigateUpFromSameTask(this); - return true; + case android.R.id.home: + NavUtils.navigateUpFromSameTask(this); + return true; } return super.onOptionsItemSelected(item); } diff --git a/commons/src/main/java/fr/free/nrw/commons/auth/WikiAccountAuthenticator.java b/commons/src/main/java/fr/free/nrw/commons/auth/WikiAccountAuthenticator.java index 0cb35cf1b..5c6e51cc5 100644 --- a/commons/src/main/java/fr/free/nrw/commons/auth/WikiAccountAuthenticator.java +++ b/commons/src/main/java/fr/free/nrw/commons/auth/WikiAccountAuthenticator.java @@ -13,6 +13,7 @@ public class WikiAccountAuthenticator extends AbstractAccountAuthenticator { public static final String COMMONS_ACCOUNT_TYPE = "fr.free.nrw.commons"; private Context context; + public WikiAccountAuthenticator(Context context) { super(context); this.context = context; @@ -43,12 +44,13 @@ public class WikiAccountAuthenticator extends AbstractAccountAuthenticator { private String getAuthCookie(String username, String password) throws IOException { MWApi api = CommonsApplication.createMWApi(); String result = api.login(username, password); - if(result.equals("Success")) { + if (result.equals("Success")) { return api.getAuthCookie(); } else { return null; } } + @Override public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException { // Extract the username and password from the Account Manager, and ask diff --git a/commons/src/main/java/fr/free/nrw/commons/auth/WikiAccountAuthenticatorService.java b/commons/src/main/java/fr/free/nrw/commons/auth/WikiAccountAuthenticatorService.java index 89521c609..5fa3273c6 100644 --- a/commons/src/main/java/fr/free/nrw/commons/auth/WikiAccountAuthenticatorService.java +++ b/commons/src/main/java/fr/free/nrw/commons/auth/WikiAccountAuthenticatorService.java @@ -4,17 +4,17 @@ import android.app.*; import android.content.*; import android.os.*; -public class WikiAccountAuthenticatorService extends Service{ +public class WikiAccountAuthenticatorService extends Service { private static WikiAccountAuthenticator wikiAccountAuthenticator = null; - + @Override public IBinder onBind(Intent intent) { if (!intent.getAction().equals(android.accounts.AccountManager.ACTION_AUTHENTICATOR_INTENT)) { - return null; + return null; } - if(wikiAccountAuthenticator == null) { + if (wikiAccountAuthenticator == null) { wikiAccountAuthenticator = new WikiAccountAuthenticator(this); } return wikiAccountAuthenticator.getIBinder(); diff --git a/commons/src/main/java/fr/free/nrw/commons/campaigns/Campaign.java b/commons/src/main/java/fr/free/nrw/commons/campaigns/Campaign.java deleted file mode 100644 index dfbf5f96a..000000000 --- a/commons/src/main/java/fr/free/nrw/commons/campaigns/Campaign.java +++ /dev/null @@ -1,190 +0,0 @@ -package fr.free.nrw.commons.campaigns; - -import android.content.ContentValues; -import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.io.Serializable; -import java.util.ArrayList; - -// FIXME: Implement Parcelable -public class Campaign implements Serializable { - private boolean enabled; - - private String autoAddWikitext; - private ArrayList autoAddCategories; - - private String name; - private String ownWorkLicenseDefault; - - private String defaultDescription; - - private JSONObject config; - private String body; - private boolean isParsed; - private String trackingCategory; - private String description; - private String title; - - public boolean isEnabled() { - return enabled; - } - - public String getAutoAddWikitext() { - if(!this.isParsed) { - this.parseConfig(); - } - return autoAddWikitext; - } - - public ArrayList getAutoAddCategories() { - if(!this.isParsed) { - this.parseConfig(); - } - return autoAddCategories; - } - - public String getName() { - return name; - } - - public String getOwnWorkLicenseDefault() { - if(!this.isParsed) { - this.parseConfig(); - } - return ownWorkLicenseDefault; - } - - public String getDefaultDescription() { - if(!this.isParsed) { - this.parseConfig(); - } - return defaultDescription; - } - - public JSONObject getConfig() { - if(!this.isParsed) { - this.parseConfig(); - } - return config; - } - - private void parseConfig() { - try { - this.config = new JSONObject(body); - } catch (JSONException e) { - throw new RuntimeException(e); // because what else are you gonna do? - } - if(config.has("autoAdd")) { - this.autoAddWikitext = config.optJSONObject("autoAdd").optString("wikitext", null); - if(config.optJSONObject("autoAdd").has("categories")) { - this.autoAddCategories = new ArrayList(); - JSONArray catsArray = config.optJSONObject("autoAdd").optJSONArray("categories"); - for(int i=0; i < catsArray.length(); i++) { - autoAddCategories.add(catsArray.optString(i)); - } - } - } - this.title = config.optString("title", name); - this.description = config.optString("description", ""); - this.isParsed = true; - } - private Campaign(String name, String body, String trackingCategory) { - this.name = name; - this.body = body; - this.trackingCategory = trackingCategory; - } - - public ContentValues toContentValues() { - ContentValues cv = new ContentValues(); - cv.put(Table.COLUMN_NAME, this.getName()); - cv.put(Table.COLUMN_ENABLED, this.isEnabled() ? 1 : 0); - cv.put(Table.COLUMN_TITLE, this.getTitle()); - cv.put(Table.COLUMN_DESCRIPTION, this.getDescription()); - cv.put(Table.COLUMN_TRACKING_CATEGORY, this.getTrackingCategory()); - cv.put(Table.COLUMN_BODY, this.body); - return cv; - } - - public static Campaign parse(String name, String body, String trackingCategory) { - Campaign c = new Campaign(name, body, trackingCategory); - c.parseConfig(); - return c; - } - - public static Campaign fromCursor(Cursor cursor) { - String name = cursor.getString(1); - Boolean enabled = cursor.getInt(2) == 1; - String title = cursor.getString(3); - String description = cursor.getString(4); - String trackingCategory = cursor.getString(5); - String body = cursor.getString(6); - Campaign c = new Campaign(name, body, trackingCategory); - c.title = title; - c.description = description; - c.enabled = enabled; - return c; - } - - public String getTrackingCategory() { - return trackingCategory; - } - - public String getDescription() { - return description; - } - - public String getTitle() { - return title; - } - - public static class Table { - public static final String TABLE_NAME = "campaigns"; - - public static final String COLUMN_ID = "_id"; - public static final String COLUMN_NAME = "name"; - public static final String COLUMN_ENABLED = "enabled"; - public static final String COLUMN_TITLE = "title"; - public static final String COLUMN_DESCRIPTION = "description"; - public static final String COLUMN_TRACKING_CATEGORY = "tracking_category"; - public static final String COLUMN_BODY = "body"; - - // NOTE! KEEP IN SAME ORDER AS THEY ARE DEFINED UP THERE. HELPS HARD CODE COLUMN INDICES. - public static final String[] ALL_FIELDS = { - COLUMN_ID, - COLUMN_NAME, - COLUMN_ENABLED, - COLUMN_TITLE, - COLUMN_DESCRIPTION, - COLUMN_TRACKING_CATEGORY, - COLUMN_BODY - }; - - - private static final String CREATE_TABLE_STATEMENT = "CREATE TABLE " + TABLE_NAME + " (" - + "_id INTEGER PRIMARY KEY," - + "name STRING," - + "enabled INTEGER," - + "title STRING," - + "description STRING," - + "tracking_category STRING," - + "body STRING" - + ");"; - - - public static void onCreate(SQLiteDatabase db) { - db.execSQL(CREATE_TABLE_STATEMENT); - } - - public static void onUpdate(SQLiteDatabase db, int from, int to) { - if(to <= 6) { - onCreate(db); - return; - } - return; - } - } -} diff --git a/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignActivity.java b/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignActivity.java deleted file mode 100644 index d9e525e2b..000000000 --- a/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignActivity.java +++ /dev/null @@ -1,59 +0,0 @@ -package fr.free.nrw.commons.campaigns; - -import android.content.ContentResolver; -import android.content.Intent; -import android.database.Cursor; -import android.os.Bundle; -import android.support.v4.app.LoaderManager; -import android.support.v4.content.CursorLoader; -import android.support.v4.content.Loader; -import android.view.View; -import android.widget.AdapterView; -import android.widget.ListView; -import com.actionbarsherlock.app.SherlockFragmentActivity; -import fr.free.nrw.commons.contributions.ContributionsActivity; -import fr.free.nrw.commons.CommonsApplication; -import fr.free.nrw.commons.R; - -public class CampaignActivity - extends SherlockFragmentActivity - implements LoaderManager.LoaderCallbacks { - - private ListView campaignsListView; - private CampaignsListAdapter campaignsListAdapter; - - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_campaigns); - - ContentResolver.setSyncAutomatically(((CommonsApplication)getApplicationContext()).getCurrentAccount(), CampaignsContentProvider.AUTHORITY, true); // Enable sync by default! - campaignsListView = (ListView) findViewById(R.id.campaignsList); - - campaignsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - public void onItemClick(AdapterView adapterView, View view, int i, long l) { - Campaign c = Campaign.fromCursor((Cursor) adapterView.getItemAtPosition(i)); - Intent intent = new Intent(CampaignActivity.this, ContributionsActivity.class); - intent.putExtra("campaign", c); - startActivity(intent); - } - }); - getSupportLoaderManager().initLoader(0, null, this); - } - - public Loader onCreateLoader(int i, Bundle bundle) { - return new CursorLoader(this, CampaignsContentProvider.BASE_URI, Campaign.Table.ALL_FIELDS, "", null, ""); - } - - public void onLoadFinished(Loader cursorLoader, Cursor cursor) { - if(campaignsListAdapter == null) { - campaignsListAdapter = new CampaignsListAdapter(this, cursor, 0); - campaignsListView.setAdapter(campaignsListAdapter); - } else { - campaignsListAdapter.swapCursor(cursor); - } - } - - public void onLoaderReset(Loader cursorLoader) { - campaignsListAdapter.swapCursor(null); - } -} \ No newline at end of file diff --git a/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignContribution.java b/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignContribution.java deleted file mode 100644 index 4cd0f77a9..000000000 --- a/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignContribution.java +++ /dev/null @@ -1,49 +0,0 @@ -package fr.free.nrw.commons.campaigns; - -import android.net.Uri; -import fr.free.nrw.commons.contributions.Contribution; - -import java.util.ArrayList; -import java.util.Date; - -public class CampaignContribution extends Contribution { - private Campaign campaign; - - private ArrayList fieldValues; - - - public CampaignContribution(Uri localUri, String remoteUri, String filename, String description, long dataLength, Date dateCreated, Date dateUploaded, String creator, String editSummary, Campaign campaign) { - super(localUri, remoteUri, filename, description, dataLength, dateCreated, dateUploaded, creator, editSummary); - this.campaign = campaign; - } - - public Campaign getCampaign() { - return campaign; - } - - public void setCampaign(Campaign campaign) { - this.campaign = campaign; - } - - @Override - public String getTrackingTemplates() { - StringBuffer buffer = new StringBuffer(); - if(campaign.getAutoAddWikitext() != null) { - buffer.append(campaign.getAutoAddWikitext()).append("\n"); - } - if(campaign.getAutoAddCategories() != null && campaign.getAutoAddCategories().size() != 0) { - for(String cat : campaign.getAutoAddCategories()) { - buffer.append("[[Category:").append(cat).append("]]").append("\n"); - } - } else { - buffer.append("{{subst:unc}}\n"); - } - buffer.append("[[Category:").append(campaign.getTrackingCategory()).append("]]").append("\n"); - return buffer.toString(); - } - - @Override - public String getDescription() { - return super.getDescription(); - } -} diff --git a/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsContentProvider.java b/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsContentProvider.java deleted file mode 100644 index 5dba82941..000000000 --- a/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsContentProvider.java +++ /dev/null @@ -1,206 +0,0 @@ -package fr.free.nrw.commons.campaigns; - -import android.content.ContentProvider; -import android.content.ContentValues; -import android.content.UriMatcher; -import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteQueryBuilder; -import android.net.Uri; -import android.text.TextUtils; -import android.util.Log; -import fr.free.nrw.commons.CommonsApplication; -import fr.free.nrw.commons.data.DBOpenHelper; - -public class CampaignsContentProvider extends ContentProvider{ - - private static final int CAMPAIGNS = 1; - private static final int CAMPAIGNS_ID = 2; - - public static final String AUTHORITY = "fr.free.nrw.commons.campaigns.contentprovider"; - private static final String BASE_PATH = "campiagns"; - - public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH); - - private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); - static { - uriMatcher.addURI(AUTHORITY, BASE_PATH, CAMPAIGNS); - uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", CAMPAIGNS_ID); - } - - - public static Uri uriForId(int id) { - return Uri.parse(BASE_URI.toString() + "/" + id); - } - - private DBOpenHelper dbOpenHelper; - @Override - public boolean onCreate() { - dbOpenHelper = ((CommonsApplication)this.getContext().getApplicationContext()).getDbOpenHelper(); - return false; - } - - @Override - public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { - SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); - queryBuilder.setTables(Campaign.Table.TABLE_NAME); - - int uriType = uriMatcher.match(uri); - - SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); - Cursor cursor; - - switch(uriType) { - case CAMPAIGNS: - cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder); - break; - case CAMPAIGNS_ID: - cursor = queryBuilder.query(db, - Campaign.Table.ALL_FIELDS, - "_id = ?", - new String[] { uri.getLastPathSegment() }, - null, - null, - sortOrder - ); - break; - default: - throw new IllegalArgumentException("Unknown URI" + uri); - } - - cursor.setNotificationUri(getContext().getContentResolver(), uri); - - return cursor; - } - - @Override - public String getType(Uri uri) { - return null; - } - - @Override - public Uri insert(Uri uri, ContentValues contentValues) { - int uriType = uriMatcher.match(uri); - SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase(); - long id = 0; - switch (uriType) { - case CAMPAIGNS: - sqlDB.beginTransaction(); - // if the campaign already exists, rip it out and then re-insert - if(campaignExists(sqlDB, contentValues)) { - sqlDB.delete( - Campaign.Table.TABLE_NAME, - Campaign.Table.COLUMN_NAME + " = ?", - new String[]{contentValues.getAsString(Campaign.Table.COLUMN_NAME)} - ); - } - id = sqlDB.insert(Campaign.Table.TABLE_NAME, null, contentValues); - sqlDB.endTransaction(); - break; - default: - throw new IllegalArgumentException("Unknown URI: " + uri); - } - getContext().getContentResolver().notifyChange(uri, null); - return Uri.parse(BASE_URI + "/" + id); - } - - @Override - public int delete(Uri uri, String s, String[] strings) { - int rows = 0; - int uriType = uriMatcher.match(uri); - - SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); - - switch(uriType) { - case CAMPAIGNS_ID: - rows = db.delete(Campaign.Table.TABLE_NAME, - "_id = ?", - new String[] { uri.getLastPathSegment() } - ); - break; - default: - throw new IllegalArgumentException("Unknown URI" + uri); - } - getContext().getContentResolver().notifyChange(uri, null); - return rows; - } - - private boolean campaignExists(SQLiteDatabase db, ContentValues campaign) { - Cursor cr = db.query( - Campaign.Table.TABLE_NAME, - new String[]{Campaign.Table.COLUMN_NAME}, - Campaign.Table.COLUMN_NAME + " = ?", - new String[]{campaign.getAsString(Campaign.Table.COLUMN_NAME)}, - "", "", "" - ); - return cr != null && cr.getCount() != 0; - } - - @Override - public int bulkInsert(Uri uri, ContentValues[] values) { - Log.d("Commons", "Hello, bulk insert!"); - int uriType = uriMatcher.match(uri); - SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase(); - sqlDB.beginTransaction(); - switch (uriType) { - case CAMPAIGNS: - for(ContentValues value: values) { - Log.d("Commons", "Inserting! " + value.toString()); - // if the campaign already exists, rip it out and then re-insert - if(campaignExists(sqlDB, value)) { - sqlDB.delete( - Campaign.Table.TABLE_NAME, - Campaign.Table.COLUMN_NAME + " = ?", - new String[]{value.getAsString(Campaign.Table.COLUMN_NAME)} - ); - } - sqlDB.insert(Campaign.Table.TABLE_NAME, null, value); - } - break; - default: - throw new IllegalArgumentException("Unknown URI: " + uri); - } - sqlDB.setTransactionSuccessful(); - sqlDB.endTransaction(); - getContext().getContentResolver().notifyChange(uri, null); - return values.length; - } - - @Override - public int update(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") - 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. - - 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); - SQLiteDatabase sqlDB = dbOpenHelper.getWritableDatabase(); - int rowsUpdated = 0; - switch (uriType) { - case CAMPAIGNS: - rowsUpdated = sqlDB.update(Campaign.Table.TABLE_NAME, - contentValues, - selection, - selectionArgs); - break; - case CAMPAIGNS_ID: - int id = Integer.valueOf(uri.getLastPathSegment()); - - if (TextUtils.isEmpty(selection)) { - rowsUpdated = sqlDB.update(Campaign.Table.TABLE_NAME, - contentValues, - Campaign.Table.COLUMN_ID + " = ?", - new String[] { String.valueOf(id) } ); - } else { - throw new IllegalArgumentException("Parameter `selection` should be empty when updating an ID"); - } - break; - default: - throw new IllegalArgumentException("Unknown URI: " + uri + " with type " + uriType); - } - getContext().getContentResolver().notifyChange(uri, null); - return rowsUpdated; - } -} diff --git a/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsListAdapter.java b/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsListAdapter.java deleted file mode 100644 index d79ed4ba4..000000000 --- a/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsListAdapter.java +++ /dev/null @@ -1,38 +0,0 @@ -package fr.free.nrw.commons.campaigns; - -import android.app.Activity; -import android.content.Context; -import android.database.Cursor; -import android.support.v4.widget.CursorAdapter; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; -import com.nostra13.universalimageloader.core.DisplayImageOptions; -import fr.free.nrw.commons.Utils; - -class CampaignsListAdapter extends CursorAdapter { - - private DisplayImageOptions contributionDisplayOptions = Utils.getGenericDisplayOptions().build();; - private Activity activity; - - public CampaignsListAdapter(Activity activity, Cursor c, int flags) { - super(activity, c, flags); - this.activity = activity; - } - - @Override - public View newView(Context context, Cursor cursor, ViewGroup viewGroup) { - View parent = activity.getLayoutInflater().inflate(android.R.layout.simple_list_item_1, viewGroup, false); - return parent; - } - - @Override - public void bindView(View view, Context context, Cursor cursor) { - TextView campaignName = (TextView)view.findViewById(android.R.id.text1); - - Campaign campaign = Campaign.fromCursor(cursor); - - campaignName.setText(campaign.getTitle()); - } - -} diff --git a/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsSyncAdapter.java b/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsSyncAdapter.java deleted file mode 100644 index 4dc78d676..000000000 --- a/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsSyncAdapter.java +++ /dev/null @@ -1,90 +0,0 @@ -package fr.free.nrw.commons.campaigns; - -import android.accounts.Account; -import android.content.*; -import android.os.Bundle; -import android.os.RemoteException; -import android.text.TextUtils; -import android.util.Log; -import org.mediawiki.api.ApiResult; -import org.mediawiki.api.MWApi; -import fr.free.nrw.commons.CommonsApplication; - -import java.io.IOException; -import java.util.ArrayList; - - -public class CampaignsSyncAdapter extends AbstractThreadedSyncAdapter { - private static int COMMIT_THRESHOLD = 10; - public CampaignsSyncAdapter(Context context, boolean autoInitialize) { - super(context, autoInitialize); - } - - private int getLimit() { - return 500; // FIXME: Parameterize! - } - - @Override - public void onPerformSync(Account account, Bundle bundle, String s, ContentProviderClient contentProviderClient, SyncResult syncResult) { - // This code is fraught with possibilities of race conditions, but lalalalala I can't hear you! - String user = account.name; - MWApi api = CommonsApplication.createMWApi(); - ApiResult result; - Boolean done = false; - String queryContinue = null; - while(!done) { - - try { - MWApi.RequestBuilder builder = api.action("query") - .param("list", "allcampaigns") - // Disabled, since we want to modify local state if the campaign was disabled - // FIXME: To be more effecient, delete the disabled campaigns locally - //.param("ucenabledonly", "true") - .param("uclimit", getLimit()); - if(!TextUtils.isEmpty(queryContinue)) { - builder.param("uccontinue", queryContinue); - } - result = builder.get(); - } catch (IOException e) { - // There isn't really much we can do, eh? - // FIXME: Perhaps add EventLogging? - syncResult.stats.numIoExceptions += 1; // Not sure if this does anything. Shitty docs - Log.d("Commons", "Syncing failed due to " + e.toString()); - return; - } - - ArrayList campaigns = result.getNodes("/api/query/allcampaigns/campaign"); - Log.d("Commons", campaigns.size() + " results!"); - ArrayList campaignValues = new ArrayList(); - for(ApiResult campaignItem: campaigns) { - String name = campaignItem.getString("@name"); - String body = campaignItem.getString("."); - Log.d("Commons", "Campaign body is " + body); - String trackingCat = campaignItem.getString("@trackingCategory"); - Campaign campaign = Campaign.parse(name, body, trackingCat); - campaignValues.add(campaign.toContentValues()); - - if(campaignValues.size() % COMMIT_THRESHOLD == 0) { - try { - contentProviderClient.bulkInsert(CampaignsContentProvider.BASE_URI, campaignValues.toArray(new ContentValues[]{})); - } catch (RemoteException e) { - throw new RuntimeException(e); - } - campaignValues.clear(); - } - } - - if(campaignValues.size() != 0) { - try { - contentProviderClient.bulkInsert(CampaignsContentProvider.BASE_URI, campaignValues.toArray(new ContentValues[]{})); - } catch (RemoteException e) { - throw new RuntimeException(e); - } - } - queryContinue = result.getString("/api/query-continue/allcampaigns/@uccontinue"); - if(TextUtils.isEmpty(queryContinue)) { - done = true; - } - } - } -} diff --git a/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsSyncService.java b/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsSyncService.java deleted file mode 100644 index 71129a095..000000000 --- a/commons/src/main/java/fr/free/nrw/commons/campaigns/CampaignsSyncService.java +++ /dev/null @@ -1,26 +0,0 @@ -package fr.free.nrw.commons.campaigns; - -import android.app.Service; -import android.content.Intent; -import android.os.IBinder; - -public class CampaignsSyncService extends Service { - - private static final Object sSyncAdapterLock = new Object(); - - private static CampaignsSyncAdapter sSyncAdapter = null; - - @Override - public void onCreate() { - synchronized (sSyncAdapterLock) { - if (sSyncAdapter == null) { - sSyncAdapter = new CampaignsSyncAdapter(getApplicationContext(), true); - } - } - } - - @Override - public IBinder onBind(Intent intent) { - return sSyncAdapter.getSyncAdapterBinder(); - } -} diff --git a/commons/src/main/java/fr/free/nrw/commons/category/CategorizationFragment.java b/commons/src/main/java/fr/free/nrw/commons/category/CategorizationFragment.java index c5ecdafa8..78c3f47c4 100644 --- a/commons/src/main/java/fr/free/nrw/commons/category/CategorizationFragment.java +++ b/commons/src/main/java/fr/free/nrw/commons/category/CategorizationFragment.java @@ -26,7 +26,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.concurrent.ScheduledThreadPoolExecutor; -public class CategorizationFragment extends SherlockFragment{ +public class CategorizationFragment extends SherlockFragment { public static interface OnCategoriesSaveHandler { public void onCategoriesSave(ArrayList categories); } @@ -86,6 +86,7 @@ public class CategorizationFragment extends SherlockFragment{ private class CategoriesUpdater extends AsyncTask> { private String filter; + @Override protected void onPreExecute() { super.onPreExecute(); @@ -101,14 +102,14 @@ public class CategorizationFragment extends SherlockFragment{ super.onPostExecute(categories); ArrayList items = new ArrayList(); HashSet existingKeys = new HashSet(); - for(CategoryItem item : categoriesAdapter.getItems()) { - if(item.selected) { + for (CategoryItem item : categoriesAdapter.getItems()) { + if (item.selected) { items.add(item); existingKeys.add(item.name); } } - for(String category : categories) { - if(!existingKeys.contains(category)) { + for (String category : categories) { + if (!existingKeys.contains(category)) { items.add(new CategoryItem(category, false)); } } @@ -116,7 +117,7 @@ public class CategorizationFragment extends SherlockFragment{ categoriesAdapter.notifyDataSetInvalidated(); categoriesSearchInProgress.setVisibility(View.GONE); if (categories.size() == 0) { - if(TextUtils.isEmpty(filter)) { + if (TextUtils.isEmpty(filter)) { // If we found no recent cats, show the skip message! categoriesSkip.setVisibility(View.VISIBLE); } else { @@ -130,7 +131,7 @@ public class CategorizationFragment extends SherlockFragment{ @Override protected ArrayList doInBackground(Void... voids) { - if(TextUtils.isEmpty(filter)) { + if (TextUtils.isEmpty(filter)) { ArrayList items = new ArrayList(); try { Cursor cursor = client.query( @@ -150,7 +151,7 @@ public class CategorizationFragment extends SherlockFragment{ } return items; } - if(categoriesCache.containsKey(filter)) { + if (categoriesCache.containsKey(filter)) { return categoriesCache.get(filter); } MWApi api = CommonsApplication.createMWApi(); @@ -167,7 +168,7 @@ public class CategorizationFragment extends SherlockFragment{ } ArrayList categoryNodes = result.getNodes("/api/query/allcategories/c"); - for(ApiResult categoryNode: categoryNodes) { + for (ApiResult categoryNode : categoryNodes) { categories.add(categoryNode.getDocument().getTextContent()); } @@ -210,7 +211,7 @@ public class CategorizationFragment extends SherlockFragment{ public View getView(int i, View view, ViewGroup viewGroup) { CheckedTextView checkedView; - if(view == null) { + if (view == null) { checkedView = (CheckedTextView) getSherlockActivity().getLayoutInflater().inflate(R.layout.layout_categories_item, null); } else { @@ -228,8 +229,8 @@ public class CategorizationFragment extends SherlockFragment{ public int getCurrentSelectedCount() { int count = 0; - for(CategoryItem item: categoriesAdapter.getItems()) { - if(item.selected) { + for (CategoryItem item : categoriesAdapter.getItems()) { + if (item.selected) { count++; } } @@ -242,7 +243,7 @@ public class CategorizationFragment extends SherlockFragment{ CategoryContentProvider.BASE_URI, Category.Table.ALL_FIELDS, Category.Table.COLUMN_NAME + "=?", - new String[] {name}, + new String[]{name}, null); if (cursor.moveToFirst()) { Category cat = Category.fromCursor(cursor); @@ -302,7 +303,7 @@ public class CategorizationFragment extends SherlockFragment{ }); ArrayList items; - if(savedInstanceState == null) { + if (savedInstanceState == null) { items = new ArrayList(); categoriesCache = new HashMap>(); } else { @@ -380,11 +381,11 @@ public class CategorizationFragment extends SherlockFragment{ @Override public boolean onOptionsItemSelected(MenuItem menuItem) { - switch(menuItem.getItemId()) { + switch (menuItem.getItemId()) { case R.id.menu_save_categories: ArrayList selectedCategories = new ArrayList(); - for(CategoryItem item: categoriesAdapter.getItems()) { - if(item.selected) { + for (CategoryItem item : categoriesAdapter.getItems()) { + if (item.selected) { selectedCategories.add(item.name); } } diff --git a/commons/src/main/java/fr/free/nrw/commons/category/Category.java b/commons/src/main/java/fr/free/nrw/commons/category/Category.java index c58b8da2c..8e01d44c5 100644 --- a/commons/src/main/java/fr/free/nrw/commons/category/Category.java +++ b/commons/src/main/java/fr/free/nrw/commons/category/Category.java @@ -28,12 +28,12 @@ public class Category { public Date getLastUsed() { // warning: Date objects are mutable. - return (Date)lastUsed.clone(); + return (Date) lastUsed.clone(); } public void setLastUsed(Date lastUsed) { // warning: Date objects are mutable. - this.lastUsed = (Date)lastUsed.clone(); + this.lastUsed = (Date) lastUsed.clone(); } public void touch() { @@ -60,12 +60,12 @@ public class Category { public void save() { try { - if(contentUri == null) { + if (contentUri == null) { contentUri = client.insert(CategoryContentProvider.BASE_URI, this.toContentValues()); } else { client.update(contentUri, toContentValues(), null, null); } - } catch(RemoteException e) { + } catch (RemoteException e) { throw new RuntimeException(e); } } @@ -118,23 +118,23 @@ public class Category { } public static void onUpdate(SQLiteDatabase db, int from, int to) { - if(from == to) { + if (from == to) { return; } - if(from < 4) { + if (from < 4) { // doesn't exist yet from++; onUpdate(db, from, to); return; } - if(from == 4) { + if (from == 4) { // table added in version 5 onCreate(db); from++; onUpdate(db, from, to); return; } - if(from == 5) { + if (from == 5) { from++; onUpdate(db, from, to); return; diff --git a/commons/src/main/java/fr/free/nrw/commons/category/CategoryContentProvider.java b/commons/src/main/java/fr/free/nrw/commons/category/CategoryContentProvider.java index 0878b8f2e..89cb46569 100644 --- a/commons/src/main/java/fr/free/nrw/commons/category/CategoryContentProvider.java +++ b/commons/src/main/java/fr/free/nrw/commons/category/CategoryContentProvider.java @@ -24,6 +24,7 @@ public class CategoryContentProvider extends ContentProvider { public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH); private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); + static { uriMatcher.addURI(AUTHORITY, BASE_PATH, CATEGORIES); uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", CATEGORIES_ID); @@ -35,9 +36,10 @@ public class CategoryContentProvider extends ContentProvider { } private DBOpenHelper dbOpenHelper; + @Override public boolean onCreate() { - dbOpenHelper = ((CommonsApplication)this.getContext().getApplicationContext()).getDbOpenHelper(); + dbOpenHelper = ((CommonsApplication) this.getContext().getApplicationContext()).getDbOpenHelper(); return false; } @@ -51,7 +53,7 @@ public class CategoryContentProvider extends ContentProvider { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor; - switch(uriType) { + switch (uriType) { case CATEGORIES: cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder); break; @@ -59,7 +61,7 @@ public class CategoryContentProvider extends ContentProvider { cursor = queryBuilder.query(db, Category.Table.ALL_FIELDS, "_id = ?", - new String[] { uri.getLastPathSegment() }, + new String[]{uri.getLastPathSegment()}, null, null, sortOrder @@ -108,7 +110,7 @@ public class CategoryContentProvider extends ContentProvider { sqlDB.beginTransaction(); switch (uriType) { case CATEGORIES: - for(ContentValues value: values) { + for (ContentValues value : values) { Log.d("Commons", "Inserting! " + value.toString()); sqlDB.insert(Category.Table.TABLE_NAME, null, value); } @@ -142,7 +144,7 @@ public class CategoryContentProvider extends ContentProvider { rowsUpdated = sqlDB.update(Category.Table.TABLE_NAME, contentValues, Category.Table.COLUMN_ID + " = ?", - new String[] { String.valueOf(id) } ); + new String[]{String.valueOf(id)}); } else { throw new IllegalArgumentException("Parameter `selection` should be empty when updating an ID"); } diff --git a/commons/src/main/java/fr/free/nrw/commons/contributions/Contribution.java b/commons/src/main/java/fr/free/nrw/commons/contributions/Contribution.java index b5ec3d155..007af7688 100644 --- a/commons/src/main/java/fr/free/nrw/commons/contributions/Contribution.java +++ b/commons/src/main/java/fr/free/nrw/commons/contributions/Contribution.java @@ -68,7 +68,7 @@ public class Contribution extends Media { public Contribution(Parcel in) { super(in); - contentUri = (Uri)in.readParcelable(Uri.class.getClassLoader()); + contentUri = (Uri) in.readParcelable(Uri.class.getClassLoader()); source = in.readString(); timestamp = (Date) in.readSerializable(); state = in.readInt(); @@ -125,21 +125,21 @@ public class Contribution extends Media { StringBuffer buffer = new StringBuffer(); SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd"); buffer - .append("== {{int:filedesc}} ==\n") + .append("== {{int:filedesc}} ==\n") .append("{{Information\n") - .append("|description=").append(getDescription()).append("\n") - .append("|source=").append("{{own}}\n") - .append("|author=[[User:").append(creator).append("|").append(creator).append("]]\n"); - if(dateCreated != null) { + .append("|description=").append(getDescription()).append("\n") + .append("|source=").append("{{own}}\n") + .append("|author=[[User:").append(creator).append("|").append(creator).append("]]\n"); + if (dateCreated != null) { buffer .append("|date={{According to EXIF data|").append(isoFormat.format(dateCreated)).append("}}\n"); } buffer .append("}}").append("\n") - .append("== {{int:license-header}} ==\n") + .append("== {{int:license-header}} ==\n") .append(Utils.licenseTemplateFor(getLicense())).append("\n\n") - .append("{{Uploaded from Mobile|platform=Android|version=").append(CommonsApplication.APPLICATION_VERSION).append("}}\n") - .append(getTrackingTemplates()); + .append("{{Uploaded from Mobile|platform=Android|version=").append(CommonsApplication.APPLICATION_VERSION).append("}}\n") + .append(getTrackingTemplates()); return buffer.toString(); } @@ -149,19 +149,19 @@ public class Contribution extends Media { public void save() { try { - if(contentUri == null) { + if (contentUri == null) { contentUri = client.insert(ContributionsContentProvider.BASE_URI, this.toContentValues()); } else { client.update(contentUri, toContentValues(), null, null); } - } catch(RemoteException e) { + } catch (RemoteException e) { throw new RuntimeException(e); } } public void delete() { try { - if(contentUri == null) { + if (contentUri == null) { // noooo throw new RuntimeException("tried to delete item with no content URI"); } else { @@ -176,20 +176,20 @@ public class Contribution extends Media { public ContentValues toContentValues() { ContentValues cv = new ContentValues(); cv.put(Table.COLUMN_FILENAME, getFilename()); - if(getLocalUri() != null) { + if (getLocalUri() != null) { cv.put(Table.COLUMN_LOCAL_URI, getLocalUri().toString()); } - if(getImageUrl() != null) { + if (getImageUrl() != null) { cv.put(Table.COLUMN_IMAGE_URL, getImageUrl().toString()); } - if(getDateUploaded() != null) { + if (getDateUploaded() != null) { cv.put(Table.COLUMN_UPLOADED, getDateUploaded().getTime()); } cv.put(Table.COLUMN_LENGTH, getDataLength()); cv.put(Table.COLUMN_TIMESTAMP, getTimestamp().getTime()); cv.put(Table.COLUMN_STATE, getState()); cv.put(Table.COLUMN_TRANSFERRED, transferred); - cv.put(Table.COLUMN_SOURCE, source); + cv.put(Table.COLUMN_SOURCE, source); cv.put(Table.COLUMN_DESCRIPTION, description); cv.put(Table.COLUMN_CREATOR, creator); cv.put(Table.COLUMN_MULTIPLE, isMultiple ? 1 : 0); @@ -222,7 +222,7 @@ public class Contribution extends Media { c.timestamp = cursor.getLong(4) == 0 ? null : new Date(cursor.getLong(4)); c.state = cursor.getInt(5); c.dataLength = cursor.getLong(6); - c.dateUploaded = cursor.getLong(7) == 0 ? null : new Date(cursor.getLong(7)); + c.dateUploaded = cursor.getLong(7) == 0 ? null : new Date(cursor.getLong(7)); c.transferred = cursor.getLong(8); c.source = cursor.getString(9); c.description = cursor.getString(10); @@ -306,7 +306,7 @@ public class Contribution extends Media { + "width INTEGER," + "height INTEGER," + "LICENSE STRING" - + ");"; + + ");"; public static void onCreate(SQLiteDatabase db) { @@ -314,36 +314,36 @@ public class Contribution extends Media { } public static void onUpdate(SQLiteDatabase db, int from, int to) { - if(from == to) { + if (from == to) { return; } - if(from == 1) { + if (from == 1) { db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN description STRING;"); db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN creator STRING;"); from++; onUpdate(db, from, to); return; } - if(from == 2) { + if (from == 2) { db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN multiple INTEGER;"); db.execSQL("UPDATE " + TABLE_NAME + " SET multiple = 0"); from++; onUpdate(db, from, to); return; } - if(from == 3) { + if (from == 3) { // Do nothing from++; onUpdate(db, from, to); return; } - if(from == 4) { + if (from == 4) { // Do nothing -- added Category from++; onUpdate(db, from, to); return; } - if(from == 5) { + if (from == 5) { // Added width and height fields db.execSQL("ALTER TABLE " + TABLE_NAME + " ADD COLUMN width INTEGER;"); db.execSQL("UPDATE " + TABLE_NAME + " SET width = 0"); diff --git a/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionController.java b/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionController.java index 7929913da..36b9a79ac 100644 --- a/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionController.java +++ b/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionController.java @@ -10,7 +10,7 @@ import android.util.Log; import com.actionbarsherlock.app.SherlockFragment; import fr.free.nrw.commons.upload.ShareActivity; import fr.free.nrw.commons.upload.UploadService; -import fr.free.nrw.commons.campaigns.Campaign; + import java.io.File; import java.io.IOException; @@ -19,15 +19,15 @@ import java.util.Date; public class ContributionController { private SherlockFragment fragment; private Activity activity; - private Campaign campaign; + private final static int SELECT_FROM_GALLERY = 1; private final static int SELECT_FROM_CAMERA = 2; - public ContributionController(SherlockFragment fragment, Campaign campaign) { + public ContributionController(SherlockFragment fragment) { this.fragment = fragment; this.activity = fragment.getActivity(); - this.campaign = campaign; + } // See http://stackoverflow.com/a/5054673/17865 for why this is done @@ -35,12 +35,12 @@ public class ContributionController { private Uri reGenerateImageCaptureURI() { String storageState = Environment.getExternalStorageState(); - if(storageState.equals(Environment.MEDIA_MOUNTED)) { + if (storageState.equals(Environment.MEDIA_MOUNTED)) { String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Commons/images/" + new Date().getTime() + ".jpg"; File _photoFile = new File(path); try { - if(_photoFile.exists() == false) { + if (_photoFile.exists() == false) { _photoFile.getParentFile().mkdirs(); _photoFile.createNewFile(); } @@ -50,7 +50,7 @@ public class ContributionController { } return Uri.fromFile(_photoFile); - } else { + } else { throw new RuntimeException("No external storage found!"); } } @@ -71,8 +71,7 @@ public class ContributionController { public void handleImagePicked(int requestCode, Intent data) { Intent shareIntent = new Intent(activity, ShareActivity.class); shareIntent.setAction(Intent.ACTION_SEND); - shareIntent.putExtra(UploadService.EXTRA_CAMPAIGN, campaign); - switch(requestCode) { + switch (requestCode) { case SELECT_FROM_GALLERY: shareIntent.setType(activity.getContentResolver().getType(data.getData())); shareIntent.putExtra(Intent.EXTRA_STREAM, data.getData()); @@ -89,13 +88,11 @@ public class ContributionController { public void saveState(Bundle outState) { outState.putParcelable("lastGeneratedCaptureURI", lastGeneratedCaptureURI); - outState.putSerializable("campaign", campaign); } public void loadState(Bundle savedInstanceState) { - if(savedInstanceState != null) { + if (savedInstanceState != null) { lastGeneratedCaptureURI = (Uri) savedInstanceState.getParcelable("lastGeneratedCaptureURI"); - campaign = (Campaign) savedInstanceState.getSerializable("campaign"); } } diff --git a/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionViewHolder.java b/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionViewHolder.java index 988538c3a..93f60db48 100644 --- a/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionViewHolder.java +++ b/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionViewHolder.java @@ -17,9 +17,9 @@ class ContributionViewHolder { ContributionViewHolder(View parent) { imageView = (MediaWikiImageView) parent.findViewById(R.id.contributionImage); - titleView = (TextView)parent.findViewById(R.id.contributionTitle); - stateView = (TextView)parent.findViewById(R.id.contributionState); - seqNumView = (TextView)parent.findViewById(R.id.contributionSequenceNumber); - progressView = (ProgressBar)parent.findViewById(R.id.contributionProgress); + titleView = (TextView) parent.findViewById(R.id.contributionTitle); + stateView = (TextView) parent.findViewById(R.id.contributionState); + seqNumView = (TextView) parent.findViewById(R.id.contributionSequenceNumber); + progressView = (ProgressBar) parent.findViewById(R.id.contributionProgress); } } diff --git a/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsActivity.java b/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsActivity.java index 06fd2d2d5..64e9605bf 100644 --- a/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsActivity.java +++ b/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsActivity.java @@ -22,20 +22,18 @@ import fr.free.nrw.commons.auth.*; import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.HandlerService; import fr.free.nrw.commons.Media; -import fr.free.nrw.commons.campaigns.Campaign; import fr.free.nrw.commons.media.*; import fr.free.nrw.commons.upload.UploadService; import java.util.ArrayList; -public class ContributionsActivity - extends AuthenticatedActivity - implements LoaderManager.LoaderCallbacks, - AdapterView.OnItemClickListener, - MediaDetailPagerFragment.MediaDetailProvider, - ContributionsListFragment.CurrentCampaignProvider, - FragmentManager.OnBackStackChangedListener, - ContributionsListFragment.SourceRefresher { +public class ContributionsActivity + extends AuthenticatedActivity + implements LoaderManager.LoaderCallbacks, + AdapterView.OnItemClickListener, + MediaDetailPagerFragment.MediaDetailProvider, + FragmentManager.OnBackStackChangedListener, + ContributionsListFragment.SourceRefresher { private Cursor allContributions; @@ -43,7 +41,6 @@ public class ContributionsActivity private MediaDetailPagerFragment mediaDetails; private ArrayList observersWaitingForLoad = new ArrayList(); - private Campaign campaign; public ContributionsActivity() { super(WikiAccountAuthenticator.COMMONS_ACCOUNT_TYPE); @@ -53,7 +50,7 @@ public class ContributionsActivity private boolean isUploadServiceConnected; private ServiceConnection uploadServiceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName componentName, IBinder binder) { - uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder)binder).getService(); + uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder) binder).getService(); isUploadServiceConnected = true; } @@ -64,11 +61,10 @@ public class ContributionsActivity }; - @Override protected void onDestroy() { super.onDestroy(); - if(isUploadServiceConnected) { + if (isUploadServiceConnected) { unbindService(uploadServiceConnection); } } @@ -115,16 +111,11 @@ public class ContributionsActivity setTitle(R.string.title_activity_contributions); setContentView(R.layout.activity_contributions); - if(getIntent().hasExtra("campaign")) { - this.campaign = (Campaign) getIntent().getSerializableExtra("campaign"); - this.setTitle(campaign.getTitle()); - } - - contributionsList = (ContributionsListFragment)getSupportFragmentManager().findFragmentById(R.id.contributionsListFragment); + contributionsList = (ContributionsListFragment) getSupportFragmentManager().findFragmentById(R.id.contributionsListFragment); getSupportFragmentManager().addOnBackStackChangedListener(this); if (savedInstanceState != null) { - mediaDetails = (MediaDetailPagerFragment)getSupportFragmentManager().findFragmentById(R.id.contributionsFragmentContainer); + mediaDetails = (MediaDetailPagerFragment) getSupportFragmentManager().findFragmentById(R.id.contributionsFragmentContainer); // onBackStackChanged uses mediaDetails.isVisible() but this returns false now. // Use the saved value from before pause or orientation change. if (mediaDetails != null && savedInstanceState.getBoolean("mediaDetailsVisible")) { @@ -143,7 +134,7 @@ public class ContributionsActivity } private void showDetail(int i) { - if(mediaDetails == null ||!mediaDetails.isVisible()) { + if (mediaDetails == null || !mediaDetails.isVisible()) { mediaDetails = new MediaDetailPagerFragment(); this.getSupportFragmentManager() .beginTransaction() @@ -158,7 +149,7 @@ public class ContributionsActivity public void retryUpload(int i) { allContributions.moveToPosition(i); Contribution c = Contribution.fromCursor(allContributions); - if(c.getState() == Contribution.STATE_FAILED) { + if (c.getState() == Contribution.STATE_FAILED) { uploadService.queue(UploadService.ACTION_UPLOAD_FILE, c); Log.d("Commons", "Restarting for" + c.toContentValues().toString()); } else { @@ -169,7 +160,7 @@ public class ContributionsActivity public void deleteUpload(int i) { allContributions.moveToPosition(i); Contribution c = Contribution.fromCursor(allContributions); - if(c.getState() == Contribution.STATE_FAILED) { + if (c.getState() == Contribution.STATE_FAILED) { Log.d("Commons", "Deleting failed contrib " + c.toContentValues().toString()); c.setContentProviderClient(getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY)); c.delete(); @@ -180,9 +171,9 @@ public class ContributionsActivity @Override public boolean onOptionsItemSelected(MenuItem item) { - switch(item.getItemId()) { + switch (item.getItemId()) { case android.R.id.home: - if(mediaDetails.isVisible()) { + if (mediaDetails.isVisible()) { getSupportFragmentManager().popBackStack(); } return true; @@ -208,54 +199,42 @@ public class ContributionsActivity } public Loader onCreateLoader(int i, Bundle bundle) { - if(campaign == null) { - return new CursorLoader(this, ContributionsContentProvider.BASE_URI, Contribution.Table.ALL_FIELDS, CONTRIBUTION_SELECTION, null, CONTRIBUTION_SORT); - } else { - return new CategoryImagesLoader(this, campaign.getTrackingCategory()); - } + + return new CursorLoader(this, ContributionsContentProvider.BASE_URI, Contribution.Table.ALL_FIELDS, CONTRIBUTION_SELECTION, null, CONTRIBUTION_SORT); + } public void onLoadFinished(Loader cursorLoader, Object result) { - if(campaign == null) { - Cursor cursor = (Cursor) result; - if(contributionsList.getAdapter() == null) { - contributionsList.setAdapter(new ContributionsListAdapter(this, cursor, 0)); - } else { - ((CursorAdapter)contributionsList.getAdapter()).swapCursor(cursor); - } - getSupportActionBar().setSubtitle(getResources().getQuantityString(R.plurals.contributions_subtitle, cursor.getCount(), cursor.getCount())); + Cursor cursor = (Cursor) result; + if (contributionsList.getAdapter() == null) { + contributionsList.setAdapter(new ContributionsListAdapter(this, cursor, 0)); } else { - if(contributionsList.getAdapter() == null) { - contributionsList.setAdapter(new MediaListAdapter(this, (ArrayList) result)); - } else { - ((MediaListAdapter)contributionsList.getAdapter()).updateMediaList((ArrayList) result); - } + ((CursorAdapter) contributionsList.getAdapter()).swapCursor(cursor); } + + getSupportActionBar().setSubtitle(getResources().getQuantityString(R.plurals.contributions_subtitle, cursor.getCount(), cursor.getCount())); + notifyAndMigrateDataSetObservers(); } public void onLoaderReset(Loader cursorLoader) { - if(campaign == null) { - ((CursorAdapter) contributionsList.getAdapter()).swapCursor(null); - } else { - contributionsList.setAdapter(null); - } + + ((CursorAdapter) contributionsList.getAdapter()).swapCursor(null); + } public Media getMediaAtPosition(int i) { if (contributionsList.getAdapter() == null) { // not yet ready to return data return null; - } else if(campaign == null) { - return Contribution.fromCursor((Cursor) contributionsList.getAdapter().getItem(i)); } else { - return (Media) contributionsList.getAdapter().getItem(i); + return Contribution.fromCursor((Cursor) contributionsList.getAdapter().getItem(i)); } } public int getTotalMediaCount() { - if(contributionsList.getAdapter() == null) { + if (contributionsList.getAdapter() == null) { return 0; } return contributionsList.getAdapter().getCount(); @@ -299,16 +278,13 @@ public class ContributionsActivity } public void onBackStackChanged() { - if(mediaDetails != null && mediaDetails.isVisible()) { + if (mediaDetails != null && mediaDetails.isVisible()) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } else { getSupportActionBar().setDisplayHomeAsUpEnabled(false); } } - public Campaign getCurrentCampaign() { - return campaign; - } public void refreshSource() { getSupportLoaderManager().restartLoader(0, null, this); diff --git a/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsContentProvider.java b/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsContentProvider.java index 0bf8a440e..8b8bce778 100644 --- a/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsContentProvider.java +++ b/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsContentProvider.java @@ -10,7 +10,7 @@ import android.util.*; import fr.free.nrw.commons.data.*; import fr.free.nrw.commons.CommonsApplication; -public class ContributionsContentProvider extends ContentProvider{ +public class ContributionsContentProvider extends ContentProvider { private static final int CONTRIBUTIONS = 1; private static final int CONTRIBUTIONS_ID = 2; @@ -21,6 +21,7 @@ public class ContributionsContentProvider extends ContentProvider{ public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH); private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); + static { uriMatcher.addURI(AUTHORITY, BASE_PATH, CONTRIBUTIONS); uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", CONTRIBUTIONS_ID); @@ -32,9 +33,10 @@ public class ContributionsContentProvider extends ContentProvider{ } private DBOpenHelper dbOpenHelper; + @Override public boolean onCreate() { - dbOpenHelper = ((CommonsApplication)this.getContext().getApplicationContext()).getDbOpenHelper(); + dbOpenHelper = ((CommonsApplication) this.getContext().getApplicationContext()).getDbOpenHelper(); return false; } @@ -48,7 +50,7 @@ public class ContributionsContentProvider extends ContentProvider{ SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor; - switch(uriType) { + switch (uriType) { case CONTRIBUTIONS: cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder); break; @@ -56,7 +58,7 @@ public class ContributionsContentProvider extends ContentProvider{ cursor = queryBuilder.query(db, Contribution.Table.ALL_FIELDS, "_id = ?", - new String[] { uri.getLastPathSegment() }, + new String[]{uri.getLastPathSegment()}, null, null, sortOrder @@ -99,12 +101,12 @@ public class ContributionsContentProvider extends ContentProvider{ SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); - switch(uriType) { + switch (uriType) { case CONTRIBUTIONS_ID: Log.d("Commons", "Deleting contribution id " + uri.getLastPathSegment()); rows = db.delete(Contribution.Table.TABLE_NAME, "_id = ?", - new String[] { uri.getLastPathSegment() } + new String[]{uri.getLastPathSegment()} ); break; default: @@ -122,7 +124,7 @@ public class ContributionsContentProvider extends ContentProvider{ sqlDB.beginTransaction(); switch (uriType) { case CONTRIBUTIONS: - for(ContentValues value: values) { + for (ContentValues value : values) { Log.d("Commons", "Inserting! " + value.toString()); sqlDB.insert(Contribution.Table.TABLE_NAME, null, value); } @@ -162,7 +164,7 @@ public class ContributionsContentProvider extends ContentProvider{ rowsUpdated = sqlDB.update(Contribution.Table.TABLE_NAME, contentValues, Contribution.Table.COLUMN_ID + " = ?", - new String[] { String.valueOf(id) } ); + new String[]{String.valueOf(id)}); } else { throw new IllegalArgumentException("Parameter `selection` should be empty when updating an ID"); } diff --git a/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsListAdapter.java b/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsListAdapter.java index e605765bc..624b22817 100644 --- a/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsListAdapter.java +++ b/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsListAdapter.java @@ -19,7 +19,8 @@ import fr.free.nrw.commons.R; class ContributionsListAdapter extends CursorAdapter { - private DisplayImageOptions contributionDisplayOptions = Utils.getGenericDisplayOptions().build();; + private DisplayImageOptions contributionDisplayOptions = Utils.getGenericDisplayOptions().build(); + ; private Activity activity; public ContributionsListAdapter(Activity activity, Cursor c, int flags) { @@ -36,14 +37,14 @@ class ContributionsListAdapter extends CursorAdapter { @Override public void bindView(View view, Context context, Cursor cursor) { - final ContributionViewHolder views = (ContributionViewHolder)view.getTag(); + final ContributionViewHolder views = (ContributionViewHolder) view.getTag(); final Contribution contribution = Contribution.fromCursor(cursor); String actualUrl = (contribution.getLocalUri() != null && !TextUtils.isEmpty(contribution.getLocalUri().toString())) ? contribution.getLocalUri().toString() : contribution.getThumbnailUrl(640); - if(views.url == null || !views.url.equals(actualUrl)) { - if(actualUrl.startsWith("http")) { - MediaWikiImageView mwImageView = (MediaWikiImageView)views.imageView; + if (views.url == null || !views.url.equals(actualUrl)) { + if (actualUrl.startsWith("http")) { + MediaWikiImageView mwImageView = (MediaWikiImageView) views.imageView; mwImageView.setMedia(contribution, ((CommonsApplication) activity.getApplicationContext()).getImageLoader()); // FIXME: For transparent images } else { @@ -51,7 +52,7 @@ class ContributionsListAdapter extends CursorAdapter { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { - if(loadedImage.hasAlpha()) { + if (loadedImage.hasAlpha()) { views.imageView.setBackgroundResource(android.R.color.white); } views.seqNumView.setVisibility(View.GONE); @@ -60,7 +61,7 @@ class ContributionsListAdapter extends CursorAdapter { @Override public void onLoadingFailed(String imageUri, View view, FailReason failReason) { super.onLoadingFailed(imageUri, view, failReason); - MediaWikiImageView mwImageView = (MediaWikiImageView)views.imageView; + MediaWikiImageView mwImageView = (MediaWikiImageView) views.imageView; mwImageView.setMedia(contribution, ((CommonsApplication) activity.getApplicationContext()).getImageLoader()); } }); @@ -68,8 +69,8 @@ class ContributionsListAdapter extends CursorAdapter { views.url = actualUrl; } - BitmapDrawable actualImageDrawable = (BitmapDrawable)views.imageView.getDrawable(); - if(actualImageDrawable != null && actualImageDrawable.getBitmap() != null && actualImageDrawable.getBitmap().hasAlpha()) { + BitmapDrawable actualImageDrawable = (BitmapDrawable) views.imageView.getDrawable(); + if (actualImageDrawable != null && actualImageDrawable.getBitmap() != null && actualImageDrawable.getBitmap().hasAlpha()) { views.imageView.setBackgroundResource(android.R.color.white); } else { views.imageView.setBackgroundDrawable(null); @@ -80,7 +81,7 @@ class ContributionsListAdapter extends CursorAdapter { views.seqNumView.setText(String.valueOf(cursor.getPosition() + 1)); views.seqNumView.setVisibility(View.VISIBLE); - switch(contribution.getState()) { + switch (contribution.getState()) { case Contribution.STATE_COMPLETED: views.stateView.setVisibility(View.GONE); views.progressView.setVisibility(View.GONE); @@ -96,10 +97,10 @@ class ContributionsListAdapter extends CursorAdapter { views.progressView.setVisibility(View.VISIBLE); long total = contribution.getDataLength(); long transferred = contribution.getTransferred(); - if(transferred == 0 || transferred >= total) { + if (transferred == 0 || transferred >= total) { views.progressView.setIndeterminate(true); } else { - views.progressView.setProgress((int)(((double)transferred / (double)total) * 100)); + views.progressView.setProgress((int) (((double) transferred / (double) total) * 100)); } break; case Contribution.STATE_FAILED: diff --git a/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsListFragment.java b/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsListFragment.java index 140168e18..280a644a8 100644 --- a/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsListFragment.java +++ b/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsListFragment.java @@ -20,13 +20,9 @@ import fr.free.nrw.commons.R; import fr.free.nrw.commons.AboutActivity; import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.SettingsActivity; -import fr.free.nrw.commons.campaigns.Campaign; public class ContributionsListFragment extends SherlockFragment { - public interface CurrentCampaignProvider { - Campaign getCurrentCampaign(); - } public interface SourceRefresher { void refreshSource(); @@ -35,7 +31,7 @@ public class ContributionsListFragment extends SherlockFragment { private GridView contributionsList; private TextView waitingMessage; private TextView emptyMessage; - private Campaign campaign; + private ContributionController controller; @@ -62,7 +58,7 @@ public class ContributionsListFragment extends SherlockFragment { @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); - if(resultCode == Activity.RESULT_OK) { + if (resultCode == Activity.RESULT_OK) { controller.handleImagePicked(requestCode, data); } } @@ -70,7 +66,7 @@ public class ContributionsListFragment extends SherlockFragment { @Override public boolean onOptionsItemSelected(MenuItem item) { - switch(item.getItemId()) { + switch (item.getItemId()) { case R.id.menu_from_gallery: controller.startGalleryPick(); return true; @@ -82,18 +78,18 @@ public class ContributionsListFragment extends SherlockFragment { startActivity(settingsIntent); return true; case R.id.menu_about: - Intent aboutIntent = new Intent(getActivity(), AboutActivity.class); + Intent aboutIntent = new Intent(getActivity(), AboutActivity.class); startActivity(aboutIntent); return true; case R.id.menu_feedback: Intent feedbackIntent = new Intent(Intent.ACTION_SEND); feedbackIntent.setType("message/rfc822"); - feedbackIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { CommonsApplication.FEEDBACK_EMAIL }); + feedbackIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{CommonsApplication.FEEDBACK_EMAIL}); feedbackIntent.putExtra(Intent.EXTRA_SUBJECT, String.format(CommonsApplication.FEEDBACK_EMAIL_SUBJECT, CommonsApplication.APPLICATION_VERSION)); startActivity(feedbackIntent); return true; case R.id.menu_refresh: - ((SourceRefresher)getActivity()).refreshSource(); + ((SourceRefresher) getActivity()).refreshSource(); return true; default: return super.onOptionsItemSelected(item); @@ -105,13 +101,13 @@ public class ContributionsListFragment extends SherlockFragment { menu.clear(); // See http://stackoverflow.com/a/8495697/17865 inflater.inflate(R.menu.fragment_contributions_list, menu); - CommonsApplication app = (CommonsApplication)getActivity().getApplicationContext(); + CommonsApplication app = (CommonsApplication) getActivity().getApplicationContext(); if (!app.deviceHasCamera()) { menu.findItem(R.id.menu_from_camera).setEnabled(false); } - if(campaign == null) { - menu.findItem(R.id.menu_refresh).setVisible(false); - } + + menu.findItem(R.id.menu_refresh).setVisible(false); + } @Override @@ -129,16 +125,16 @@ public class ContributionsListFragment extends SherlockFragment { public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); - campaign = ((CurrentCampaignProvider)getActivity()).getCurrentCampaign(); - controller = new ContributionController(this, campaign); + + controller = new ContributionController(this); controller.loadState(savedInstanceState); - contributionsList = (GridView)getView().findViewById(R.id.contributionsList); - waitingMessage = (TextView)getView().findViewById(R.id.waitingMessage); - emptyMessage = (TextView)getView().findViewById(R.id.waitingMessage); + contributionsList = (GridView) getView().findViewById(R.id.contributionsList); + waitingMessage = (TextView) getView().findViewById(R.id.waitingMessage); + emptyMessage = (TextView) getView().findViewById(R.id.waitingMessage); - contributionsList.setOnItemClickListener((AdapterView.OnItemClickListener)getActivity()); - if(savedInstanceState != null) { + contributionsList.setOnItemClickListener((AdapterView.OnItemClickListener) getActivity()); + if (savedInstanceState != null) { Log.d("Commons", "Scrolling to " + savedInstanceState.getInt("grid-position")); contributionsList.setSelection(savedInstanceState.getInt("grid-position")); } diff --git a/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsSyncAdapter.java b/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsSyncAdapter.java index 80151715e..273bec580 100644 --- a/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsSyncAdapter.java +++ b/commons/src/main/java/fr/free/nrw/commons/contributions/ContributionsSyncAdapter.java @@ -18,6 +18,7 @@ import fr.free.nrw.commons.Utils; public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter { private static int COMMIT_THRESHOLD = 10; + public ContributionsSyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); } @@ -26,15 +27,16 @@ public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter { return 500; // FIXME: Parameterize! } - private static final String[] existsQuery = { Contribution.Table.COLUMN_FILENAME }; + private static final String[] existsQuery = {Contribution.Table.COLUMN_FILENAME}; private static final String existsSelection = Contribution.Table.COLUMN_FILENAME + " = ?"; + private boolean fileExists(ContentProviderClient client, String filename) { Cursor cursor = null; try { cursor = client.query(ContributionsContentProvider.BASE_URI, existsQuery, existsSelection, - new String[] { filename }, + new String[]{filename}, "" ); } catch (RemoteException e) { @@ -54,7 +56,7 @@ public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter { ApiResult result; Boolean done = false; String queryContinue = null; - while(!done) { + while (!done) { try { MWApi.RequestBuilder builder = api.action("query") @@ -63,10 +65,10 @@ public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter { .param("leprop", "title|timestamp") .param("leuser", user) .param("lelimit", getLimit()); - if(!TextUtils.isEmpty(lastModified)) { + if (!TextUtils.isEmpty(lastModified)) { builder.param("leend", lastModified); } - if(!TextUtils.isEmpty(queryContinue)) { + if (!TextUtils.isEmpty(queryContinue)) { builder.param("lestart", queryContinue); } result = builder.get(); @@ -82,9 +84,9 @@ public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter { ArrayList uploads = result.getNodes("/api/query/logevents/item"); Log.d("Commons", uploads.size() + " results!"); ArrayList imageValues = new ArrayList(); - for(ApiResult image: uploads) { + for (ApiResult image : uploads) { String filename = image.getString("@title"); - if(fileExists(contentProviderClient, filename)) { + if (fileExists(contentProviderClient, filename)) { Log.d("Commons", "Skipping " + filename); continue; } @@ -94,7 +96,7 @@ public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter { contrib.setState(Contribution.STATE_COMPLETED); imageValues.add(contrib.toContentValues()); - if(imageValues.size() % COMMIT_THRESHOLD == 0) { + if (imageValues.size() % COMMIT_THRESHOLD == 0) { try { contentProviderClient.bulkInsert(ContributionsContentProvider.BASE_URI, imageValues.toArray(new ContentValues[]{})); } catch (RemoteException e) { @@ -104,7 +106,7 @@ public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter { } } - if(imageValues.size() != 0) { + if (imageValues.size() != 0) { try { contentProviderClient.bulkInsert(ContributionsContentProvider.BASE_URI, imageValues.toArray(new ContentValues[]{})); } catch (RemoteException e) { @@ -112,7 +114,7 @@ public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter { } } queryContinue = result.getString("/api/query-continue/logevents/@lestart"); - if(TextUtils.isEmpty(queryContinue)) { + if (TextUtils.isEmpty(queryContinue)) { done = true; } } diff --git a/commons/src/main/java/fr/free/nrw/commons/contributions/MediaListAdapter.java b/commons/src/main/java/fr/free/nrw/commons/contributions/MediaListAdapter.java index 2a84db1f8..3c63bc6f6 100644 --- a/commons/src/main/java/fr/free/nrw/commons/contributions/MediaListAdapter.java +++ b/commons/src/main/java/fr/free/nrw/commons/contributions/MediaListAdapter.java @@ -21,19 +21,20 @@ public class MediaListAdapter extends BaseAdapter { public void updateMediaList(ArrayList newMediaList) { // FIXME: Hack for now, replace with something more efficient later on - for(Media newMedia: newMediaList) { + for (Media newMedia : newMediaList) { boolean isDuplicate = false; - for(Media oldMedia: mediaList ) { - if(newMedia.getFilename().equals(oldMedia.getFilename())) { + for (Media oldMedia : mediaList) { + if (newMedia.getFilename().equals(oldMedia.getFilename())) { isDuplicate = true; break; } } - if(!isDuplicate) { + if (!isDuplicate) { mediaList.add(0, newMedia); } } } + public int getCount() { return mediaList.size(); } @@ -47,14 +48,14 @@ public class MediaListAdapter extends BaseAdapter { } public View getView(int i, View view, ViewGroup viewGroup) { - if(view == null) { + if (view == null) { view = activity.getLayoutInflater().inflate(R.layout.layout_contribution, null, false); view.setTag(new ContributionViewHolder(view)); } Media m = (Media) getItem(i); ContributionViewHolder holder = (ContributionViewHolder) view.getTag(); - holder.imageView.setMedia(m, ((CommonsApplication)activity.getApplicationContext()).getImageLoader()); + holder.imageView.setMedia(m, ((CommonsApplication) activity.getApplicationContext()).getImageLoader()); holder.titleView.setText(m.getDisplayTitle()); return view; } diff --git a/commons/src/main/java/fr/free/nrw/commons/data/DBOpenHelper.java b/commons/src/main/java/fr/free/nrw/commons/data/DBOpenHelper.java index b475a4c72..a1e6453c9 100644 --- a/commons/src/main/java/fr/free/nrw/commons/data/DBOpenHelper.java +++ b/commons/src/main/java/fr/free/nrw/commons/data/DBOpenHelper.java @@ -4,11 +4,10 @@ import android.content.*; import android.database.sqlite.*; import fr.free.nrw.commons.modifications.ModifierSequence; -import fr.free.nrw.commons.campaigns.Campaign; import fr.free.nrw.commons.category.Category; import fr.free.nrw.commons.contributions.*; -public class DBOpenHelper extends SQLiteOpenHelper{ +public class DBOpenHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "commons.db"; private static final int DATABASE_VERSION = 6; @@ -22,7 +21,6 @@ public class DBOpenHelper extends SQLiteOpenHelper{ Contribution.Table.onCreate(sqLiteDatabase); ModifierSequence.Table.onCreate(sqLiteDatabase); Category.Table.onCreate(sqLiteDatabase); - Campaign.Table.onCreate(sqLiteDatabase); } @Override @@ -30,6 +28,5 @@ public class DBOpenHelper extends SQLiteOpenHelper{ Contribution.Table.onUpdate(sqLiteDatabase, from, to); ModifierSequence.Table.onUpdate(sqLiteDatabase, from, to); Category.Table.onUpdate(sqLiteDatabase, from, to); - Campaign.Table.onUpdate(sqLiteDatabase, from, to); } } diff --git a/commons/src/main/java/fr/free/nrw/commons/media/CategoryImagesLoader.java b/commons/src/main/java/fr/free/nrw/commons/media/CategoryImagesLoader.java index 28e882ecd..69135929a 100644 --- a/commons/src/main/java/fr/free/nrw/commons/media/CategoryImagesLoader.java +++ b/commons/src/main/java/fr/free/nrw/commons/media/CategoryImagesLoader.java @@ -12,7 +12,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; -public class CategoryImagesLoader extends AsyncTaskLoader>{ +public class CategoryImagesLoader extends AsyncTaskLoader> { private final CommonsApplication app; private final String category; @@ -49,7 +49,7 @@ public class CategoryImagesLoader extends AsyncTaskLoader>{ Log.d("Commons", Utils.getStringFromDOM(result.getDocument())); List members = result.getNodes("/api/query/categorymembers/cm"); - for(ApiResult member : members) { + for (ApiResult member : members) { mediaList.add(new Media(member.getString("@title"))); } return mediaList; diff --git a/commons/src/main/java/fr/free/nrw/commons/media/MediaDetailFragment.java b/commons/src/main/java/fr/free/nrw/commons/media/MediaDetailFragment.java index e7b608938..72bbe97d0 100644 --- a/commons/src/main/java/fr/free/nrw/commons/media/MediaDetailFragment.java +++ b/commons/src/main/java/fr/free/nrw/commons/media/MediaDetailFragment.java @@ -64,7 +64,7 @@ public class MediaDetailFragment extends SherlockFragment { private ViewTreeObserver.OnGlobalLayoutListener layoutListener; // for layout stuff, only used once! private ViewTreeObserver.OnScrollChangedListener scrollListener; DataSetObserver dataObserver; - private AsyncTask detailFetchTask; + private AsyncTask detailFetchTask; private LicenseList licenseList; @@ -84,9 +84,9 @@ public class MediaDetailFragment extends SherlockFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - detailProvider = (MediaDetailPagerFragment.MediaDetailProvider)getActivity(); + detailProvider = (MediaDetailPagerFragment.MediaDetailProvider) getActivity(); - if(savedInstanceState != null) { + if (savedInstanceState != null) { editable = savedInstanceState.getBoolean("editable"); index = savedInstanceState.getInt("index"); initialListTop = savedInstanceState.getInt("listTop"); @@ -169,9 +169,9 @@ public class MediaDetailFragment extends SherlockFragment { private void displayMediaDetails(final Media media) { String actualUrl = (media.getLocalUri() != null && !TextUtils.isEmpty(media.getLocalUri().toString())) ? media.getLocalUri().toString() : media.getThumbnailUrl(640); - if(actualUrl.startsWith("http")) { - ImageLoader loader = ((CommonsApplication)getActivity().getApplicationContext()).getImageLoader(); - MediaWikiImageView mwImage = (MediaWikiImageView)image; + if (actualUrl.startsWith("http")) { + ImageLoader loader = ((CommonsApplication) getActivity().getApplicationContext()).getImageLoader(); + MediaWikiImageView mwImage = (MediaWikiImageView) image; mwImage.setLoadingView(loadingProgress); //FIXME: Set this as an attribute mwImage.setMedia(media, loader); Log.d("Volley", actualUrl); @@ -241,7 +241,7 @@ public class MediaDetailFragment extends SherlockFragment { loadingProgress.setVisibility(View.GONE); loadingFailed.setVisibility(View.GONE); image.setVisibility(View.VISIBLE); - if(bitmap.hasAlpha()) { + if (bitmap.hasAlpha()) { image.setBackgroundResource(android.R.color.white); } } @@ -276,7 +276,7 @@ public class MediaDetailFragment extends SherlockFragment { } if (scrollListener != null) { getView().getViewTreeObserver().removeOnScrollChangedListener(scrollListener); - scrollListener = null; + scrollListener = null; } if (dataObserver != null) { detailProvider.unregisterDataSetObserver(dataObserver); @@ -296,7 +296,7 @@ public class MediaDetailFragment extends SherlockFragment { private View buildCatLabel(String cat) { final String catName = cat; final View item = getLayoutInflater(null).inflate(R.layout.detail_category_item, null, false); - final TextView textView = (TextView)item.findViewById(R.id.mediaDetailCategoryItemText); + final TextView textView = (TextView) item.findViewById(R.id.mediaDetailCategoryItemText); textView.setText(cat); if (categoriesLoaded && categoriesPresent) { @@ -317,7 +317,7 @@ public class MediaDetailFragment extends SherlockFragment { // You must face the darkness alone int scrollY = scrollView.getScrollY(); int scrollMax = getView().getHeight(); - float scrollPercentage = (float)scrollY / (float)scrollMax; + float scrollPercentage = (float) scrollY / (float) scrollMax; final float transparencyMax = 0.75f; if (scrollPercentage > transparencyMax) { scrollPercentage = transparencyMax; diff --git a/commons/src/main/java/fr/free/nrw/commons/media/MediaDetailPagerFragment.java b/commons/src/main/java/fr/free/nrw/commons/media/MediaDetailPagerFragment.java index 5b20167d3..d98f78667 100644 --- a/commons/src/main/java/fr/free/nrw/commons/media/MediaDetailPagerFragment.java +++ b/commons/src/main/java/fr/free/nrw/commons/media/MediaDetailPagerFragment.java @@ -42,11 +42,16 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa public interface MediaDetailProvider { public Media getMediaAtPosition(int i); + public int getTotalMediaCount(); + public void notifyDatasetChanged(); + public void registerDataSetObserver(DataSetObserver observer); + public void unregisterDataSetObserver(DataSetObserver observer); } + private class MediaDetailAdapter extends FragmentStatePagerAdapter { public MediaDetailAdapter(FragmentManager fm) { @@ -55,7 +60,7 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa @Override public Fragment getItem(int i) { - if(i == 0) { + if (i == 0) { // See bug https://code.google.com/p/android/issues/detail?id=27526 pager.postDelayed(new Runnable() { public void run() { @@ -68,7 +73,7 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa @Override public int getCount() { - return ((MediaDetailProvider)getActivity()).getTotalMediaCount(); + return ((MediaDetailProvider) getActivity()).getTotalMediaCount(); } } @@ -85,7 +90,7 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa View view = inflater.inflate(R.layout.fragment_media_detail_pager, container, false); pager = (ViewPager) view.findViewById(R.id.mediaDetailsPager); pager.setOnPageChangeListener(this); - if(savedInstanceState != null) { + if (savedInstanceState != null) { final int pageNumber = savedInstanceState.getInt("current-page"); // Adapter doesn't seem to be loading immediately. // Dear God, please forgive us for our sins @@ -112,18 +117,18 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - if(savedInstanceState != null) { + if (savedInstanceState != null) { editable = savedInstanceState.getBoolean("editable"); } - app = (CommonsApplication)getActivity().getApplicationContext(); + app = (CommonsApplication) getActivity().getApplicationContext(); setHasOptionsMenu(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { - MediaDetailProvider provider = (MediaDetailProvider)getSherlockActivity(); + MediaDetailProvider provider = (MediaDetailProvider) getSherlockActivity(); Media m = provider.getMediaAtPosition(pager.getCurrentItem()); - switch(item.getItemId()) { + switch (item.getItemId()) { case R.id.menu_share_current_image: EventLog.schema(CommonsApplication.EVENT_SHARE_ATTEMPT) .param("username", app.getCurrentAccount().name) @@ -146,12 +151,12 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa return true; case R.id.menu_retry_current_image: // Is this... sane? :) - ((ContributionsActivity)getActivity()).retryUpload(pager.getCurrentItem()); + ((ContributionsActivity) getActivity()).retryUpload(pager.getCurrentItem()); getSherlockActivity().getSupportFragmentManager().popBackStack(); return true; case R.id.menu_cancel_current_image: // todo: delete image - ((ContributionsActivity)getActivity()).deleteUpload(pager.getCurrentItem()); + ((ContributionsActivity) getActivity()).deleteUpload(pager.getCurrentItem()); getSherlockActivity().getSupportFragmentManager().popBackStack(); return true; default: @@ -167,7 +172,7 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa */ private void downloadMedia(Media m) { String imageUrl = m.getImageUrl(), - fileName = m.getFilename(); + fileName = m.getFilename(); // Strip 'File:' from beginning of filename, we really shouldn't store it fileName = fileName.replaceFirst("^File:", ""); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { @@ -194,7 +199,7 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa } } - final DownloadManager manager = (DownloadManager)getActivity().getSystemService(Context.DOWNLOAD_SERVICE); + final DownloadManager manager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE); final long downloadId = manager.enqueue(req); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { @@ -204,8 +209,8 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa public void onReceive(Context context, Intent intent) { // Check if the download has completed... Cursor c = manager.query(new DownloadManager.Query() - .setFilterById(downloadId) - .setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL | DownloadManager.STATUS_FAILED) + .setFilterById(downloadId) + .setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL | DownloadManager.STATUS_FAILED) ); if (c.moveToFirst()) { int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)); @@ -229,13 +234,13 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - if(!editable) { // Disable menu options for editable views + if (!editable) { // Disable menu options for editable views menu.clear(); // see http://stackoverflow.com/a/8495697/17865 inflater.inflate(R.menu.fragment_image_detail, menu); - if(pager != null) { - MediaDetailProvider provider = (MediaDetailProvider)getSherlockActivity(); + if (pager != null) { + MediaDetailProvider provider = (MediaDetailProvider) getSherlockActivity(); Media m = provider.getMediaAtPosition(pager.getCurrentItem()); - if(m != null) { + if (m != null) { // Enable default set of actions, then re-enable different set of actions only if it is a failed contrib menu.findItem(R.id.menu_retry_current_image).setEnabled(false).setVisible(false); menu.findItem(R.id.menu_cancel_current_image).setEnabled(false).setVisible(false); @@ -243,9 +248,9 @@ public class MediaDetailPagerFragment extends SherlockFragment implements ViewPa menu.findItem(R.id.menu_share_current_image).setEnabled(true).setVisible(true); menu.findItem(R.id.menu_download_current_image).setEnabled(true).setVisible(true); - if(m instanceof Contribution) { - Contribution c = (Contribution)m; - switch(c.getState()) { + if (m instanceof Contribution) { + Contribution c = (Contribution) m; + switch (c.getState()) { case Contribution.STATE_FAILED: menu.findItem(R.id.menu_retry_current_image).setEnabled(true).setVisible(true); menu.findItem(R.id.menu_cancel_current_image).setEnabled(true).setVisible(true); diff --git a/commons/src/main/java/fr/free/nrw/commons/modifications/CategoryModifier.java b/commons/src/main/java/fr/free/nrw/commons/modifications/CategoryModifier.java index 1a4b5ffce..eb281ff6b 100644 --- a/commons/src/main/java/fr/free/nrw/commons/modifications/CategoryModifier.java +++ b/commons/src/main/java/fr/free/nrw/commons/modifications/CategoryModifier.java @@ -14,7 +14,7 @@ public class CategoryModifier extends PageModifier { public CategoryModifier(String... categories) { super(MODIFIER_NAME); JSONArray categoriesArray = new JSONArray(); - for(String category: categories) { + for (String category : categories) { categoriesArray.put(category); } try { @@ -35,7 +35,7 @@ public class CategoryModifier extends PageModifier { categories = params.optJSONArray(PARAM_CATEGORIES); StringBuffer categoriesString = new StringBuffer(); - for(int i=0; i < categories.length(); i++) { + for (int i = 0; i < categories.length(); i++) { String category = categories.optString(i); categoriesString.append("\n[[Category:").append(category).append("]]"); } diff --git a/commons/src/main/java/fr/free/nrw/commons/modifications/ModificationsContentProvider.java b/commons/src/main/java/fr/free/nrw/commons/modifications/ModificationsContentProvider.java index 32449128d..0109c0def 100644 --- a/commons/src/main/java/fr/free/nrw/commons/modifications/ModificationsContentProvider.java +++ b/commons/src/main/java/fr/free/nrw/commons/modifications/ModificationsContentProvider.java @@ -10,7 +10,7 @@ import android.util.*; import fr.free.nrw.commons.data.*; import fr.free.nrw.commons.CommonsApplication; -public class ModificationsContentProvider extends ContentProvider{ +public class ModificationsContentProvider extends ContentProvider { private static final int MODIFICATIONS = 1; private static final int MODIFICATIONS_ID = 2; @@ -21,6 +21,7 @@ public class ModificationsContentProvider extends ContentProvider{ public static final Uri BASE_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH); private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); + static { uriMatcher.addURI(AUTHORITY, BASE_PATH, MODIFICATIONS); uriMatcher.addURI(AUTHORITY, BASE_PATH + "/#", MODIFICATIONS_ID); @@ -32,9 +33,10 @@ public class ModificationsContentProvider extends ContentProvider{ } private DBOpenHelper dbOpenHelper; + @Override public boolean onCreate() { - dbOpenHelper = ((CommonsApplication)this.getContext().getApplicationContext()).getDbOpenHelper(); + dbOpenHelper = ((CommonsApplication) this.getContext().getApplicationContext()).getDbOpenHelper(); return false; } @@ -45,7 +47,7 @@ public class ModificationsContentProvider extends ContentProvider{ int uriType = uriMatcher.match(uri); - switch(uriType) { + switch (uriType) { case MODIFICATIONS: break; default: @@ -90,8 +92,8 @@ public class ModificationsContentProvider extends ContentProvider{ String id = uri.getLastPathSegment(); sqlDB.delete(ModifierSequence.Table.TABLE_NAME, "_id = ?", - new String[] { id } - ); + new String[]{id} + ); return 1; default: throw new IllegalArgumentException("Unknown URI: " + uri); @@ -106,7 +108,7 @@ public class ModificationsContentProvider extends ContentProvider{ sqlDB.beginTransaction(); switch (uriType) { case MODIFICATIONS: - for(ContentValues value: values) { + for (ContentValues value : values) { Log.d("Commons", "Inserting! " + value.toString()); sqlDB.insert(ModifierSequence.Table.TABLE_NAME, null, value); } @@ -146,7 +148,7 @@ public class ModificationsContentProvider extends ContentProvider{ rowsUpdated = sqlDB.update(ModifierSequence.Table.TABLE_NAME, contentValues, ModifierSequence.Table.COLUMN_ID + " = ?", - new String[] { String.valueOf(id) } ); + new String[]{String.valueOf(id)}); } else { throw new IllegalArgumentException("Parameter `selection` should be empty when updating an ID"); } diff --git a/commons/src/main/java/fr/free/nrw/commons/modifications/ModificationsSyncAdapter.java b/commons/src/main/java/fr/free/nrw/commons/modifications/ModificationsSyncAdapter.java index f38a51ef0..7f6e3f53f 100644 --- a/commons/src/main/java/fr/free/nrw/commons/modifications/ModificationsSyncAdapter.java +++ b/commons/src/main/java/fr/free/nrw/commons/modifications/ModificationsSyncAdapter.java @@ -37,14 +37,14 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter { } // Exit early if nothing to do - if(allModifications == null || allModifications.getCount() == 0) { + if (allModifications == null || allModifications.getCount() == 0) { Log.d("Commons", "No modifications to perform"); return; } String authCookie; try { - authCookie = AccountManager.get(getContext()).blockingGetAuthToken(account, "", false); + authCookie = AccountManager.get(getContext()).blockingGetAuthToken(account, "", false); } catch (OperationCanceledException e) { throw new RuntimeException(e); } catch (IOException e) { @@ -75,7 +75,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter { try { contributionsClient = getContext().getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY); - while(!allModifications.isAfterLast()) { + while (!allModifications.isAfterLast()) { ModifierSequence sequence = ModifierSequence.fromCursor(allModifications); sequence.setContentProviderClient(contentProviderClient); Contribution contrib; @@ -89,7 +89,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter { contributionCursor.moveToFirst(); contrib = Contribution.fromCursor(contributionCursor); - if(contrib.getState() == Contribution.STATE_COMPLETED) { + if (contrib.getState() == Contribution.STATE_COMPLETED) { try { requestResult = api.action("query") @@ -104,7 +104,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter { Log.d("Commons", "Page content is " + Utils.getStringFromDOM(requestResult.getDocument())); String pageContent = requestResult.getString("/api/query/pages/page/revisions/rev"); - String processedPageContent = sequence.executeModifications(contrib.getFilename(), pageContent); + String processedPageContent = sequence.executeModifications(contrib.getFilename(), pageContent); try { responseResult = api.action("edit") @@ -121,7 +121,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter { Log.d("Commons", "Response is" + Utils.getStringFromDOM(responseResult.getDocument())); String result = responseResult.getString("/api/edit/@result"); - if(!result.equals("Success")) { + if (!result.equals("Success")) { // FIXME: Log this somewhere else Log.d("Commons", "Non success result!" + result); } else { @@ -132,7 +132,7 @@ public class ModificationsSyncAdapter extends AbstractThreadedSyncAdapter { } } finally { - if(contributionsClient != null) { + if (contributionsClient != null) { contributionsClient.release(); } diff --git a/commons/src/main/java/fr/free/nrw/commons/modifications/ModifierSequence.java b/commons/src/main/java/fr/free/nrw/commons/modifications/ModifierSequence.java index 789e448be..d4f139bcc 100644 --- a/commons/src/main/java/fr/free/nrw/commons/modifications/ModifierSequence.java +++ b/commons/src/main/java/fr/free/nrw/commons/modifications/ModifierSequence.java @@ -26,7 +26,7 @@ public class ModifierSequence { public ModifierSequence(Uri mediaUri, JSONObject data) { this(mediaUri); 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))); } } @@ -40,15 +40,15 @@ public class ModifierSequence { } public String executeModifications(String pageName, String pageContents) { - for(PageModifier modifier: modifiers) { - pageContents = modifier.doModification(pageName, pageContents); + for (PageModifier modifier : modifiers) { + pageContents = modifier.doModification(pageName, pageContents); } return pageContents; } public String getEditSummary() { StringBuffer editSummary = new StringBuffer(); - for(PageModifier modifier: modifiers) { + for (PageModifier modifier : modifiers) { editSummary.append(modifier.getEditSumary()).append(" "); } editSummary.append("Via Commons Mobile App"); @@ -59,7 +59,7 @@ public class ModifierSequence { JSONObject data = new JSONObject(); try { JSONArray modifiersJSON = new JSONArray(); - for(PageModifier modifier: modifiers) { + for (PageModifier modifier : modifiers) { modifiersJSON.put(modifier.toJSON()); } data.put("modifiers", modifiersJSON); @@ -91,12 +91,12 @@ public class ModifierSequence { public void save() { try { - if(contentUri == null) { + if (contentUri == null) { contentUri = client.insert(ModificationsContentProvider.BASE_URI, this.toContentValues()); } else { client.update(contentUri, toContentValues(), null, null); } - } catch(RemoteException e) { + } catch (RemoteException e) { throw new RuntimeException(e); } } diff --git a/commons/src/main/java/fr/free/nrw/commons/modifications/PageModifier.java b/commons/src/main/java/fr/free/nrw/commons/modifications/PageModifier.java index f4b3c7359..0da25d9a6 100644 --- a/commons/src/main/java/fr/free/nrw/commons/modifications/PageModifier.java +++ b/commons/src/main/java/fr/free/nrw/commons/modifications/PageModifier.java @@ -7,9 +7,9 @@ public abstract class PageModifier { public static PageModifier fromJSON(JSONObject data) { String name = data.optString("name"); - if(name.equals(CategoryModifier.MODIFIER_NAME)) { + if (name.equals(CategoryModifier.MODIFIER_NAME)) { return new CategoryModifier(data.optJSONObject("data")); - } else if(name.equals(TemplateRemoveModifier.MODIFIER_NAME)) { + } else if (name.equals(TemplateRemoveModifier.MODIFIER_NAME)) { return new TemplateRemoveModifier(data.optJSONObject("data")); } diff --git a/commons/src/main/java/fr/free/nrw/commons/modifications/TemplateRemoveModifier.java b/commons/src/main/java/fr/free/nrw/commons/modifications/TemplateRemoveModifier.java index 21b4872b7..77f98dfe0 100644 --- a/commons/src/main/java/fr/free/nrw/commons/modifications/TemplateRemoveModifier.java +++ b/commons/src/main/java/fr/free/nrw/commons/modifications/TemplateRemoveModifier.java @@ -42,18 +42,18 @@ public class TemplateRemoveModifier extends PageModifier { Pattern templateStartPattern = Pattern.compile("\\{\\{" + templateNormalized, Pattern.CASE_INSENSITIVE); Matcher matcher = templateStartPattern.matcher(pageContents); - while(matcher.find()) { + while (matcher.find()) { int braceCount = 1; int startIndex = matcher.start(); int curIndex = matcher.end(); Matcher openMatch = PATTERN_TEMPLATE_OPEN.matcher(pageContents); Matcher closeMatch = PATTERN_TEMPLATE_CLOSE.matcher(pageContents); - while(curIndex < pageContents.length()) { + while (curIndex < pageContents.length()) { boolean openFound = openMatch.find(curIndex); boolean closeFound = closeMatch.find(curIndex); - if(openFound && (!closeFound || openMatch.start() < closeMatch.start())) { + if (openFound && (!closeFound || openMatch.start() < closeMatch.start())) { braceCount++; curIndex = openMatch.end(); } else if (closeFound) { @@ -72,8 +72,8 @@ public class TemplateRemoveModifier extends PageModifier { } // Strip trailing whitespace - while(curIndex < pageContents.length()) { - if(pageContents.charAt(curIndex) == ' ' || pageContents.charAt(curIndex) == '\n') { + while (curIndex < pageContents.length()) { + if (pageContents.charAt(curIndex) == ' ' || pageContents.charAt(curIndex) == '\n') { curIndex++; } else { break; diff --git a/commons/src/main/java/fr/free/nrw/commons/upload/MultipleShareActivity.java b/commons/src/main/java/fr/free/nrw/commons/upload/MultipleShareActivity.java index bd7a0be03..a6953badc 100644 --- a/commons/src/main/java/fr/free/nrw/commons/upload/MultipleShareActivity.java +++ b/commons/src/main/java/fr/free/nrw/commons/upload/MultipleShareActivity.java @@ -26,12 +26,12 @@ import fr.free.nrw.commons.modifications.TemplateRemoveModifier; import fr.free.nrw.commons.contributions.*; import fr.free.nrw.commons.media.*; -public class MultipleShareActivity - extends AuthenticatedActivity - implements MediaDetailPagerFragment.MediaDetailProvider, - AdapterView.OnItemClickListener, - FragmentManager.OnBackStackChangedListener, - MultipleUploadListFragment.OnMultipleUploadInitiatedHandler, +public class MultipleShareActivity + extends AuthenticatedActivity + implements MediaDetailPagerFragment.MediaDetailProvider, + AdapterView.OnItemClickListener, + FragmentManager.OnBackStackChangedListener, + MultipleUploadListFragment.OnMultipleUploadInitiatedHandler, CategorizationFragment.OnCategoriesSaveHandler { private CommonsApplication app; private ArrayList photosList = null; @@ -51,14 +51,14 @@ public class MultipleShareActivity } public int getTotalMediaCount() { - if(photosList == null) { + if (photosList == null) { return 0; } return photosList.size(); } public void notifyDatasetChanged() { - if(uploadsList != null) { + if (uploadsList != null) { uploadsList.notifyDatasetChanged(); } } @@ -84,14 +84,14 @@ public class MultipleShareActivity dialog.setTitle(getResources().getQuantityString(R.plurals.starting_multiple_uploads, photosList.size(), photosList.size())); dialog.show(); - for(int i = 0; i < photosList.size(); i++) { + for (int i = 0; i < photosList.size(); i++) { Contribution up = photosList.get(i); final int uploadCount = i + 1; // Goddamn Java uploadController.startUpload(up, new UploadController.ContributionUploadProgress() { public void onUploadStarted(Contribution contribution) { dialog.setProgress(uploadCount); - if(uploadCount == photosList.size()) { + if (uploadCount == photosList.size()) { dialog.dismiss(); Toast startingToast = Toast.makeText(getApplicationContext(), R.string.uploading_started, Toast.LENGTH_LONG); startingToast.show(); @@ -103,7 +103,7 @@ public class MultipleShareActivity uploadsList.setImageOnlyMode(true); categorizationFragment = (CategorizationFragment) this.getSupportFragmentManager().findFragmentByTag("categorization"); - if(categorizationFragment == null) { + if (categorizationFragment == null) { categorizationFragment = new CategorizationFragment(); } // FIXME: Stops the keyboard from being shown 'stale' while moving out of this fragment into the next @@ -118,9 +118,9 @@ public class MultipleShareActivity } public void onCategoriesSave(ArrayList categories) { - if(categories.size() > 0) { - ContentProviderClient client = getContentResolver().acquireContentProviderClient(ModificationsContentProvider.AUTHORITY); - for(Contribution contribution: photosList) { + if (categories.size() > 0) { + ContentProviderClient client = getContentResolver().acquireContentProviderClient(ModificationsContentProvider.AUTHORITY); + for (Contribution contribution : photosList) { ModifierSequence categoriesSequence = new ModifierSequence(contribution.getContentUri()); categoriesSequence.queueModifier(new CategoryModifier(categories.toArray(new String[]{}))); @@ -145,9 +145,9 @@ public class MultipleShareActivity @Override public boolean onOptionsItemSelected(MenuItem item) { - switch(item.getItemId()) { + switch (item.getItemId()) { case android.R.id.home: - if(mediaDetails.isVisible()) { + if (mediaDetails.isVisible()) { getSupportFragmentManager().popBackStack(); } return true; @@ -161,9 +161,9 @@ public class MultipleShareActivity uploadController = new UploadController(this); setContentView(R.layout.activity_multiple_uploads); - app = (CommonsApplication)this.getApplicationContext(); + app = (CommonsApplication) this.getApplicationContext(); - if(savedInstanceState != null) { + if (savedInstanceState != null) { photosList = savedInstanceState.getParcelableArrayList("uploadsList"); } @@ -180,7 +180,7 @@ public class MultipleShareActivity } private void showDetail(int i) { - if(mediaDetails == null ||!mediaDetails.isVisible()) { + if (mediaDetails == null || !mediaDetails.isVisible()) { mediaDetails = new MediaDetailPagerFragment(true); this.getSupportFragmentManager() .beginTransaction() @@ -203,11 +203,11 @@ public class MultipleShareActivity app.getApi().setAuthCookie(authCookie); Intent intent = getIntent(); - if(intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) { - if(photosList == null) { + if (intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) { + if (photosList == null) { photosList = new ArrayList(); ArrayList urisList = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); - for(int i=0; i < urisList.size(); i++) { + for (int i = 0; i < urisList.size(); i++) { Contribution up = new Contribution(); Uri uri = urisList.get(i); up.setLocalUri(uri); @@ -220,8 +220,8 @@ public class MultipleShareActivity } uploadsList = (MultipleUploadListFragment) getSupportFragmentManager().findFragmentByTag("uploadsList"); - if(uploadsList == null) { - uploadsList = new MultipleUploadListFragment(); + if (uploadsList == null) { + uploadsList = new MultipleUploadListFragment(); this.getSupportFragmentManager() .beginTransaction() .add(R.id.uploadsFragmentContainer, uploadsList, "uploadsList") @@ -245,7 +245,7 @@ public class MultipleShareActivity @Override public void onBackPressed() { super.onBackPressed(); - if(categorizationFragment != null && categorizationFragment.isVisible()) { + if (categorizationFragment != null && categorizationFragment.isVisible()) { EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT) .param("username", app.getCurrentAccount().name) .param("categories-count", categorizationFragment.getCurrentSelectedCount()) @@ -264,7 +264,7 @@ public class MultipleShareActivity } public void onBackStackChanged() { - if(mediaDetails != null && mediaDetails.isVisible()) { + if (mediaDetails != null && mediaDetails.isVisible()) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } else { getSupportActionBar().setDisplayHomeAsUpEnabled(false); diff --git a/commons/src/main/java/fr/free/nrw/commons/upload/MultipleUploadListFragment.java b/commons/src/main/java/fr/free/nrw/commons/upload/MultipleUploadListFragment.java index 267a9642d..70b7cc2ec 100644 --- a/commons/src/main/java/fr/free/nrw/commons/upload/MultipleUploadListFragment.java +++ b/commons/src/main/java/fr/free/nrw/commons/upload/MultipleUploadListFragment.java @@ -64,7 +64,7 @@ public class MultipleUploadListFragment extends SherlockFragment { public View getView(int i, View view, ViewGroup viewGroup) { UploadHolderView holder; - if(view == null) { + if (view == null) { view = getLayoutInflater(null).inflate(R.layout.layout_upload_item, null); holder = new UploadHolderView(); holder.image = (ImageView) view.findViewById(R.id.uploadImage); @@ -75,18 +75,18 @@ public class MultipleUploadListFragment extends SherlockFragment { view.setTag(holder); } else { - holder = (UploadHolderView)view.getTag(); + holder = (UploadHolderView) view.getTag(); } - Contribution up = (Contribution)this.getItem(i); + Contribution up = (Contribution) this.getItem(i); - if(holder.imageUri == null || !holder.imageUri.equals(up.getLocalUri())) { + if (holder.imageUri == null || !holder.imageUri.equals(up.getLocalUri())) { ImageLoader.getInstance().displayImage(up.getLocalUri().toString(), holder.image, uploadDisplayOptions); holder.imageUri = up.getLocalUri(); } - if(!imageOnlyMode) { + if (!imageOnlyMode) { holder.overlay.setVisibility(View.VISIBLE); holder.title.setText(up.getFilename()); } else { @@ -117,21 +117,21 @@ public class MultipleUploadListFragment extends SherlockFragment { int screenHeight = screenMetrics.heightPixels; int picWidth = Math.min((int) Math.sqrt(screenWidth * screenHeight / count), screenWidth); - picWidth = Math.min((int)(192 * screenMetrics.density), Math.max((int) (120 * screenMetrics.density), picWidth / 48 * 48)); - int picHeight = Math.min(picWidth, (int)(192 * screenMetrics.density)); // Max Height is same as Contributions list + picWidth = Math.min((int) (192 * screenMetrics.density), Math.max((int) (120 * screenMetrics.density), picWidth / 48 * 48)); + int picHeight = Math.min(picWidth, (int) (192 * screenMetrics.density)); // Max Height is same as Contributions list return new Point(picWidth, picHeight); } public void notifyDatasetChanged() { - if(photosAdapter != null) { + if (photosAdapter != null) { photosAdapter.notifyDataSetChanged(); } } public void setImageOnlyMode(boolean mode) { imageOnlyMode = mode; - if(imageOnlyMode) { + if (imageOnlyMode) { baseTitle.setVisibility(View.GONE); } else { baseTitle.setVisibility(View.VISIBLE); @@ -143,13 +143,13 @@ public class MultipleUploadListFragment extends SherlockFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_multiple_uploads_list, null); - photosGrid = (GridView)view.findViewById(R.id.multipleShareBackground); - baseTitle = (EditText)view.findViewById(R.id.multipleBaseTitle); + photosGrid = (GridView) view.findViewById(R.id.multipleShareBackground); + baseTitle = (EditText) view.findViewById(R.id.multipleBaseTitle); photosAdapter = new PhotoDisplayAdapter(); photosGrid.setAdapter(photosAdapter); - photosGrid.setOnItemClickListener((AdapterView.OnItemClickListener)getActivity()); + photosGrid.setOnItemClickListener((AdapterView.OnItemClickListener) getActivity()); photoSize = calculatePicDimension(detailProvider.getTotalMediaCount()); photosGrid.setColumnWidth(photoSize.x); @@ -159,12 +159,12 @@ public class MultipleUploadListFragment extends SherlockFragment { } public void onTextChanged(CharSequence charSequence, int i1, int i2, int i3) { - for(int i = 0; i < detailProvider.getTotalMediaCount(); i++) { + for (int i = 0; i < detailProvider.getTotalMediaCount(); i++) { Contribution up = (Contribution) detailProvider.getMediaAtPosition(i); - Boolean isDirty = (Boolean)up.getTag("isDirty"); - if(isDirty == null || !isDirty) { - if(!TextUtils.isEmpty(charSequence)) { - up.setFilename(charSequence.toString() + " - " + ((Integer)up.getTag("sequence") + 1)); + Boolean isDirty = (Boolean) up.getTag("isDirty"); + if (isDirty == null || !isDirty) { + if (!TextUtils.isEmpty(charSequence)) { + up.setFilename(charSequence.toString() + " - " + ((Integer) up.getTag("sequence") + 1)); } else { up.setFilename(""); } @@ -191,7 +191,7 @@ public class MultipleUploadListFragment extends SherlockFragment { @Override public boolean onOptionsItemSelected(MenuItem item) { - switch(item.getItemId()) { + switch (item.getItemId()) { case R.id.menu_upload_multiple: multipleUploadInitiatedHandler.OnMultipleUploadInitiated(); return true; @@ -204,7 +204,7 @@ public class MultipleUploadListFragment extends SherlockFragment { super.onCreate(savedInstanceState); uploadDisplayOptions = Utils.getGenericDisplayOptions().build(); - detailProvider = (MediaDetailPagerFragment.MediaDetailProvider)getActivity(); + detailProvider = (MediaDetailPagerFragment.MediaDetailProvider) getActivity(); multipleUploadInitiatedHandler = (OnMultipleUploadInitiatedHandler) getActivity(); setHasOptionsMenu(true); diff --git a/commons/src/main/java/fr/free/nrw/commons/upload/ShareActivity.java b/commons/src/main/java/fr/free/nrw/commons/upload/ShareActivity.java index 2742b4985..a18feb3fb 100644 --- a/commons/src/main/java/fr/free/nrw/commons/upload/ShareActivity.java +++ b/commons/src/main/java/fr/free/nrw/commons/upload/ShareActivity.java @@ -13,7 +13,6 @@ import fr.free.nrw.commons.modifications.CategoryModifier; import fr.free.nrw.commons.modifications.TemplateRemoveModifier; import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.EventLog; -import fr.free.nrw.commons.campaigns.Campaign; import fr.free.nrw.commons.category.CategorizationFragment; import fr.free.nrw.commons.contributions.*; import fr.free.nrw.commons.auth.*; @@ -23,9 +22,9 @@ import fr.free.nrw.commons.modifications.ModifierSequence; import java.util.ArrayList; -public class ShareActivity - extends AuthenticatedActivity - implements SingleUploadFragment.OnUploadActionInitiated, +public class ShareActivity + extends AuthenticatedActivity + implements SingleUploadFragment.OnUploadActionInitiated, CategorizationFragment.OnCategoriesSaveHandler { private SingleUploadFragment shareView; @@ -51,7 +50,7 @@ public class ShareActivity public void uploadActionInitiated(String title, String description) { Toast startingToast = Toast.makeText(getApplicationContext(), R.string.uploading_started, Toast.LENGTH_LONG); startingToast.show(); - uploadController.startUpload(title, mediaUri, description, mimeType, source, new UploadController.ContributionUploadProgress() { + uploadController.startUpload(title, mediaUri, description, mimeType, source, new UploadController.ContributionUploadProgress() { public void onUploadStarted(Contribution contribution) { ShareActivity.this.contribution = contribution; showPostUpload(); @@ -60,7 +59,7 @@ public class ShareActivity } private void showPostUpload() { - if(categorizationFragment == null) { + if (categorizationFragment == null) { categorizationFragment = new CategorizationFragment(); } getSupportFragmentManager().beginTransaction() @@ -69,7 +68,7 @@ public class ShareActivity } public void onCategoriesSave(ArrayList categories) { - if(categories.size() > 0) { + if (categories.size() > 0) { ModifierSequence categoriesSequence = new ModifierSequence(contribution.getContentUri()); categoriesSequence.queueModifier(new CategoryModifier(categories.toArray(new String[]{}))); @@ -95,7 +94,7 @@ public class ShareActivity @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); - if(contribution != null) { + if (contribution != null) { outState.putParcelable("contribution", contribution); } } @@ -103,7 +102,7 @@ public class ShareActivity @Override public void onBackPressed() { super.onBackPressed(); - if(categorizationFragment != null && categorizationFragment.isVisible()) { + if (categorizationFragment != null && categorizationFragment.isVisible()) { EventLog.schema(CommonsApplication.EVENT_CATEGORIZATION_ATTEMPT) .param("username", app.getCurrentAccount().name) .param("categories-count", categorizationFragment.getCurrentSelectedCount()) @@ -129,12 +128,12 @@ public class ShareActivity shareView = (SingleUploadFragment) getSupportFragmentManager().findFragmentByTag("shareView"); categorizationFragment = (CategorizationFragment) getSupportFragmentManager().findFragmentByTag("categorization"); - if(shareView == null && categorizationFragment == null) { - shareView = new SingleUploadFragment(); - this.getSupportFragmentManager() - .beginTransaction() - .add(R.id.single_upload_fragment_container, shareView, "shareView") - .commit(); + if (shareView == null && categorizationFragment == null) { + shareView = new SingleUploadFragment(); + this.getSupportFragmentManager() + .beginTransaction() + .add(R.id.single_upload_fragment_container, shareView, "shareView") + .commit(); } uploadController.prepareService(); @@ -151,22 +150,19 @@ public class ShareActivity @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - Campaign campaign = null; - if(getIntent().hasExtra(UploadService.EXTRA_CAMPAIGN)) { - campaign = (Campaign) getIntent().getSerializableExtra(UploadService.EXTRA_CAMPAIGN); - } - uploadController = new UploadController(this, campaign); + + uploadController = new UploadController(this); setContentView(R.layout.activity_share); - - app = (CommonsApplication)this.getApplicationContext(); - - backgroundImageView = (ImageView)findViewById(R.id.backgroundImage); + + app = (CommonsApplication) this.getApplicationContext(); + + backgroundImageView = (ImageView) findViewById(R.id.backgroundImage); Intent intent = getIntent(); - if(intent.getAction().equals(Intent.ACTION_SEND)) { + if (intent.getAction().equals(Intent.ACTION_SEND)) { mediaUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); - if(intent.hasExtra(UploadService.EXTRA_SOURCE)) { + if (intent.hasExtra(UploadService.EXTRA_SOURCE)) { source = intent.getStringExtra(UploadService.EXTRA_SOURCE); } else { source = Contribution.SOURCE_EXTERNAL; @@ -177,7 +173,7 @@ public class ShareActivity ImageLoader.getInstance().displayImage(mediaUri.toString(), backgroundImageView); - if(savedInstanceState != null) { + if (savedInstanceState != null) { contribution = savedInstanceState.getParcelable("contribution"); } diff --git a/commons/src/main/java/fr/free/nrw/commons/upload/SingleUploadFragment.java b/commons/src/main/java/fr/free/nrw/commons/upload/SingleUploadFragment.java index 70e399d20..f8d621957 100644 --- a/commons/src/main/java/fr/free/nrw/commons/upload/SingleUploadFragment.java +++ b/commons/src/main/java/fr/free/nrw/commons/upload/SingleUploadFragment.java @@ -39,7 +39,7 @@ public class SingleUploadFragment extends SherlockFragment { @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.activity_share, menu); - if(titleEdit != null) { + if (titleEdit != null) { menu.findItem(R.id.menu_upload_single).setEnabled(titleEdit.getText().length() != 0); } } @@ -59,17 +59,19 @@ public class SingleUploadFragment extends SherlockFragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_single_upload, null); - titleEdit = (EditText)rootView.findViewById(R.id.titleEdit); - descEdit = (EditText)rootView.findViewById(R.id.descEdit); - licenseSummaryView = (TextView)rootView.findViewById(R.id.share_license_summary); + titleEdit = (EditText) rootView.findViewById(R.id.titleEdit); + descEdit = (EditText) rootView.findViewById(R.id.descEdit); + licenseSummaryView = (TextView) rootView.findViewById(R.id.share_license_summary); TextWatcher uploadEnabler = new TextWatcher() { - public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } + public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { + } - public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {} + public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { + } public void afterTextChanged(Editable editable) { - if(getSherlockActivity() != null) { + if (getSherlockActivity() != null) { getSherlockActivity().invalidateOptionsMenu(); } } diff --git a/commons/src/main/java/fr/free/nrw/commons/upload/UploadController.java b/commons/src/main/java/fr/free/nrw/commons/upload/UploadController.java index fff719615..a90e913dc 100644 --- a/commons/src/main/java/fr/free/nrw/commons/upload/UploadController.java +++ b/commons/src/main/java/fr/free/nrw/commons/upload/UploadController.java @@ -15,8 +15,7 @@ import fr.free.nrw.commons.CommonsApplication; import fr.free.nrw.commons.HandlerService; import fr.free.nrw.commons.Prefs; import fr.free.nrw.commons.Utils; -import fr.free.nrw.commons.campaigns.Campaign; -import fr.free.nrw.commons.campaigns.CampaignContribution; + import java.io.IOException; import java.util.Date; @@ -25,7 +24,6 @@ public class UploadController { private UploadService uploadService; private final Activity activity; - private Campaign campaign; final CommonsApplication app; public interface ContributionUploadProgress { @@ -34,18 +32,14 @@ public class UploadController { public UploadController(Activity activity) { this.activity = activity; - app = (CommonsApplication)activity.getApplicationContext(); + app = (CommonsApplication) activity.getApplicationContext(); } - public UploadController(Activity activity, Campaign campaign) { - this(activity); - this.campaign = campaign; - } private boolean isUploadServiceConnected; private ServiceConnection uploadServiceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName componentName, IBinder binder) { - uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder)binder).getService(); + uploadService = (UploadService) ((HandlerService.HandlerServiceLocalBinder) binder).getService(); isUploadServiceConnected = true; } @@ -63,7 +57,7 @@ public class UploadController { } public void cleanup() { - if(isUploadServiceConnected) { + if (isUploadServiceConnected) { activity.unbindService(uploadServiceConnection); } } @@ -77,15 +71,13 @@ public class UploadController { if (extension != null && extension.toLowerCase().equals("jpeg")) { extension = "jpg"; } - if(extension != null && !title.toLowerCase().endsWith(extension.toLowerCase())) { + if (extension != null && !title.toLowerCase().endsWith(extension.toLowerCase())) { title += "." + extension; } - if(campaign == null) { - contribution = new Contribution(mediaUri, null, title, description, -1, null, null, app.getCurrentAccount().name, CommonsApplication.DEFAULT_EDIT_SUMMARY); - } else { - contribution = new CampaignContribution(mediaUri, null, title, description, -1, null, null, app.getCurrentAccount().name, CommonsApplication.DEFAULT_EDIT_SUMMARY, campaign); - } + + contribution = new Contribution(mediaUri, null, title, description, -1, null, null, app.getCurrentAccount().name, CommonsApplication.DEFAULT_EDIT_SUMMARY); + contribution.setTag("mimeType", mimeType); contribution.setSource(source); @@ -95,11 +87,11 @@ public class UploadController { public void startUpload(final Contribution contribution, final ContributionUploadProgress onComplete) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity); - if(TextUtils.isEmpty(contribution.getCreator())) { + if (TextUtils.isEmpty(contribution.getCreator())) { contribution.setCreator(app.getCurrentAccount().name); } - if(contribution.getDescription() == null) { + if (contribution.getDescription() == null) { contribution.setDescription(""); } @@ -115,30 +107,30 @@ public class UploadController { protected Contribution doInBackground(Void... voids /* stare into you */) { long length; try { - if(contribution.getDataLength() <= 0) { + if (contribution.getDataLength() <= 0) { length = activity.getContentResolver().openAssetFileDescriptor(contribution.getLocalUri(), "r").getLength(); - if(length == -1) { + if (length == -1) { // Let us find out the long way! length = Utils.countBytes(activity.getContentResolver().openInputStream(contribution.getLocalUri())); } contribution.setDataLength(length); } - } catch(IOException e) { + } catch (IOException e) { throw new RuntimeException(e); } - String mimeType = (String)contribution.getTag("mimeType"); - if(mimeType == null || TextUtils.isEmpty(mimeType) || mimeType.endsWith("*")) { + String mimeType = (String) contribution.getTag("mimeType"); + if (mimeType == null || TextUtils.isEmpty(mimeType) || mimeType.endsWith("*")) { mimeType = activity.getContentResolver().getType(contribution.getLocalUri()); - if(mimeType != null) { + if (mimeType != null) { contribution.setTag("mimeType", mimeType); } } - if(mimeType.startsWith("image/") && contribution.getDateCreated() == null) { + if (mimeType.startsWith("image/") && contribution.getDateCreated() == null) { Cursor cursor = activity.getContentResolver().query(contribution.getLocalUri(), new String[]{MediaStore.Images.ImageColumns.DATE_TAKEN}, null, null, null); - if(cursor != null && cursor.getCount() != 0) { + if (cursor != null && cursor.getCount() != 0) { cursor.moveToFirst(); contribution.setDateCreated(new Date(cursor.getLong(0))); } // FIXME: Alternate way of setting dateCreated if this data is not found diff --git a/commons/src/main/java/fr/free/nrw/commons/upload/UploadService.java b/commons/src/main/java/fr/free/nrw/commons/upload/UploadService.java index 36090e390..dd631889e 100644 --- a/commons/src/main/java/fr/free/nrw/commons/upload/UploadService.java +++ b/commons/src/main/java/fr/free/nrw/commons/upload/UploadService.java @@ -72,12 +72,12 @@ public class UploadService extends HandlerService { @Override public void onProgress(long transferred, long total) { Log.d("Commons", String.format("Uploaded %d of %d", transferred, total)); - if(!notificationTitleChanged) { + if (!notificationTitleChanged) { curProgressNotification.setContentTitle(notificationProgressTitle); notificationTitleChanged = true; contribution.setState(Contribution.STATE_IN_PROGRESS); } - if(transferred == total) { + if (transferred == total) { // Completed! curProgressNotification.setContentTitle(notificationFinishingTitle); curProgressNotification.setProgress(0, 100, true); @@ -110,7 +110,7 @@ public class UploadService extends HandlerService { @Override protected void handle(int what, Contribution contribution) { - switch(what) { + switch (what) { case ACTION_UPLOAD_FILE: uploadContribution(contribution); break; @@ -148,14 +148,14 @@ public class UploadService extends HandlerService { @Override public int onStartCommand(Intent intent, int flags, int startId) { - if(intent.getAction() == ACTION_START_SERVICE && freshStart) { + if (intent.getAction() == ACTION_START_SERVICE && freshStart) { ContentValues failedValues = new ContentValues(); failedValues.put(Contribution.Table.COLUMN_STATE, Contribution.STATE_FAILED); int updated = getContentResolver().update(ContributionsContentProvider.BASE_URI, failedValues, Contribution.Table.COLUMN_STATE + " = ? OR " + Contribution.Table.COLUMN_STATE + " = ?", - new String[]{ String.valueOf(Contribution.STATE_QUEUED), String.valueOf(Contribution.STATE_IN_PROGRESS) } + new String[]{String.valueOf(Contribution.STATE_QUEUED), String.valueOf(Contribution.STATE_IN_PROGRESS)} ); Log.d("Commons", "Set " + updated + " uploads to failed"); Log.d("Commons", "Flags is" + flags + " id is" + startId); @@ -175,7 +175,7 @@ public class UploadService extends HandlerService { try { file = this.getContentResolver().openInputStream(contribution.getLocalUri()); - } catch(FileNotFoundException e) { + } catch (FileNotFoundException e) { throw new RuntimeException(e); } @@ -195,9 +195,9 @@ public class UploadService extends HandlerService { try { String filename = findUniqueFilename(contribution.getFilename()); - if(!api.validateLogin()) { + if (!api.validateLogin()) { // Need to revalidate! - if(app.revalidateAuthToken()) { + if (app.revalidateAuthToken()) { Log.d("Commons", "Successfully revalidated token!"); } else { Log.d("Commons", "Unable to revalidate :("); @@ -222,7 +222,7 @@ public class UploadService extends HandlerService { String resultStatus = result.getString("/api/upload/@result"); - if(!resultStatus.equals("Success")) { + if (!resultStatus.equals("Success")) { String errorCode = result.getString("/api/error/@code"); showFailedNotification(contribution); fr.free.nrw.commons.EventLog.schema(CommonsApplication.EVENT_UPLOAD_ATTEMPT) @@ -251,13 +251,13 @@ public class UploadService extends HandlerService { .param("result", "success") .log(); } - } catch(IOException e) { + } catch (IOException e) { Log.d("Commons", "I have a network fuckup"); showFailedNotification(contribution); return; } finally { toUpload--; - if(toUpload == 0) { + if (toUpload == 0) { // Sync modifications right after all uplaods are processed ContentResolver.requestSync(((CommonsApplication) getApplicationContext()).getCurrentAccount(), ModificationsContentProvider.AUTHORITY, new Bundle()); stopForeground(true); @@ -285,7 +285,7 @@ public class UploadService extends HandlerService { return findUniqueFilename(fileName, 1); } - private String findUniqueFilename(String fileName, int sequenceNumber) throws IOException { + private String findUniqueFilename(String fileName, int sequenceNumber) throws IOException { String sequenceFileName; if (sequenceNumber == 1) { sequenceFileName = fileName;