From 9d61d6c7329a5535f11c6e077ba5b17051b92a0e Mon Sep 17 00:00:00 2001 From: Loic Blot Date: Tue, 3 Nov 2015 23:00:31 +0100 Subject: [PATCH] Refactor code with Java best practices, helped by AS --- .../activities/GeneralSettingsActivity.java | 81 ++++--- .../activities/LoginActivity.java | 25 ++- .../owncloud_sms/activities/MainActivity.java | 66 +++--- .../remote_account/AccountListActivity.java | 18 +- .../remote_account/ContactListActivity.java | 34 +-- .../adapters/ContactListAdapter.java | 32 ++- .../authenticators/OwnCloudAuthenticator.java | 65 +++--- .../owncloud_sms/engine/ASyncContactLoad.java | 54 ++--- .../owncloud_sms/engine/ASyncSMSSync.java | 27 +-- .../engine/ConnectivityMonitor.java | 10 +- .../engine/OCSMSOwnCloudClient.java | 202 +++++++++--------- .../owncloud_sms/engine/SmsFetcher.java | 49 ++--- .../OCSMSNotificationManager.java | 8 +- .../owncloud_sms/observers/SmsObserver.java | 20 +- .../owncloud_sms/prefs/OCSMSSharedPrefs.java | 8 +- .../providers/SmsDataProvider.java | 29 +-- .../sync_adapters/SmsSyncService.java | 8 +- 17 files changed, 365 insertions(+), 371 deletions(-) diff --git a/src/main/java/fr/unix_experience/owncloud_sms/activities/GeneralSettingsActivity.java b/src/main/java/fr/unix_experience/owncloud_sms/activities/GeneralSettingsActivity.java index 0f7a0bd..594ed7a 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/activities/GeneralSettingsActivity.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/activities/GeneralSettingsActivity.java @@ -17,8 +17,6 @@ package fr.unix_experience.owncloud_sms.activities; * along with this program. If not, see . */ -import java.util.List; - import android.accounts.Account; import android.accounts.AccountManager; import android.content.ContentResolver; @@ -26,6 +24,9 @@ import android.content.PeriodicSync; import android.os.Bundle; import android.preference.ListPreference; import android.util.Log; + +import java.util.List; + import fr.nrz.androidlib.activities.NrzSettingsActivity; import fr.unix_experience.owncloud_sms.R; import fr.unix_experience.owncloud_sms.defines.DefaultPrefs; @@ -39,87 +40,81 @@ public class GeneralSettingsActivity extends NrzSettingsActivity { private static String _accountType; @Override - protected void onPostCreate(final Bundle savedInstanceState) { - _accountMgr = AccountManager.get(getBaseContext()); - _accountAuthority = getString(R.string.account_authority); - _accountType = getString(R.string.account_type); - _prefsRessourceFile = R.xml.pref_data_sync; + protected void onPostCreate(Bundle savedInstanceState) { + GeneralSettingsActivity._accountMgr = AccountManager.get(getBaseContext()); + GeneralSettingsActivity._accountAuthority = getString(R.string.account_authority); + GeneralSettingsActivity._accountType = getString(R.string.account_type); + NrzSettingsActivity._prefsRessourceFile = R.xml.pref_data_sync; // Bind our boolean preferences - _boolPrefs.add(new BindObjectPref("push_on_receive", DefaultPrefs.pushOnReceive)); - _boolPrefs.add(new BindObjectPref("sync_wifi", DefaultPrefs.syncWifi)); - _boolPrefs.add(new BindObjectPref("sync_4g", DefaultPrefs.sync4G)); - _boolPrefs.add(new BindObjectPref("sync_3g", DefaultPrefs.sync3G)); - _boolPrefs.add(new BindObjectPref("sync_gprs", DefaultPrefs.syncGPRS)); - _boolPrefs.add(new BindObjectPref("sync_2g", DefaultPrefs.sync2G)); - _boolPrefs.add(new BindObjectPref("sync_others", DefaultPrefs.syncOthers)); + NrzSettingsActivity._boolPrefs.add(new BindObjectPref("push_on_receive", DefaultPrefs.pushOnReceive)); + NrzSettingsActivity._boolPrefs.add(new BindObjectPref("sync_wifi", DefaultPrefs.syncWifi)); + NrzSettingsActivity._boolPrefs.add(new BindObjectPref("sync_4g", DefaultPrefs.sync4G)); + NrzSettingsActivity._boolPrefs.add(new BindObjectPref("sync_3g", DefaultPrefs.sync3G)); + NrzSettingsActivity._boolPrefs.add(new BindObjectPref("sync_gprs", DefaultPrefs.syncGPRS)); + NrzSettingsActivity._boolPrefs.add(new BindObjectPref("sync_2g", DefaultPrefs.sync2G)); + NrzSettingsActivity._boolPrefs.add(new BindObjectPref("sync_others", DefaultPrefs.syncOthers)); // Bind our string preferences - _stringPrefs.add(new BindObjectPref("sync_frequency", "")); + NrzSettingsActivity._stringPrefs.add(new BindObjectPref("sync_frequency", "")); // Must be at the end, after preference bind super.onPostCreate(savedInstanceState); } - protected static void handleCheckboxPreference(final String key, final Boolean value) { + protected static void handleCheckboxPreference(String key, Boolean value) { // Network types allowed for sync - if(key.equals(new String("push_on_receive")) || - key.equals(new String("sync_wifi")) || key.equals("sync_2g") || - key.equals(new String("sync_3g")) || key.equals("sync_gprs") || - key.equals("sync_4g") || key.equals("sync_others")) { - final OCSMSSharedPrefs prefs = new OCSMSSharedPrefs(_context); - Log.d(TAG,"GeneralSettingsActivity.handleCheckboxPreference: set " + key + " to " + if("push_on_receive".equals(key) || + "sync_wifi".equals(key) || "sync_2g".equals(key) || + "sync_3g".equals(key) || "sync_gprs".equals(key) || + "sync_4g".equals(key) || "sync_others".equals(key)) { + OCSMSSharedPrefs prefs = new OCSMSSharedPrefs(NrzSettingsActivity._context); + Log.d(GeneralSettingsActivity.TAG,"GeneralSettingsActivity.handleCheckboxPreference: set " + key + " to " + value.toString()); prefs.putBoolean(key, value); } - else { - // Unknown option - } } - protected static void handleListPreference(final String key, final String value, - final ListPreference preference) { + protected static void handleListPreference(String key, String value, + ListPreference preference) { // For list preferences, look up the correct display value in // the preference's 'entries' list. - final int index = preference.findIndexOfValue(value); + int index = preference.findIndexOfValue(value); // Set the summary to reflect the new value. preference - .setSummary(index >= 0 ? preference.getEntries()[index] - : null); + .setSummary((index >= 0) ? preference.getEntries()[index] + : null); // Handle sync frequency change - if (key.equals("sync_frequency")) { - final Account[] myAccountList = _accountMgr.getAccountsByType(_accountType); - final long syncFreq = Long.parseLong(value); + if ("sync_frequency".equals(key)) { + Account[] myAccountList = GeneralSettingsActivity._accountMgr.getAccountsByType(GeneralSettingsActivity._accountType); + long syncFreq = Long.parseLong(value); // Get ownCloud SMS account list for (int i = 0; i < myAccountList.length; i++) { // And get all authorities for this account - final List syncList = ContentResolver.getPeriodicSyncs(myAccountList[i], _accountAuthority); + List syncList = ContentResolver.getPeriodicSyncs(myAccountList[i], GeneralSettingsActivity._accountAuthority); boolean foundSameSyncCycle = false; for (int j = 0; j < syncList.size(); j++) { - final PeriodicSync ps = syncList.get(i); + PeriodicSync ps = syncList.get(i); - if (ps.period == syncFreq && ps.extras.getInt("synctype") == 1) { + if ((ps.period == syncFreq) && (ps.extras.getInt("synctype") == 1)) { foundSameSyncCycle = true; } } - if (foundSameSyncCycle == false) { - final Bundle b = new Bundle(); + if (!foundSameSyncCycle) { + Bundle b = new Bundle(); b.putInt("synctype", 1); ContentResolver.removePeriodicSync(myAccountList[i], - _accountAuthority, b); + GeneralSettingsActivity._accountAuthority, b); ContentResolver.addPeriodicSync(myAccountList[i], - _accountAuthority, b, syncFreq * 60); + GeneralSettingsActivity._accountAuthority, b, syncFreq * 60); } } } - else { - // Unhandled option - } } } diff --git a/src/main/java/fr/unix_experience/owncloud_sms/activities/LoginActivity.java b/src/main/java/fr/unix_experience/owncloud_sms/activities/LoginActivity.java index bedc6ed..5d5cf72 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/activities/LoginActivity.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/activities/LoginActivity.java @@ -83,7 +83,7 @@ public class LoginActivity extends Activity { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { - if (id == R.id.oc_login || id == EditorInfo.IME_NULL) { + if ((id == R.id.oc_login) || (id == EditorInfo.IME_NULL)) { attemptLogin(); return true; } @@ -161,12 +161,14 @@ public class LoginActivity extends Activity { if (cancel) { // There was an error; don't attempt login and focus the first // form field with an error. - focusView.requestFocus(); - } else { + if (focusView != null) { + focusView.requestFocus(); + } + } else { // Show a progress spinner, and kick off a background task to // perform the user login attempt. showProgress(true); - String serverURL = new String(protocol + serverAddr); + String serverURL = protocol + serverAddr; mAuthTask = new UserLoginTask(serverURL, login, password); mAuthTask.execute((Void) null); } @@ -254,12 +256,12 @@ public class LoginActivity extends Activity { } @Override - protected void onPostExecute(final Boolean success) { + protected void onPostExecute(Boolean success) { mAuthTask = null; showProgress(false); if (success) { - String accountType = getIntent().getStringExtra(PARAM_AUTHTOKEN_TYPE); + String accountType = getIntent().getStringExtra(UserLoginTask.PARAM_AUTHTOKEN_TYPE); if (accountType == null) { accountType = getString(R.string.account_type); } @@ -268,7 +270,7 @@ public class LoginActivity extends Activity { String accountLabel = _login + "@" + _serverURI.getHost(); // We create the account - final Account account = new Account(accountLabel, accountType); + Account account = new Account(accountLabel, accountType); Bundle accountBundle = new Bundle(); accountBundle.putString("ocLogin", _login); accountBundle.putString("ocURI", _serverURI.toString()); @@ -293,7 +295,9 @@ public class LoginActivity extends Activity { getApplicationContext().startActivity(settingsIntent); } else { switch (_returnCode) { - case INVALID_ADDR: + case OK: + break; + case INVALID_ADDR: _serverView.setError(getString(R.string.error_invalid_server_address)); _serverView.requestFocus(); break; @@ -331,7 +335,6 @@ public class LoginActivity extends Activity { private final String _password; private LoginReturnCode _returnCode; - public static final String PARAM_AUTHTOKEN_TYPE = "auth.token"; - public static final String PARAM_CREATE = "create"; - } + public static final String PARAM_AUTHTOKEN_TYPE = "auth.token"; + } } diff --git a/src/main/java/fr/unix_experience/owncloud_sms/activities/MainActivity.java b/src/main/java/fr/unix_experience/owncloud_sms/activities/MainActivity.java index da69fc2..b2f25e5 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/activities/MainActivity.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/activities/MainActivity.java @@ -25,11 +25,6 @@ package fr.unix_experience.owncloud_sms.activities; * SUCH DAMAGE. */ -import java.util.List; -import java.util.Vector; - -import org.json.JSONArray; - import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; @@ -45,6 +40,12 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; + +import org.json.JSONArray; + +import java.util.List; +import java.util.Vector; + import fr.unix_experience.owncloud_sms.R; import fr.unix_experience.owncloud_sms.activities.remote_account.AccountListActivity; import fr.unix_experience.owncloud_sms.engine.ASyncSMSSync.SyncTask; @@ -69,14 +70,14 @@ public class MainActivity extends Activity { ViewPager mViewPager; @Override - protected void onCreate(final Bundle savedInstanceState) { + protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. - final List fragments = new Vector(); + List fragments = new Vector<>(); /* * Add the Main tabs here @@ -101,13 +102,13 @@ public class MainActivity extends Activity { private final List mFragments; - public MainPagerAdapter(final FragmentManager fragmentManager, final List fragments) { + public MainPagerAdapter(FragmentManager fragmentManager, List fragments) { super(fragmentManager); mFragments = fragments; } @Override - public Fragment getItem(final int position) { + public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class // below). @@ -126,53 +127,50 @@ public class MainActivity extends Activity { */ public static class StarterFragment extends Fragment { @Override - public View onCreateView(final LayoutInflater inflater, final ViewGroup container, - final Bundle savedInstanceState) { - final View rootView = inflater.inflate(R.layout.fragment_mainactivity_main, container, - false); - return rootView; + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + return inflater.inflate(R.layout.fragment_mainactivity_main, container, + false); } } public static class SecondTestFragment extends Fragment { @Override - public View onCreateView(final LayoutInflater inflater, final ViewGroup container, - final Bundle savedInstanceState) { - final View rootView = inflater.inflate(R.layout.fragment_mainactivity_gotosettings, container, - false); - return rootView; + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + return inflater.inflate(R.layout.fragment_mainactivity_gotosettings, container, + false); } } public static class ThanksAndRateFragment extends Fragment { @Override - public View onCreateView(final LayoutInflater inflater, final ViewGroup container, - final Bundle savedInstanceState) { - final View rootView = inflater.inflate(R.layout.fragment_mainactivity_thanks_note, container, - false); - return rootView; + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + return inflater.inflate(R.layout.fragment_mainactivity_thanks_note, container, + false); } } - public void openAppSettings(final View view) { + public void openAppSettings(View view) { startActivity(new Intent(this, GeneralSettingsActivity.class)); } - public void openAddAccount(final View view) { + public void openAddAccount(View view) { startActivity(new Intent(Settings.ACTION_ADD_ACCOUNT)); } - public void syncAllMessages(final View view) { - final Context ctx = getApplicationContext(); - final ConnectivityMonitor cMon = new ConnectivityMonitor(ctx); + public void syncAllMessages(View view) { + Context ctx = getApplicationContext(); + ConnectivityMonitor cMon = new ConnectivityMonitor(ctx); if (cMon.isValid()) { // Now fetch messages since last stored date - final JSONArray smsList = new SmsFetcher(ctx) + JSONArray smsList = new SmsFetcher(ctx) .bufferMessagesSinceDate((long) 0); if (smsList != null) { - final OCSMSNotificationManager nMgr = new OCSMSNotificationManager(ctx); + OCSMSNotificationManager nMgr = new OCSMSNotificationManager(ctx); nMgr.setSyncProcessMsg(); new SyncTask(getApplicationContext(), smsList).execute(); } @@ -182,16 +180,16 @@ public class MainActivity extends Activity { } } - public void selectRemoteAccount(final View view) { + public void selectRemoteAccount(View view) { startActivity(new Intent(this, AccountListActivity.class)); } - public void openGooglePlayStore(final View view) { + public void openGooglePlayStore(View view) { Intent intent; try { intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getPackageName())); - } catch (final android.content.ActivityNotFoundException anfe) { + } catch (android.content.ActivityNotFoundException anfe) { intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName())); } diff --git a/src/main/java/fr/unix_experience/owncloud_sms/activities/remote_account/AccountListActivity.java b/src/main/java/fr/unix_experience/owncloud_sms/activities/remote_account/AccountListActivity.java index aec1001..b06da75 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/activities/remote_account/AccountListActivity.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/activities/remote_account/AccountListActivity.java @@ -1,23 +1,25 @@ package fr.unix_experience.owncloud_sms.activities.remote_account; -import java.util.ArrayList; - import android.accounts.Account; import android.accounts.AccountManager; import android.app.ListActivity; import android.os.Bundle; + +import java.util.ArrayList; +import java.util.Collections; + import fr.nrz.androidlib.adapters.AndroidAccountAdapter; import fr.unix_experience.owncloud_sms.R; public class AccountListActivity extends ListActivity { - ArrayList listItems = new ArrayList(); + ArrayList listItems = new ArrayList<>(); AndroidAccountAdapter adapter; @Override - public void onCreate(final Bundle icicle) { + public void onCreate(Bundle icicle) { super.onCreate(icicle); - final AccountManager _accountMgr = AccountManager.get(getBaseContext()); + AccountManager _accountMgr = AccountManager.get(getBaseContext()); setContentView(R.layout.restore_activity_accountlist); adapter = new AndroidAccountAdapter(this, @@ -27,11 +29,9 @@ public class AccountListActivity extends ListActivity { R.id.accountname, ContactListActivity.class); setListAdapter(adapter); - final Account[] accountList = + Account[] accountList = _accountMgr.getAccountsByType(getString(R.string.account_type)); - for (final Account element : accountList) { - listItems.add(element); - } + Collections.addAll(listItems, accountList); adapter.notifyDataSetChanged(); } diff --git a/src/main/java/fr/unix_experience/owncloud_sms/activities/remote_account/ContactListActivity.java b/src/main/java/fr/unix_experience/owncloud_sms/activities/remote_account/ContactListActivity.java index bacb5c4..546356c 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/activities/remote_account/ContactListActivity.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/activities/remote_account/ContactListActivity.java @@ -30,19 +30,19 @@ public class ContactListActivity extends Activity implements ASyncContactLoad { ArrayList objects; @Override - protected void onCreate(final Bundle savedInstanceState) { + protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); assert getIntent().getExtras() != null; - final String accountName = getIntent().getExtras().getString("account"); + String accountName = getIntent().getExtras().getString("account"); // accountName cannot be null, devel error assert accountName != null; - _accountMgr = AccountManager.get(getBaseContext()); - final Account[] myAccountList = - _accountMgr.getAccountsByType(getString(R.string.account_type)); + ContactListActivity._accountMgr = AccountManager.get(getBaseContext()); + Account[] myAccountList = + ContactListActivity._accountMgr.getAccountsByType(getString(R.string.account_type)); // Init view objects = new ArrayList<>(); @@ -79,8 +79,8 @@ public class ContactListActivity extends Activity implements ASyncContactLoad { Integer smsCount = 0; // @TODO asynctask to load more datas - if (phoneList.size() > 0) { - String res = new String(""); + if (!phoneList.isEmpty()) { + String res = ""; for (String pn: phoneList) { res += "- " + pn + "\n"; } @@ -101,28 +101,34 @@ public class ContactListActivity extends Activity implements ASyncContactLoad { Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " = ?", new String[]{name}, null); - people.moveToFirst(); + if (people == null) { + return new Vector<>(); + } - Vector r = new Vector<>(); + people.moveToFirst(); + + Vector r = new Vector<>(); if (people.getCount() == 0) { return r; } String contactId = people.getString(people.getColumnIndex(ContactsContract.Contacts._ID)); - if (people.getString(people.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) - .equalsIgnoreCase("1")) { + if ("1".equalsIgnoreCase(people.getString(people.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)))) { Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{contactId}, null); - while (phones.moveToNext()) { + while ((phones != null) && phones.moveToNext()) { String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)) .replaceAll(" ", ""); r.add(phoneNumber); } - phones.close(); - } + + if (phones != null) { + phones.close(); + } + } return r; } }); diff --git a/src/main/java/fr/unix_experience/owncloud_sms/adapters/ContactListAdapter.java b/src/main/java/fr/unix_experience/owncloud_sms/adapters/ContactListAdapter.java index 829fc2e..5db2e9d 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/adapters/ContactListAdapter.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/adapters/ContactListAdapter.java @@ -1,50 +1,48 @@ package fr.unix_experience.owncloud_sms.adapters; -import java.util.ArrayList; - import android.app.Activity; import android.content.Context; -import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.TextView; +import java.util.ArrayList; + public class ContactListAdapter extends ArrayAdapter { private final ArrayList _objects; private static int _itemLayout; private static int _fieldId; - private Activity _activity; + private final Activity _activity; - public ContactListAdapter(final Context context, final int resource, - final ArrayList objects, final int itemLayout, - final int fieldId, final Activity activity) { + public ContactListAdapter(Context context, int resource, + ArrayList objects, int itemLayout, + int fieldId, Activity activity) { super(context, resource, objects); _objects = objects; - _itemLayout = itemLayout; - _fieldId = fieldId; + ContactListAdapter._itemLayout = itemLayout; + ContactListAdapter._fieldId = fieldId; _activity = activity; } @Override - public View getView(final int position, final View convertView, final ViewGroup parent) { + public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { - final LayoutInflater inflater = + LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); - v = inflater.inflate(_itemLayout, null); + v = inflater.inflate(ContactListAdapter._itemLayout, null); } - if (_objects.size() == 0) { + if (_objects.isEmpty()) { return null; } - final String element = _objects.get(position); + String element = _objects.get(position); if (element != null) { - final TextView label = (TextView) v.findViewById(_fieldId); + TextView label = (TextView) v.findViewById(ContactListAdapter._fieldId); if (label != null) { label.setText(element); } @@ -52,6 +50,4 @@ public class ContactListAdapter extends ArrayAdapter { return v; } - - private static final String TAG = ContactListAdapter.class.getSimpleName(); } diff --git a/src/main/java/fr/unix_experience/owncloud_sms/authenticators/OwnCloudAuthenticator.java b/src/main/java/fr/unix_experience/owncloud_sms/authenticators/OwnCloudAuthenticator.java index cc0bacf..abbf346 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/authenticators/OwnCloudAuthenticator.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/authenticators/OwnCloudAuthenticator.java @@ -17,16 +17,6 @@ package fr.unix_experience.owncloud_sms.authenticators; * along with this program. If not, see . */ -import java.io.IOException; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.http.HttpStatus; -import org.json.JSONObject; - -import com.owncloud.android.lib.common.OwnCloudClient; - -import fr.unix_experience.owncloud_sms.activities.LoginActivity; -import fr.unix_experience.owncloud_sms.enums.LoginReturnCode; import android.accounts.AbstractAccountAuthenticator; import android.accounts.Account; import android.accounts.AccountAuthenticatorResponse; @@ -37,6 +27,18 @@ import android.content.Intent; import android.os.Bundle; import android.util.Log; +import com.owncloud.android.lib.common.OwnCloudClient; + +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.http.HttpStatus; +import org.json.JSONObject; + +import java.io.IOException; + +import fr.unix_experience.owncloud_sms.activities.LoginActivity; +import fr.unix_experience.owncloud_sms.enums.LoginReturnCode; + public class OwnCloudAuthenticator extends AbstractAccountAuthenticator { // Simple constructor public OwnCloudAuthenticator(Context context) { @@ -56,8 +58,8 @@ public class OwnCloudAuthenticator extends AbstractAccountAuthenticator { String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { - final Bundle result; - final Intent intent; + Bundle result; + Intent intent; intent = new Intent(_context, LoginActivity.class); @@ -112,11 +114,11 @@ public class OwnCloudAuthenticator extends AbstractAccountAuthenticator { */ public LoginReturnCode testCredentials() { LoginReturnCode bRet = LoginReturnCode.OK; - GetMethod get = null; - int status = -1; + GetMethod get; + int status; try { - get = new GetMethod(_client.getBaseUri() + "/index.php/ocs/cloud/user?format=json"); + get = new GetMethod(_client.getBaseUri() + "/index.php/ocs/cloud/user?format=json"); } catch (IllegalArgumentException e) { return LoginReturnCode.INVALID_ADDR; } @@ -136,37 +138,32 @@ public class OwnCloudAuthenticator extends AbstractAccountAuthenticator { try { if(isSuccess(status)) { String response = get.getResponseBodyAsString(); - Log.d(TAG, "Successful response: " + response); + Log.d(OwnCloudAuthenticator.TAG, "Successful response: " + response); // Parse the response JSONObject respJSON = new JSONObject(response); - JSONObject respOCS = respJSON.getJSONObject(NODE_OCS); - JSONObject respData = respOCS.getJSONObject(NODE_DATA); - String id = respData.getString(NODE_ID); - String displayName = respData.getString(NODE_DISPLAY_NAME); - String email = respData.getString(NODE_EMAIL); + JSONObject respOCS = respJSON.getJSONObject(OwnCloudAuthenticator.NODE_OCS); + JSONObject respData = respOCS.getJSONObject(OwnCloudAuthenticator.NODE_DATA); + String id = respData.getString(OwnCloudAuthenticator.NODE_ID); + String displayName = respData.getString(OwnCloudAuthenticator.NODE_DISPLAY_NAME); + String email = respData.getString(OwnCloudAuthenticator.NODE_EMAIL); - Log.d(TAG, "*** Parsed user information: " + id + " - " + displayName + " - " + email); + Log.d(OwnCloudAuthenticator.TAG, "*** Parsed user information: " + id + " - " + displayName + " - " + email); } else { String response = get.getResponseBodyAsString(); - Log.e(TAG, "Failed response while getting user information "); + Log.e(OwnCloudAuthenticator.TAG, "Failed response while getting user information "); if (response != null) { - Log.e(TAG, "*** status code: " + status + " ; response message: " + response); + Log.e(OwnCloudAuthenticator.TAG, "*** status code: " + status + " ; response message: " + response); } else { - Log.e(TAG, "*** status code: " + status); - } - - if (status == 401) { - bRet = LoginReturnCode.INVALID_LOGIN; - } - else { - bRet = LoginReturnCode.UNKNOWN_ERROR; + Log.e(OwnCloudAuthenticator.TAG, "*** status code: " + status); } + + bRet = (status == 401) ? LoginReturnCode.INVALID_LOGIN : LoginReturnCode.UNKNOWN_ERROR; } } catch (Exception e) { - Log.e(TAG, "Exception while getting OC user information", e); + Log.e(OwnCloudAuthenticator.TAG, "Exception while getting OC user information", e); bRet = LoginReturnCode.UNKNOWN_ERROR; } finally { @@ -183,7 +180,7 @@ public class OwnCloudAuthenticator extends AbstractAccountAuthenticator { _client = oc; } - private Context _context; + private final Context _context; private OwnCloudClient _client; private static final String TAG = OwnCloudAuthenticator.class.getSimpleName(); diff --git a/src/main/java/fr/unix_experience/owncloud_sms/engine/ASyncContactLoad.java b/src/main/java/fr/unix_experience/owncloud_sms/engine/ASyncContactLoad.java index 70c3b52..017ab98 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/engine/ASyncContactLoad.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/engine/ASyncContactLoad.java @@ -28,20 +28,20 @@ public interface ASyncContactLoad { private static AccountManager _accountMgr = null; private static Account _account; private final Context _context; - private ContactListAdapter _adapter; - private ArrayList _objects; - private SwipeRefreshLayout _layout; - private ProgressBar _pg; - private Spinner _contactSpinner; + private final ContactListAdapter _adapter; + private final ArrayList _objects; + private final SwipeRefreshLayout _layout; + private final ProgressBar _pg; + private final Spinner _contactSpinner; - public ContactLoadTask(final Account account, final Context context, + public ContactLoadTask(Account account, Context context, ContactListAdapter adapter, ArrayList objects, SwipeRefreshLayout layout, ProgressBar pg, Spinner sp) { - if (_accountMgr == null) { - _accountMgr = AccountManager.get(context); + if (ContactLoadTask._accountMgr == null) { + ContactLoadTask._accountMgr = AccountManager.get(context); } - _account = account; + ContactLoadTask._account = account; _context = context; _adapter = adapter; _objects = objects; @@ -50,19 +50,19 @@ public interface ASyncContactLoad { _contactSpinner = sp; } @Override - protected Boolean doInBackground(final Void... params) { + protected Boolean doInBackground(Void... params) { // Create client - final String ocURI = _accountMgr.getUserData(_account, "ocURI"); + String ocURI = ContactLoadTask._accountMgr.getUserData(ContactLoadTask._account, "ocURI"); if (ocURI == null) { // @TODO: Handle the problem return false; } - final Uri serverURI = Uri.parse(ocURI); + Uri serverURI = Uri.parse(ocURI); - final OCSMSOwnCloudClient _client = new OCSMSOwnCloudClient(_context, - serverURI, _accountMgr.getUserData(_account, "ocLogin"), - _accountMgr.getPassword(_account)); + OCSMSOwnCloudClient _client = new OCSMSOwnCloudClient(_context, + serverURI, ContactLoadTask._accountMgr.getUserData(ContactLoadTask._account, "ocLogin"), + ContactLoadTask._accountMgr.getPassword(ContactLoadTask._account)); // Remove all objects, due to refreshing handling _objects.clear(); @@ -84,8 +84,8 @@ public interface ASyncContactLoad { ContentResolver cr = _context.getContentResolver(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); - if (cur.getCount() > 0) { - while (cur.moveToNext()) { + if (((cur != null) ? cur.getCount() : 0) > 0) { + while ((cur != null) && cur.moveToNext()) { String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID)); String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); if (Integer.parseInt(cur.getString( @@ -97,7 +97,7 @@ public interface ASyncContactLoad { null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null); - while (pCur.moveToNext()) { + while ((pCur != null) && pCur.moveToNext()) { String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)) .replaceAll(" ", ""); if (serverPhoneList.contains(phoneNo)) { @@ -107,13 +107,17 @@ public interface ASyncContactLoad { serverPhoneList.remove(phoneNo); } } - pCur.close(); - } + if (pCur != null) { + pCur.close(); + } + } } } - cur.close(); + if (cur != null) { + cur.close(); + } - for (String phone : serverPhoneList) { + for (String phone : serverPhoneList) { _objects.add(phone); } @@ -122,14 +126,14 @@ public interface ASyncContactLoad { } catch (JSONException e) { _objects.add(_context.getString(R.string.err_fetch_phonelist)); return false; - } catch (final OCSyncException e) { + } catch (OCSyncException e) { _objects.add(_context.getString(e.getErrorId())); return false; } return true; } - protected void onPostExecute(final Boolean success) { + protected void onPostExecute(Boolean success) { _adapter.notifyDataSetChanged(); _layout.setRefreshing(false); if (_pg != null) { @@ -142,5 +146,5 @@ public interface ASyncContactLoad { } } - static final String TAG = ASyncContactLoad.class.getSimpleName(); + String TAG = ASyncContactLoad.class.getSimpleName(); } diff --git a/src/main/java/fr/unix_experience/owncloud_sms/engine/ASyncSMSSync.java b/src/main/java/fr/unix_experience/owncloud_sms/engine/ASyncSMSSync.java index b432555..1c6cf65 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/engine/ASyncSMSSync.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/engine/ASyncSMSSync.java @@ -17,45 +17,46 @@ package fr.unix_experience.owncloud_sms.engine; * along with this program. If not, see . */ -import org.json.JSONArray; - import android.accounts.Account; import android.accounts.AccountManager; import android.content.Context; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; + +import org.json.JSONArray; + import fr.unix_experience.owncloud_sms.R; import fr.unix_experience.owncloud_sms.exceptions.OCSyncException; import fr.unix_experience.owncloud_sms.notifications.OCSMSNotificationManager; public interface ASyncSMSSync { class SyncTask extends AsyncTask { - public SyncTask(final Context context, final JSONArray smsList) { + public SyncTask(Context context, JSONArray smsList) { _context = context; _smsList = smsList; } @Override - protected Void doInBackground(final Void... params) { + protected Void doInBackground(Void... params) { // Get ownCloud SMS account list - final AccountManager _accountMgr = AccountManager.get(_context); - final Account[] myAccountList = _accountMgr.getAccountsByType(_context.getString(R.string.account_type)); + AccountManager _accountMgr = AccountManager.get(_context); + Account[] myAccountList = _accountMgr.getAccountsByType(_context.getString(R.string.account_type)); // Notify that we are syncing SMS - final OCSMSNotificationManager nMgr = new OCSMSNotificationManager(_context); - for (final Account element : myAccountList) { - final Uri serverURI = Uri.parse(_accountMgr.getUserData(element, "ocURI")); + OCSMSNotificationManager nMgr = new OCSMSNotificationManager(_context); + for (Account element : myAccountList) { + Uri serverURI = Uri.parse(_accountMgr.getUserData(element, "ocURI")); - final OCSMSOwnCloudClient _client = new OCSMSOwnCloudClient(_context, + OCSMSOwnCloudClient _client = new OCSMSOwnCloudClient(_context, serverURI, _accountMgr.getUserData(element, "ocLogin"), _accountMgr.getPassword(element)); try { _client.doPushRequest(_smsList); nMgr.dropSyncErrorMsg(); - } catch (final OCSyncException e) { - Log.e(TAG, _context.getString(e.getErrorId())); + } catch (OCSyncException e) { + Log.e(ASyncSMSSync.TAG, _context.getString(e.getErrorId())); nMgr.setSyncErrorMsg(_context.getString(e.getErrorId())); } } @@ -67,5 +68,5 @@ public interface ASyncSMSSync { private final JSONArray _smsList; } - static final String TAG = ASyncSMSSync.class.getSimpleName(); + String TAG = ASyncSMSSync.class.getSimpleName(); } diff --git a/src/main/java/fr/unix_experience/owncloud_sms/engine/ConnectivityMonitor.java b/src/main/java/fr/unix_experience/owncloud_sms/engine/ConnectivityMonitor.java index 3882457..5e40ad3 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/engine/ConnectivityMonitor.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/engine/ConnectivityMonitor.java @@ -23,7 +23,7 @@ import android.telephony.TelephonyManager; import fr.unix_experience.owncloud_sms.prefs.OCSMSSharedPrefs; public class ConnectivityMonitor { - public ConnectivityMonitor(final Context context) { + public ConnectivityMonitor(Context context) { _context = context; } @@ -33,17 +33,17 @@ public class ConnectivityMonitor { _cMgr = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); } - final android.net.NetworkInfo niWiFi = _cMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); - final android.net.NetworkInfo niMobile = _cMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); + android.net.NetworkInfo niWiFi = _cMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); + android.net.NetworkInfo niMobile = _cMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (niWiFi.isAvailable() || niMobile.isAvailable()) { // Load the connectivity manager to determine on which network we are connected - final NetworkInfo netInfo = _cMgr.getActiveNetworkInfo(); + NetworkInfo netInfo = _cMgr.getActiveNetworkInfo(); if (netInfo == null) { return false; } - final OCSMSSharedPrefs prefs = new OCSMSSharedPrefs(_context); + OCSMSSharedPrefs prefs = new OCSMSSharedPrefs(_context); // Check switch (netInfo.getType()) { diff --git a/src/main/java/fr/unix_experience/owncloud_sms/engine/OCSMSOwnCloudClient.java b/src/main/java/fr/unix_experience/owncloud_sms/engine/OCSMSOwnCloudClient.java index b65d830..6e71af0 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/engine/OCSMSOwnCloudClient.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/engine/OCSMSOwnCloudClient.java @@ -17,9 +17,13 @@ package fr.unix_experience.owncloud_sms.engine; * along with this program. If not, see . */ -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.ConnectException; +import android.content.Context; +import android.net.Uri; +import android.util.Log; + +import com.owncloud.android.lib.common.OwnCloudClient; +import com.owncloud.android.lib.common.OwnCloudClientFactory; +import com.owncloud.android.lib.common.OwnCloudCredentialsFactory; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; @@ -31,13 +35,9 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import android.content.Context; -import android.net.Uri; -import android.util.Log; - -import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.OwnCloudClientFactory; -import com.owncloud.android.lib.common.OwnCloudCredentialsFactory; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.ConnectException; import fr.unix_experience.owncloud_sms.R; import fr.unix_experience.owncloud_sms.enums.OCSyncErrorType; @@ -47,7 +47,7 @@ import fr.unix_experience.owncloud_sms.prefs.OCSMSSharedPrefs; @SuppressWarnings("deprecation") public class OCSMSOwnCloudClient { - public OCSMSOwnCloudClient(final Context context, final Uri serverURI, final String accountName, final String accountPassword) { + public OCSMSOwnCloudClient(Context context, Uri serverURI, String accountName, String accountPassword) { _context = context; _ocClient = OwnCloudClientFactory.createOwnCloudClient( @@ -62,8 +62,8 @@ public class OCSMSOwnCloudClient { } public Integer getServerAPIVersion() throws OCSyncException { - final GetMethod get = createGetVersionRequest(); - final JSONObject obj = doHttpRequest(get, true); + GetMethod get = createGetVersionRequest(); + JSONObject obj = doHttpRequest(get, true); if (obj == null) { // Return default version return 1; @@ -72,8 +72,8 @@ public class OCSMSOwnCloudClient { try { _serverAPIVersion = obj.getInt("version"); } - catch (final JSONException e) { - Log.e(TAG, "No version received from server, assuming version 1", e); + catch (JSONException e) { + Log.e(OCSMSOwnCloudClient.TAG, "No version received from server, assuming version 1", e); _serverAPIVersion = 1; } @@ -81,21 +81,21 @@ public class OCSMSOwnCloudClient { } public JSONArray getServerPhoneNumbers() throws OCSyncException { - final GetMethod get = createGetPhoneListRequest(); - final JSONObject obj = doHttpRequest(get, true); + GetMethod get = createGetPhoneListRequest(); + JSONObject obj = doHttpRequest(get, true); if (obj == null) { return null; } try { return obj.getJSONArray("phoneList"); - } catch (final JSONException e) { - Log.e(TAG, "No phonelist received from server, empty it", e); + } catch (JSONException e) { + Log.e(OCSMSOwnCloudClient.TAG, "No phonelist received from server, empty it", e); return null; } } - public void doPushRequest(final JSONArray smsList) throws OCSyncException { + public void doPushRequest(JSONArray smsList) throws OCSyncException { /** * If we need other API push, set it here */ @@ -110,8 +110,8 @@ public class OCSMSOwnCloudClient { Long lastMsgDate = (long) 0; if (smsList == null) { - final GetMethod get = createGetSmsIdListRequest(); - final JSONObject smsGetObj = doHttpRequest(get); + GetMethod get = createGetSmsIdListRequest(); + JSONObject smsGetObj = doHttpRequest(get); if (smsGetObj == null) { return; } @@ -120,34 +120,34 @@ public class OCSMSOwnCloudClient { JSONArray inboxSmsList = null, sentSmsList = null, draftsSmsList = null; try { smsBoxes = smsGetObj.getJSONObject("smslist"); - } catch (final JSONException e) { + } catch (JSONException e) { try { smsGetObj.getJSONArray("smslist"); - } catch (final JSONException e2) { - Log.e(TAG, "Invalid datas received from server (doPushRequest, get SMS list)", e); + } catch (JSONException e2) { + Log.e(OCSMSOwnCloudClient.TAG, "Invalid datas received from server (doPushRequest, get SMS list)", e); throw new OCSyncException(R.string.err_sync_get_smslist, OCSyncErrorType.PARSE); } } try { inboxSmsList = smsBoxes.getJSONArray("inbox"); - } catch (final JSONException e) { - Log.d(TAG, "No inbox Sms received from server (doPushRequest, get SMS list)"); + } catch (JSONException e) { + Log.d(OCSMSOwnCloudClient.TAG, "No inbox Sms received from server (doPushRequest, get SMS list)"); } try { sentSmsList = smsBoxes.getJSONArray("sent"); - } catch (final JSONException e) { - Log.d(TAG, "No sent Sms received from server (doPushRequest, get SMS list)"); + } catch (JSONException e) { + Log.d(OCSMSOwnCloudClient.TAG, "No sent Sms received from server (doPushRequest, get SMS list)"); } try { draftsSmsList = smsBoxes.getJSONArray("drafts"); - } catch (final JSONException e) { - Log.d(TAG, "No drafts Sms received from server (doPushRequest, get SMS list)"); + } catch (JSONException e) { + Log.d(OCSMSOwnCloudClient.TAG, "No drafts Sms received from server (doPushRequest, get SMS list)"); } - final SmsFetcher fetcher = new SmsFetcher(_context); + SmsFetcher fetcher = new SmsFetcher(_context); fetcher.setExistingInboxMessages(inboxSmsList); fetcher.setExistingSentMessages(sentSmsList); fetcher.setExistingDraftsMessages(draftsSmsList); @@ -159,19 +159,19 @@ public class OCSMSOwnCloudClient { } if (smsList.length() == 0) { - Log.d(TAG, "No new SMS to sync, sync done"); + Log.d(OCSMSOwnCloudClient.TAG, "No new SMS to sync, sync done"); return; } - final PostMethod post = createPushRequest(smsList); + PostMethod post = createPushRequest(smsList); if (post == null) { - Log.e(TAG,"Push request for POST is null"); + Log.e(OCSMSOwnCloudClient.TAG,"Push request for POST is null"); throw new OCSyncException(R.string.err_sync_craft_http_request, OCSyncErrorType.IO); } - final JSONObject obj = doHttpRequest(post); + JSONObject obj = doHttpRequest(post); if (obj == null) { - Log.e(TAG,"Request failed. It doesn't return a valid JSON Object"); + Log.e(OCSMSOwnCloudClient.TAG,"Request failed. It doesn't return a valid JSON Object"); throw new OCSyncException(R.string.err_sync_push_request, OCSyncErrorType.IO); } @@ -181,87 +181,81 @@ public class OCSMSOwnCloudClient { pushStatus = obj.getBoolean("status"); pushMessage = obj.getString("msg"); } - catch (final JSONException e) { - Log.e(TAG, "Invalid datas received from server", e); + catch (JSONException e) { + Log.e(OCSMSOwnCloudClient.TAG, "Invalid datas received from server", e); throw new OCSyncException(R.string.err_sync_push_request_resp, OCSyncErrorType.PARSE); } // Push was OK, we can save the lastMessageDate which was saved to server (new OCSMSSharedPrefs(_context)).setLastMessageDate(lastMsgDate); - Log.d(TAG, "SMS Push request said: status " + pushStatus + " - " + pushMessage); + Log.d(OCSMSOwnCloudClient.TAG, "SMS Push request said: status " + pushStatus + " - " + pushMessage); } public GetMethod createGetVersionRequest() { - return createGetRequest(OC_GET_VERSION); + return createGetRequest(OCSMSOwnCloudClient.OC_GET_VERSION); } public GetMethod createGetPhoneListRequest() { - return createGetRequest(OC_GET_PHONELIST); + return createGetRequest(OCSMSOwnCloudClient.OC_GET_PHONELIST); } public GetMethod createGetSmsIdListRequest() { - return createGetRequest(OC_GET_ALL_SMS_IDS); + return createGetRequest(OCSMSOwnCloudClient.OC_GET_ALL_SMS_IDS); } public GetMethod createGetSmsIdListWithStateRequest() { - return createGetRequest(OC_GET_ALL_SMS_IDS_WITH_STATUS); + return createGetRequest(OCSMSOwnCloudClient.OC_GET_ALL_SMS_IDS_WITH_STATUS); } public GetMethod createGetLastSmsTimestampRequest() { - return createGetRequest(OC_GET_LAST_MSG_TIMESTAMP); + return createGetRequest(OCSMSOwnCloudClient.OC_GET_LAST_MSG_TIMESTAMP); } - private GetMethod createGetRequest(final String oc_call) { - final GetMethod get = new GetMethod(_ocClient.getBaseUri() + oc_call); + private GetMethod createGetRequest(String oc_call) { + GetMethod get = new GetMethod(_ocClient.getBaseUri() + oc_call); get.addRequestHeader("OCS-APIREQUEST", "true"); return get; } - public PostMethod createPushRequest() throws OCSyncException { - final SmsFetcher fetcher = new SmsFetcher(_context); - final JSONArray smsList = fetcher.fetchAllMessages(); - return createPushRequest(smsList); - } - - public PostMethod createPushRequest(final JSONArray smsList) throws OCSyncException { - final JSONObject obj = createPushJSONObject(smsList); + public PostMethod createPushRequest(JSONArray smsList) throws OCSyncException { + JSONObject obj = createPushJSONObject(smsList); if (obj == null) { return null; } - final StringRequestEntity ent = createJSONRequestEntity(obj); + StringRequestEntity ent = createJSONRequestEntity(obj); if (ent == null) { return null; } - final PostMethod post = new PostMethod(_ocClient.getBaseUri() + OC_PUSH_ROUTE); + PostMethod post = new PostMethod(_ocClient.getBaseUri() + OCSMSOwnCloudClient.OC_PUSH_ROUTE); post.addRequestHeader("OCS-APIREQUEST", "true"); post.setRequestEntity(ent); return post; } - private JSONObject createPushJSONObject(final JSONArray smsList) throws OCSyncException { + private JSONObject createPushJSONObject(JSONArray smsList) throws OCSyncException { if (smsList == null) { - Log.e(TAG,"NULL SMS List"); + Log.e(OCSMSOwnCloudClient.TAG,"NULL SMS List"); throw new OCSyncException(R.string.err_sync_create_json_null_smslist, OCSyncErrorType.IO); } - final JSONObject reqJSON = new JSONObject(); + JSONObject reqJSON = new JSONObject(); try { reqJSON.put("smsDatas", smsList); - reqJSON.put("smsCount", smsList == null ? 0 : smsList.length()); - } catch (final JSONException e) { - Log.e(TAG,"JSON Exception when creating JSON request object"); + reqJSON.put("smsCount", smsList.length()); + } catch (JSONException e) { + Log.e(OCSMSOwnCloudClient.TAG,"JSON Exception when creating JSON request object"); throw new OCSyncException(R.string.err_sync_create_json_put_smslist, OCSyncErrorType.PARSE); } return reqJSON; } - private StringRequestEntity createJSONRequestEntity(final JSONObject obj) throws OCSyncException { + private StringRequestEntity createJSONRequestEntity(JSONObject obj) throws OCSyncException { StringRequestEntity requestEntity; try { requestEntity = new StringRequestEntity( @@ -269,32 +263,32 @@ public class OCSMSOwnCloudClient { "application/json", "UTF-8"); - } catch (final UnsupportedEncodingException e) { - Log.e(TAG,"Unsupported encoding when generating request"); + } catch (UnsupportedEncodingException e) { + Log.e(OCSMSOwnCloudClient.TAG,"Unsupported encoding when generating request"); throw new OCSyncException(R.string.err_sync_create_json_request_encoding, OCSyncErrorType.PARSE); } return requestEntity; } - private JSONObject doHttpRequest(final HttpMethod req) throws OCSyncException { + private JSONObject doHttpRequest(HttpMethod req) throws OCSyncException { return doHttpRequest(req, false); } // skipError permit to skip invalid JSON datas - private JSONObject doHttpRequest(final HttpMethod req, final Boolean skipError) throws OCSyncException { - JSONObject respJSON = null; + private JSONObject doHttpRequest(HttpMethod req, Boolean skipError) throws OCSyncException { + JSONObject respJSON; int status = 0; // We try maximumHttpReqTries because sometimes network is slow or unstable int tryNb = 0; - final ConnectivityMonitor cMon = new ConnectivityMonitor(_context); + ConnectivityMonitor cMon = new ConnectivityMonitor(_context); - while (tryNb < maximumHttpReqTries) { + while (tryNb < OCSMSOwnCloudClient.maximumHttpReqTries) { tryNb++; if (!cMon.isValid()) { - if (tryNb == maximumHttpReqTries) { + if (tryNb == OCSMSOwnCloudClient.maximumHttpReqTries) { req.releaseConnection(); throw new OCSyncException(R.string.err_sync_no_connection_available, OCSyncErrorType.IO); } @@ -304,31 +298,31 @@ public class OCSMSOwnCloudClient { try { status = _ocClient.executeMethod(req); - Log.d(TAG, "HTTP Request done at try " + tryNb); + Log.d(OCSMSOwnCloudClient.TAG, "HTTP Request done at try " + tryNb); // Force loop exit - tryNb = maximumHttpReqTries; - } catch (final ConnectException e) { - Log.e(TAG, "Unable to perform a connection to ownCloud instance", e); + tryNb = OCSMSOwnCloudClient.maximumHttpReqTries; + } catch (ConnectException e) { + Log.e(OCSMSOwnCloudClient.TAG, "Unable to perform a connection to ownCloud instance", e); // If it's the last try - if (tryNb == maximumHttpReqTries) { + if (tryNb == OCSMSOwnCloudClient.maximumHttpReqTries) { req.releaseConnection(); throw new OCSyncException(R.string.err_sync_http_request_connect, OCSyncErrorType.IO); } - } catch (final HttpException e) { - Log.e(TAG, "Unable to perform a connection to ownCloud instance", e); + } catch (HttpException e) { + Log.e(OCSMSOwnCloudClient.TAG, "Unable to perform a connection to ownCloud instance", e); // If it's the last try - if (tryNb == maximumHttpReqTries) { + if (tryNb == OCSMSOwnCloudClient.maximumHttpReqTries) { req.releaseConnection(); throw new OCSyncException(R.string.err_sync_http_request_httpexception, OCSyncErrorType.IO); } - } catch (final IOException e) { - Log.e(TAG, "Unable to perform a connection to ownCloud instance", e); + } catch (IOException e) { + Log.e(OCSMSOwnCloudClient.TAG, "Unable to perform a connection to ownCloud instance", e); // If it's the last try - if (tryNb == maximumHttpReqTries) { + if (tryNb == OCSMSOwnCloudClient.maximumHttpReqTries) { req.releaseConnection(); throw new OCSyncException(R.string.err_sync_http_request_ioexception, OCSyncErrorType.IO); } @@ -336,11 +330,11 @@ public class OCSMSOwnCloudClient { } if(status == HttpStatus.SC_OK) { - String response = null; + String response; try { response = req.getResponseBodyAsString(); - } catch (final IOException e) { - Log.e(TAG, "Unable to parse server response", e); + } catch (IOException e) { + Log.e(OCSMSOwnCloudClient.TAG, "Unable to parse server response", e); throw new OCSyncException(R.string.err_sync_http_request_resp, OCSyncErrorType.IO); } //Log.d(TAG, "Successful response: " + response); @@ -348,15 +342,15 @@ public class OCSMSOwnCloudClient { // Parse the response try { respJSON = new JSONObject(response); - } catch (final JSONException e) { - if (skipError == false) { + } catch (JSONException e) { + if (!skipError) { if (response.contains("ownCloud") && response.contains("DOCTYPE")) { - Log.e(TAG, "OcSMS app not enabled or ownCloud upgrade is required"); + Log.e(OCSMSOwnCloudClient.TAG, "OcSMS app not enabled or ownCloud upgrade is required"); throw new OCSyncException(R.string.err_sync_ocsms_not_installed_or_oc_upgrade_required, OCSyncErrorType.SERVER_ERROR); } else { - Log.e(TAG, "Unable to parse server response", e); + Log.e(OCSMSOwnCloudClient.TAG, "Unable to parse server response", e); throw new OCSyncException(R.string.err_sync_http_request_parse_resp, OCSyncErrorType.PARSE); } } @@ -368,40 +362,38 @@ public class OCSMSOwnCloudClient { throw new OCSyncException(R.string.err_sync_auth_failed, OCSyncErrorType.AUTH); } else { // Unk error - String response = null; + String response; try { response = req.getResponseBodyAsString(); - } catch (final IOException e) { - Log.e(TAG, "Unable to parse server response", e); + } catch (IOException e) { + Log.e(OCSMSOwnCloudClient.TAG, "Unable to parse server response", e); throw new OCSyncException(R.string.err_sync_http_request_resp, OCSyncErrorType.PARSE); } - Log.e(TAG, "Server set unhandled HTTP return code " + status); + Log.e(OCSMSOwnCloudClient.TAG, "Server set unhandled HTTP return code " + status); if (response != null) { - Log.e(TAG, "Status code: " + status + ". Response message: " + response); + Log.e(OCSMSOwnCloudClient.TAG, "Status code: " + status + ". Response message: " + response); } else { - Log.e(TAG, "Status code: " + status); + Log.e(OCSMSOwnCloudClient.TAG, "Status code: " + status); } throw new OCSyncException(R.string.err_sync_http_request_returncode_unhandled, OCSyncErrorType.SERVER_ERROR); } return respJSON; } - public OwnCloudClient getOCClient() { return _ocClient; } - - private static int maximumHttpReqTries = 3; + private static final int maximumHttpReqTries = 3; private final OwnCloudClient _ocClient; private final Context _context; private Integer _serverAPIVersion; - private static String OC_GET_VERSION = "/index.php/apps/ocsms/get/apiversion?format=json"; - private static String OC_GET_ALL_SMS_IDS = "/index.php/apps/ocsms/get/smsidlist?format=json"; - private static String OC_GET_ALL_SMS_IDS_WITH_STATUS = "/index.php/apps/ocsms/get/smsidstate?format=json"; - private static String OC_GET_LAST_MSG_TIMESTAMP = "/index.php/apps/ocsms/get/lastmsgtime?format=json"; - private static String OC_PUSH_ROUTE = "/index.php/apps/ocsms/push?format=json"; - private static String OC_GET_PHONELIST = "/index.php/apps/ocsms/get/phones/numberlist?format=json"; + private static final String OC_GET_VERSION = "/index.php/apps/ocsms/get/apiversion?format=json"; + private static final String OC_GET_ALL_SMS_IDS = "/index.php/apps/ocsms/get/smsidlist?format=json"; + private static final String OC_GET_ALL_SMS_IDS_WITH_STATUS = "/index.php/apps/ocsms/get/smsidstate?format=json"; + private static final String OC_GET_LAST_MSG_TIMESTAMP = "/index.php/apps/ocsms/get/lastmsgtime?format=json"; + private static final String OC_PUSH_ROUTE = "/index.php/apps/ocsms/push?format=json"; + private static final String OC_GET_PHONELIST = "/index.php/apps/ocsms/get/phones/numberlist?format=json"; private static final String TAG = OCSMSOwnCloudClient.class.getSimpleName(); diff --git a/src/main/java/fr/unix_experience/owncloud_sms/engine/SmsFetcher.java b/src/main/java/fr/unix_experience/owncloud_sms/engine/SmsFetcher.java index f8823e6..1df7bd1 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/engine/SmsFetcher.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/engine/SmsFetcher.java @@ -17,15 +17,16 @@ package fr.unix_experience.owncloud_sms.engine; * along with this program. If not, see . */ +import android.content.Context; +import android.database.Cursor; +import android.util.Log; + import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import fr.unix_experience.owncloud_sms.enums.MailboxID; import fr.unix_experience.owncloud_sms.providers.SmsDataProvider; -import android.content.Context; -import android.database.Cursor; -import android.util.Log; public class SmsFetcher { public SmsFetcher(Context ct) { @@ -48,13 +49,13 @@ public class SmsFetcher { private void bufferMailboxMessages(MailboxID mbID) { String mbURI = mapMailboxIDToURI(mbID); - if (_context == null || mbURI == null) { + if ((_context == null) || (mbURI == null)) { return; } - if (mbID != MailboxID.INBOX && mbID != MailboxID.SENT && - mbID != MailboxID.DRAFTS) { - Log.e(TAG,"Unhandled MailboxID " + mbID.ordinal()); + if ((mbID != MailboxID.INBOX) && (mbID != MailboxID.SENT) && + (mbID != MailboxID.DRAFTS)) { + Log.e(SmsFetcher.TAG,"Unhandled MailboxID " + mbID.ordinal()); return; } @@ -64,7 +65,7 @@ public class SmsFetcher { Cursor c = new SmsDataProvider(_context).queryNonExistingMessages(mbURI, existingIDs); // Reading mailbox - if (c != null && c.getCount() > 0) { + if ((c != null) && (c.getCount() > 0)) { c.moveToFirst(); do { JSONObject entry = new JSONObject(); @@ -82,12 +83,12 @@ public class SmsFetcher { // Seen and read must be pseudo boolean case "read": case "seen": - entry.put(colName, c.getInt(idx) > 0 ? "true" : "false"); + entry.put(colName, (c.getInt(idx) > 0) ? "true" : "false"); break; default: // Special case for date, we need to record last without searching - if (colName.equals("date")) { - final Long tmpDate = c.getLong(idx); + if ("date".equals(colName)) { + Long tmpDate = c.getLong(idx); if (tmpDate > _lastMsgDate) { _lastMsgDate = tmpDate; } @@ -103,13 +104,13 @@ public class SmsFetcher { _jsonDataDump.put(entry); } catch (JSONException e) { - Log.e(TAG, "JSON Exception when reading SMS Mailbox", e); + Log.e(SmsFetcher.TAG, "JSON Exception when reading SMS Mailbox", e); c.close(); } } while(c.moveToNext()); - Log.d(TAG, c.getCount() + " messages read from " + mbURI); + Log.d(SmsFetcher.TAG, c.getCount() + " messages read from " + mbURI); c.close(); } @@ -119,7 +120,7 @@ public class SmsFetcher { public JSONArray getLastMessage(MailboxID mbID) { String mbURI = mapMailboxIDToURI(mbID); - if (_context == null || mbURI == null) { + if ((_context == null) || (mbURI == null)) { return null; } @@ -146,7 +147,7 @@ public class SmsFetcher { // Seen and read must be pseudo boolean case "read": case "seen": - entry.put(colName, c.getInt(idx) > 0 ? "true" : "false"); + entry.put(colName, (c.getInt(idx) > 0) ? "true" : "false"); break; case "type": mboxId = c.getInt(idx); @@ -167,7 +168,7 @@ public class SmsFetcher { results.put(entry); } catch (JSONException e) { - Log.e(TAG, "JSON Exception when reading SMS Mailbox", e); + Log.e(SmsFetcher.TAG, "JSON Exception when reading SMS Mailbox", e); c.close(); } @@ -189,14 +190,14 @@ public class SmsFetcher { public void bufferMessagesSinceDate(MailboxID mbID, Long sinceDate) { String mbURI = mapMailboxIDToURI(mbID); - if (_context == null || mbURI == null) { + if ((_context == null) || (mbURI == null)) { return; } Cursor c = new SmsDataProvider(_context).query(mbURI, "date > ?", new String[] { sinceDate.toString() }); // Reading mailbox - if (c != null && c.getCount() > 0) { + if ((c != null) && (c.getCount() > 0)) { c.moveToFirst(); do { JSONObject entry = new JSONObject(); @@ -214,12 +215,12 @@ public class SmsFetcher { // Seen and read must be pseudo boolean case "read": case "seen": - entry.put(colName, c.getInt(idx) > 0 ? "true" : "false"); + entry.put(colName, (c.getInt(idx) > 0) ? "true" : "false"); break; default: // Special case for date, we need to record last without searching - if (colName.equals("date")) { - final Long tmpDate = c.getLong(idx); + if ("date".equals(colName)) { + Long tmpDate = c.getLong(idx); if (tmpDate > _lastMsgDate) { _lastMsgDate = tmpDate; } @@ -235,13 +236,13 @@ public class SmsFetcher { _jsonDataDump.put(entry); } catch (JSONException e) { - Log.e(TAG, "JSON Exception when reading SMS Mailbox", e); + Log.e(SmsFetcher.TAG, "JSON Exception when reading SMS Mailbox", e); c.close(); } } while(c.moveToNext()); - Log.d(TAG, c.getCount() + " messages read from " + mbURI); + Log.d(SmsFetcher.TAG, c.getCount() + " messages read from " + mbURI); c.close(); } @@ -309,7 +310,7 @@ public class SmsFetcher { return _lastMsgDate; } - private Context _context; + private final Context _context; private JSONArray _jsonDataDump; private JSONArray _existingInboxMessages; private JSONArray _existingSentMessages; diff --git a/src/main/java/fr/unix_experience/owncloud_sms/notifications/OCSMSNotificationManager.java b/src/main/java/fr/unix_experience/owncloud_sms/notifications/OCSMSNotificationManager.java index 1d42159..4b21595 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/notifications/OCSMSNotificationManager.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/notifications/OCSMSNotificationManager.java @@ -24,7 +24,7 @@ import fr.unix_experience.owncloud_sms.enums.OCSMSNotificationType; public class OCSMSNotificationManager { - public OCSMSNotificationManager(final Context context) { + public OCSMSNotificationManager(Context context) { _context = context; _notification = new NrzNotification(_context, R.drawable.ic_stat_ocsms); } @@ -40,7 +40,7 @@ public class OCSMSNotificationManager { _notification.cancelNotify(OCSMSNotificationType.SYNC.ordinal()); } - public void setSyncErrorMsg(final String errMsg) { + public void setSyncErrorMsg(String errMsg) { createNotificationIfPossible(OCSMSNotificationType.SYNC_FAILED, _context.getString(R.string.sync_title), _context.getString(R.string.fatal_error) + "\n" + errMsg @@ -51,13 +51,13 @@ public class OCSMSNotificationManager { _notification.cancelNotify(OCSMSNotificationType.SYNC_FAILED.ordinal()); } - public void setDebugMsg(final String errMsg) { + public void setDebugMsg(String errMsg) { createNotificationIfPossible(OCSMSNotificationType.DEBUG, "DEBUG", errMsg ); } - private void createNotificationIfPossible(final OCSMSNotificationType nType, final String nTitle, final String nMsg) { + private void createNotificationIfPossible(OCSMSNotificationType nType, String nTitle, String nMsg) { _notification.createNotify(nType.ordinal(), nTitle, nMsg); } diff --git a/src/main/java/fr/unix_experience/owncloud_sms/observers/SmsObserver.java b/src/main/java/fr/unix_experience/owncloud_sms/observers/SmsObserver.java index c547377..882dea8 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/observers/SmsObserver.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/observers/SmsObserver.java @@ -17,6 +17,13 @@ package fr.unix_experience.owncloud_sms.observers; * along with this program. If not, see . */ +import android.accounts.Account; +import android.accounts.AccountManager; +import android.content.Context; +import android.database.ContentObserver; +import android.os.Handler; +import android.util.Log; + import org.json.JSONArray; import fr.unix_experience.owncloud_sms.R; @@ -26,13 +33,6 @@ import fr.unix_experience.owncloud_sms.engine.OCSMSOwnCloudClient; import fr.unix_experience.owncloud_sms.engine.SmsFetcher; import fr.unix_experience.owncloud_sms.enums.MailboxID; -import android.accounts.Account; -import android.accounts.AccountManager; -import android.content.Context; -import android.database.ContentObserver; -import android.os.Handler; -import android.util.Log; - public class SmsObserver extends ContentObserver implements ASyncSMSSync { public SmsObserver(Handler handler) { @@ -46,10 +46,10 @@ public class SmsObserver extends ContentObserver implements ASyncSMSSync { public void onChange(boolean selfChange) { super.onChange(selfChange); - Log.d(TAG, "onChange SmsObserver"); + Log.d(SmsObserver.TAG, "onChange SmsObserver"); // No account, abort - final Account[] myAccountList = AccountManager.get(_context). + Account[] myAccountList = AccountManager.get(_context). getAccountsByType(_context.getString(R.string.account_type)); if (myAccountList.length == 0) { return; @@ -61,7 +61,7 @@ public class SmsObserver extends ContentObserver implements ASyncSMSSync { ConnectivityMonitor cMon = new ConnectivityMonitor(_context); // Synchronize if network is valid and there are SMS - if (cMon.isValid() && smsList != null) { + if (cMon.isValid() && (smsList != null)) { new SyncTask(_context, smsList).execute(); } } diff --git a/src/main/java/fr/unix_experience/owncloud_sms/prefs/OCSMSSharedPrefs.java b/src/main/java/fr/unix_experience/owncloud_sms/prefs/OCSMSSharedPrefs.java index 2c6df03..2d76ab9 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/prefs/OCSMSSharedPrefs.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/prefs/OCSMSSharedPrefs.java @@ -25,14 +25,14 @@ import fr.unix_experience.owncloud_sms.defines.DefaultPrefs; public class OCSMSSharedPrefs extends SharedPrefs { - public OCSMSSharedPrefs(final Context context) { + public OCSMSSharedPrefs(Context context) { super(context, R.string.shared_preference_file); } - public void setLastMessageDate(final Long msgDate) { - final SharedPreferences.Editor editor = _sPrefs.edit(); + public void setLastMessageDate(Long msgDate) { + SharedPreferences.Editor editor = _sPrefs.edit(); editor.putLong(_context.getString(R.string.pref_lastmsgdate), msgDate); - editor.commit(); + editor.apply(); } public Long getLastMessageDate() { diff --git a/src/main/java/fr/unix_experience/owncloud_sms/providers/SmsDataProvider.java b/src/main/java/fr/unix_experience/owncloud_sms/providers/SmsDataProvider.java index 2a7faaa..f5eccd0 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/providers/SmsDataProvider.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/providers/SmsDataProvider.java @@ -22,11 +22,12 @@ import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; +import android.support.annotation.NonNull; public class SmsDataProvider extends ContentProvider { public SmsDataProvider () {} - public SmsDataProvider (final Context ct) { + public SmsDataProvider (Context ct) { super(); _context = ct; } @@ -36,29 +37,29 @@ public class SmsDataProvider extends ContentProvider { return false; } - public Cursor query(final String mailBox) { + public Cursor query(String mailBox) { return query(Uri.parse(mailBox), new String[] { "read", "date", "address", "seen", "body", "_id", "type", }, null, null, null ); } - public Cursor query(final String mailBox, final String selection) { + public Cursor query(String mailBox, String selection) { return query(Uri.parse(mailBox), new String[] { "read", "date", "address", "seen", "body", "_id", "type", }, selection, null, null ); } - public Cursor queryNonExistingMessages(final String mailBox, final String existingIds) { - if (existingIds.length() > 0) { + public Cursor queryNonExistingMessages(String mailBox, String existingIds) { + if (!existingIds.isEmpty()) { return query(mailBox, "_id NOT IN (" + existingIds + ")"); } return query(mailBox); } - public Cursor query(final String mailBox, final String selection, final String[] selectionArgs) { + public Cursor query(String mailBox, String selection, String[] selectionArgs) { return query(Uri.parse(mailBox), new String[] { "read", "date", "address", "seen", "body", "_id", "type", }, selection, selectionArgs, null @@ -66,9 +67,9 @@ public class SmsDataProvider extends ContentProvider { } @Override - public Cursor query(final Uri uri, final String[] projection, final String selection, - final String[] selectionArgs, final String sortOrder) { - if (_context != null && _context.getContentResolver() != null) { + public Cursor query(@NonNull Uri uri, String[] projection, String selection, + String[] selectionArgs, String sortOrder) { + if ((_context != null) && (_context.getContentResolver() != null)) { return _context.getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder); } @@ -76,26 +77,26 @@ public class SmsDataProvider extends ContentProvider { } @Override - public String getType(final Uri uri) { + public String getType(@NonNull Uri uri) { // TODO Auto-generated method stub return null; } @Override - public Uri insert(final Uri uri, final ContentValues values) { + public Uri insert(@NonNull Uri uri, ContentValues values) { // TODO Auto-generated method stub return null; } @Override - public int delete(final Uri uri, final String selection, final String[] selectionArgs) { + public int delete(@NonNull Uri uri, String selection, String[] selectionArgs) { // TODO Auto-generated method stub return 0; } @Override - public int update(final Uri uri, final ContentValues values, final String selection, - final String[] selectionArgs) { + public int update(@NonNull Uri uri, ContentValues values, String selection, + String[] selectionArgs) { // TODO Auto-generated method stub return 0; } diff --git a/src/main/java/fr/unix_experience/owncloud_sms/sync_adapters/SmsSyncService.java b/src/main/java/fr/unix_experience/owncloud_sms/sync_adapters/SmsSyncService.java index 002348a..82d2e23 100644 --- a/src/main/java/fr/unix_experience/owncloud_sms/sync_adapters/SmsSyncService.java +++ b/src/main/java/fr/unix_experience/owncloud_sms/sync_adapters/SmsSyncService.java @@ -44,9 +44,9 @@ public class SmsSyncService extends Service { * Set the sync adapter as syncable * Disallow parallel syncs */ - synchronized (sSyncAdapterLock) { - if (_adapter == null) { - _adapter = new SmsSyncAdapter(getApplicationContext(), true); + synchronized (SmsSyncService.sSyncAdapterLock) { + if (SmsSyncService._adapter == null) { + SmsSyncService._adapter = new SmsSyncAdapter(getApplicationContext(), true); } } } @@ -63,6 +63,6 @@ public class SmsSyncService extends Service { * in the base class code when the SyncAdapter * constructors call super() */ - return _adapter.getSyncAdapterBinder(); + return SmsSyncService._adapter.getSyncAdapterBinder(); } }