diff --git a/android-core/build.gradle b/android-core/build.gradle index e92819e43..2cbdfb89c 100644 --- a/android-core/build.gradle +++ b/android-core/build.gradle @@ -137,7 +137,7 @@ dependencies { api 'androidx.localbroadcastmanager:localbroadcastmanager:1.1.0' - lintPublish project( path: ':tooling:custom-lint-rules', configuration: 'lintBuild') + lintPublish project(path: ':tooling:custom-lint-rules', configuration: 'lintBuild') //the junit tests seem to explicitly need this dependency while //working in Android studio, but from the command line it's not necessary @@ -168,5 +168,6 @@ configurations { } } -boolean useOrchestrator() { return project.hasProperty('orchestrator') ? project.property('orchestrator') : false +boolean useOrchestrator() { + return project.hasProperty('orchestrator') ? project.property('orchestrator') : false } \ No newline at end of file diff --git a/android-core/lint-baseline.xml b/android-core/lint-baseline.xml index 35b4a62cc..d08ba51a1 100644 --- a/android-core/lint-baseline.xml +++ b/android-core/lint-baseline.xml @@ -2,20 +2,20 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/android-core/src/androidTest/AndroidManifest.xml b/android-core/src/androidTest/AndroidManifest.xml index 8300569a6..b3bfd6cba 100644 --- a/android-core/src/androidTest/AndroidManifest.xml +++ b/android-core/src/androidTest/AndroidManifest.xml @@ -1,25 +1,30 @@ - + - - - - - + + + + + - + - + - + diff --git a/android-core/src/androidTest/java/com/mparticle/internal/MParticleJSInterfaceITest.java b/android-core/src/androidTest/java/com/mparticle/internal/MParticleJSInterfaceITest.java index f64abc36d..3fb2094bd 100644 --- a/android-core/src/androidTest/java/com/mparticle/internal/MParticleJSInterfaceITest.java +++ b/android-core/src/androidTest/java/com/mparticle/internal/MParticleJSInterfaceITest.java @@ -216,12 +216,12 @@ public void run() { @Test public void testSetUserAttribute() throws Exception { - final String key = mRandomUtils.getAlphaNumericString(25); - final String value = mRandomUtils.getAlphaNumericString(25); + final String key = mRandomUtils.getAlphaNumericString(25); + final String value = mRandomUtils.getAlphaNumericString(25); String testJavascript = String.format("mParticle.Identity.getCurrentUser().setUserAttribute(\"%s\", \"%s\");\n", key, value); final MutableBoolean called = new MutableBoolean(false); final CountDownLatch latch = new MPLatch(1); - runJavascriptTest(testJavascript, new MParticleJSInterface(){ + runJavascriptTest(testJavascript, new MParticleJSInterface() { @Override @JavascriptInterface public void setUserAttribute(String json) { @@ -232,8 +232,7 @@ public void setUserAttribute(String json) { assertEquals(value, jsonObject.getString("value")); called.value = true; latch.countDown(); - } - catch (JSONException jse) { + } catch (JSONException jse) { jse.printStackTrace(); } @@ -249,7 +248,7 @@ public void testRemoveUserAttribute() throws Exception { String testJavascript = String.format("mParticle.Identity.getCurrentUser().removeUserAttribute(\"%s\");\n", key); final MutableBoolean called = new MutableBoolean(false); final CountDownLatch latch = new MPLatch(1); - runJavascriptTest(testJavascript, new MParticleJSInterface(){ + runJavascriptTest(testJavascript, new MParticleJSInterface() { @Override @JavascriptInterface public void removeUserAttribute(String json) { @@ -259,8 +258,7 @@ public void removeUserAttribute(String json) { assertEquals(key, jsonObject.getString("key")); called.value = true; latch.countDown(); - } - catch (JSONException jse) { + } catch (JSONException jse) { jse.printStackTrace(); } } @@ -276,7 +274,7 @@ public void testSetUserTag() throws Exception { final MutableBoolean called = new MutableBoolean(false); final CountDownLatch latch = new MPLatch(1); //This is acceptable if the JS SDK calls either setUserTag, or setUserAttribute with a null value - runJavascriptTest(testJavascript, new MParticleJSInterface(){ + runJavascriptTest(testJavascript, new MParticleJSInterface() { @Override @JavascriptInterface public void setUserTag(String json) { @@ -286,8 +284,7 @@ public void setUserTag(String json) { assertEquals(tag, jsonObject.getString("key")); called.value = true; latch.countDown(); - } - catch (JSONException jse) { + } catch (JSONException jse) { jse.printStackTrace(); } } @@ -302,8 +299,7 @@ public void setUserAttribute(String json) { assertEquals(jsonObject.optString("value", "null"), "null"); called.value = true; latch.countDown(); - } - catch (JSONException jse) { + } catch (JSONException jse) { jse.printStackTrace(); } } @@ -314,7 +310,7 @@ public void setUserAttribute(String json) { @Test public void testLogEvent() throws Exception { - final JSONObject customAttributes = MPUtility.mapToJson( mRandomUtils.getRandomAttributes(10)); + final JSONObject customAttributes = MPUtility.mapToJson(mRandomUtils.getRandomAttributes(10)); final JSONObject customFlagsJSON = MPUtility.mapToJson(getCustomFlags()); String testJavascript = String.format("mParticle.logEvent('Play Movie Tapped',\n" + " mParticle.EventType.Navigation,\n" + @@ -371,7 +367,7 @@ public void logEvent(String json) { @Test public void testLogCommerceEvent() throws Exception { - final JSONObject customAttributes = MPUtility.mapToJson( mRandomUtils.getRandomAttributes(10)); + final JSONObject customAttributes = MPUtility.mapToJson(mRandomUtils.getRandomAttributes(10)); final JSONObject customFlags = MPUtility.mapToJson(getCustomFlags()); String testJavascript = String.format("// 1. Create the product\n" + "var product = mParticle.eCommerce.createProduct(\n" + @@ -454,7 +450,7 @@ public void logEvent(String json) { @Test public void testLogout() throws Exception { - final Map userIdentityMap = mRandomUtils.getRandomUserIdentities(); + final Map userIdentityMap = mRandomUtils.getRandomUserIdentities(); JSONObject jsonObject = userIdentityMapToJson(userIdentityMap); String testJavascript = String.format("mParticle.Identity.logout(%s , null);", jsonObject.toString(4)); @@ -506,7 +502,7 @@ public void logout() { @Test public void testLogin() throws Exception { - final Map userIdentityMap = mRandomUtils.getRandomUserIdentities(); + final Map userIdentityMap = mRandomUtils.getRandomUserIdentities(); JSONObject jsonObject = userIdentityMapToJson(userIdentityMap); String testJavascript = String.format("mParticle.Identity.login(%s , null);", jsonObject.toString(4)); @@ -558,7 +554,7 @@ public void login() { @Test public void testModify() throws Exception { - final Map userIdentities = mRandomUtils.getRandomUserIdentities(); + final Map userIdentities = mRandomUtils.getRandomUserIdentities(); JSONObject jsonObject = userIdentityMapToJson(userIdentities); String testJavascript = String.format("mParticle.Identity.modify(%s , null);", jsonObject.toString(4)); diff --git a/android-core/src/androidTest/kotlin/com.mparticle/BatchCreationCallbackTests.kt b/android-core/src/androidTest/kotlin/com.mparticle/BatchCreationCallbackTests.kt index 711e8463b..b2747c74a 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/BatchCreationCallbackTests.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/BatchCreationCallbackTests.kt @@ -69,7 +69,9 @@ class BatchCreationCallbackTests : BaseCleanInstallEachTest() { it.optJSONArray("msgs") ?.toList() ?.filterIsInstance() - ?.any { it.optString("n") == targetEventName && it.optString("mb").isNullOrEmpty() } ?: false + ?.any { + it.optString("n") == targetEventName && it.optString("mb").isNullOrEmpty() + } ?: false } ) @@ -77,7 +79,8 @@ class BatchCreationCallbackTests : BaseCleanInstallEachTest() { it.bodyJson.optJSONArray("msgs") ?.toList() ?.filterIsInstance() - ?.any { it.optString("n") == targetEventName && it.optString("mb").isNullOrEmpty() } ?: false + ?.any { it.optString("n") == targetEventName && it.optString("mb").isNullOrEmpty() } + ?: false }.let { assertTrue { it } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt index 11334cbd1..ab0ce5524 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/PushRegistrationTest.kt @@ -117,7 +117,8 @@ class PushRegistrationTest : BaseCleanStartedEachTest() { var setPushes = arrayOf( object : SetPush { override fun setPushRegistration(pushRegistration: PushRegistration) { - MParticle.getInstance()?.logPushRegistration(pushRegistration.instanceId, pushRegistration.senderId) + MParticle.getInstance() + ?.logPushRegistration(pushRegistration.instanceId, pushRegistration.senderId) } override val name: String @@ -134,8 +135,10 @@ class PushRegistrationTest : BaseCleanStartedEachTest() { }, object : SetPush { override fun setPushRegistration(pushRegistration: PushRegistration) { - MParticle.getInstance()?.mInternal?.configManager?.pushSenderId = pushRegistration.senderId - MParticle.getInstance()?.mInternal?.configManager?.pushInstanceId = pushRegistration.instanceId + MParticle.getInstance()?.mInternal?.configManager?.pushSenderId = + pushRegistration.senderId + MParticle.getInstance()?.mInternal?.configManager?.pushInstanceId = + pushRegistration.instanceId } override val name: String diff --git a/android-core/src/androidTest/kotlin/com.mparticle/UploadEventKotlinTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/UploadEventKotlinTest.kt index 90c26b690..351a56e58 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/UploadEventKotlinTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/UploadEventKotlinTest.kt @@ -121,7 +121,9 @@ class UploadEventKotlinTest : BaseCleanStartedEachTest() { it.optJSONArray("msgs")?.let { messagesArray -> (0 until messagesArray.length()) .any { - val eventProductName = messagesArray.getJSONObject(it).optJSONObject("pd")?.optJSONArray("pl")?.optJSONObject(0)?.optString("nm") + val eventProductName = + messagesArray.getJSONObject(it).optJSONObject("pd") + ?.optJSONArray("pl")?.optJSONObject(0)?.optString("nm") assertNotEquals("Should Not Upload", eventProductName) if (eventProductName == "Should Upload 1" || eventProductName == "Should Upload 2") { numUploadedEvents++ diff --git a/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiTest.kt index 301d2f67a..5781b3128 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiTest.kt @@ -15,7 +15,6 @@ import org.json.JSONObject import org.junit.Assert import org.junit.Before import org.junit.Test -import java.lang.Exception import java.util.UUID import java.util.concurrent.CountDownLatch diff --git a/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleUserDelegateITest.kt b/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleUserDelegateITest.kt index ac17fd3fa..23e507f99 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleUserDelegateITest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleUserDelegateITest.kt @@ -34,7 +34,7 @@ class MParticleUserDelegateITest : BaseCleanStartedEachTest() { val attributes = HashMap>() for (i in 0..4) { val mpid = ran.nextLong() - val pairs = HashMap () + val pairs = HashMap() attributes[mpid] = pairs for (j in 0..2) { val identityType = diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/ApplicationContextWrapperITest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/ApplicationContextWrapperITest.kt index 9847cea94..52c923913 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/ApplicationContextWrapperITest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/ApplicationContextWrapperITest.kt @@ -19,7 +19,10 @@ class ApplicationContextWrapperITest { @OrchestratorOnly @Test fun testRegisterListenerBackgroundThread() { - val applicationContextWrapper = ApplicationContextWrapper(InstrumentationRegistry.getInstrumentation().getContext().applicationContext as Application) + val applicationContextWrapper = ApplicationContextWrapper( + InstrumentationRegistry.getInstrumentation() + .getContext().applicationContext as Application + ) var exception: Exception? = null assertNull(Looper.myLooper()) try { diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/BatchSessionInfoTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/BatchSessionInfoTest.kt index 64dcdb10f..dd504b01c 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/BatchSessionInfoTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/BatchSessionInfoTest.kt @@ -41,7 +41,9 @@ class BatchSessionInfoTest : BaseCleanStartedEachTest() { @Test fun testProperSessionAttachedToBatch() { InstallReferrerHelper.setInstallReferrer(mContext, "111") - (0..150).forEach { MParticle.getInstance()?.logEvent(MPEvent.Builder(it.toString()).build()) } + (0..150).forEach { + MParticle.getInstance()?.logEvent(MPEvent.Builder(it.toString()).build()) + } AccessUtils.awaitMessageHandler() MParticle.getInstance()?.Internal()?.apply { @@ -56,7 +58,8 @@ class BatchSessionInfoTest : BaseCleanStartedEachTest() { MParticle.getInstance()?.upload() mServer.waitForVerify( Matcher(mServer.Endpoints().getEventsUrl()).bodyMatch { - val version = it.getJSONObject("ai").getString(Constants.MessageKey.INSTALL_REFERRER) + val version = + it.getJSONObject("ai").getString(Constants.MessageKey.INSTALL_REFERRER) if (it.has("msgs")) { var messages = it.getJSONArray("msgs") for (i in 0 until messages.length()) { @@ -77,7 +80,8 @@ class BatchSessionInfoTest : BaseCleanStartedEachTest() { } mServer.waitForVerify( Matcher(mServer.Endpoints().getEventsUrl()).bodyMatch { - val version = it.getJSONObject("ai").getString(Constants.MessageKey.INSTALL_REFERRER) + val version = + it.getJSONObject("ai").getString(Constants.MessageKey.INSTALL_REFERRER) assertEquals("222", version) true } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigManagerInstrumentedTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigManagerInstrumentedTest.kt index e55bae15c..cd4680d43 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigManagerInstrumentedTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigManagerInstrumentedTest.kt @@ -66,14 +66,16 @@ class ConfigManagerInstrumentedTest : BaseAbstractTest() { MParticle.getInstance() ?.Identity()?.currentUser?.id ) - MParticle.getInstance()?.Identity()?.currentUser?.isLoggedIn?.let { TestCase.assertTrue(it) } + MParticle.getInstance() + ?.Identity()?.currentUser?.isLoggedIn?.let { TestCase.assertTrue(it) } configManager?.setMpid(mpid3, true) TestCase.assertEquals( mpid3, MParticle.getInstance() ?.Identity()?.currentUser?.id ) - MParticle.getInstance()?.Identity()?.currentUser?.isLoggedIn?.let { TestCase.assertTrue(it) } + MParticle.getInstance() + ?.Identity()?.currentUser?.isLoggedIn?.let { TestCase.assertTrue(it) } } @Test @@ -111,8 +113,14 @@ class ConfigManagerInstrumentedTest : BaseAbstractTest() { .configuration(AddConfigListener(configLoadedListener)) ) latch.await() - TestCase.assertEquals("", MParticle.getInstance()?.Internal()?.configManager?.workspaceToken) - TestCase.assertEquals(90, MParticle.getInstance()?.Internal()?.configManager?.aliasMaxWindow) + TestCase.assertEquals( + "", + MParticle.getInstance()?.Internal()?.configManager?.workspaceToken + ) + TestCase.assertEquals( + 90, + MParticle.getInstance()?.Internal()?.configManager?.aliasMaxWindow + ) } @Test @@ -208,6 +216,7 @@ class ConfigManagerInstrumentedTest : BaseAbstractTest() { override fun configures(): Class { return ConfigManager::class.java } + override fun apply(configManager: ConfigManager?) { configManager?.addConfigUpdatedListener(configLoadedListener) } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigMigrationTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigMigrationTest.kt index eef4c14e8..7d4587905 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigMigrationTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigMigrationTest.kt @@ -124,17 +124,30 @@ class ConfigMigrationTest : BaseCleanInstallEachTest() { } private fun setOldConfigState(config: JSONObject) { - ConfigManager.getInstance(mContext).getKitConfigPreferences().edit().remove(ConfigManager.KIT_CONFIG_KEY) - ConfigManager.getPreferences(mContext).edit().putString(oldConfigSharedprefsKey, config.toString()).apply() + ConfigManager.getInstance(mContext).getKitConfigPreferences().edit() + .remove(ConfigManager.KIT_CONFIG_KEY) + ConfigManager.getPreferences(mContext).edit() + .putString(oldConfigSharedprefsKey, config.toString()).apply() } private fun assertOldConfigState(config: JSONObject) { - assertEquals(config.toString(), ConfigManager.getPreferences(mContext).getString(oldConfigSharedprefsKey, JSONArray().toString())) + assertEquals( + config.toString(), + ConfigManager.getPreferences(mContext) + .getString(oldConfigSharedprefsKey, JSONArray().toString()) + ) } private fun assertNewConfigState(config: JSONObject) { - val configString = ConfigManager.getPreferences(mContext).getString(ConfigManager.CONFIG_JSON, JSONArray().toString()) + val configString = ConfigManager.getPreferences(mContext) + .getString(ConfigManager.CONFIG_JSON, JSONArray().toString()) assertNull(JSONObject(configString).optJSONArray(ConfigManager.KEY_EMBEDDED_KITS)) - assertEquals(config.optString(ConfigManager.KEY_EMBEDDED_KITS, JSONArray().toString()), ConfigManager.getInstance(mContext).kitConfigPreferences.getString(ConfigManager.KIT_CONFIG_KEY, JSONArray().toString())) + assertEquals( + config.optString(ConfigManager.KEY_EMBEDDED_KITS, JSONArray().toString()), + ConfigManager.getInstance(mContext).kitConfigPreferences.getString( + ConfigManager.KIT_CONFIG_KEY, + JSONArray().toString() + ) + ) } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigRequestTests.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigRequestTests.kt index 9f8a3eee0..84c22bac6 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigRequestTests.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigRequestTests.kt @@ -101,6 +101,9 @@ class ConfigRequestTests : BaseCleanInstallEachTest() { } startMParticle() latch.await() - assertEquals(simpleConfigWithKits[ConfigManager.KEY_EMBEDDED_KITS].toString(), MParticle.getInstance()?.Internal()?.configManager?.latestKitConfiguration.toString()) + assertEquals( + simpleConfigWithKits[ConfigManager.KEY_EMBEDDED_KITS].toString(), + MParticle.getInstance()?.Internal()?.configManager?.latestKitConfiguration.toString() + ) } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/MPUtilityTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/MPUtilityTest.kt index f5e581674..62aadb097 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/MPUtilityTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/MPUtilityTest.kt @@ -5,7 +5,6 @@ import android.telephony.TelephonyManager import com.mparticle.testutils.BaseCleanInstallEachTest import org.junit.Assert import org.junit.Test -import java.lang.Exception import java.util.Hashtable import java.util.TreeMap diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/UpdateAdIdIdentityTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/UpdateAdIdIdentityTest.kt index f604e0805..f2a5ed578 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/UpdateAdIdIdentityTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/UpdateAdIdIdentityTest.kt @@ -34,7 +34,8 @@ class UpdateAdIdIdentityTest : BaseCleanInstallEachTest() { // force a modify request to ensure that the modify request from the CheckAdIdRunnable is completed val latch2 = MPLatch(1) - MParticle.getInstance()!!.Identity().modify(IdentityApiRequest.withEmptyUser().customerId("someId").build()) + MParticle.getInstance()!!.Identity() + .modify(IdentityApiRequest.withEmptyUser().customerId("someId").build()) .addSuccessListener { latch2.countDown() } latch2.await() diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeMessageTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeMessageTableTest.kt index 3556fd93b..63b1b29ec 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeMessageTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeMessageTableTest.kt @@ -26,7 +26,11 @@ class UpgradeMessageTableTest : BaseTableTest() { helper.onUpgrade(database, oldVersion, newVersion) } - override fun onDowngrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) { + override fun onDowngrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int + ) { helper.onDowngrade(database, oldVersion, newVersion) } }, diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeVersionTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeVersionTest.kt index 822d80e44..3d2d95da4 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeVersionTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/UpgradeVersionTest.kt @@ -57,7 +57,11 @@ class UpgradeVersionTest : BaseTableTest() { helper.onUpgrade(database, oldVersion, newVersion) } - override fun onDowngrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) { + override fun onDowngrade( + database: SQLiteDatabase, + oldVersion: Int, + newVersion: Int + ) { helper.onDowngrade(database, oldVersion, newVersion) } }, diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/MParticleDBManagerTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/MParticleDBManagerTest.kt index 9344df60e..9b180d231 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/MParticleDBManagerTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/MParticleDBManagerTest.kt @@ -12,8 +12,6 @@ import com.mparticle.testutils.MPLatch import org.junit.Assert import org.junit.Test import java.util.TreeMap -import kotlin.collections.ArrayList -import kotlin.collections.HashMap class MParticleDBManagerTest : BaseCleanInstallEachTest() { @Test diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BaseTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BaseTableTest.kt index ef85048dd..cc2e08af2 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BaseTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BaseTableTest.kt @@ -18,7 +18,8 @@ open class BaseTableTest : BaseCleanInstallEachTest() { var openHelper = helper?.let { TestSQLiteOpenHelper(it, DB_NAME, oldVersion) } openHelper?.writableDatabase openHelper?.onCreateLatch?.await() - openHelper = helper?.let { TestSQLiteOpenHelper(it, DB_NAME, MParticleDatabaseHelper.DB_VERSION) } + openHelper = + helper?.let { TestSQLiteOpenHelper(it, DB_NAME, MParticleDatabaseHelper.DB_VERSION) } openHelper?.writableDatabase if (oldVersion < MParticleDatabaseHelper.DB_VERSION) { openHelper?.onUpgradeLatch?.await() diff --git a/android-core/src/androidTest/res/layout/web_view_activity.xml b/android-core/src/androidTest/res/layout/web_view_activity.xml index 98cc24c7a..5aa35914b 100644 --- a/android-core/src/androidTest/res/layout/web_view_activity.xml +++ b/android-core/src/androidTest/res/layout/web_view_activity.xml @@ -1,6 +1,7 @@ + diff --git a/android-core/src/main/java/com/mparticle/AttributionError.java b/android-core/src/main/java/com/mparticle/AttributionError.java index bb93c3468..316213ea1 100644 --- a/android-core/src/main/java/com/mparticle/AttributionError.java +++ b/android-core/src/main/java/com/mparticle/AttributionError.java @@ -25,9 +25,8 @@ public AttributionError setServiceProviderId(int id) { /** * Get the service provider or integration id associated with this result. * - * @see com.mparticle.MParticle.ServiceProviders - * * @return the id of the associated integration + * @see com.mparticle.MParticle.ServiceProviders */ public int getServiceProviderId() { return serviceProviderId; diff --git a/android-core/src/main/java/com/mparticle/AttributionListener.java b/android-core/src/main/java/com/mparticle/AttributionListener.java index 9ac496c8c..a88714990 100644 --- a/android-core/src/main/java/com/mparticle/AttributionListener.java +++ b/android-core/src/main/java/com/mparticle/AttributionListener.java @@ -7,5 +7,6 @@ */ public interface AttributionListener { void onResult(@NonNull AttributionResult result); + void onError(@NonNull AttributionError error); } \ No newline at end of file diff --git a/android-core/src/main/java/com/mparticle/AttributionResult.java b/android-core/src/main/java/com/mparticle/AttributionResult.java index 8753f17dd..3e78307dd 100644 --- a/android-core/src/main/java/com/mparticle/AttributionResult.java +++ b/android-core/src/main/java/com/mparticle/AttributionResult.java @@ -50,9 +50,8 @@ public AttributionResult setServiceProviderId(int id) { /** * Get the service provider or integration id associated with this result. * - * @see com.mparticle.MParticle.ServiceProviders - * * @return the id of the associated integration + * @see com.mparticle.MParticle.ServiceProviders */ public int getServiceProviderId() { return serviceProviderId; diff --git a/android-core/src/main/java/com/mparticle/BaseEvent.java b/android-core/src/main/java/com/mparticle/BaseEvent.java index 71c9db106..2579a745d 100644 --- a/android-core/src/main/java/com/mparticle/BaseEvent.java +++ b/android-core/src/main/java/com/mparticle/BaseEvent.java @@ -78,7 +78,7 @@ public Map getCustomAttributeStrings() { return null; } Map attributes = new HashMap<>(); - for (Map.Entry entry: mCustomAttributes.entrySet()) { + for (Map.Entry entry : mCustomAttributes.entrySet()) { Object value = entry.getValue(); attributes.put(entry.getKey(), value == null ? null : value.toString()); } diff --git a/android-core/src/main/java/com/mparticle/Configuration.java b/android-core/src/main/java/com/mparticle/Configuration.java index 847263f0f..c80f1d41f 100644 --- a/android-core/src/main/java/com/mparticle/Configuration.java +++ b/android-core/src/main/java/com/mparticle/Configuration.java @@ -1,6 +1,7 @@ package com.mparticle; public interface Configuration { - Class configures(); - void apply(T t); + Class configures(); + + void apply(T t); } diff --git a/android-core/src/main/java/com/mparticle/InstallReferrerHelper.java b/android-core/src/main/java/com/mparticle/InstallReferrerHelper.java index 32ce99955..17c23bc36 100644 --- a/android-core/src/main/java/com/mparticle/InstallReferrerHelper.java +++ b/android-core/src/main/java/com/mparticle/InstallReferrerHelper.java @@ -4,6 +4,7 @@ import android.content.SharedPreferences; import android.os.Looper; import android.os.RemoteException; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -59,8 +60,7 @@ public void onInstallReferrerSetupFinished(int responseCode) { } catch (RemoteException e) { Logger.warning("InstallReferrer Remote Exception, using InstallReferrer from intent."); callback.onFailed(); - } - catch (Exception e) { + } catch (Exception e) { Logger.warning("InstallReferrer Exception: " + e.getMessage() + ", using InstallReferrer from intent"); callback.onFailed(); } @@ -85,8 +85,7 @@ public void onInstallReferrerServiceDisconnected() { } }; mReferrerClient.startConnection(listener); - } - catch (Exception e) { + } catch (Exception e) { Logger.error("Exception while fetching install referrer: " + e.getMessage()); callback.onFailed(); } @@ -98,8 +97,7 @@ public void onInstallReferrerServiceDisconnected() { } else { runnable.run(); } - } - catch (Exception ignored) { + } catch (Exception ignored) { callback.onFailed(); } } else { @@ -109,6 +107,7 @@ public void onInstallReferrerServiceDisconnected() { public interface InstallReferrerCallback { void onReceived(@Nullable String installReferrer); + void onFailed(); } diff --git a/android-core/src/main/java/com/mparticle/MPEvent.java b/android-core/src/main/java/com/mparticle/MPEvent.java index 73fe983e3..651c2b3bc 100644 --- a/android-core/src/main/java/com/mparticle/MPEvent.java +++ b/android-core/src/main/java/com/mparticle/MPEvent.java @@ -25,13 +25,11 @@ /** - * * Class representation of an event. * * MPEvent implements the Builder pattern, see {@link com.mparticle.MPEvent.Builder} for more information. * * @see com.mparticle.MParticle#logEvent(BaseEvent) - * */ public class MPEvent extends BaseEvent { private MParticle.EventType eventType; @@ -42,21 +40,22 @@ public class MPEvent extends BaseEvent { private boolean entering = true; private boolean screenEvent; - private MPEvent(){ + private MPEvent() { super(Type.EVENT); } - private MPEvent(Builder builder){ + + private MPEvent(Builder builder) { super(Type.EVENT); - if (builder.eventType == null){ + if (builder.eventType == null) { Logger.error("MPEvent created with no event type!"); } else { eventType = builder.eventType; } - if (builder.eventName == null){ + if (builder.eventName == null) { Logger.error("MPEvent created with no event name!"); } else { - if (builder.eventName.length() > Constants.LIMIT_ATTR_KEY){ + if (builder.eventName.length() > Constants.LIMIT_ATTR_KEY) { Logger.error("MPEvent created with too long of a name and will be truncated, the limit is: " + Constants.LIMIT_ATTR_KEY); eventName = builder.eventName.substring(0, Constants.LIMIT_ATTR_KEY); } else { @@ -67,20 +66,20 @@ private MPEvent(Builder builder){ entering = builder.entering; setCustomAttributes(builder.customAttributes); - if (builder.category != null){ + if (builder.category != null) { category = builder.category; - if (getCustomAttributeStrings() == null){ + if (getCustomAttributeStrings() == null) { setCustomAttributes(new HashMap()); } getCustomAttributeStrings().put(Constants.MessageKey.EVENT_CATEGORY, builder.category); } - if (builder.duration != null){ + if (builder.duration != null) { duration = builder.duration; } - if (builder.endTime != null){ + if (builder.endTime != null) { endTime = builder.endTime; } - if (builder.startTime != null){ + if (builder.startTime != null) { startTime = builder.startTime; } if (builder.customFlags != null) { @@ -98,11 +97,11 @@ public boolean equals(@Nullable Object o) { } /** - * @deprecated use {@link MPEvent#setCustomAttributes(Map)} instead * @param info + * @deprecated use {@link MPEvent#setCustomAttributes(Map)} instead */ @Deprecated - public void setInfo(@Nullable Map info){ + public void setInfo(@Nullable Map info) { setCustomAttributes(info); } @@ -117,7 +116,7 @@ public MPEvent(@NonNull MPEvent mpEvent) { eventName = mpEvent.eventName; if (mpEvent.getCustomAttributes() != null) { setCustomAttributes(mpEvent.getCustomAttributes()); - }else { + } else { setCustomAttributes(null); } category = mpEvent.category; @@ -137,30 +136,29 @@ public String toString() { StringBuilder builder = new StringBuilder(); if (eventName != null) { builder.append("Event name: ") - .append(eventName) - .append("\n"); + .append(eventName) + .append("\n"); } - if (eventType != null){ + if (eventType != null) { builder.append("type: ") - .append(eventType.name()) - .append("\n"); + .append(eventType.name()) + .append("\n"); } Double length = getLength(); - if (length != null && length > 0){ + if (length != null && length > 0) { builder.append("length: ") .append(length).append("ms") .append("\n"); } - if (getCustomAttributeStrings() != null){ + if (getCustomAttributeStrings() != null) { builder.append("customAttributes:\n"); List sortedKeys = new ArrayList(getCustomAttributeStrings().keySet()); Collections.sort(sortedKeys); - for (String key : sortedKeys) - { + for (String key : sortedKeys) { builder.append(key) - .append(":") - .append(getCustomAttributeStrings().get(key)) - .append("\n"); + .append(":") + .append(getCustomAttributeStrings().get(key)) + .append("\n"); } } if (getCustomFlags() != null) { @@ -187,7 +185,7 @@ protected MPEvent setScreenEvent(boolean screenEvent) { } public int getEventHash() { - if (eventHash == 0){ + if (eventHash == 0) { eventHash = MPUtility.mpHash(eventType.ordinal() + eventName); } return eventHash; @@ -199,8 +197,8 @@ public String getCategory() { } /** - * @deprecated use {@link MPEvent#getCustomAttributes()} instead * @return + * @deprecated use {@link MPEvent#getCustomAttributes()} instead */ @Deprecated @Nullable @@ -255,18 +253,18 @@ public static class Builder { private boolean entering = true; private Boolean shouldUploadEvent; - private Builder(){} + private Builder() { + } /** * Starting point of the builder with two required parameters. The rest of the fields * of this class are optional. Once the desired fields have been set, use {@link #build()} to * create the {@link com.mparticle.MPEvent} object. * - * * @param eventName the name of the event to be tracked (required) * @param eventType the type of the event to be tracked (required) */ - public Builder(@NonNull String eventName,@NonNull MParticle.EventType eventType){ + public Builder(@NonNull String eventName, @NonNull MParticle.EventType eventType) { this.eventName = eventName; this.eventType = eventType; } @@ -276,10 +274,9 @@ public Builder(@NonNull String eventName,@NonNull MParticle.EventType eventType) * of this class are optional. Once the desired fields have been set, use {@link #build()} to * create the {@link com.mparticle.MPEvent} object. * - * * @param eventName the name of the event to be tracked (required) */ - public Builder(@NonNull String eventName){ + public Builder(@NonNull String eventName) { this.eventName = eventName; this.eventType = MParticle.EventType.Other; } @@ -312,7 +309,7 @@ public Builder(@NonNull MPEvent event) { * @return returns this builder for easy method chaining */ @NonNull - public Builder eventName(@NonNull String eventName){ + public Builder eventName(@NonNull String eventName) { if (eventName != null) { this.eventName = eventName; } @@ -324,11 +321,10 @@ public Builder eventName(@NonNull String eventName){ * * @param eventType * @return returns this builder for easy method chaining - * * @see com.mparticle.MParticle.EventType */ @NonNull - public Builder eventType(@NonNull MParticle.EventType eventType){ + public Builder eventType(@NonNull MParticle.EventType eventType) { if (eventType != null) { this.eventType = eventType; } @@ -339,7 +335,7 @@ public Builder eventType(@NonNull MParticle.EventType eventType){ * Add a custom flag to this event. Flag keys can have multiple values - if the provided flag key already has an associated * value, the value will be appended. * - * @param key (required) a flag key, retrieve this from the mParticle docs or solution team for your intended services(s) + * @param key (required) a flag key, retrieve this from the mParticle docs or solution team for your intended services(s) * @param value (required) a flag value to be send to the service indicated by the flag key * @return returns this builder for easy method chaining */ @@ -368,14 +364,13 @@ public Builder customFlags(@Nullable Map> customFlags) { } /** - * * The Google Analytics category with which to associate this event. * * @param category * @return returns this builder for easy method chaining */ @NonNull - public Builder category(@Nullable String category){ + public Builder category(@Nullable String category) { this.category = category; return this; } @@ -389,22 +384,21 @@ public Builder category(@Nullable String category){ * @return returns this builder for easy method chaining */ @NonNull - public Builder duration(double durationMillis){ + public Builder duration(double durationMillis) { this.duration = durationMillis; return this; } /** + * @param info + * @return returns this builder for easy method chaining * @deprecated user {@link MPEvent.Builder#customAttributes} instead * * Data attributes to associate with the event. - * - * @param info - * @return returns this builder for easy method chaining */ @Deprecated @NonNull - public Builder info(@Nullable Map info){ + public Builder info(@Nullable Map info) { this.customAttributes = info; return this; } @@ -426,7 +420,7 @@ public Builder customAttributes(@Nullable Map customAttributes) { * @return returns this builder for easy method chaining */ @NonNull - private Builder startTime(double startTimeMillis){ + private Builder startTime(double startTimeMillis) { this.startTime = startTimeMillis; return this; } @@ -439,7 +433,7 @@ private Builder startTime(double startTimeMillis){ * @return returns this builder for easy method chaining */ @NonNull - public Builder startTime(){ + public Builder startTime() { return startTime(System.currentTimeMillis()); } @@ -451,7 +445,7 @@ public Builder startTime(){ * @return returns this builder for easy method chaining */ @NonNull - public Builder endTime(){ + public Builder endTime() { return endTime(System.currentTimeMillis()); } @@ -463,7 +457,7 @@ public Builder endTime(){ * @param endTimeMillis * @return returns this builder for easy method chaining */ - private Builder endTime(double endTimeMillis){ + private Builder endTime(double endTimeMillis) { this.endTime = endTimeMillis; return this; } @@ -471,12 +465,11 @@ private Builder endTime(double endTimeMillis){ /** * Beta API, subject to change. Used internally to signify if a user is entering or exiting a screen. * - * * @param entering True if a user is navigating to a screen, False when navigating away * @return returns this builder for easy method chaining */ @NonNull - public Builder internalNavigationDirection(boolean entering){ + public Builder internalNavigationDirection(boolean entering) { this.entering = entering; return this; } @@ -501,11 +494,10 @@ public Builder shouldUploadEvent(boolean shouldUploadEvent) { * MPEvent is invalid. * * @return returns the MPEvent object to be logged - * * @see MParticle#logEvent(BaseEvent) */ @NonNull - public MPEvent build(){ + public MPEvent build() { return new MPEvent(this); } @@ -516,28 +508,28 @@ public MPEvent build(){ * @return returns this builder for easy method chaining */ @Nullable - public static Builder parseString(@NonNull String builderString){ + public static Builder parseString(@NonNull String builderString) { Builder builder = null; - try{ + try { JSONObject json = new JSONObject(builderString); builder = new Builder(json.getString(EVENT_NAME), MParticle.EventType.valueOf(json.getString(EVENT_TYPE))); builder.category = json.optString(EVENT_CATEGORY); - if (json.has(EVENT_DURATION)){ + if (json.has(EVENT_DURATION)) { builder.duration = json.getDouble(EVENT_DURATION); } - if (json.has(EVENT_START_TIME)){ + if (json.has(EVENT_START_TIME)) { builder.startTime = json.getDouble(EVENT_START_TIME); } - if (json.has(EVENT_END_TIME)){ + if (json.has(EVENT_END_TIME)) { builder.endTime = json.getDouble(EVENT_END_TIME); } - if (json.has(EVENT_INFO)){ + if (json.has(EVENT_INFO)) { JSONObject infoObject = json.getJSONObject(EVENT_INFO); Map info = new HashMap(); Iterator keys = infoObject.keys(); - while( keys.hasNext() ){ - String key = (String)keys.next(); + while (keys.hasNext()) { + String key = (String) keys.next(); info.put(key, infoObject.getString(key)); } builder.customAttributes = new HashMap<>(info); @@ -547,7 +539,7 @@ public static Builder parseString(@NonNull String builderString){ Map> cFlags = new HashMap>(); Iterator keys = flags.keys(); - while( keys.hasNext() ){ + while (keys.hasNext()) { String key = keys.next(); JSONArray values = flags.getJSONArray(key); cFlags.put(key, new LinkedList()); @@ -562,7 +554,7 @@ public static Builder parseString(@NonNull String builderString){ } return builder; - }catch (Exception e){ + } catch (Exception e) { Logger.warning("Failed to deserialize MPEvent.Builder: " + e.toString()); return builder; } @@ -574,8 +566,8 @@ public static Builder parseString(@NonNull String builderString){ private final static String EVENT_CATEGORY = "category"; private final static String EVENT_DURATION = "duration"; private final static String EVENT_INFO = "customAttributes"; - private final static String EVENT_START_TIME= "startTime"; - private final static String EVENT_END_TIME= "endTime"; + private final static String EVENT_START_TIME = "startTime"; + private final static String EVENT_END_TIME = "endTime"; private final static String EVENT_SHOULD_UPLOAD_EVENT = "shouldUploadEvent"; /** @@ -587,28 +579,27 @@ public static Builder parseString(@NonNull String builderString){ @Override @NonNull public String toString() { - try{ + try { JSONObject jsonObject = new JSONObject(); jsonObject.put(EVENT_TYPE, eventType.toString()); jsonObject.put(EVENT_NAME, eventName); if (category != null) { jsonObject.put(EVENT_CATEGORY, category); } - if (duration != null){ + if (duration != null) { jsonObject.put(EVENT_DURATION, duration); } - if (customAttributes != null){ + if (customAttributes != null) { JSONObject jsonInfo = new JSONObject(); - for (Map.Entry entry : customAttributes.entrySet()) - { + for (Map.Entry entry : customAttributes.entrySet()) { jsonInfo.put(entry.getKey(), entry.getValue()); } jsonObject.put(EVENT_INFO, jsonInfo); } - if (startTime != null){ + if (startTime != null) { jsonObject.put(EVENT_START_TIME, startTime); } - if (endTime != null){ + if (endTime != null) { jsonObject.put(EVENT_END_TIME, endTime); } if (customFlags != null) { @@ -624,7 +615,7 @@ public String toString() { jsonObject.put(EVENT_SHOULD_UPLOAD_EVENT, shouldUploadEvent); } return jsonObject.toString(); - }catch (JSONException jse){ + } catch (JSONException jse) { Logger.warning("Failed to serialize MPEvent.Builder: " + jse.toString()); } return super.toString(); diff --git a/android-core/src/main/java/com/mparticle/MPReceiver.java b/android-core/src/main/java/com/mparticle/MPReceiver.java index d0cb78b0b..a6a56005b 100644 --- a/android-core/src/main/java/com/mparticle/MPReceiver.java +++ b/android-core/src/main/java/com/mparticle/MPReceiver.java @@ -5,6 +5,7 @@ import android.content.Intent; import android.os.Handler; import android.os.Looper; + import androidx.annotation.NonNull; import com.mparticle.messaging.MPMessagingAPI; @@ -46,8 +47,6 @@ * * * } - * - * */ public class MPReceiver extends BroadcastReceiver { @@ -69,7 +68,8 @@ public void run() { }); } - @NonNull public static final String MPARTICLE_IGNORE = "mparticle_ignore"; + @NonNull + public static final String MPARTICLE_IGNORE = "mparticle_ignore"; public MPReceiver() { } @@ -77,15 +77,15 @@ public MPReceiver() { @Override public final void onReceive(@NonNull Context context, @NonNull Intent intent) { if (!MPARTICLE_IGNORE.equals(intent.getAction()) && !intent.getBooleanExtra(MPARTICLE_IGNORE, false)) { - if (MPMessagingAPI.BROADCAST_NOTIFICATION_TAPPED.equalsIgnoreCase(intent.getAction())){ + if (MPMessagingAPI.BROADCAST_NOTIFICATION_TAPPED.equalsIgnoreCase(intent.getAction())) { ProviderCloudMessage message = intent.getParcelableExtra(MPMessagingAPI.CLOUD_MESSAGE_EXTRA); - if (!onNotificationTapped(message)){ + if (!onNotificationTapped(message)) { MPServiceUtil.runIntentInService(context, intent); } return; - } else if (MPMessagingAPI.BROADCAST_NOTIFICATION_RECEIVED.equalsIgnoreCase(intent.getAction())){ + } else if (MPMessagingAPI.BROADCAST_NOTIFICATION_RECEIVED.equalsIgnoreCase(intent.getAction())) { ProviderCloudMessage message = intent.getParcelableExtra(MPMessagingAPI.CLOUD_MESSAGE_EXTRA); - if (!onNotificationReceived(message)){ + if (!onNotificationReceived(message)) { MPServiceUtil.runIntentInService(context, intent); } return; @@ -96,14 +96,13 @@ public final void onReceive(@NonNull Context context, @NonNull Intent intent) { } - /** * Override this method to listen for when a notification has been received. * * @param message The message that was received. * @return True if you would like to handle this notification, False if you would like the mParticle to generate and show a {@link android.app.Notification}. */ - protected boolean onNotificationReceived(@NonNull ProviderCloudMessage message){ + protected boolean onNotificationReceived(@NonNull ProviderCloudMessage message) { return false; } @@ -113,7 +112,7 @@ protected boolean onNotificationReceived(@NonNull ProviderCloudMessage message){ * @param message The message that was tapped. * @return True if you would like to consume this tap/action, False if the mParticle SDK should attempt to handle it. */ - protected boolean onNotificationTapped(@NonNull ProviderCloudMessage message){ + protected boolean onNotificationTapped(@NonNull ProviderCloudMessage message) { return false; } diff --git a/android-core/src/main/java/com/mparticle/MPService.java b/android-core/src/main/java/com/mparticle/MPService.java index dfc3d2422..fc7aa5b08 100644 --- a/android-core/src/main/java/com/mparticle/MPService.java +++ b/android-core/src/main/java/com/mparticle/MPService.java @@ -2,7 +2,6 @@ import android.annotation.SuppressLint; import android.app.IntentService; - import android.content.Intent; import androidx.annotation.NonNull; @@ -25,7 +24,6 @@ public MPService() { } - /** * */ diff --git a/android-core/src/main/java/com/mparticle/MPServiceUtil.java b/android-core/src/main/java/com/mparticle/MPServiceUtil.java index 70fb31d49..fe8f9894e 100644 --- a/android-core/src/main/java/com/mparticle/MPServiceUtil.java +++ b/android-core/src/main/java/com/mparticle/MPServiceUtil.java @@ -65,8 +65,7 @@ public static void runIntentInService(Context context, Intent intent) { intent.setClass(context, MPService.class); try { context.startService(intent); - } - catch (IllegalStateException ignore) { + } catch (IllegalStateException ignore) { new MPServiceUtil(context).onHandleIntent(intent); } } @@ -92,8 +91,7 @@ public void onHandleIntent(Intent intent) { final ProviderCloudMessage message = intent.getParcelableExtra(MPMessagingAPI.CLOUD_MESSAGE_EXTRA); showNotification(message); } - } - finally { + } finally { synchronized (LOCK) { if (sWakeLock != null && sWakeLock.isHeld()) { sWakeLock.release(); diff --git a/android-core/src/main/java/com/mparticle/SdkListener.java b/android-core/src/main/java/com/mparticle/SdkListener.java index 6a5cdf919..f11103781 100644 --- a/android-core/src/main/java/com/mparticle/SdkListener.java +++ b/android-core/src/main/java/com/mparticle/SdkListener.java @@ -25,8 +25,9 @@ public class SdkListener { /** * Indicates that an API method was called. This includes invocations both from external sources (your code) * and those which originated from within the SDK. - * @param apiName the name of the Api method - * @param objects the arguments used in the invocation + * + * @param apiName the name of the Api method + * @param objects the arguments used in the invocation * @param isExternal true, if the call originated from outside of the SDK */ public void onApiCalled(@NonNull String apiName, @NonNull List objects, boolean isExternal) { @@ -35,9 +36,10 @@ public void onApiCalled(@NonNull String apiName, @NonNull List objects, /** * Indicates that a new Database entry has been created. - * @param tableName the name of the table, see {@link DatabaseTable} + * + * @param tableName the name of the table, see {@link DatabaseTable} * @param primaryKey a unique identifier for the database row - * @param message the database entry in JSON form + * @param message the database entry in JSON form */ public void onEntityStored(@NonNull DatabaseTable tableName, @NonNull long primaryKey, @NonNull JSONObject message) { @@ -47,8 +49,9 @@ public void onEntityStored(@NonNull DatabaseTable tableName, @NonNull long prima * Indicates that a Network Request has been started. Network Requests for a given {@link Endpoint} are performed. * synchronously, so the next invocation of {@link #onNetworkRequestStarted(Endpoint, String, JSONObject)} * of the same {@link Endpoint}, will refer to the same request + * * @param type the type of network request, see {@link Endpoint} - * @param url the URL of the request + * @param url the URL of the request * @param body the response body in JSON form */ public void onNetworkRequestStarted(@NonNull Endpoint type, @NonNull String url, @NonNull JSONObject body) { @@ -59,9 +62,10 @@ public void onNetworkRequestStarted(@NonNull Endpoint type, @NonNull String url, * Indicates that a Network Request has completed. Network Requests for a given {@link Endpoint} are performed * synchronously, so any invocation will refer to the same request as the most recent. * {@link #onNetworkRequestStarted(Endpoint, String, JSONObject)} invocation of the same {@link Endpoint} - * @param type the type of network request, see {@link Endpoint} - * @param url the URL of the request - * @param response the response body in JSON form + * + * @param type the type of network request, see {@link Endpoint} + * @param url the URL of the request + * @param response the response body in JSON form * @param responseCode the HTTP response code */ public void onNetworkRequestFinished(@NonNull Endpoint type, @NonNull String url, @Nullable JSONObject response, int responseCode) { @@ -70,12 +74,13 @@ public void onNetworkRequestFinished(@NonNull Endpoint type, @NonNull String url /** * Indicates that a Kit method was invoked. - * @param kitId the id of the kit, corresponds with a {@link com.mparticle.MParticle.ServiceProviders} - * @param apiName the method name which was invoked - * @param invokingMethodName the SDK Api call which triggered the invocation, if there was one + * + * @param kitId the id of the kit, corresponds with a {@link com.mparticle.MParticle.ServiceProviders} + * @param apiName the method name which was invoked + * @param invokingMethodName the SDK Api call which triggered the invocation, if there was one * @param kitManagerMethodName the KitManager call which serverd as the intermediate trigger of the invocation, if there was one - * @param objects the arguments passed - * @param used whether a {@link com.mparticle.internal.database.services.ReportingService.ReportingMessage} was generated as a result of the invocation. {@link com.mparticle.internal.database.services.ReportingService.ReportingMessage} indicate that an argument was consumed by the Kit + * @param objects the arguments passed + * @param used whether a {@link com.mparticle.internal.database.services.ReportingService.ReportingMessage} was generated as a result of the invocation. {@link com.mparticle.internal.database.services.ReportingService.ReportingMessage} indicate that an argument was consumed by the Kit */ public void onKitApiCalled(int kitId, @NonNull String apiName, @Nullable String invokingMethodName, @Nullable String kitManagerMethodName, @NonNull List objects, boolean used) { @@ -83,6 +88,7 @@ public void onKitApiCalled(int kitId, @NonNull String apiName, @Nullable String /** * Indicates that a Kit module, with kitId, is present in the classpath. + * * @param kitId the id of the kit, corresponse with a {@link com.mparticle.MParticle.ServiceProviders} */ public void onKitDetected(int kitId) { @@ -91,7 +97,8 @@ public void onKitDetected(int kitId) { /** * Indicates that a Configuration for a kit with kitId is being applied. - * @param kitId the id of the kit, corresponse with a {@link com.mparticle.MParticle.ServiceProviders} + * + * @param kitId the id of the kit, corresponse with a {@link com.mparticle.MParticle.ServiceProviders} * @param configuration the configuration in JSON form */ public void onKitConfigReceived(int kitId, @NonNull JSONObject configuration) { @@ -100,6 +107,7 @@ public void onKitConfigReceived(int kitId, @NonNull JSONObject configuration) { /** * Indicates that a kit with kitId was successfully started. + * * @param kitId the id of the kit, corresponse with a {@link com.mparticle.MParticle.ServiceProviders} */ public void onKitStarted(int kitId) { @@ -111,7 +119,8 @@ public void onKitStarted(int kitId) { * Possibilities for why this may happen include: {@link MParticleUser}'s loggedIn status or * {@link com.mparticle.consent.ConsentState} required it to be stopped, the Kit crashed, or a * configuration was received with excluded the kit. - * @param kitId the id of the kit, corresponse with a {@link com.mparticle.MParticle.ServiceProviders} + * + * @param kitId the id of the kit, corresponse with a {@link com.mparticle.MParticle.ServiceProviders} * @param reason a message containing the reason a kit was stopped */ public void onKitExcluded(int kitId, @NonNull String reason) { @@ -120,6 +129,7 @@ public void onKitExcluded(int kitId, @NonNull String reason) { /** * Indicates that state of a Session may have changed. + * * @param session the current {@link InternalSession} instance */ public void onSessionUpdated(@Nullable InternalSession session) { @@ -128,9 +138,11 @@ public void onSessionUpdated(@Nullable InternalSession session) { /** * Callback for {@link com.mparticle.identity.IdentityApi#aliasUsers(AliasRequest)} results. + * * @param aliasResponse */ - public void onAliasRequestFinished(AliasResponse aliasResponse) { } + public void onAliasRequestFinished(AliasResponse aliasResponse) { + } public enum Endpoint { IDENTITY_LOGIN, diff --git a/android-core/src/main/java/com/mparticle/Session.java b/android-core/src/main/java/com/mparticle/Session.java index 8271d528c..cc3ffc8e5 100644 --- a/android-core/src/main/java/com/mparticle/Session.java +++ b/android-core/src/main/java/com/mparticle/Session.java @@ -9,7 +9,6 @@ /** * Public Session API exposing characteristics of a given session. - * */ public class Session { @@ -20,6 +19,7 @@ private Session() { mUUID = null; mSessionStartTime = null; } + Session(String uuid, Long sessionStartTime) { this.mUUID = uuid; this.mSessionStartTime = sessionStartTime; @@ -72,7 +72,7 @@ public boolean equals(@Nullable Object obj) { } String sessionId = getSessionUUID(); Long sessionStartTime = getSessionStartTime(); - Session comparisonSession = ((Session)obj); + Session comparisonSession = ((Session) obj); String comparisonSessionId = comparisonSession.getSessionUUID(); Long comparisonSessionStartTime = comparisonSession.getSessionStartTime(); if (sessionId == comparisonSessionId && diff --git a/android-core/src/main/java/com/mparticle/commerce/CommerceEvent.java b/android-core/src/main/java/com/mparticle/commerce/CommerceEvent.java index 9c5b47db4..911edacac 100644 --- a/android-core/src/main/java/com/mparticle/commerce/CommerceEvent.java +++ b/android-core/src/main/java/com/mparticle/commerce/CommerceEvent.java @@ -33,7 +33,6 @@ * * @see com.mparticle.commerce.CommerceEvent.Builder * @see MParticle#logEvent(BaseEvent) - * */ public final class CommerceEvent extends BaseEvent { private String mEventName; @@ -110,7 +109,7 @@ private CommerceEvent(Builder builder) { && !mProductAction.equals(Product.REMOVE_FROM_WISHLIST)) { Logger.error("CommerceEvent created with unrecognized Product action: " + mProductAction); } - } else if (mPromotionAction != null ) { + } else if (mPromotionAction != null) { if (productList != null && productList.size() > 0) { Logger.error("Promotion CommerceEvent should not contain Products."); } @@ -229,7 +228,7 @@ public String toString() { if (impression.getListName() != null) { impressionJson.put("pil", impression.getListName()); } - if (impression.getProducts() != null && impression.getProducts() .size() > 0) { + if (impression.getProducts() != null && impression.getProducts().size() > 0) { JSONArray productsJson = new JSONArray(); impressionJson.put("pl", productsJson); for (Product product : impression.getProducts()) { @@ -256,7 +255,6 @@ public String toString() { * Retrieve the Screen where the event occurred. * * @return the String descriptor/name of the Screen where this event occurred, or null if this is not set. - * * @see com.mparticle.commerce.CommerceEvent.Builder#screen(String). */ @Nullable @@ -268,9 +266,7 @@ public String getScreen() { * Retrieve the boolean indicating if the event was triggered by a user. * * @return a Boolean indicating if this event was triggered by a user, or null if not set. - * * @see com.mparticle.commerce.CommerceEvent.Builder#nonInteraction(boolean). - * */ @Nullable public Boolean getNonInteraction() { @@ -282,7 +278,6 @@ public Boolean getNonInteraction() { * will be null in the case of Promotion and Impression CommerceEvents. * * @return a String indicating the Product action, or null if this is not a Product-based CommerceEvent. - * * @see Builder(java.lang.String, com.mparticle.commerce.Product). * @see Product */ @@ -315,7 +310,6 @@ public String getCheckoutOptions() { * Retrieve the Product List Name associated with the CommerceEvent. This value should be set for {@link Product#DETAIL} and {@link Product#CLICK} CommerceEvents. * * @return the product list name, or null if not set. - * * @see com.mparticle.commerce.CommerceEvent.Builder#productListName(String). */ @Nullable @@ -327,7 +321,6 @@ public String getProductListName() { * Retrieve the product list source associated with the CommerceEvent. This value should be set for {@link Product#DETAIL} and {@link Product#CLICK} CommerceEvents. * * @return the product list source, or null if not set. - * * @see com.mparticle.commerce.CommerceEvent.Builder#productListSource(String). */ @Nullable @@ -339,7 +332,6 @@ public String getProductListSource() { * Retrieve the {@link TransactionAttributes} object associated with the CommerceEvent. * * @return the TransactionAttributes object, or null if not set. - * * @see com.mparticle.commerce.CommerceEvent.Builder#transactionAttributes(TransactionAttributes). */ @Nullable @@ -351,7 +343,6 @@ public TransactionAttributes getTransactionAttributes() { * Retrieve the list of Products to which the CommerceEvent applies. This should only be set for Product-type CommerceEvents. * * @return the list of Products, or null if not set. - * * @see Builder(java.lang.String, com.mparticle.commerce.Product). * @see com.mparticle.commerce.CommerceEvent.Builder#addProduct(Product). * @see com.mparticle.commerce.CommerceEvent.Builder#products(List). @@ -369,7 +360,6 @@ public List getProducts() { * will be null in the case of Product and Impression CommerceEvents. * * @return a String indicating the Promotion action, or null if this is not a Promotion-based CommerceEvent. - * * @see Builder(java.lang.String, com.mparticle.commerce.Promotion) * @see Promotion for supported product actions. */ @@ -382,7 +372,6 @@ public String getPromotionAction() { * Retrieve the {@link Promotion} list associated with the CommerceEvent. * * @return returns an unmodifiable List of Promotions, or null if this is a {@link Product} or {@link Impression} based {@link CommerceEvent}. - * * @see Builder(java.lang.String, com.mparticle.commerce.Promotion). * @see com.mparticle.commerce.CommerceEvent.Builder#addPromotion(Promotion). * @see com.mparticle.commerce.CommerceEvent.Builder#promotions(List). @@ -409,7 +398,6 @@ public int hashCode() { * Retrieve the {@link Impression} list associated with the CommerceEvent. * * @return returns an unmodifiable List of Impressions, or null if this is a {@link Product} or {@link Promotion} based {@link CommerceEvent}. - * * @see Builder(java.lang.String, com.mparticle.commerce.Impression). * @see com.mparticle.commerce.CommerceEvent.Builder#addImpression(Impression). * @see com.mparticle.commerce.CommerceEvent.Builder#impressions(List). @@ -525,9 +513,7 @@ public static class Builder { * Constructor for a {@link Product}-based CommerceEvent. * * @param productAction a String representing the action that the user performed. This must be one of the String constants defined by the {@link Product} class. Must not be null. - * @param product at {@link Product} object to associate with the given action. Must not be null. - * - * + * @param product at {@link Product} object to associate with the given action. Must not be null. * @see Product#CLICK * @see Product#DETAIL * @see Product#CHECKOUT @@ -538,7 +524,6 @@ public static class Builder { * @see Product#CHECKOUT * @see Product#CHECKOUT_OPTION * @see Product#PURCHASE - * */ public Builder(@NonNull @Product.ProductConstant String productAction, Product product) { mProductAction = productAction; @@ -550,8 +535,7 @@ public Builder(@NonNull @Product.ProductConstant String productAction, Product p * Constructor for a {@link Promotion}-based CommerceEvent. * * @param promotionAction a String representing the action that use user performed. This must be on the String constants defined by the {@link Promotion} class. Must not be null. - * @param promotion at least 1 {@link Promotion} object to associate with the given action. Must not be null. - * + * @param promotion at least 1 {@link Promotion} object to associate with the given action. Must not be null. * @see Promotion#CLICK * @see Promotion#VIEW */ @@ -698,7 +682,7 @@ public Builder customAttributes(@Nullable Map attributes) { * Add a custom flag to this event. Flag keys can have multiple values - if the provided flag key already has an associated * value, the value will be appended. * - * @param key (required) a flag key, retrieve this from the mParticle docs or solution team for your intended services(s) + * @param key (required) a flag key, retrieve this from the mParticle docs or solution team for your intended services(s) * @param value (required) a flag value to be send to the service indicated by the flag key * @return returns this builder for easy method chaining */ @@ -779,7 +763,6 @@ public Builder addImpression(@NonNull Impression impression) { /** * Set custom options to be associated with the event. Should be used with the {@link Product#CHECKOUT} and {@link Product#CHECKOUT_OPTION} actions. * - * * @param options a String describing this checkout step * @return returns this Builder for easy method chaining. */ @@ -796,7 +779,6 @@ public Builder checkoutOptions(@Nullable String options) { * {@link Product} objects with {@link Promotion} objects. When in {@link com.mparticle.MParticle.Environment#Production} mode, errors will be logged to the console. * * @return returns the resulting immutable CommerceEvent to be logged - * * @see MParticle.logEvent(com.mparticle.commerce.CommerceEvent) */ @NonNull @@ -866,7 +848,6 @@ public Builder promotions(@NonNull List promotions) { /** * Private API used internally by the SDK. - * */ @NonNull public Builder internalEventName(@Nullable String eventName) { diff --git a/android-core/src/main/java/com/mparticle/commerce/Impression.java b/android-core/src/main/java/com/mparticle/commerce/Impression.java index 8f3c98a5c..61c754784 100644 --- a/android-core/src/main/java/com/mparticle/commerce/Impression.java +++ b/android-core/src/main/java/com/mparticle/commerce/Impression.java @@ -7,7 +7,6 @@ /** * Class representing an impression of one of more {@link Product} objects. - * */ public class Impression { private String mListName = null; @@ -17,7 +16,7 @@ public class Impression { * Create an Impression object. * * @param listName a string name given to the list where the given Products displayed - * @param product a Product to associate with the Impression + * @param product a Product to associate with the Impression */ public Impression(@NonNull String listName, @NonNull Product product) { super(); diff --git a/android-core/src/main/java/com/mparticle/commerce/Product.java b/android-core/src/main/java/com/mparticle/commerce/Product.java index 10827aaed..a0ca01d64 100644 --- a/android-core/src/main/java/com/mparticle/commerce/Product.java +++ b/android-core/src/main/java/com/mparticle/commerce/Product.java @@ -22,24 +22,34 @@ * The Product class is built to be immutable - use the {@link com.mparticle.commerce.Product.Builder} class to create a Product. * * Product objects are designed to be used with {@link CommerceEvent}. - * */ public final class Product { @Retention(RetentionPolicy.CLASS) @StringDef({ADD_TO_CART, REMOVE_FROM_CART, ADD_TO_WISHLIST, REMOVE_FROM_WISHLIST, CHECKOUT, CLICK, DETAIL, PURCHASE, REFUND, CHECKOUT_OPTION}) - @interface ProductConstant{} - - @NonNull public static final String ADD_TO_CART = "add_to_cart"; - @NonNull public static final String REMOVE_FROM_CART = "remove_from_cart"; - @NonNull public static final String ADD_TO_WISHLIST = "add_to_wishlist"; - @NonNull public static final String REMOVE_FROM_WISHLIST = "remove_from_wishlist"; - @NonNull public static final String CHECKOUT = "checkout"; - @NonNull public static final String CLICK = "click"; - @NonNull public static final String DETAIL = "view_detail"; - @NonNull public static final String PURCHASE = "purchase"; - @NonNull public static final String REFUND = "refund"; - @NonNull public static final String CHECKOUT_OPTION = "checkout_option"; + @interface ProductConstant { + } + + @NonNull + public static final String ADD_TO_CART = "add_to_cart"; + @NonNull + public static final String REMOVE_FROM_CART = "remove_from_cart"; + @NonNull + public static final String ADD_TO_WISHLIST = "add_to_wishlist"; + @NonNull + public static final String REMOVE_FROM_WISHLIST = "remove_from_wishlist"; + @NonNull + public static final String CHECKOUT = "checkout"; + @NonNull + public static final String CLICK = "click"; + @NonNull + public static final String DETAIL = "view_detail"; + @NonNull + public static final String PURCHASE = "purchase"; + @NonNull + public static final String REFUND = "refund"; + @NonNull + public static final String CHECKOUT_OPTION = "checkout_option"; private static EqualityComparator mComparator = new DefaultComparator(); private Map mCustomAttributes; private String mName = null; @@ -54,11 +64,7 @@ public final class Product { private String mVariant; /** - * - * * @return Retrieve the Map of custom attributes set on this Product - * - * * @see com.mparticle.commerce.Product.Builder#customAttributes(Map) */ @Nullable @@ -125,7 +131,6 @@ void updateTimeAdded() { } /** - * * @return the name description of the Product */ @NonNull @@ -134,7 +139,6 @@ public String getName() { } /** - * * @return the category description of the Product */ @Nullable @@ -143,8 +147,6 @@ public String getCategory() { } /** - * - * * @return the coupon code associated with the Product */ @Nullable @@ -153,7 +155,6 @@ public String getCouponCode() { } /** - * * @return the SKU/ID associated with the Product */ @NonNull @@ -162,7 +163,6 @@ public String getSku() { } /** - * * @return the position of the product on the page/product impression list */ @Nullable @@ -171,7 +171,6 @@ public Integer getPosition() { } /** - * * @return the unit price of a single Product */ public double getUnitPrice() { @@ -179,7 +178,6 @@ public double getUnitPrice() { } /** - * * @return the quantity of Products */ public double getQuantity() { @@ -209,7 +207,6 @@ public boolean equals(@Nullable Object object) { } /** - * * @return the brand of the Product */ @Nullable @@ -218,8 +215,6 @@ public String getBrand() { } /** - * - * * @return the variant or version of the Product */ @Nullable @@ -343,7 +338,6 @@ public boolean equals(@Nullable Product product1, @Nullable Product product2) { /** * This class is designed to construct a Product object using the Builder pattern. - * */ public static class Builder { private String mName = null; @@ -365,8 +359,8 @@ public static class Builder { * Create a Product.Builder. The parameters of this method are all * required for a valid product. * - * @param name a description/name for the Product - * @param sku a SKU or ID that uniquely identifies this Product + * @param name a description/name for the Product + * @param sku a SKU or ID that uniquely identifies this Product * @param unitPrice the cost of a single Product */ public Builder(@NonNull String name, @NonNull String sku, double unitPrice) { @@ -424,7 +418,6 @@ public Builder category(@Nullable String category) { } /** - * * Sets the coupon code to associate with this Product. * * @param couponCode the Product's coupon code diff --git a/android-core/src/main/java/com/mparticle/commerce/Promotion.java b/android-core/src/main/java/com/mparticle/commerce/Promotion.java index dd38de6ff..431d151b1 100644 --- a/android-core/src/main/java/com/mparticle/commerce/Promotion.java +++ b/android-core/src/main/java/com/mparticle/commerce/Promotion.java @@ -36,18 +36,19 @@ public class Promotion { @Retention(RetentionPolicy.CLASS) @StringDef({CLICK, VIEW}) - @interface PromotionConstant {} + @interface PromotionConstant { + } /** * The Promotion action constant used to track when a user taps or clicks on a Promotion. - * */ - @NonNull public static final String CLICK = "click"; + @NonNull + public static final String CLICK = "click"; /** * The Promotion action constant used to track when a user views a Promotion. - * */ - @NonNull public static final String VIEW = "view"; + @NonNull + public static final String VIEW = "view"; private String mCreative = null; private String mId = null; diff --git a/android-core/src/main/java/com/mparticle/commerce/TransactionAttributes.java b/android-core/src/main/java/com/mparticle/commerce/TransactionAttributes.java index c764500ef..351601963 100644 --- a/android-core/src/main/java/com/mparticle/commerce/TransactionAttributes.java +++ b/android-core/src/main/java/com/mparticle/commerce/TransactionAttributes.java @@ -6,7 +6,6 @@ /** * Class encaspulating the parameters of a given Product CommerceEvent. - * */ public class TransactionAttributes { private String mAffiliation = null; @@ -34,7 +33,6 @@ public String getId() { * Create a TransactionAttributes object to be associated with a {@link CommerceEvent}. * * Note that transaction ID is required for {@link Product#PURCHASE} and {@link Product#REFUND} events. - * */ public TransactionAttributes() { super(); diff --git a/android-core/src/main/java/com/mparticle/commerce/package-info.java b/android-core/src/main/java/com/mparticle/commerce/package-info.java index fcd4c94cc..29df67b9a 100644 --- a/android-core/src/main/java/com/mparticle/commerce/package-info.java +++ b/android-core/src/main/java/com/mparticle/commerce/package-info.java @@ -1,6 +1,4 @@ /** - * * Package containing the mParticle eCommerce APIs. - * */ package com.mparticle.commerce; \ No newline at end of file diff --git a/android-core/src/main/java/com/mparticle/consent/CCPAConsent.java b/android-core/src/main/java/com/mparticle/consent/CCPAConsent.java index 046aba009..c40240a9e 100644 --- a/android-core/src/main/java/com/mparticle/consent/CCPAConsent.java +++ b/android-core/src/main/java/com/mparticle/consent/CCPAConsent.java @@ -13,7 +13,8 @@ */ public class CCPAConsent extends ConsentInstance { - private CCPAConsent() { } + private CCPAConsent() { + } private CCPAConsent(Builder builder) { if (builder.mTimestamp == null) { diff --git a/android-core/src/main/java/com/mparticle/consent/GDPRConsent.java b/android-core/src/main/java/com/mparticle/consent/GDPRConsent.java index 7e1cb6272..adfe42180 100644 --- a/android-core/src/main/java/com/mparticle/consent/GDPRConsent.java +++ b/android-core/src/main/java/com/mparticle/consent/GDPRConsent.java @@ -13,7 +13,8 @@ */ public final class GDPRConsent extends ConsentInstance { - private GDPRConsent() {} + private GDPRConsent() { + } private GDPRConsent(GDPRConsent.Builder builder) { if (builder.mTimestamp == null) { diff --git a/android-core/src/main/java/com/mparticle/consent/package-info.java b/android-core/src/main/java/com/mparticle/consent/package-info.java index b6ca1b335..12d5ff9af 100644 --- a/android-core/src/main/java/com/mparticle/consent/package-info.java +++ b/android-core/src/main/java/com/mparticle/consent/package-info.java @@ -1,6 +1,4 @@ /** - * * Package containing the mParticle SDK Consent and GDPR APIs. - * */ package com.mparticle.consent; \ No newline at end of file diff --git a/android-core/src/main/java/com/mparticle/identity/AliasRequest.java b/android-core/src/main/java/com/mparticle/identity/AliasRequest.java index ee11417ae..0748df529 100644 --- a/android-core/src/main/java/com/mparticle/identity/AliasRequest.java +++ b/android-core/src/main/java/com/mparticle/identity/AliasRequest.java @@ -47,6 +47,7 @@ public long getEndTime() { /** * Create an empty {@link AliasRequest.Builder} instance + * * @return */ public static Builder builder() { @@ -63,7 +64,7 @@ public static Builder builder() { * after applying this adjustment it will be impossible to create an aliasRequest passes the aliasUsers() * validation that the startTime must be less than the endTime * - * @param sourceUser the user which is to be "copied" over + * @param sourceUser the user which is to be "copied" over * @param destinationUser the user which the sourceUser will be "copied" onto */ public static Builder builder(@NonNull MParticleUser sourceUser, @NonNull MParticleUser destinationUser) { @@ -78,7 +79,7 @@ public static Builder builder(@NonNull MParticleUser sourceUser, @NonNull MParti @Override public boolean equals(Object obj) { if (obj instanceof AliasRequest) { - AliasRequest request = ((AliasRequest)obj); + AliasRequest request = ((AliasRequest) obj); return request.getEndTime() == getEndTime() && request.getStartTime() == getStartTime() && request.getSourceMpid() == getSourceMpid() && @@ -103,6 +104,7 @@ public static class Builder { /** * set the user which the sourceUser will be "copied" onto + * * @param mpid the destination user's mpid * @return */ @@ -113,6 +115,7 @@ public Builder destinationMpid(long mpid) { /** * set the mpid of the user which is to be "copied" over + * * @return the source user's mpid */ public Builder sourceMpid(long mpid) { @@ -122,6 +125,7 @@ public Builder sourceMpid(long mpid) { /** * set a time indicating the beginning of the window of activity which should be aliased + * * @param startTime the time, in milliseconds * @return */ @@ -133,6 +137,7 @@ public Builder startTime(long startTime) { /** * set a time indicating the end of the window of activity which should be aliased + * * @param endTime the time, in milliseconds */ public Builder endTime(long endTime) { @@ -147,6 +152,7 @@ private Builder implicitStartTime(boolean implicitStartTime) { /** * build the {@link AliasRequest.Builder} into an immutable {@link AliasRequest} + * * @return */ public AliasRequest build() { diff --git a/android-core/src/main/java/com/mparticle/identity/AliasResponse.java b/android-core/src/main/java/com/mparticle/identity/AliasResponse.java index 70dd461de..7cef3b4ae 100644 --- a/android-core/src/main/java/com/mparticle/identity/AliasResponse.java +++ b/android-core/src/main/java/com/mparticle/identity/AliasResponse.java @@ -27,6 +27,7 @@ public AliasResponse(@NonNull MParticleApiClient.AliasNetworkResponse response, /** * The HTTP response code for the Alias network request + * * @return */ public int getResponseCode() { @@ -35,6 +36,7 @@ public int getResponseCode() { /** * The internal ID for the Alias request. Each {@link AliasRequest} has a unique, consistent request id + * * @return */ @NonNull @@ -45,6 +47,7 @@ public String getRequestId() { /** * A copy of the {@link AliasRequest} object passed into {@link IdentityApi#aliasUsers(AliasRequest)} * that this {@link AliasResponse} is describing + * * @return */ @NonNull @@ -54,6 +57,7 @@ public AliasRequest getRequest() { /** * Whether or not the request was successful + * * @return */ public boolean isSuccessful() { @@ -65,6 +69,7 @@ public boolean isSuccessful() { * indicate that any action needs to be taken. Requests that result in recoverable errors, such as * rate limiting server error will be retried, while authentication errors, malformed requests and * others will not be retried + * * @return */ public boolean willRetry() { @@ -73,6 +78,7 @@ public boolean willRetry() { /** * The error response message returned by the server, if there was one + * * @return */ @Nullable diff --git a/android-core/src/main/java/com/mparticle/identity/BaseIdentityTask.java b/android-core/src/main/java/com/mparticle/identity/BaseIdentityTask.java index 38b910ea2..075871168 100644 --- a/android-core/src/main/java/com/mparticle/identity/BaseIdentityTask.java +++ b/android-core/src/main/java/com/mparticle/identity/BaseIdentityTask.java @@ -2,6 +2,7 @@ import android.os.Handler; import android.os.Looper; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -23,7 +24,7 @@ public void setFailed(@Nullable final IdentityHttpResponse errorResponse) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { - for(TaskFailureListener listener: failureListeners) { + for (TaskFailureListener listener : failureListeners) { listener.onFailure(errorResponse); } } @@ -38,7 +39,7 @@ public void setSuccessful(@NonNull final IdentityApiResult result) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { - for (TaskSuccessListener listener: successListeners) { + for (TaskSuccessListener listener : successListeners) { listener.onSuccess(result); } } diff --git a/android-core/src/main/java/com/mparticle/identity/IdentityApi.java b/android-core/src/main/java/com/mparticle/identity/IdentityApi.java index 7633a12ee..b7348845f 100644 --- a/android-core/src/main/java/com/mparticle/identity/IdentityApi.java +++ b/android-core/src/main/java/com/mparticle/identity/IdentityApi.java @@ -4,13 +4,13 @@ import android.content.Context; import android.os.Handler; import android.os.Looper; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.mparticle.MParticle; import com.mparticle.MParticleTask; import com.mparticle.SdkListener; -import com.mparticle.internal.listeners.ApiClass; import com.mparticle.internal.AppStateManager; import com.mparticle.internal.BaseHandler; import com.mparticle.internal.ConfigManager; @@ -19,6 +19,7 @@ import com.mparticle.internal.Logger; import com.mparticle.internal.MPUtility; import com.mparticle.internal.MessageManager; +import com.mparticle.internal.listeners.ApiClass; import java.util.ArrayList; import java.util.Collections; @@ -52,7 +53,8 @@ public class IdentityApi { Set identityStateListeners = new HashSet(); private static Object lock = new Object(); - protected IdentityApi() {} + protected IdentityApi() { + } @SuppressLint("UnknownNullness") public IdentityApi(Context context, AppStateManager appStateManager, MessageManager messageManager, ConfigManager configManager, KitManager kitManager, MParticle.OperatingSystem operatingSystem) { @@ -91,9 +93,9 @@ public MParticleUser getCurrentUser() { */ @Nullable public MParticleUser getUser(@NonNull Long mpid) { - if (!Constants.TEMPORARY_MPID.equals(mpid) && mConfigManager.mpidExists(mpid)) { - return MParticleUserImpl.getInstance(mContext, mpid, mUserDelegate); - } else { + if (!Constants.TEMPORARY_MPID.equals(mpid) && mConfigManager.mpidExists(mpid)) { + return MParticleUserImpl.getInstance(mContext, mpid, mUserDelegate); + } else { return null; } } @@ -101,6 +103,7 @@ public MParticleUser getUser(@NonNull Long mpid) { /** * returns a list of {@link MParticleUser}s that have been seen by this device. The collection * is ordered by {@link MParticleUser#getLastSeenTime()}, from most to least recent + * * @return a collection of {@link MParticleUser} ordered by descending {@link MParticleUser#getLastSeenTime()} */ @NonNull @@ -108,7 +111,7 @@ public List getUsers() { List users = new ArrayList(); Set mpids = mConfigManager.getMpids(); mpids.remove(Constants.TEMPORARY_MPID); - for (Long mpid: mpids) { + for (Long mpid : mpids) { users.add(MParticleUserImpl.getInstance(mContext, mpid, mUserDelegate)); } sortUsers(users); @@ -122,8 +125,8 @@ public String getDeviceApplicationStamp() { /** * Adds a global listener which will be invoked when the MPID or "logged in" status changes for the current user. - * @param listener callback for Identity State changes * + * @param listener callback for Identity State changes * @see IdentityStateListener */ public void addIdentityStateListener(@NonNull IdentityStateListener listener) { @@ -132,8 +135,8 @@ public void addIdentityStateListener(@NonNull IdentityStateListener listener) { /** * Removes an instance of a global listener by reference. - * @param listener callback for Identity State changes * + * @param listener callback for Identity State changes * @see IdentityStateListener */ public void removeIdentityStateListener(@NonNull IdentityStateListener listener) { @@ -144,7 +147,6 @@ public void removeIdentityStateListener(@NonNull IdentityStateListener listener) * Calls the Identity Logout endpoint with an empty IdentityApiRequest. * * @return an MParticleTask to handle the Asynchronous results - * * @see MParticleTask and * @see IdentityApiResult */ @@ -154,12 +156,10 @@ public MParticleTask logout() { } /** + * @return an MParticleTask to handle the Asynchronous results * @see IdentityApiRequest * * calls the Identity Logout endpoint - * - * @return an MParticleTask to handle the Asynchronous results - * * @see MParticleTask and * @see IdentityApiResult */ @@ -182,7 +182,6 @@ public void onPostExecute(IdentityApiResult result) { * Calls the Identity Login endpoint with an empty IdentityApiRequest. * * @return an MParticleTask to handle the Asynchronous results - * * @see MParticleTask and * @see IdentityApiResult */ @@ -193,11 +192,9 @@ public MParticleTask login() { /** * Calls the Identity Login endpoint. - * @see IdentityApiRequest - * * * @return an MParticleTask to handle the Asynchronous results - * + * @see IdentityApiRequest * @see MParticleTask and * @see IdentityApiResult */ @@ -218,11 +215,9 @@ public void onPostExecute(IdentityApiResult result) { /** * Calls the Identity Identify endpoint. - * @see IdentityApiRequest - * * * @return an MParticleTask to handle the Asynchronous results - * + * @see IdentityApiRequest * @see MParticleTask and * @see IdentityApiResult */ @@ -244,12 +239,9 @@ public void onPostExecute(IdentityApiResult result) { /** * Calls the Identity Modify endpoint. This should be used in place of the pre-version-5 * MParticle.setUserAttribute() and MParticle.setUserIdentity() methods. - * - * @see IdentityApiRequest - * * * @return an MParticleTask to handle the Asynchronous results - * + * @see IdentityApiRequest * @see BaseIdentityTask */ @NonNull @@ -299,6 +291,7 @@ public void run() { * Initiate an Alias request. Retries are handled internally, so one an {@link AliasRequest} is submitted, * it will be retried unless there are unrecoverable errors. To listen for updates submit an * implementation of {@link com.mparticle.SdkListener} to {@link com.mparticle.MParticle#addListener(Context, SdkListener)} + * * @param aliasRequest * @return */ @@ -416,6 +409,7 @@ void setApiClient(MParticleIdentityClient client) { interface IdentityNetworkRequestRunnable { IdentityHttpResponse request(IdentityApiRequest request) throws Exception; + void onPostExecute(IdentityApiResult result); } diff --git a/android-core/src/main/java/com/mparticle/identity/IdentityApiRequest.java b/android-core/src/main/java/com/mparticle/identity/IdentityApiRequest.java index 3117131ee..1a8c42cdc 100644 --- a/android-core/src/main/java/com/mparticle/identity/IdentityApiRequest.java +++ b/android-core/src/main/java/com/mparticle/identity/IdentityApiRequest.java @@ -20,7 +20,6 @@ * @see IdentityApi#logout(IdentityApiRequest) * @see IdentityApi#identify(IdentityApiRequest) * @see IdentityApi#modify(IdentityApiRequest) - * */ public final class IdentityApiRequest { private UserAliasHandler userAliasHandler = null; @@ -31,7 +30,7 @@ public final class IdentityApiRequest { Long mpid; private IdentityApiRequest(IdentityApiRequest.Builder builder) { - if (builder.userIdentities != null){ + if (builder.userIdentities != null) { this.userIdentities = builder.userIdentities; } if (builder.userAliasHandler != null) { @@ -49,8 +48,7 @@ private IdentityApiRequest(IdentityApiRequest.Builder builder) { /** * Instantiate an IdentityApiRequest.Builder() with no existing state (no UserIdentities). * - * @return an IdentityApiRequest.Builder - * + * @return an IdentityApiRequest.Builder * @see IdentityApiRequest.Builder */ @NonNull @@ -62,9 +60,7 @@ public static Builder withEmptyUser() { * instantiate an IdentityApiRequest.Builder() with an existing user's UserIdentities. * * @param currentUser an MParticleUser - * * @return an IdentityApiRequest.Builder - * * @see IdentityApiRequest.Builder */ @NonNull @@ -117,7 +113,6 @@ protected Builder() { * Set the IdentityType MParticle.IdentityType.Email. * * @param email the email to be set - * * @return the instance of the builder, for chaining calls */ @NonNull @@ -129,7 +124,6 @@ public Builder email(@Nullable String email) { * Set the IdentityType MParticle.IdentityType.CustomerId. * * @param customerId the customerId to be set - * * @return the instance of the builder, for chaining calls */ @NonNull @@ -160,11 +154,9 @@ protected Builder googleAdId(@Nullable String newGoogleAdId, @Nullable String ol /** * Set the value for the provided IdentityType key. * - * @param identityType the IdentityType to be set + * @param identityType the IdentityType to be set * @param identityValue the value the IdentityType should be set to - * * @return the instance of the builder, for chaining calls - * * @see MParticle.IdentityType */ @NonNull @@ -180,14 +172,12 @@ public Builder userIdentity(@NonNull MParticle.IdentityType identityType, @Nulla * Set IdentityTypes in bulk. * * @param userIdentities the IdentityTypes to be set - * * @return the instance of the builder, for chaining calls - * * @see MParticle.IdentityType */ @NonNull public Builder userIdentities(@NonNull Map userIdentities) { - for (Map.Entry entry: userIdentities.entrySet()) { + for (Map.Entry entry : userIdentities.entrySet()) { userIdentity(entry.getKey(), entry.getValue()); } return this; @@ -210,6 +200,7 @@ public IdentityApiRequest build() { * in you {@link UserAliasHandler}, using the {@link MParticleUser}s returned by * {@link IdentityApiResult#getUser()} and {@link IdentityApiResult#getPreviousUser()} in place * of "newUser" and "previousUser" respectively + * * @param userAliasHandler * @return */ diff --git a/android-core/src/main/java/com/mparticle/identity/IdentityApiResult.java b/android-core/src/main/java/com/mparticle/identity/IdentityApiResult.java index a96c040ec..60134fc49 100644 --- a/android-core/src/main/java/com/mparticle/identity/IdentityApiResult.java +++ b/android-core/src/main/java/com/mparticle/identity/IdentityApiResult.java @@ -17,6 +17,7 @@ public IdentityApiResult(@NonNull MParticleUser user, @Nullable MParticleUser pr /** * Query the User which was returned by the IdentityApi request + * * @return the User */ @NonNull @@ -27,6 +28,7 @@ public MParticleUser getUser() { /** * The User which is being replaced, if the IdentityApi call this instance is describing, resulted * in a new {@link IdentityApi#getCurrentUser()}, otherwise 'null' + * * @return */ @Nullable diff --git a/android-core/src/main/java/com/mparticle/identity/IdentityHttpResponse.java b/android-core/src/main/java/com/mparticle/identity/IdentityHttpResponse.java index f1d20b675..00ca54d5a 100644 --- a/android-core/src/main/java/com/mparticle/identity/IdentityHttpResponse.java +++ b/android-core/src/main/java/com/mparticle/identity/IdentityHttpResponse.java @@ -19,16 +19,24 @@ public final class IdentityHttpResponse { private int httpCode; private boolean loggedIn; - @NonNull public static final String MPID = "mpid"; - @NonNull public static final String CONTEXT = "context"; - @NonNull public static final String ERRORS = "errors"; - @NonNull public static final String LOGGED_IN = "is_logged_in"; - @NonNull public static final String CODE = "code"; - @NonNull public static final String MESSAGE = "message"; + @NonNull + public static final String MPID = "mpid"; + @NonNull + public static final String CONTEXT = "context"; + @NonNull + public static final String ERRORS = "errors"; + @NonNull + public static final String LOGGED_IN = "is_logged_in"; + @NonNull + public static final String CODE = "code"; + @NonNull + public static final String MESSAGE = "message"; - @NonNull public static final String UNKNOWN = "UNKNOWN"; + @NonNull + public static final String UNKNOWN = "UNKNOWN"; - private IdentityHttpResponse() {} + private IdentityHttpResponse() { + } public IdentityHttpResponse(int code, long mpid, @Nullable String context, @Nullable ArrayList errors) { this.httpCode = code; @@ -98,8 +106,10 @@ public boolean isLoggedIn() { } public static class Error { - @NonNull public final String message; - @NonNull public final String code; + @NonNull + public final String message; + @NonNull + public final String code; public Error(@NonNull String errorCode, @NonNull String message) { this.code = errorCode; diff --git a/android-core/src/main/java/com/mparticle/identity/IdentityStateListener.java b/android-core/src/main/java/com/mparticle/identity/IdentityStateListener.java index 0abdcbf90..32de15817 100644 --- a/android-core/src/main/java/com/mparticle/identity/IdentityStateListener.java +++ b/android-core/src/main/java/com/mparticle/identity/IdentityStateListener.java @@ -5,7 +5,6 @@ import androidx.annotation.Nullable; /** - * * The IdentityStateListener is a callback which will be invoked when either a new user is identified, * or the current user's "logged in" status changes. The "user" received in the onUserIdentified() implementation * is the new current user and should be equal, although not referentially. The "previousUser" parameter refers diff --git a/android-core/src/main/java/com/mparticle/identity/MParticleIdentityClient.java b/android-core/src/main/java/com/mparticle/identity/MParticleIdentityClient.java index fccff789e..4004dc5d7 100644 --- a/android-core/src/main/java/com/mparticle/identity/MParticleIdentityClient.java +++ b/android-core/src/main/java/com/mparticle/identity/MParticleIdentityClient.java @@ -2,9 +2,12 @@ import com.mparticle.networking.MParticleBaseClient; -public interface MParticleIdentityClient extends MParticleBaseClient{ +public interface MParticleIdentityClient extends MParticleBaseClient { IdentityHttpResponse login(IdentityApiRequest request) throws Exception; + IdentityHttpResponse logout(IdentityApiRequest request) throws Exception; + IdentityHttpResponse identify(IdentityApiRequest request) throws Exception; + IdentityHttpResponse modify(IdentityApiRequest request) throws Exception; } diff --git a/android-core/src/main/java/com/mparticle/identity/MParticleIdentityClientImpl.java b/android-core/src/main/java/com/mparticle/identity/MParticleIdentityClientImpl.java index 39ce823d6..06117fe7f 100644 --- a/android-core/src/main/java/com/mparticle/identity/MParticleIdentityClientImpl.java +++ b/android-core/src/main/java/com/mparticle/identity/MParticleIdentityClientImpl.java @@ -208,7 +208,7 @@ private JSONObject getChangeJson(IdentityApiRequest request) throws JSONExceptio Set identityTypes = new HashSet(userIdentities.keySet()); identityTypes.addAll(userIdentities.keySet()); - for (MParticle.IdentityType identityType: identityTypes) { + for (MParticle.IdentityType identityType : identityTypes) { String idTypeString = getStringValue(identityType); if (!MPUtility.isEmpty(idTypeString)) { JSONObject changeJson = new JSONObject(); @@ -222,7 +222,7 @@ private JSONObject getChangeJson(IdentityApiRequest request) throws JSONExceptio } } } - for (Map.Entry otherIdentities: request.getOtherNewIdentities().entrySet()) { + for (Map.Entry otherIdentities : request.getOtherNewIdentities().entrySet()) { String identityType = otherIdentities.getKey(); String newValue = otherIdentities.getValue(); String oldValue = request.getOtherOldIdentities().get(identityType); @@ -286,7 +286,6 @@ private MPConnection getPostConnection(String endpoint, String message) throws I } - MPUrl getUrl(long mpId, String endpoint) throws MalformedURLException { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(mpId); diff --git a/android-core/src/main/java/com/mparticle/identity/MParticleUser.java b/android-core/src/main/java/com/mparticle/identity/MParticleUser.java index cc243bb49..9e76802e3 100644 --- a/android-core/src/main/java/com/mparticle/identity/MParticleUser.java +++ b/android-core/src/main/java/com/mparticle/identity/MParticleUser.java @@ -33,7 +33,6 @@ public interface MParticleUser { * query the attributes of the User asynchronously * * @param listener a callback for querying User's attributes - * * @return */ @Nullable @@ -43,7 +42,6 @@ public interface MParticleUser { * assign attributes to the User in bulk * * @param userAttributes the attributes to be set - * * @return whether the attributes were successfully set */ boolean setUserAttributes(@NonNull Map userAttributes); @@ -52,7 +50,6 @@ public interface MParticleUser { * query the Identities of the User * * @return the User's Identities - * */ @NonNull Map getUserIdentities(); @@ -60,9 +57,8 @@ public interface MParticleUser { /** * set a single attribute for the user * - * @param key the key of the attribute + * @param key the key of the attribute * @param value the value of the attribute - * * @return whether the attributes were successfully set */ boolean setUserAttribute(@NonNull String key, @NonNull Object value); @@ -70,9 +66,8 @@ public interface MParticleUser { /** * set a single attribute for the user whose value is an Object, not just a String * - * @param key the key of the attribute + * @param key the key of the attribute * @param value the value of the attribute - * * @return whether the attributes were successfully set */ boolean setUserAttributeList(@NonNull String key, @NonNull Object value); @@ -80,9 +75,8 @@ public interface MParticleUser { /** * increment an attribute for the user * - * @param key the key of the attribute + * @param key the key of the attribute * @param value the value of the attribute - * * @return whether the attributes were successfully set */ boolean incrementUserAttribute(@NonNull String key, Number value); @@ -91,7 +85,6 @@ public interface MParticleUser { * remove an attribute for the user * * @param key the key of the attribute which is to be removed - * * @return whether the attributes were successfully removed */ boolean removeUserAttribute(@NonNull String key); @@ -100,7 +93,6 @@ public interface MParticleUser { * set a tag for a User. A tag is represented by a key and a value of "null" * * @param tag the tag to be set for the user - * * @return whether the tag was successfully set */ boolean setUserTag(@NonNull String tag); @@ -125,12 +117,14 @@ public interface MParticleUser { /** * The timestamp representing the first time this user was observed on this device + * * @return */ long getFirstSeenTime(); /** * The timestamp representing the last time this user was the "currentUser" on this device + * * @return the time, in milliseconds */ long getLastSeenTime(); diff --git a/android-core/src/main/java/com/mparticle/identity/MParticleUserDelegate.java b/android-core/src/main/java/com/mparticle/identity/MParticleUserDelegate.java index 16e1359c8..87ba0a64d 100644 --- a/android-core/src/main/java/com/mparticle/identity/MParticleUserDelegate.java +++ b/android-core/src/main/java/com/mparticle/identity/MParticleUserDelegate.java @@ -21,14 +21,14 @@ import org.json.JSONException; import org.json.JSONObject; -import java.text.NumberFormat; -import java.text.ParseException; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; import java.util.Map; -/** package-private **/class MParticleUserDelegate { +/** + * package-private + **/ +class MParticleUserDelegate { private AppStateManager mAppStateManager; private ConfigManager mConfigManager; private MessageManager mMessageManager; @@ -49,7 +49,7 @@ public Map getUserAttributes(final UserAttributeListenerType lis return mMessageManager.getUserAttributes(new UserAttributeListenerWrapper(listener), mpId); } - public Map getUserIdentities(long mpId){ + public Map getUserIdentities(long mpId) { return mMessageManager.getUserIdentities(mpId); } @@ -139,7 +139,6 @@ public boolean setUserAttribute(String key, Object value, long userMpId) { * setUserAttributes is an asynchronous method, and should normally be run as such. In certain * cases, like when an IdentityApiRequest has copyUserAttributes set to true, we need to set the * user attributes on the new user synchronously, and only then should we use this flag - * */ boolean setUserAttribute(String key, Object value, long userMpId, boolean synchronously) { if (mConfigManager.isEnabled()) { @@ -162,7 +161,7 @@ boolean setUserAttribute(String key, Object value, long userMpId, boolean synchr for (int i = 0; i < values.size(); i++) { totalLength += values.get(i).toString().length(); if (totalLength > Constants.LIMIT_ATTR_VALUE) { - Logger.warning("Error while setting user attribute - attribute lists cannot contain values of combined length greater than " + Constants.LIMIT_ATTR_VALUE + " characters. Attribute not set." ); + Logger.warning("Error while setting user attribute - attribute lists cannot contain values of combined length greater than " + Constants.LIMIT_ATTR_VALUE + " characters. Attribute not set."); return false; } else { clonedList.add(values.get(i).toString()); @@ -270,7 +269,7 @@ boolean setUser(Context context, long previousMpid, long newMpid, Map getUserAttributes() { * Query the attributes of the User asynchronously. * * @param listener a callback for querying User's attributes - * * @return */ public Map getUserAttributes(final UserAttributeListenerType listener) { @@ -59,7 +60,7 @@ public boolean setUserAttributes(Map userAttributes) { if (userAttributes == null) { return false; } - for(Map.Entry entry: userAttributes.entrySet()) { + for (Map.Entry entry : userAttributes.entrySet()) { if (!setUserAttribute(entry.getKey(), entry.getValue())) { success = false; } @@ -76,7 +77,7 @@ void setUserIdentities(Map userIdentities) { if (userIdentities == null) { return; } - for(Map.Entry entry: userIdentities.entrySet()) { + for (Map.Entry entry : userIdentities.entrySet()) { mUserDelegate.setUserIdentity(entry.getValue(), entry.getKey(), getId()); } } diff --git a/android-core/src/main/java/com/mparticle/identity/UserAliasHandler.java b/android-core/src/main/java/com/mparticle/identity/UserAliasHandler.java index d5787a721..67e59e0ec 100644 --- a/android-core/src/main/java/com/mparticle/identity/UserAliasHandler.java +++ b/android-core/src/main/java/com/mparticle/identity/UserAliasHandler.java @@ -16,8 +16,9 @@ public interface UserAliasHandler { /** * A handler for when Users change. Any carry-over in state between an outgoing user and an incoming user, should take place here. + * * @param previousUser the outgoing User - * @param newUser the incoming User + * @param newUser the incoming User */ void onUserAlias(@NonNull MParticleUser previousUser, @NonNull MParticleUser newUser); } diff --git a/android-core/src/main/java/com/mparticle/identity/package-info.java b/android-core/src/main/java/com/mparticle/identity/package-info.java index 69b3e9f74..8477d4dbc 100644 --- a/android-core/src/main/java/com/mparticle/identity/package-info.java +++ b/android-core/src/main/java/com/mparticle/identity/package-info.java @@ -1,6 +1,4 @@ /** - * * Package containing the mParticle SDK IDSync APIs. - * */ package com.mparticle.identity; \ No newline at end of file diff --git a/android-core/src/main/java/com/mparticle/internal/AppStateManager.java b/android-core/src/main/java/com/mparticle/internal/AppStateManager.java index 639c693f5..9d76d16a8 100644 --- a/android-core/src/main/java/com/mparticle/internal/AppStateManager.java +++ b/android-core/src/main/java/com/mparticle/internal/AppStateManager.java @@ -31,7 +31,7 @@ /** * This class is responsible for maintaining the session state by listening to the Activity lifecycle. */ -public class AppStateManager { +public class AppStateManager { private ConfigManager mConfigManager; Context mContext; @@ -81,7 +81,7 @@ public class AppStateManager { private Uri mLaunchUri; private String mLaunchAction; - public AppStateManager(Context context, boolean unitTesting){ + public AppStateManager(Context context, boolean unitTesting) { mUnitTesting = unitTesting; mContext = context.getApplicationContext(); mLastStoppedTime = new AtomicLong(getTime()); @@ -114,18 +114,18 @@ public Uri getLaunchUri() { return mLaunchUri; } - public void setConfigManager(ConfigManager manager){ + public void setConfigManager(ConfigManager manager) { mConfigManager = manager; } - public void setMessageManager(MessageManager manager){ + public void setMessageManager(MessageManager manager) { mMessageManager = manager; } - private long getTime(){ - if (mUnitTesting){ + private long getTime() { + if (mUnitTesting) { return System.currentTimeMillis(); - }else { + } else { return SystemClock.elapsedRealtime(); } } @@ -146,7 +146,7 @@ public void onActivityResumed(Activity activity) { if (callingApplication != null) { previousSessionPackage = callingApplication.getPackageName(); } - if(activity.getIntent() != null) { + if (activity.getIntent() != null) { previousSessionUri = activity.getIntent().getDataString(); if (mLaunchUri == null) { mLaunchUri = activity.getIntent().getData(); @@ -173,7 +173,7 @@ public void onActivityResumed(Activity activity) { initialize(mCurrentActivityName, previousSessionUri, previousSessionParameters, previousSessionPackage); } else if (isBackgrounded() && mLastStoppedTime.get() > 0) { isBackToForeground = true; - MPUtility.AdIdInfo adIdInfo = MPUtility.getAdIdInfo(mContext); + MPUtility.AdIdInfo adIdInfo = MPUtility.getAdIdInfo(mContext); String currentGoogleAdId = (adIdInfo == null ? null : (adIdInfo.isLimitAdTrackingEnabled ? null : adIdInfo.id)); mMessageManager.postToMessageThread(new CheckAdIdRunnable(currentGoogleAdId, mConfigManager.getPreviousAdId())); logStateTransition(Constants.StateTransitionType.STATE_TRANS_FORE, @@ -205,7 +205,7 @@ public void onActivityResumed(Activity activity) { instance.Internal().getKitManager().onActivityResumed(activity); } } catch (Exception e) { - Logger.verbose("Failed while trying to track activity resume: " + e.getMessage()); + Logger.verbose("Failed while trying to track activity resume: " + e.getMessage()); } } @@ -227,7 +227,7 @@ public void run() { logBackgrounded(); mConfigManager.setPreviousAdId(); } - }catch (Exception e){ + } catch (Exception e) { e.printStackTrace(); } } @@ -244,7 +244,7 @@ public void run() { } instance.Internal().getKitManager().onActivityPaused(activity); } - }catch (Exception e) { + } catch (Exception e) { Logger.verbose("Failed while trying to track activity pause: " + e.getMessage()); } } @@ -257,7 +257,7 @@ public void ensureActiveSession() { session.mLastEventTime = System.currentTimeMillis(); if (!session.isActive()) { newSession(); - }else{ + } else { mMessageManager.updateSessionEnd(getSession()); } } @@ -293,12 +293,12 @@ private void newSession() { checkSessionTimeout(); } - private void enableLocationTracking(){ - if (mPreferences.contains(Constants.PrefKeys.LOCATION_PROVIDER)){ + private void enableLocationTracking() { + if (mPreferences.contains(Constants.PrefKeys.LOCATION_PROVIDER)) { String provider = mPreferences.getString(Constants.PrefKeys.LOCATION_PROVIDER, null); long minTime = mPreferences.getLong(Constants.PrefKeys.LOCATION_MINTIME, 0); long minDistance = mPreferences.getLong(Constants.PrefKeys.LOCATION_MINDISTANCE, 0); - if (provider != null && minTime > 0 && minDistance > 0){ + if (provider != null && minTime > 0 && minDistance > 0) { MParticle instance = MParticle.getInstance(); if (instance != null) { instance.enableLocationTracking(provider, minTime, minDistance); @@ -317,7 +317,7 @@ boolean shouldEndSession() { } private void checkSessionTimeout() { - delayedBackgroundCheckHandler.postDelayed( new Runnable() { + delayedBackgroundCheckHandler.postDelayed(new Runnable() { @Override public void run() { if (shouldEndSession()) { @@ -340,14 +340,14 @@ private void initialize(String currentActivityName, String previousSessionUri, S 0); } - public void onActivityCreated(Activity activity, Bundle savedInstanceState){ + public void onActivityCreated(Activity activity, Bundle savedInstanceState) { MParticle instance = MParticle.getInstance(); if (instance != null) { instance.Internal().getKitManager().onActivityCreated(activity, savedInstanceState); } } - public void onActivityStarted(Activity activity){ + public void onActivityStarted(Activity activity) { MParticle instance = MParticle.getInstance(); if (instance != null) { instance.Internal().getKitManager().onActivityStarted(activity); @@ -361,7 +361,7 @@ public void onActivityStopped(Activity activity) { } } - private void logBackgrounded(){ + private void logBackgrounded() { MParticle instance = MParticle.getInstance(); if (instance != null) { logStateTransition(Constants.StateTransitionType.STATE_TRANS_BG, mCurrentActivityName); @@ -483,6 +483,7 @@ static class Builder extends IdentityApiRequest.Builder { Builder(MParticleUser user) { super(user); } + Builder() { super(); } diff --git a/android-core/src/main/java/com/mparticle/internal/ApplicationContextWrapper.java b/android-core/src/main/java/com/mparticle/internal/ApplicationContextWrapper.java index 14f871651..5cb0cb466 100644 --- a/android-core/src/main/java/com/mparticle/internal/ApplicationContextWrapper.java +++ b/android-core/src/main/java/com/mparticle/internal/ApplicationContextWrapper.java @@ -25,7 +25,9 @@ public class ApplicationContextWrapper extends Application { private boolean mRecord = true; private ActivityLifecycleCallbackRecorder mActivityLifecycleCallbackRecorder; - enum MethodType { ON_CREATED, ON_STARTED, ON_RESUMED, ON_PAUSED, ON_STOPPED, ON_SAVE_INSTANCE_STATE, ON_DESTROYED}; + enum MethodType {ON_CREATED, ON_STARTED, ON_RESUMED, ON_PAUSED, ON_STOPPED, ON_SAVE_INSTANCE_STATE, ON_DESTROYED} + + ; public ApplicationContextWrapper(Application application) { mBaseApplication = application; @@ -42,7 +44,7 @@ public boolean isReplayActivityLifecycle() { return mReplay; } - public void setRecordActivityLifecycle(boolean record){ + public void setRecordActivityLifecycle(boolean record) { if (this.mRecord = record) { startRecordLifecycles(); } else { @@ -257,7 +259,7 @@ public LifeCycleEvent(MethodType methodType, WeakReference activityRef @Override public boolean equals(Object o) { if (o instanceof LifeCycleEvent) { - LifeCycleEvent l = (LifeCycleEvent)o; + LifeCycleEvent l = (LifeCycleEvent) o; boolean matchingActivityRef = false; if (l.activityRef == null && activityRef == null) { matchingActivityRef = true; diff --git a/android-core/src/main/java/com/mparticle/internal/BaseHandler.java b/android-core/src/main/java/com/mparticle/internal/BaseHandler.java index 9bf091f47..455b80630 100644 --- a/android-core/src/main/java/com/mparticle/internal/BaseHandler.java +++ b/android-core/src/main/java/com/mparticle/internal/BaseHandler.java @@ -4,7 +4,6 @@ import android.os.Looper; import android.os.Message; - import com.mparticle.internal.listeners.InternalListenerManager; import java.util.Set; @@ -20,7 +19,8 @@ public Set getMessageQueue() { return messageQueue.keySet(); } - public BaseHandler() {} + public BaseHandler() { + } public BaseHandler(Looper looper) { super(looper); @@ -29,11 +29,11 @@ public BaseHandler(Looper looper) { public void disable(boolean disable) { this.disabled = disable; removeCallbacksAndMessages(null); - while (handling) {} + while (handling) { + } } - public boolean isDisabled() { return disabled; } @@ -54,7 +54,7 @@ public final void handleMessage(Message msg) { messageQueue.remove(msg); } if (msg != null && msg.what == -1 && msg.obj instanceof CountDownLatch) { - ((CountDownLatch)msg.obj).countDown(); + ((CountDownLatch) msg.obj).countDown(); } else { if (InternalListenerManager.isEnabled()) { InternalListenerManager.getListener().onThreadMessage(getClass().getName(), msg, true); @@ -65,8 +65,7 @@ public final void handleMessage(Message msg) { Logger.error("Out of memory"); } } - } - finally { + } finally { handling = false; } } @@ -87,7 +86,7 @@ public boolean sendMessageAtTime(Message msg, long uptimeMillis) { public void removeMessage(int what) { Set messages = messageQueue.keySet(); - for (Message message: messages) { + for (Message message : messages) { if (message.what == what) { messageQueue.remove(message); } @@ -96,5 +95,6 @@ public void removeMessage(int what) { } //Override this in order to handle messages - public void handleMessageImpl(Message msg) {} + public void handleMessageImpl(Message msg) { + } } diff --git a/android-core/src/main/java/com/mparticle/internal/BatchId.java b/android-core/src/main/java/com/mparticle/internal/BatchId.java index 1a9c5bebc..72f5b624b 100644 --- a/android-core/src/main/java/com/mparticle/internal/BatchId.java +++ b/android-core/src/main/java/com/mparticle/internal/BatchId.java @@ -47,7 +47,7 @@ public boolean equals(@Nullable Object obj) { if (!(obj instanceof BatchId)) { return false; } - BatchId batchId = (BatchId)obj; + BatchId batchId = (BatchId) obj; for (int i = 0; i < fields().length; i++) { if (!MPUtility.isEqual(fields()[i], batchId.fields()[i])) { return false; diff --git a/android-core/src/main/java/com/mparticle/internal/Constants.java b/android-core/src/main/java/com/mparticle/internal/Constants.java index 2238d489f..406fe71e4 100644 --- a/android-core/src/main/java/com/mparticle/internal/Constants.java +++ b/android-core/src/main/java/com/mparticle/internal/Constants.java @@ -10,6 +10,7 @@ public class Constants { private static int MAX_MESSAGE_PER_BATCH = 100; + public static int getMaxMessagePerBatch() { return MAX_MESSAGE_PER_BATCH; } @@ -486,7 +487,6 @@ public interface Commerce { String EVENT_TYPE_STRING_UNKNOWN = "Unknown"; - } public interface PrefKeys { diff --git a/android-core/src/main/java/com/mparticle/internal/CoreCallbacks.java b/android-core/src/main/java/com/mparticle/internal/CoreCallbacks.java index a3c925c25..9f0c9a984 100644 --- a/android-core/src/main/java/com/mparticle/internal/CoreCallbacks.java +++ b/android-core/src/main/java/com/mparticle/internal/CoreCallbacks.java @@ -14,37 +14,66 @@ public interface CoreCallbacks { boolean isBackgrounded(); + int getUserBucket(); + boolean isEnabled(); + void setIntegrationAttributes(int kitId, Map integrationAttributes); + Map getIntegrationAttributes(int kitId); + WeakReference getCurrentActivity(); + @WorkerThread JSONArray getLatestKitConfiguration(); + MParticleOptions.DataplanOptions getDataplanOptions(); + boolean isPushEnabled(); + String getPushSenderId(); + String getPushInstanceId(); + Uri getLaunchUri(); + String getLaunchAction(); + KitListener getKitListener(); interface KitListener { void kitFound(int kitId); + void kitConfigReceived(int kitId, String configuration); + void kitExcluded(int kitId, String reason); + void kitStarted(int kitId); + void onKitApiCalled(int kitId, Boolean used, Object... objects); + void onKitApiCalled(String methodName, int kitId, Boolean used, Object... objects); KitListener EMPTY = new KitListener() { - public void kitFound(int kitId) {} - public void kitConfigReceived(int kitId, String configuration) { } - public void kitExcluded(int kitId, String reason) { } - public void kitStarted(int kitId) { } - public void onKitApiCalled(int kitId, Boolean used, Object... objects) { } - public void onKitApiCalled(String methodName, int kitId, Boolean used, Object... objects) { } + public void kitFound(int kitId) { + } + + public void kitConfigReceived(int kitId, String configuration) { + } + + public void kitExcluded(int kitId, String reason) { + } + + public void kitStarted(int kitId) { + } + + public void onKitApiCalled(int kitId, Boolean used, Object... objects) { + } + + public void onKitApiCalled(String methodName, int kitId, Boolean used, Object... objects) { + } }; } } diff --git a/android-core/src/main/java/com/mparticle/internal/InternalSession.java b/android-core/src/main/java/com/mparticle/internal/InternalSession.java index 0011f6685..c322348cc 100644 --- a/android-core/src/main/java/com/mparticle/internal/InternalSession.java +++ b/android-core/src/main/java/com/mparticle/internal/InternalSession.java @@ -37,7 +37,7 @@ public InternalSession(InternalSession session) { mTimeInBackground = session.mTimeInBackground; try { mSessionAttributes = new JSONObject(session.mSessionAttributes.toString()); - }catch (JSONException jse){ + } catch (JSONException jse) { } } @@ -62,7 +62,7 @@ public boolean isTimedOut(int sessionTimeout) { public long getLength() { long time = mLastEventTime - mSessionStartTime; - if (time >= 0){ + if (time >= 0) { return time; } return time; diff --git a/android-core/src/main/java/com/mparticle/internal/JellybeanHelper.java b/android-core/src/main/java/com/mparticle/internal/JellybeanHelper.java index 669be260c..6b22e3b77 100644 --- a/android-core/src/main/java/com/mparticle/internal/JellybeanHelper.java +++ b/android-core/src/main/java/com/mparticle/internal/JellybeanHelper.java @@ -10,12 +10,12 @@ */ @TargetApi(18) public class JellybeanHelper { - public static long getAvailableMemory(StatFs stat){ + public static long getAvailableMemory(StatFs stat) { try { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) { return stat.getAvailableBlocksLong() * stat.getBlockSizeLong(); } - }catch (Exception e) { + } catch (Exception e) { //For some reason, it appears some devices even in jelly bean don't have this method. } diff --git a/android-core/src/main/java/com/mparticle/internal/KitContext.java b/android-core/src/main/java/com/mparticle/internal/KitContext.java index ebf474d18..c7ec89be3 100644 --- a/android-core/src/main/java/com/mparticle/internal/KitContext.java +++ b/android-core/src/main/java/com/mparticle/internal/KitContext.java @@ -11,7 +11,7 @@ public class KitContext extends ContextWrapper { public KitContext(Context base) { super(base); - applicationContextWrapper = new ApplicationContextWrapper((Application)base.getApplicationContext()); + applicationContextWrapper = new ApplicationContextWrapper((Application) base.getApplicationContext()); } @Override diff --git a/android-core/src/main/java/com/mparticle/internal/KitKatHelper.java b/android-core/src/main/java/com/mparticle/internal/KitKatHelper.java index 8061c76fb..b6e8ba548 100644 --- a/android-core/src/main/java/com/mparticle/internal/KitKatHelper.java +++ b/android-core/src/main/java/com/mparticle/internal/KitKatHelper.java @@ -11,7 +11,7 @@ */ @TargetApi(19) public class KitKatHelper { - public static void remove(JSONArray array, int index){ + public static void remove(JSONArray array, int index) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { array.remove(index); } diff --git a/android-core/src/main/java/com/mparticle/internal/KitsLoadedCallback.kt b/android-core/src/main/java/com/mparticle/internal/KitsLoadedCallback.kt index 6f102c223..005f40221 100644 --- a/android-core/src/main/java/com/mparticle/internal/KitsLoadedCallback.kt +++ b/android-core/src/main/java/com/mparticle/internal/KitsLoadedCallback.kt @@ -1,9 +1,11 @@ package com.mparticle.internal class KitsLoadedCallback { - @Volatile private var onKitsLoadedRunnable: OnKitManagerLoaded? = null + @Volatile + private var onKitsLoadedRunnable: OnKitManagerLoaded? = null - @Volatile private var loaded: Boolean = false + @Volatile + private var loaded: Boolean = false fun setKitsLoaded() { synchronized(this) { diff --git a/android-core/src/main/java/com/mparticle/internal/KitsLoadedListenerConfiguration.kt b/android-core/src/main/java/com/mparticle/internal/KitsLoadedListenerConfiguration.kt index 544fab7f5..552ac7079 100644 --- a/android-core/src/main/java/com/mparticle/internal/KitsLoadedListenerConfiguration.kt +++ b/android-core/src/main/java/com/mparticle/internal/KitsLoadedListenerConfiguration.kt @@ -2,7 +2,9 @@ package com.mparticle.internal import com.mparticle.Configuration -internal class KitsLoadedListenerConfiguration(private var kitsLoadedListener: KitsLoadedListener) : Configuration { +internal class KitsLoadedListenerConfiguration(private var kitsLoadedListener: KitsLoadedListener) : + Configuration { override fun configures() = KitFrameworkWrapper::class.java - override fun apply(kitFrameworkWrapper: KitFrameworkWrapper) = kitFrameworkWrapper.addKitsLoadedListener(kitsLoadedListener) + override fun apply(kitFrameworkWrapper: KitFrameworkWrapper) = + kitFrameworkWrapper.addKitsLoadedListener(kitsLoadedListener) } diff --git a/android-core/src/main/java/com/mparticle/internal/Logger.java b/android-core/src/main/java/com/mparticle/internal/Logger.java index 9ee29fb99..c0efcefc7 100644 --- a/android-core/src/main/java/com/mparticle/internal/Logger.java +++ b/android-core/src/main/java/com/mparticle/internal/Logger.java @@ -71,7 +71,7 @@ public static void error(Throwable error, String... messages) { private static String getMessage(String... messages) { StringBuilder logMessage = new StringBuilder(); - for (String m : messages){ + for (String m : messages) { logMessage.append(m); } return logMessage.toString(); @@ -81,6 +81,7 @@ private static String getMessage(String... messages) { /** * Testing method. Use this method to intercept Logs, or customize what happens when something is logged. * For example, you can use this method to throw an exception every time an "error" log is called. + * * @param logListener */ public static void setLogHandler(AbstractLogHandler logListener) { @@ -98,7 +99,7 @@ public abstract static class AbstractLogHandler { public void log(LogLevel priority, Throwable error, String messages) { if (messages != null && isLoggable(priority.logLevel)) { - switch (priority){ + switch (priority) { case ERROR: error(error, messages); break; @@ -124,11 +125,9 @@ private boolean isLoggable(int logLevel) { //This block will catch the exception that is thrown during testing. try { isADBLoggable = isADBLoggable(Constants.LOG_TAG, logLevel); - } - catch (UnsatisfiedLinkError ex) { + } catch (UnsatisfiedLinkError ex) { return false; - } - catch (RuntimeException ignored) { + } catch (RuntimeException ignored) { return false; } return isADBLoggable || (isAPILoggable && MPUtility.isDevEnv()); @@ -140,17 +139,21 @@ protected boolean isADBLoggable(String tag, int logLevel) { } public abstract void verbose(Throwable error, String message); + public abstract void info(Throwable error, String message); + public abstract void debug(Throwable error, String message); + public abstract void warning(Throwable error, String message); + public abstract void error(Throwable error, String message); } - + public static class DefaultLogHandler extends AbstractLogHandler { @Override public void verbose(Throwable error, String messages) { - if (error != null){ + if (error != null) { Log.v(Constants.LOG_TAG, messages, error); } else { Log.v(Constants.LOG_TAG, messages); @@ -168,7 +171,7 @@ public void info(Throwable error, String messages) { @Override public void debug(Throwable error, String messages) { - if (error != null){ + if (error != null) { Log.d(Constants.LOG_TAG, messages, error); } else { Log.d(Constants.LOG_TAG, messages); @@ -177,7 +180,7 @@ public void debug(Throwable error, String messages) { @Override public void warning(Throwable error, String messages) { - if (error != null){ + if (error != null) { Log.w(Constants.LOG_TAG, messages, error); } else { Log.w(Constants.LOG_TAG, messages); @@ -186,7 +189,7 @@ public void warning(Throwable error, String messages) { @Override public void error(Throwable error, String messages) { - if (error != null){ + if (error != null) { Log.e(Constants.LOG_TAG, messages, error); } else { Log.e(Constants.LOG_TAG, messages); diff --git a/android-core/src/main/java/com/mparticle/internal/MPLifecycleCallbackDelegate.java b/android-core/src/main/java/com/mparticle/internal/MPLifecycleCallbackDelegate.java index 60e5eee45..d8265a937 100644 --- a/android-core/src/main/java/com/mparticle/internal/MPLifecycleCallbackDelegate.java +++ b/android-core/src/main/java/com/mparticle/internal/MPLifecycleCallbackDelegate.java @@ -6,8 +6,6 @@ import android.os.Build; import android.os.Bundle; -import com.mparticle.internal.AppStateManager; - /** * This class is used by the AppStateManager to determine when the app is visible or in the background. * @@ -16,6 +14,7 @@ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) class MPLifecycleCallbackDelegate implements Application.ActivityLifecycleCallbacks { private AppStateManager mStateManager; + public MPLifecycleCallbackDelegate(AppStateManager stateManager) { mStateManager = stateManager; } diff --git a/android-core/src/main/java/com/mparticle/internal/MPUtility.java b/android-core/src/main/java/com/mparticle/internal/MPUtility.java index a636bb86d..b31f9a15b 100644 --- a/android-core/src/main/java/com/mparticle/internal/MPUtility.java +++ b/android-core/src/main/java/com/mparticle/internal/MPUtility.java @@ -97,8 +97,8 @@ public static long getSystemMemoryThreshold(Context context) { public static long getRemainingHeapInBytes() { final Runtime runtime = Runtime.getRuntime(); - final long usedMemBytes=(runtime.totalMemory() - runtime.freeMemory()); - final long maxHeapSizeInBytes=runtime.maxMemory(); + final long usedMemBytes = (runtime.totalMemory() - runtime.freeMemory()); + final long maxHeapSizeInBytes = runtime.maxMemory(); return maxHeapSizeInBytes - usedMemBytes; } @@ -310,7 +310,7 @@ public static JSONObject getJsonResponse(InputStream is) { return null; } - public static long getDiskSpace(Context context, File path){ + public static long getDiskSpace(Context context, File path) { if (MPUtility.isInstantApp(context)) { return 0L; } @@ -319,7 +319,7 @@ public static long getDiskSpace(Context context, File path){ if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) { availableSpace = JellybeanHelper.getAvailableMemory(stat); } - if (availableSpace == 0){ + if (availableSpace == 0) { availableSpace = (long) stat.getAvailableBlocks() * (long) stat.getBlockSize(); } return availableSpace; @@ -339,13 +339,12 @@ public static String getErrorMessage(HttpURLConnection connection) { } in.close(); return responseBuilder.toString(); - } - catch (Exception e) { + } catch (Exception e) { return e.getMessage(); } } - public static long millitime(){ + public static long millitime() { return TimeUnit.MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS); } @@ -363,9 +362,9 @@ public static String getTimeZone() { try { //Some Android 8 devices crash here for no clear reason. return TimeZone.getDefault().getDisplayName(false, 0); + } catch (Exception ignored) { + } catch (AssertionError e) { } - catch (Exception ignored){ } - catch (AssertionError e){ } return null; } @@ -462,7 +461,7 @@ static String getBuildUUID(String versionCode) { } try { return UUID.nameUUIDFromBytes(versionCode.getBytes()).toString(); - }catch (AssertionError e) { + } catch (AssertionError e) { //Some devices do not have MD5 and will throw a NoSuchAlgorithmException. return DeviceAttributes.UNKNOWN; } @@ -535,7 +534,8 @@ public static boolean isBluetoothEnabled(Context context) { try { //noinspection MissingPermission return mBluetoothAdapter.isEnabled(); - } catch (SecurityException se) { } + } catch (SecurityException se) { + } } } return false; @@ -550,7 +550,8 @@ public static boolean isGmsAdIdAvailable() { try { Class.forName("com.google.android.gms.ads.identifier.AdvertisingIdClient"); return true; - } catch (ClassNotFoundException ignored) { } + } catch (ClassNotFoundException ignored) { + } return false; } @@ -558,7 +559,8 @@ public static boolean isSupportLibAvailable() { try { Class.forName("android.support.v4.app.FragmentActivity"); return true; - } catch (ClassNotFoundException ignored) { } + } catch (ClassNotFoundException ignored) { + } return false; } @@ -574,8 +576,8 @@ public static Boolean isFirebaseAvailablePostV21() { try { Class.forName("com.google.firebase.messaging.FirebaseMessaging"); return true; + } catch (ClassNotFoundException ignored) { } - catch (ClassNotFoundException ignored) { } return false; } @@ -583,8 +585,8 @@ public static Boolean isFirebaseAvailablePreV21() { try { Class.forName("com.google.firebase.iid.FirebaseInstanceId"); return true; + } catch (ClassNotFoundException ignored) { } - catch (ClassNotFoundException ignored) { } return false; } @@ -592,7 +594,8 @@ public static boolean isInstallRefApiAvailable() { try { Class.forName("com.android.installreferrer.api.InstallReferrerStateListener"); return true; - } catch (Exception ignored) {} + } catch (Exception ignored) { + } return false; } @@ -643,7 +646,7 @@ public static JSONObject wrapExtras(Bundle extras) { } } return parameters; - }else{ + } else { return null; } } @@ -659,7 +662,7 @@ public static JSONObject mapToJson(Map map) { String key = entry.getKey(); if (value instanceof List) { JSONArray array = new JSONArray(); - for (Object v: (List)value) { + for (Object v : (List) value) { array.put(v); } attrs.put(key, array); @@ -668,16 +671,15 @@ public static JSONObject mapToJson(Map map) { } else { attrs.put(key, value); } - } - catch (JSONException ignore) { + } catch (JSONException ignore) { } } return attrs; } - public static boolean isAppDebuggable(Context context){ - return ( 0 != ( context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE ) ); + public static boolean isAppDebuggable(Context context) { + return (0 != (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)); } public static boolean isDevEnv() { @@ -704,6 +706,7 @@ public static JSONObject enforceAttributeConstraints(Map attribu } return checkedAttributes; } + public static Boolean setCheckedAttribute(JSONObject attributes, String key, Object value, boolean increment, boolean userAttribute) { return setCheckedAttribute(attributes, key, value, false, increment, userAttribute); } @@ -718,37 +721,37 @@ public static Boolean setCheckedAttribute(JSONObject attributes, String key, Obj } if (Constants.LIMIT_ATTR_COUNT == attributes.length() && !attributes.has(key)) { - Logger.error( "Attribute count exceeds limit. Discarding attribute: " + key); + Logger.error("Attribute count exceeds limit. Discarding attribute: " + key); return false; } if (value != null) { String stringValue = value.toString(); - if (stringValue.length() > Constants.LIMIT_ATTR_VALUE){ - Logger.error( "Attribute value length exceeds limit. Discarding attribute: " + key); + if (stringValue.length() > Constants.LIMIT_ATTR_VALUE) { + Logger.error("Attribute value length exceeds limit. Discarding attribute: " + key); return false; } } if (key.length() > Constants.LIMIT_ATTR_KEY) { - Logger.error( "Attribute name length exceeds limit. Discarding attribute: " + key); + Logger.error("Attribute name length exceeds limit. Discarding attribute: " + key); return false; } if (value == null) { value = JSONObject.NULL; } - if (increment){ + if (increment) { String oldValue = attributes.optString(key, "0"); int oldInt = Integer.parseInt(oldValue); - value = Integer.toString((Integer)value + oldInt); + value = Integer.toString((Integer) value + oldInt); } attributes.put(key, value); } catch (JSONException e) { - Logger.error( "JSON error processing attributes. Discarding attribute: " + key); + Logger.error("JSON error processing attributes. Discarding attribute: " + key); return false; - } catch (NumberFormatException nfe){ - Logger.error( "Attempted to increment a key that could not be parsed as an integer: " + key); + } catch (NumberFormatException nfe) { + Logger.error("Attempted to increment a key that could not be parsed as an integer: " + key); return false; - } catch (Exception e){ - Logger.error( "Failed to add attribute: " + e.getMessage()); + } catch (Exception e) { + Logger.error("Failed to add attribute: " + e.getMessage()); return false; } return true; @@ -777,13 +780,11 @@ public Boolean run() { return InstantApps.isInstantApp(context); } }.run(); - } - catch (ClassNotFoundException ignored) { + } catch (ClassNotFoundException ignored) { try { Class.forName("com.google.android.instantapps.supervisor.InstantAppsRuntime"); return true; - } - catch (ClassNotFoundException a) { + } catch (ClassNotFoundException a) { return false; } } @@ -824,11 +825,11 @@ public static String getProp(String key) { } public static Number addNumbers(Number number1, Number number2) { - if(number1 instanceof Double || number2 instanceof Double) { + if (number1 instanceof Double || number2 instanceof Double) { return number1.doubleValue() + number2.doubleValue(); - } else if(number1 instanceof Float || number2 instanceof Float) { + } else if (number1 instanceof Float || number2 instanceof Float) { return number1.floatValue() + number2.floatValue(); - } else if(number1 instanceof Long || number2 instanceof Long) { + } else if (number1 instanceof Long || number2 instanceof Long) { return number1.longValue() + number2.longValue(); } else { return number1.intValue() + number2.intValue(); @@ -839,14 +840,15 @@ public static Object toNumberOrString(String stringValue) { if (stringValue == null) { return stringValue; } - for(Character c: stringValue.toCharArray()) { + for (Character c : stringValue.toCharArray()) { if (!Character.isDigit(c) && c != '.' && c != '-') { return stringValue; } } try { return NumberFormat.getInstance().parse(stringValue); - } catch (ParseException e) { } + } catch (ParseException e) { + } return stringValue; } diff --git a/android-core/src/main/java/com/mparticle/internal/MParticleApiClient.java b/android-core/src/main/java/com/mparticle/internal/MParticleApiClient.java index fb6df0ab3..5d3593179 100644 --- a/android-core/src/main/java/com/mparticle/internal/MParticleApiClient.java +++ b/android-core/src/main/java/com/mparticle/internal/MParticleApiClient.java @@ -15,10 +15,15 @@ */ public interface MParticleApiClient extends MParticleBaseClient { void fetchConfig() throws IOException, MParticleApiClientImpl.MPConfigException; + void fetchConfig(boolean force) throws IOException, MParticleApiClientImpl.MPConfigException; + int sendMessageBatch(String message) throws IOException, MParticleApiClientImpl.MPThrottleException, MParticleApiClientImpl.MPRampException; + JSONObject fetchAudiences(); + JSONObject getCookies(); + @NonNull AliasNetworkResponse sendAliasRequest(@NonNull String message) throws JSONException, IOException, MParticleApiClientImpl.MPThrottleException, MParticleApiClientImpl.MPRampException; diff --git a/android-core/src/main/java/com/mparticle/internal/MParticleApiClientImpl.java b/android-core/src/main/java/com/mparticle/internal/MParticleApiClientImpl.java index 0487d6a96..fe21fc182 100644 --- a/android-core/src/main/java/com/mparticle/internal/MParticleApiClientImpl.java +++ b/android-core/src/main/java/com/mparticle/internal/MParticleApiClientImpl.java @@ -75,12 +75,12 @@ public class MParticleApiClientImpl extends MParticleBaseClientImpl implements M * Default throttle time - in the worst case scenario if the server is busy, the soonest * the SDK will attempt to contact the server again will be after this 2 hour window. */ - static final long DEFAULT_THROTTLE_MILLIS = 1000*60*60*2; - static final long MAX_THROTTLE_MILLIS = 1000*60*60*24; + static final long DEFAULT_THROTTLE_MILLIS = 1000 * 60 * 60 * 2; + static final long MAX_THROTTLE_MILLIS = 1000 * 60 * 60 * 24; /** * Minimum time between passive Config requests, 10 minutes */ - private static final int MIN_CONFIG_REQUEST_INTERVAL = 10*60*1000; + private static final int MIN_CONFIG_REQUEST_INTERVAL = 10 * 60 * 1000; private long mConfigLastFetched = -1; private boolean alreadyWarned; @@ -117,8 +117,9 @@ public void fetchConfig() throws IOException, MPConfigException { /** * Fetches a remote configuration. Minimum time constraint based on MIN_CONFIG_REQUEST_INTERVAL * if not forced, configuration request will not take place if minimum time has not elapsed + * * @param force: if true, minimum elpsed time criteria will be ignored, and configuration - * request will take place regardless of elapsed time + * request will take place regardless of elapsed time */ public void fetchConfig(boolean force) throws IOException, MPConfigException { if (!force) { @@ -130,7 +131,7 @@ public void fetchConfig(boolean force) throws IOException, MPConfigException { } } try { - if (mConfigUrl == null){ + if (mConfigUrl == null) { mConfigUrl = getUrl(Endpoint.CONFIG); } MPConnection connection = mConfigUrl.openConnection(); @@ -145,11 +146,11 @@ public void fetchConfig(boolean force) throws IOException, MPConfigException { connection.setRequestProperty("User-Agent", mUserAgent); String etag = mConfigManager.getEtag(); - if (etag != null){ + if (etag != null) { connection.setRequestProperty("If-None-Match", etag); } String modified = mConfigManager.getIfModified(); - if (modified != null){ + if (modified != null) { connection.setRequestProperty("If-Modified-Since", modified); } @@ -169,14 +170,14 @@ public void fetchConfig(boolean force) throws IOException, MPConfigException { try { response = MPUtility.getJsonResponse(connection); InternalListenerManager.getListener().onNetworkRequestFinished(SdkListener.Endpoint.CONFIG, connection.getURL().toString(), response, responseCode); + } catch (Exception ex) { } - catch (Exception ex) {} if (responseCode >= 200 && responseCode < 300) { parseCookies(response); Logger.verbose("Config result: \n " + connection.getResponseCode() + ": " + - connection.getResponseMessage() +"\n" + + connection.getResponseMessage() + "\n" + "response:\n" + response.toString()); String newEtag = connection.getHeaderField("ETag"); @@ -202,7 +203,7 @@ public void fetchConfig(boolean force) throws IOException, MPConfigException { } } - public JSONObject fetchAudiences() { + public JSONObject fetchAudiences() { JSONObject response = null; try { @@ -214,13 +215,13 @@ public JSONObject fetchAudiences() { addMessageSignature(connection, null); makeUrlRequest(Endpoint.AUDIENCE, connection, true); - if (connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN){ + if (connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) { Logger.error("Segment call forbidden: is Segmentation enabled for your account?"); } - response = MPUtility.getJsonResponse(connection); + response = MPUtility.getJsonResponse(connection); parseCookies(response); - }catch (Exception e){ + } catch (Exception e) { Logger.error("Segment call failed: " + e.getMessage()); } return response; @@ -229,7 +230,7 @@ public JSONObject fetchAudiences() { public int sendMessageBatch(String message) throws IOException, MPThrottleException, MPRampException { checkThrottleTime(Endpoint.EVENTS); checkRampValue(); - if (mEventUrl == null){ + if (mEventUrl == null) { mEventUrl = getUrl(Endpoint.EVENTS); } MPConnection connection = mEventUrl.openConnection(); @@ -256,7 +257,8 @@ public int sendMessageBatch(String message) throws IOException, MPThrottleExcept try { InternalListenerManager.getListener().onNetworkRequestStarted(SdkListener.Endpoint.EVENTS, connection.getURL().toString(), new JSONObject(message), message); - } catch (Exception e) { } + } catch (Exception e) { + } makeUrlRequest(Endpoint.EVENTS, connection, message, true); @@ -275,18 +277,19 @@ public int sendMessageBatch(String message) throws IOException, MPThrottleExcept Logger.verbose("Upload result response: \n" + connection.getResponseCode() + ": " + - connection.getResponseMessage() + "\n" + - "response:\n" + response.toString()); + connection.getResponseMessage() + "\n" + + "response:\n" + response.toString()); parseCookies(response); } else { Logger.error("Upload request failed- " + responseCode + ": " + connection.getResponseMessage()); try { InternalListenerManager.getListener().onNetworkRequestFinished(SdkListener.Endpoint.EVENTS, connection.getURL().getFile(), new JSONObject().put(SdkListener.ERROR_MESSAGE, connection.getResponseMessage()), responseCode); - } catch (Exception e) { } + } catch (Exception e) { + } } return connection.getResponseCode(); } - + @Override public AliasNetworkResponse sendAliasRequest(String message) throws IOException, MPThrottleException, MPRampException { checkThrottleTime(Endpoint.ALIAS); @@ -309,7 +312,8 @@ public AliasNetworkResponse sendAliasRequest(String message) throws IOException, try { url = connection.getURL().toString(); InternalListenerManager.getListener().onNetworkRequestStarted(SdkListener.Endpoint.EVENTS, url, new JSONObject(message), message); - } catch (Exception ignore) {} + } catch (Exception ignore) { + } connection = makeUrlRequest(Endpoint.ALIAS, connection, message, false); int responseCode = connection.getResponseCode(); @@ -360,7 +364,7 @@ void addMessageSignature(MPConnection request, String message) { Logger.error("Error signing message."); } catch (NoSuchAlgorithmException e) { Logger.error("Error signing message."); - } catch (UnsupportedEncodingException e){ + } catch (UnsupportedEncodingException e) { Logger.error("Error signing message."); } } @@ -371,7 +375,8 @@ private void parseCookies(JSONObject jsonResponse) { JSONObject consumerInfo = jsonResponse.getJSONObject(CONSUMER_INFO); setCookies(consumerInfo.optJSONObject(Constants.MessageKey.COOKIES)); } - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } } public final class MPThrottleException extends Exception { @@ -393,29 +398,31 @@ public static final class MPRampException extends Exception { } public static final class MPNoConfigException extends Exception { - MPNoConfigException() {super("No API key and/or API secret."); } + MPNoConfigException() { + super("No API key and/or API secret."); + } } void checkThrottleTime(Endpoint endpoint) throws MPThrottleException { - if (System.currentTimeMillis() < getNextRequestTime(endpoint)){ + if (System.currentTimeMillis() < getNextRequestTime(endpoint)) { throw new MPThrottleException(); } } private void checkRampValue() throws MPRampException { - if (mDeviceRampNumber == null){ + if (mDeviceRampNumber == null) { mDeviceRampNumber = MPUtility.hashFnv1A(MPUtility.getRampUdid(mContext).getBytes()) .mod(BigInteger.valueOf(100)) .intValue(); } int currentRamp = mConfigManager.getCurrentRampValue(); if (currentRamp > 0 && currentRamp < 100 && - mDeviceRampNumber > mConfigManager.getCurrentRampValue()){ + mDeviceRampNumber > mConfigManager.getCurrentRampValue()) { throw new MPRampException(); } } - private String getSupportedKitString(){ + private String getSupportedKitString() { if (sSupportedKits == null) { MParticle instance = MParticle.getInstance(); if (instance != null) { @@ -457,8 +464,8 @@ public void setCookies(JSONObject serverCookies) { } } - public JSONObject getCookies() { - if (mCurrentCookies == null){ + public JSONObject getCookies() { + if (mCurrentCookies == null) { String currentCookies = mConfigManager.getUserStorage().getCookies(); if (MPUtility.isEmpty(currentCookies)) { mCurrentCookies = new JSONObject(); @@ -491,18 +498,18 @@ public JSONObject getCookies() { } } - }catch (JSONException jse){ + } catch (JSONException jse) { } } - for (String key : keysToRemove){ + for (String key : keysToRemove) { mCurrentCookies.remove(key); } if (keysToRemove.size() > 0) { mConfigManager.getUserStorage().setCookies(mCurrentCookies.toString()); } return mCurrentCookies; - }else{ + } else { return mCurrentCookies; } } diff --git a/android-core/src/main/java/com/mparticle/internal/MParticleJSInterface.java b/android-core/src/main/java/com/mparticle/internal/MParticleJSInterface.java index f58028d37..07966ee98 100644 --- a/android-core/src/main/java/com/mparticle/internal/MParticleJSInterface.java +++ b/android-core/src/main/java/com/mparticle/internal/MParticleJSInterface.java @@ -15,10 +15,8 @@ import com.mparticle.commerce.Product; import com.mparticle.commerce.Promotion; import com.mparticle.commerce.TransactionAttributes; -import com.mparticle.identity.IdentityApi; import com.mparticle.identity.IdentityApi.SingleUserIdentificationCallback; import com.mparticle.identity.IdentityApiRequest; -import com.mparticle.identity.IdentityStateListener; import com.mparticle.identity.MParticleUser; import org.json.JSONArray; @@ -37,7 +35,6 @@ * * This class knows how to parse JSON that has been generated by the mParticle Javascript SDK, basically * creating a bridge between the two SDKs. - * */ public class MParticleJSInterface { public static final String INTERFACE_BASE_NAME = "mParticleAndroid"; @@ -51,7 +48,7 @@ public class MParticleJSInterface { protected static final String JS_KEY_OPTOUT = "OptOut"; protected static final int JS_MSG_TYPE_SS = 1; - protected static final int JS_MSG_TYPE_SE = 2; + protected static final int JS_MSG_TYPE_SE = 2; protected static final int JS_MSG_TYPE_PV = 3; protected static final int JS_MSG_TYPE_PE = 4; protected static final int JS_MSG_TYPE_CR = 5; @@ -135,8 +132,7 @@ public void login(String json) { try { JSONObject jsonObject = new JSONObject(json); request = getIdentityApiRequest(jsonObject); - } - catch (JSONException jse) { + } catch (JSONException jse) { Logger.warning(String.format(errorMsg, jse.getMessage())); } MParticle.getInstance().Identity().login(request); @@ -154,8 +150,7 @@ public void logout(String json) { try { JSONObject jsonObject = new JSONObject(json); request = getIdentityApiRequest(jsonObject); - } - catch (JSONException jse) { + } catch (JSONException jse) { Logger.warning(String.format(errorMsg, jse.getMessage())); } MParticle.getInstance().Identity().logout(request); @@ -167,8 +162,7 @@ public void modify(String json) { try { JSONObject jsonObject = new JSONObject(json); request = getIdentityApiRequest(jsonObject); - } - catch (JSONException jse) { + } catch (JSONException jse) { Logger.warning(String.format(errorMsg, jse.getMessage())); } MParticle.getInstance().Identity().modify(request); @@ -185,21 +179,21 @@ public void logEvent(String json) { Map> eventFlags = convertToListMap(event.optJSONObject(JS_KEY_EVENT_FLAGS)); int messageType = event.getInt(JS_KEY_EVENT_DATATYPE); - switch (messageType){ + switch (messageType) { case JS_MSG_TYPE_PE: logEvent( new MPEvent.Builder(name, eventType) - .customAttributes(eventAttributes) - .customFlags(eventFlags) - .build() + .customAttributes(eventAttributes) + .customFlags(eventFlags) + .build() ); break; case JS_MSG_TYPE_PV: logScreen( new MPEvent.Builder(name, eventType) - .customAttributes(eventAttributes) - .customFlags(eventFlags) - .build() + .customAttributes(eventAttributes) + .customFlags(eventFlags) + .build() ); break; case JS_MSG_TYPE_OO: @@ -249,8 +243,8 @@ public void onUserFound(MParticleUser user) { } @JavascriptInterface - public void removeUserTag(String json){ - try{ + public void removeUserTag(String json) { + try { JSONObject attribute = new JSONObject(json); final String key = attribute.getString("key"); if (MParticle.getInstance().Identity().getCurrentUser() != null) { @@ -263,13 +257,13 @@ public void onUserFound(MParticleUser user) { } }); } - }catch (JSONException jse){ + } catch (JSONException jse) { Logger.warning(String.format(errorMsg, jse.getMessage())); } } @JavascriptInterface - public void setUserAttribute(String json){ + public void setUserAttribute(String json) { try { JSONObject attribute = new JSONObject(json); final String key = attribute.getString("key"); @@ -290,8 +284,8 @@ public void onUserFound(MParticleUser user) { } @JavascriptInterface - public void removeUserAttribute(String json){ - try{ + public void removeUserAttribute(String json) { + try { JSONObject attribute = new JSONObject(json); final String key = attribute.getString("key"); if (MParticle.getInstance().Identity().getCurrentUser() != null) { @@ -304,13 +298,13 @@ public void onUserFound(MParticleUser user) { } }); } - }catch (JSONException jse){ + } catch (JSONException jse) { Logger.warning(String.format(errorMsg, jse.getMessage())); } } @JavascriptInterface - public void setSessionAttribute(String json){ + public void setSessionAttribute(String json) { try { JSONObject attribute = new JSONObject(json); MParticle.getInstance().setSessionAttribute(attribute.getString("key"), attribute.getString("value")); @@ -320,13 +314,13 @@ public void setSessionAttribute(String json){ } @JavascriptInterface - public void setUserIdentity(String json){ + public void setUserIdentity(String json) { //do nothing } @JavascriptInterface - public void removeUserIdentity(String json){ - // do nothing + public void removeUserIdentity(String json) { + // do nothing } @JavascriptInterface @@ -422,18 +416,18 @@ public String getUserAttributesLists() { if (user == null) { return new JSONObject().toString(); } - for (Map.Entry entry: user.getUserAttributes().entrySet()) { + for (Map.Entry entry : user.getUserAttributes().entrySet()) { if (entry.getValue() instanceof List) { - attributeMap.put(entry.getKey(), (List)entry.getValue()); + attributeMap.put(entry.getKey(), (List) entry.getValue()); } } JSONArray jsonArray = new JSONArray(); - for (Map.Entry entry: attributeMap.entrySet()) { + for (Map.Entry entry : attributeMap.entrySet()) { try { JSONObject jsonObject = new JSONObject(); jsonObject.put("key", entry.getKey()); JSONArray jsonArray1 = new JSONArray(); - for (Object attribute: entry.getValue()) { + for (Object attribute : entry.getValue()) { jsonArray1.put(attribute); } jsonObject.put("value", jsonArray1.toString()); @@ -452,7 +446,7 @@ public String getAllUserAttributes() { //place across platforms Map attributeMap = MParticle.getInstance().Identity().getCurrentUser().getUserAttributes(); JSONArray jsonArray = new JSONArray(); - for (Map.Entry entry: attributeMap.entrySet()) { + for (Map.Entry entry : attributeMap.entrySet()) { try { JSONObject jsonObject = new JSONObject(); jsonObject.put("key", entry.getKey()); @@ -512,14 +506,14 @@ protected CommerceEvent toCommerceEvent(JSONObject jsonObject) { if (productAction != null && productArray != null) { for (int i = 0; i < productArray.length(); i++) { Product product = toProduct(productArray.optJSONObject(i)); - if (builder == null) { - builder = new CommerceEvent.Builder(productAction, product); - } else { - builder.addProduct(product); - } + if (builder == null) { + builder = new CommerceEvent.Builder(productAction, product); + } else { + builder.addProduct(product); + } } if (builder == null) { - builder = new CommerceEvent.Builder(productAction, (Product)null); + builder = new CommerceEvent.Builder(productAction, (Product) null); } TransactionAttributes transactionAttributes = getTransactionAttributes(productActionObj); if (transactionAttributes != null) { @@ -539,14 +533,14 @@ protected CommerceEvent toCommerceEvent(JSONObject jsonObject) { if (promotionAction != null && promotionArray != null) { for (int i = 0; i < promotionArray.length(); i++) { Promotion promotion = toPromotion(promotionArray.optJSONObject(i)); - if (builder == null) { - builder = new CommerceEvent.Builder(promotionAction, promotion); - } else { - builder.addPromotion(promotion); - } + if (builder == null) { + builder = new CommerceEvent.Builder(promotionAction, promotion); + } else { + builder.addPromotion(promotion); + } } if (builder == null) { - builder = new CommerceEvent.Builder(promotionAction, (Promotion)null); + builder = new CommerceEvent.Builder(promotionAction, (Promotion) null); } } } @@ -641,16 +635,16 @@ String getPromotionAction(String promotionActionEnum) { } return promotionActionEnum; } - + private TransactionAttributes getTransactionAttributes(JSONObject jsonObject) { TransactionAttributes attributes = null; if (jsonObject != null && (jsonObject.has(TRANSACTION_ID) || - jsonObject.has(AFFILIATION) || - jsonObject.has(COUPON_CODE) || - jsonObject.has(TOTAL_AMOUNT) || - jsonObject.has(TAX_AMOUNT) || - jsonObject.has(SHIPPING_AMOUNT))) { + jsonObject.has(AFFILIATION) || + jsonObject.has(COUPON_CODE) || + jsonObject.has(TOTAL_AMOUNT) || + jsonObject.has(TAX_AMOUNT) || + jsonObject.has(SHIPPING_AMOUNT))) { attributes = new TransactionAttributes(); attributes .setId(jsonObject.optString(TRANSACTION_ID, attributes.getId())) @@ -664,7 +658,9 @@ private TransactionAttributes getTransactionAttributes(JSONObject jsonObject) { } Product toProduct(JSONObject jsonObject) { - if (jsonObject == null) { return null; } + if (jsonObject == null) { + return null; + } try { Product.Builder builder = new Product.Builder(jsonObject.getString(NAME), jsonObject.optString(SKU, null), jsonObject.optDouble(PRICE, 0)); builder.category(jsonObject.optString(CATEGORY, null)); @@ -682,8 +678,7 @@ Product toProduct(JSONObject jsonObject) { builder.customAttributes(customAttributes); } return builder.build(); - } - catch (JSONException ignore) { + } catch (JSONException ignore) { return null; } } @@ -711,8 +706,8 @@ protected static Map> convertToListMap(JSONObject customFla if (null != customFlags) { Iterator keys = customFlags.keys(); Map> parsedFlags = new HashMap>(); - while(keys.hasNext()) { - String key = (String)keys.next(); + while (keys.hasNext()) { + String key = (String) keys.next(); try { JSONArray valueArray = customFlags.optJSONArray(key); if (valueArray != null) { @@ -720,8 +715,7 @@ protected static Map> convertToListMap(JSONObject customFla for (int i = 0; i < valueArray.length(); i++) { try { flags.add(valueArray.getString(i)); - } - catch (JSONException jse) { + } catch (JSONException jse) { Logger.warning("Could not parse custom flag array value."); } } @@ -730,8 +724,7 @@ protected static Map> convertToListMap(JSONObject customFla String stringValue = customFlags.getString(key); parsedFlags.put(key, Collections.singletonList(stringValue)); } - } - catch (Exception e) { + } catch (Exception e) { Logger.warning(e, "Could not parse custom flag value."); } } @@ -742,7 +735,9 @@ protected static Map> convertToListMap(JSONObject customFla private Impression toImpression(JSONObject jsonObject) { Impression impression = null; - if (jsonObject == null) { return impression; } + if (jsonObject == null) { + return impression; + } if (jsonObject.has(PRODUCT_IMPRESSION_NAME)) { JSONArray jsonArray = jsonObject.optJSONArray(PRODUCT_LIST); if (jsonArray != null) { @@ -762,7 +757,7 @@ private Impression toImpression(JSONObject jsonObject) { } return impression; } - + private Promotion toPromotion(JSONObject jsonObject) { if (jsonObject == null) { return null; @@ -783,8 +778,7 @@ protected IdentityApiRequest getIdentityApiRequest(JSONObject jsonObject) { try { JSONObject object = identitiesArray.getJSONObject(i); identities.put(getIdentityType(object), object.getString(IDENTITY)); - } - catch (JSONException jse){ + } catch (JSONException jse) { Logger.warning(String.format(errorMsg, jse.getMessage())); } } @@ -808,8 +802,7 @@ private MParticle.IdentityType getIdentityType(JSONObject object) { try { identityType = MParticle.IdentityType.parseInt(object.getInt(TYPE)); - } - catch (JSONException jse) { + } catch (JSONException jse) { previousErrorMessage = jse.getMessage(); } if (identityType != null) { @@ -817,8 +810,7 @@ private MParticle.IdentityType getIdentityType(JSONObject object) { } try { identityType = MParticle.IdentityType.valueOf(object.getString(TYPE)); - } - catch (JSONException jse) { + } catch (JSONException jse) { Logger.warning(String.format(errorMsg, (jse.getMessage() + (!MPUtility.isEmpty(previousErrorMessage) ? "\n" + previousErrorMessage : "")))); } return identityType; @@ -833,7 +825,7 @@ public static void registerWebView(WebView webView, String workspaceToken) { ); } } - + static String getBridgeName(String workspaceToken) { StringBuilder bridgeName = new StringBuilder(MParticleJSInterface.INTERFACE_BASE_NAME); bridgeName.append("_"); diff --git a/android-core/src/main/java/com/mparticle/internal/MessageBatch.java b/android-core/src/main/java/com/mparticle/internal/MessageBatch.java index afe187c30..3a3eade54 100644 --- a/android-core/src/main/java/com/mparticle/internal/MessageBatch.java +++ b/android-core/src/main/java/com/mparticle/internal/MessageBatch.java @@ -36,9 +36,9 @@ public static MessageBatch create(boolean history, ConfigManager configManager, uploadMessage.put(Constants.MessageKey.TIMESTAMP, System.currentTimeMillis()); uploadMessage.put(Constants.MessageKey.MPARTICLE_VERSION, Constants.MPARTICLE_VERSION); uploadMessage.put(Constants.MessageKey.OPT_OUT_HEADER, configManager.getOptedOut()); - uploadMessage.put(Constants.MessageKey.CONFIG_UPLOAD_INTERVAL, configManager.getUploadInterval()/1000); + uploadMessage.put(Constants.MessageKey.CONFIG_UPLOAD_INTERVAL, configManager.getUploadInterval() / 1000); uploadMessage.put(Constants.MessageKey.MPARTICLE_CONFIG_VERSION, configManager.getEtag()); - uploadMessage.put(Constants.MessageKey.CONFIG_SESSION_TIMEOUT, configManager.getSessionTimeout()/1000); + uploadMessage.put(Constants.MessageKey.CONFIG_SESSION_TIMEOUT, configManager.getSessionTimeout() / 1000); uploadMessage.put(Constants.MessageKey.MPID, String.valueOf(batchId.getMpid())); uploadMessage.put(Constants.MessageKey.SANDBOX, configManager.getEnvironment().equals(MParticle.Environment.Development)); uploadMessage.put(Constants.MessageKey.DEVICE_APPLICATION_STAMP, configManager.getDeviceApplicationStamp()); @@ -83,7 +83,8 @@ public void addConsentState(ConsentState consentState) { state.put(Constants.MessageKey.CONSENT_STATE_CCPA, ccpa); addConsentStateJSON(ccpa, Constants.MessageKey.CCPA_CONSENT_KEY, ccpaConsent); } - } catch (JSONException ignored) { } + } catch (JSONException ignored) { + } } } @@ -105,7 +106,8 @@ public void addSessionHistoryMessage(JSONObject message) { put(Constants.MessageKey.HISTORY, new JSONArray()); } getJSONArray(Constants.MessageKey.HISTORY).put(message); - } catch (JSONException ignored) { } + } catch (JSONException ignored) { + } } public void addMessage(JSONObject message) { @@ -114,7 +116,8 @@ public void addMessage(JSONObject message) { put(Constants.MessageKey.MESSAGES, new JSONArray()); } getJSONArray(Constants.MessageKey.MESSAGES).put(message); - } catch (JSONException ignored) { } + } catch (JSONException ignored) { + } } public void addReportingMessage(JSONObject reportingMessage) { @@ -123,19 +126,22 @@ public void addReportingMessage(JSONObject reportingMessage) { put(Constants.MessageKey.REPORTING, new JSONArray()); } getJSONArray(Constants.MessageKey.REPORTING).put(reportingMessage); - } catch (JSONException ignored) { } + } catch (JSONException ignored) { + } } public void setAppInfo(JSONObject appInfo) { try { put(Constants.MessageKey.APP_INFO, appInfo); - } catch (JSONException ignored) { } + } catch (JSONException ignored) { + } } public void setDeviceInfo(JSONObject deviceInfo) { try { put(Constants.MessageKey.DEVICE_INFO, deviceInfo); - } catch (JSONException ignored) { } + } catch (JSONException ignored) { + } } public JSONObject getAppInfo() { @@ -173,13 +179,15 @@ public JSONArray getMessages() { public void setIdentities(JSONArray identities) { try { put(Constants.MessageKey.USER_IDENTITIES, identities); - } catch (JSONException ignored) { } + } catch (JSONException ignored) { + } } public void setUserAttributes(JSONObject userAttributes) { try { put(Constants.MessageKey.USER_ATTRIBUTES, userAttributes); - } catch (JSONException ignored) { } + } catch (JSONException ignored) { + } } public long getMessageLengthBytes() { diff --git a/android-core/src/main/java/com/mparticle/internal/MessageHandler.java b/android-core/src/main/java/com/mparticle/internal/MessageHandler.java index 6f5b02639..f9ff968cd 100644 --- a/android-core/src/main/java/com/mparticle/internal/MessageHandler.java +++ b/android-core/src/main/java/com/mparticle/internal/MessageHandler.java @@ -16,8 +16,6 @@ import org.json.JSONException; import org.json.JSONObject; -import java.text.NumberFormat; -import java.text.ParseException; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -86,7 +84,7 @@ public void handleMessageImpl(Message msg) { return; } mMessageManagerCallbacks.delayedStart(); - }catch (Exception e) { + } catch (Exception e) { Logger.verbose(e.toString()); } switch (msg.what) { @@ -99,11 +97,11 @@ public void handleMessageImpl(Message msg) { // session record first. if (MessageType.SESSION_START.equals(messageType)) { dbInsertSession(message); - }else{ + } else { mMParticleDBManager.updateSessionEndTime(message.getSessionId(), message.getLong(MessageKey.TIMESTAMP), 0); message.put(Constants.MessageKey.ID, UUID.randomUUID().toString()); } - if (MessageType.ERROR.equals(messageType)){ + if (MessageType.ERROR.equals(messageType)) { mMParticleDBManager.appendBreadcrumbs(message); } try { @@ -121,7 +119,7 @@ public void handleMessageImpl(Message msg) { case INSTALL_REFERRER_UPDATED: try { mMParticleDBManager.updateSessionInstallReferrer((String) msg.obj, mMessageManagerCallbacks.getDeviceAttributes().getAppInfo(mContext, true)); - }catch (Exception e) { + } catch (Exception e) { Logger.error(e, "Error updating session attributes in mParticle DB."); } break; @@ -150,31 +148,31 @@ public void handleMessageImpl(Message msg) { Map.Entry> entry = (Map.Entry>) msg.obj; BaseMPMessage endMessage = null; String sessionId = entry.getKey(); - try { - endMessage = mMParticleDBManager.getSessionForSessionEndMessage(sessionId, ((MessageManager)mMessageManagerCallbacks).getLocation(), entry.getValue()); - }catch (JSONException jse){ - Logger.warning("Failed to create mParticle session end message."); - } - if (endMessage != null) { - try { - Logger.verbose("Creating session end message for session ID: " + sessionId); - mMParticleDBManager.insertMessage(mMessageManagerCallbacks.getApiKey(), endMessage, mDataplanId, mDataplanVersion); - mMParticleDBManager.updateSessionStatus(sessionId, SessionTable.SessionStatus.CLOSED); - } catch (MParticleApiClientImpl.MPNoConfigException e) { - Logger.error("Unable to process uploads, API key and/or API Secret are missing."); - return; - } + try { + endMessage = mMParticleDBManager.getSessionForSessionEndMessage(sessionId, ((MessageManager) mMessageManagerCallbacks).getLocation(), entry.getValue()); + } catch (JSONException jse) { + Logger.warning("Failed to create mParticle session end message."); + } + if (endMessage != null) { + try { + Logger.verbose("Creating session end message for session ID: " + sessionId); + mMParticleDBManager.insertMessage(mMessageManagerCallbacks.getApiKey(), endMessage, mDataplanId, mDataplanVersion); + mMParticleDBManager.updateSessionStatus(sessionId, SessionTable.SessionStatus.CLOSED); + } catch (MParticleApiClientImpl.MPNoConfigException e) { + Logger.error("Unable to process uploads, API key and/or API Secret are missing."); + return; + } } else { Logger.error("Error creating session end, no entry for sessionId in mParticle DB."); } //1 means this came from ending the session - if (msg.arg1 == 1){ + if (msg.arg1 == 1) { mMessageManagerCallbacks.endUploadLoop(); } } catch (Exception e) { Logger.error(e, "Error creating session end message in mParticle DB."); - }finally { + } finally { } break; @@ -182,9 +180,9 @@ public void handleMessageImpl(Message msg) { try { Logger.verbose("Ending orphaned sessions."); // Find left-over sessions that exist during startup and end them. - Long mpid = (Long)msg.obj; + Long mpid = (Long) msg.obj; List sessionIds = mMParticleDBManager.getOrphanSessionIds(mMessageManagerCallbacks.getApiKey()); - for (String sessionId: sessionIds) { + for (String sessionId : sessionIds) { Map.Entry> entry = new HashMap.SimpleEntry>(sessionId, Collections.singleton(mpid)); sendMessage(obtainMessage(MessageHandler.CREATE_SESSION_END_MESSAGE, 0, 0, entry)); } @@ -208,30 +206,30 @@ public void handleMessageImpl(Message msg) { } break; case STORE_REPORTING_MESSAGE_LIST: - try{ - MessageManager.ReportingMpidMessage reportingMessages = (MessageManager.ReportingMpidMessage)msg.obj; - mMParticleDBManager.insertReportingMessages((List)reportingMessages.reportingMessages, reportingMessages.mpid); - }catch (Exception e) { + try { + MessageManager.ReportingMpidMessage reportingMessages = (MessageManager.ReportingMpidMessage) msg.obj; + mMParticleDBManager.insertReportingMessages((List) reportingMessages.reportingMessages, reportingMessages.mpid); + } catch (Exception e) { Logger.verbose(e, "Error while inserting reporting messages: ", e.toString()); } break; case REMOVE_USER_ATTRIBUTE: try { - mMParticleDBManager.removeUserAttribute((MParticleDBManager.UserAttributeRemoval)msg.obj, mMessageManagerCallbacks); - }catch (Exception e) { + mMParticleDBManager.removeUserAttribute((MParticleDBManager.UserAttributeRemoval) msg.obj, mMessageManagerCallbacks); + } catch (Exception e) { Logger.error(e, "Error while removing user attribute: ", e.toString()); } break; case SET_USER_ATTRIBUTE: try { - setUserAttributes((MParticleDBManager.UserAttributeResponse)msg.obj); + setUserAttributes((MParticleDBManager.UserAttributeResponse) msg.obj); } catch (Exception e) { Logger.error(e, "Error while setting user attribute: ", e.toString()); } break; case INCREMENT_USER_ATTRIBUTE: try { - IncrementUserAttributeMessage obj = (IncrementUserAttributeMessage)msg.obj; + IncrementUserAttributeMessage obj = (IncrementUserAttributeMessage) msg.obj; incrementUserAttribute(obj); } catch (Exception e) { Logger.error(e, "Error while incrementing user attribute: ", e.toString()); @@ -288,7 +286,7 @@ private void incrementUserAttribute(IncrementUserAttributeMessage message) { wrapper.attributeSingles.put(message.key, newValue); wrapper.mpId = message.mpid; List attributionChanges = mMParticleDBManager.setUserAttribute(wrapper); - for (MParticleDBManager.AttributionChange attributeChange: attributionChanges) { + for (MParticleDBManager.AttributionChange attributeChange : attributionChanges) { logUserAttributeChanged(attributeChange); } MParticle instance = MParticle.getInstance(); @@ -299,7 +297,7 @@ private void incrementUserAttribute(IncrementUserAttributeMessage message) { private void dbInsertSession(BaseMPMessage message) throws JSONException { try { - DeviceAttributes deviceAttributes = mMessageManagerCallbacks.getDeviceAttributes(); + DeviceAttributes deviceAttributes = mMessageManagerCallbacks.getDeviceAttributes(); mMParticleDBManager.insertSession(message, mMessageManagerCallbacks.getApiKey(), deviceAttributes.getAppInfo(mContext), deviceAttributes.getDeviceInfo(mContext)); } catch (MParticleApiClientImpl.MPNoConfigException ex) { Logger.error("Unable to process uploads, API key and/or API Secret are missing."); diff --git a/android-core/src/main/java/com/mparticle/internal/MessageManager.java b/android-core/src/main/java/com/mparticle/internal/MessageManager.java index 1b87eb44c..8824a7e2e 100644 --- a/android-core/src/main/java/com/mparticle/internal/MessageManager.java +++ b/android-core/src/main/java/com/mparticle/internal/MessageManager.java @@ -52,7 +52,6 @@ /** * This class is primarily responsible for generating BaseMPMessage objects, and then adding them to a * queue which is then processed in a background thread for further processing and database storage. - * */ public class MessageManager implements MessageManagerCallbacks, ReportingManager { private static Context sContext = null; @@ -79,6 +78,7 @@ public class MessageManager implements MessageManagerCallbacks, ReportingManager */ MessageHandler mMessageHandler; public UploadHandler mUploadHandler; + /** * Ideally these threads would not be started in a static initializer * block. but this is cleaner than checking if they have been started in @@ -96,6 +96,7 @@ private static void startThreads() { sMessageHandlerThread.start(); sUploadHandlerThread.start(); } + /** * Used to communicate the current location at the time of message generation. Can be set * manually by the customer, or automatically via our our location listener, if enabled. @@ -285,7 +286,7 @@ public BaseMPMessage startSession(InternalSession session) { } catch (JSONException e) { Logger.warning("Failed to create First Run Message."); } - }else{ + } else { mMessageHandler.sendMessage(mMessageHandler.obtainMessage(MessageHandler.END_ORPHAN_SESSIONS, mConfigManager.getMpid())); } @@ -623,7 +624,7 @@ public BaseMPMessage logStateTransition(String stateTransInit, String currentAct } public void logNotification(ProviderCloudMessage cloudMessage, String appState) { - try{ + try { BaseMPMessage message = new BaseMPMessage.Builder(MessageType.PUSH_RECEIVED) .timestamp(System.currentTimeMillis()) .name("gcm") @@ -639,7 +640,7 @@ public void logNotification(ProviderCloudMessage cloudMessage, String appState) message.put(MessageKey.APP_STATE, appState); mMessageHandler.sendMessage(mMessageHandler.obtainMessage(MessageHandler.STORE_MESSAGE, message)); - }catch (JSONException e) { + } catch (JSONException e) { } } @@ -728,7 +729,7 @@ public BaseMPMessage logUserAttributeChangeMessage(String userAttributeKey, Obje } else if (newValue instanceof List) { JSONArray newValueArray = new JSONArray(); for (int i = 0; i < ((List) newValue).size(); i++) { - String value = (String)((List) newValue).get(i); + String value = (String) ((List) newValue).get(i); newValueArray.put(value); } newValue = newValueArray; @@ -740,7 +741,7 @@ public BaseMPMessage logUserAttributeChangeMessage(String userAttributeKey, Obje } else if (oldValue instanceof List) { JSONArray oldValueArray = new JSONArray(); for (int i = 0; i < ((List) oldValue).size(); i++) { - String value = (String)((List) oldValue).get(i); + String value = (String) ((List) oldValue).get(i); oldValueArray.put(value); } oldValue = oldValueArray; @@ -807,7 +808,7 @@ public void onFailed() { } }); } - }catch (Exception e){ + } catch (Exception e) { //this can sometimes fail due to wonky-device reasons. } } @@ -820,7 +821,7 @@ public void endUploadLoop() { @Override public void checkForTrigger(BaseMPMessage message) { - if (mConfigManager.shouldTrigger(message)){ + if (mConfigManager.shouldTrigger(message)) { mUploadHandler.removeMessages(UploadHandler.UPLOAD_TRIGGER_MESSAGES, mConfigManager.getMpid()); mUploadHandler.sendMessageDelayed(mUploadHandler.obtainMessage(UploadHandler.UPLOAD_TRIGGER_MESSAGES, 1, 0, mConfigManager.getMpid()), Constants.TRIGGER_MESSAGE_DELAY); } @@ -898,7 +899,7 @@ public void setUserAttribute(String key, Object value, long mpId, boolean synchr if (value instanceof List) { container.attributeLists = new HashMap<>(); container.attributeLists.put(key, (List) value); - }else { + } else { container.attributeSingles = new HashMap<>(); container.attributeSingles.put(key, value); } @@ -924,7 +925,7 @@ public Map getUserIdentities(long mpId) { return mConfigManager.getUserIdentities(mpId); } - public JSONArray getUserIdentityJson(long mpId){ + public JSONArray getUserIdentityJson(long mpId) { return mConfigManager.getUserIdentityJson(mpId); } @@ -944,7 +945,7 @@ Map> toStringListMap(Map map) { return null; } Map> listMap = new HashMap>(); - for (Map.Entry entry: map.entrySet()) { + for (Map.Entry entry : map.entrySet()) { listMap.put(entry.getKey(), Collections.singletonList(entry.getValue())); } return listMap; @@ -993,7 +994,7 @@ public void onReceive(Context appContext, Intent intent) { int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); sBatteryLevel = level / (double) scale; } - }catch (Exception e){ + } catch (Exception e) { //sometimes we're given a null intent, //or even if we have permissions to ACCESS_NETWORK_STATE, the call may fail. } @@ -1030,6 +1031,7 @@ public void disable() { mUploadHandler.disable(true); } } + public static void destroy() { if (sMessageHandlerThread != null) { sMessageHandlerThread.quit(); diff --git a/android-core/src/main/java/com/mparticle/internal/MessageManagerCallbacks.java b/android-core/src/main/java/com/mparticle/internal/MessageManagerCallbacks.java index b4c2f465c..8e07baa5f 100644 --- a/android-core/src/main/java/com/mparticle/internal/MessageManagerCallbacks.java +++ b/android-core/src/main/java/com/mparticle/internal/MessageManagerCallbacks.java @@ -4,12 +4,20 @@ public interface MessageManagerCallbacks { String getApiKey() throws MParticleApiClientImpl.MPNoConfigException; + void delayedStart(); + void endUploadLoop(); + void checkForTrigger(BaseMPMessage message); + void logNotification(int contentId, String payload, String appState, int behavior); + void attributeRemoved(String key, long mpId); + BaseMPMessage logUserAttributeChangeMessage(String userAttributeKey, Object newValue, Object oldValue, boolean deleted, boolean isNewAttribute, long time, long mpId); + DeviceAttributes getDeviceAttributes(); + void messagesClearedForUpload(); } diff --git a/android-core/src/main/java/com/mparticle/internal/ProviderPersistence.java b/android-core/src/main/java/com/mparticle/internal/ProviderPersistence.java index 7a04690b7..1ec4b98b4 100644 --- a/android-core/src/main/java/com/mparticle/internal/ProviderPersistence.java +++ b/android-core/src/main/java/com/mparticle/internal/ProviderPersistence.java @@ -2,9 +2,6 @@ import android.content.Context; import android.content.SharedPreferences; -import android.text.TextUtils; - -import com.mparticle.internal.MPUtility; import org.json.JSONArray; import org.json.JSONException; @@ -21,7 +18,7 @@ * server side via mParticle. Rather than start from stratch, it's crucial that we can query data that * the given SDK had been storing client-side. */ -class ProviderPersistence extends JSONObject{ +class ProviderPersistence extends JSONObject { static final String KEY_PERSISTENCE = "cms"; private static final String KEY_PERSISTENCE_ID = "id"; @@ -42,28 +39,28 @@ class ProviderPersistence extends JSONObject{ private static final int PERSISTENCE_TYPE_LONG = 5; - ProviderPersistence(JSONObject config, Context context) throws JSONException{ + ProviderPersistence(JSONObject config, Context context) throws JSONException { super(); JSONArray configPersistence = config.getJSONArray(KEY_PERSISTENCE); - for (int i = 0; i < configPersistence.length(); i++){ + for (int i = 0; i < configPersistence.length(); i++) { JSONObject values = new JSONObject(); - if (configPersistence.getJSONObject(i).has(KEY_PERSISTENCE_ANDROID)){ + if (configPersistence.getJSONObject(i).has(KEY_PERSISTENCE_ANDROID)) { JSONArray files = configPersistence.getJSONObject(i).getJSONArray(KEY_PERSISTENCE_ANDROID); - for (int fileIndex = 0; fileIndex < files.length(); fileIndex++){ + for (int fileIndex = 0; fileIndex < files.length(); fileIndex++) { JSONObject fileObject = files.getJSONObject(fileIndex); SharedPreferences preferences = context.getSharedPreferences(fileObject.getString(KEY_PERSISTENCE_FILE), fileObject.getInt(KEY_PERSISTENCE_MODE)); JSONArray fileObjects = fileObject.getJSONArray(KEY_PERSISTENCE_KEY_LIST); SharedPreferences.Editor editor = preferences.edit(); - for (int keyIndex = 0; keyIndex < fileObjects.length(); keyIndex++){ + for (int keyIndex = 0; keyIndex < fileObjects.length(); keyIndex++) { final int type = fileObjects.getJSONObject(keyIndex).getInt(KEY_PERSISTENCE_TYPE); final String key = fileObjects.getJSONObject(keyIndex).getString(KEY_PERSISTENCE_KEY); final String mpKey = fileObjects.getJSONObject(keyIndex).getString(KEY_PERSISTENCE_MPVAR); final String mpPersistenceKey = MPPREFIX + mpKey; - if (preferences.contains(mpPersistenceKey)){ + if (preferences.contains(mpPersistenceKey)) { values.put(mpKey, preferences.getString(mpPersistenceKey, null)); - }else{ + } else { String resolvedValue = null; if (preferences.contains(key)) { switch (type) { @@ -83,7 +80,7 @@ class ProviderPersistence extends JSONObject{ resolvedValue = Long.toString(preferences.getLong(key, 0)); break; } - }else{ + } else { resolvedValue = applyMacro(fileObjects.getJSONObject(keyIndex).getString(KEY_PERSISTENCE_DEFAULT)); } @@ -112,17 +109,17 @@ class ProviderPersistence extends JSONObject{ * Macros are used so that the /config API call can come from a CDN (not user-specific). */ private static String applyMacro(String defaultString) { - if (!MPUtility.isEmpty(defaultString) && defaultString.startsWith("%")){ + if (!MPUtility.isEmpty(defaultString) && defaultString.startsWith("%")) { defaultString = defaultString.toLowerCase(); - if (defaultString.equalsIgnoreCase(MACRO_GUID_NO_DASHES)){ + if (defaultString.equalsIgnoreCase(MACRO_GUID_NO_DASHES)) { return UUID.randomUUID().toString().replace("-", ""); - }else if (defaultString.equals(MACRO_OMNITURE_AID)){ + } else if (defaultString.equals(MACRO_OMNITURE_AID)) { return generateAID(); - }else if (defaultString.equals(MACRO_GUID)){ + } else if (defaultString.equals(MACRO_GUID)) { return UUID.randomUUID().toString(); - }else if (defaultString.equals(MACRO_TIMESTAMP)){ + } else if (defaultString.equals(MACRO_TIMESTAMP)) { return Long.toString(System.currentTimeMillis()); - }else if (defaultString.equals(MACRO_GUID_LEAST_SIG)){ + } else if (defaultString.equals(MACRO_GUID_LEAST_SIG)) { return Long.toString(UUID.randomUUID().getLeastSignificantBits()); } } diff --git a/android-core/src/main/java/com/mparticle/internal/PushRegistrationHelper.java b/android-core/src/main/java/com/mparticle/internal/PushRegistrationHelper.java index e1860ab12..6403201fc 100644 --- a/android-core/src/main/java/com/mparticle/internal/PushRegistrationHelper.java +++ b/android-core/src/main/java/com/mparticle/internal/PushRegistrationHelper.java @@ -29,22 +29,22 @@ public void run() { if (MPUtility.isFirebaseAvailablePreV21()) { Class clazz = Class.forName("com.google.firebase.iid.FirebaseInstanceId"); Object instance = clazz.getMethod("getInstance").invoke(null); - String instanceId = (String)clazz.getMethod("getToken", String.class, String.class).invoke(instance, senderId, "FCM"); + String instanceId = (String) clazz.getMethod("getToken", String.class, String.class).invoke(instance, senderId, "FCM"); setPushRegistration(context, instanceId, senderId); } else if (MPUtility.isFirebaseAvailablePostV21()) { com.google.firebase.messaging.FirebaseMessaging.getInstance().getToken() - .addOnSuccessListener(new OnSuccessListener() { - @Override - public void onSuccess(String instanceId) { - setPushRegistration(context, instanceId, senderId); - } - }) - .addOnFailureListener(new OnFailureListener() { - @Override - public void onFailure(@NonNull Exception e) { - Logger.error("Error registering for FCM Instance ID: ", e.getMessage()); - } - }); + .addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(String instanceId) { + setPushRegistration(context, instanceId, senderId); + } + }) + .addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + Logger.error("Error registering for FCM Instance ID: ", e.getMessage()); + } + }); } else { Logger.error("Error registering FCM Instance ID: no Firebase library"); } @@ -82,8 +82,10 @@ static void setPushRegistration(Context context, String instanceId, String sende } public static class PushRegistration { - @Nullable public String senderId; - @Nullable public String instanceId; + @Nullable + public String senderId; + @Nullable + public String instanceId; public PushRegistration(@Nullable String instanceId, @Nullable String senderId) { this.instanceId = instanceId; diff --git a/android-core/src/main/java/com/mparticle/internal/ReportingManager.java b/android-core/src/main/java/com/mparticle/internal/ReportingManager.java index 7f6f2920f..6c60800df 100644 --- a/android-core/src/main/java/com/mparticle/internal/ReportingManager.java +++ b/android-core/src/main/java/com/mparticle/internal/ReportingManager.java @@ -5,5 +5,6 @@ public interface ReportingManager { void log(JsonReportingMessage message); + void logAll(List messageList); } diff --git a/android-core/src/main/java/com/mparticle/internal/SegmentDatabase.java b/android-core/src/main/java/com/mparticle/internal/SegmentDatabase.java index 20a508cd8..761de42c8 100644 --- a/android-core/src/main/java/com/mparticle/internal/SegmentDatabase.java +++ b/android-core/src/main/java/com/mparticle/internal/SegmentDatabase.java @@ -44,9 +44,7 @@ interface SegmentMembershipTable { SegmentMembershipTable.SEGMENT_ID + " INTEGER NOT NULL, " + SegmentMembershipTable.TIMESTAMP + " REAL NOT NULL, " + SegmentMembershipTable.MEMBERSHIP_ACTION + " INTEGER NOT NULL, " + - " FOREIGN KEY ("+ SegmentMembershipTable.SEGMENT_ID+") REFERENCES "+ SegmentTable.TABLE_NAME+" ("+ SegmentTable.SEGMENT_ID +"));"; - - + " FOREIGN KEY (" + SegmentMembershipTable.SEGMENT_ID + ") REFERENCES " + SegmentTable.TABLE_NAME + " (" + SegmentTable.SEGMENT_ID + "));"; SegmentDatabase(Context context) { diff --git a/android-core/src/main/java/com/mparticle/internal/SegmentRetriever.java b/android-core/src/main/java/com/mparticle/internal/SegmentRetriever.java index 87a56c49e..44d2ae07f 100644 --- a/android-core/src/main/java/com/mparticle/internal/SegmentRetriever.java +++ b/android-core/src/main/java/com/mparticle/internal/SegmentRetriever.java @@ -43,7 +43,7 @@ SegmentMembership queryAudiences(String endpointId) { String selection = null; String[] args = null; - if (endpointId != null && endpointId.length() > 0){ + if (endpointId != null && endpointId.length() > 0) { selection = SegmentDatabase.SegmentTable.ENDPOINTS + " like ?"; args = new String[1]; args[0] = "%\"" + endpointId + "\"%"; @@ -59,8 +59,8 @@ SegmentMembership queryAudiences(String endpointId) { SparseArray audiences = new SparseArray(); StringBuilder keys = new StringBuilder("("); - if (audienceCursor.getCount() > 0){ - while (audienceCursor.moveToNext()){ + if (audienceCursor.getCount() > 0) { + while (audienceCursor.moveToNext()) { int id = audienceCursor.getInt(audienceCursor.getColumnIndexOrThrow(SegmentDatabase.SegmentTable.SEGMENT_ID)); Segment segment = new Segment(id, @@ -72,7 +72,7 @@ SegmentMembership queryAudiences(String endpointId) { } audienceCursor.close(); - keys.delete(keys.length()-2, keys.length()); + keys.delete(keys.length() - 2, keys.length()); keys.append(")"); long currentTime = System.currentTimeMillis(); @@ -91,12 +91,12 @@ SegmentMembership queryAudiences(String endpointId) { ArrayList finalSegments = new ArrayList(); int currentId = -1; - while (membershipCursor.moveToNext()){ + while (membershipCursor.moveToNext()) { int id = membershipCursor.getInt(1); if (id != currentId) { currentId = id; String action = membershipCursor.getString(2); - if (action.equals(Constants.Audience.ACTION_ADD)){ + if (action.equals(Constants.Audience.ACTION_ADD)) { finalSegments.add(audiences.get(currentId)); } } @@ -105,7 +105,7 @@ SegmentMembership queryAudiences(String endpointId) { db.close(); return new SegmentMembership(finalSegments); - }else{ + } else { return new SegmentMembership(new ArrayList()); } @@ -119,7 +119,7 @@ SegmentMembership queryAudiences(String endpointId) { SegmentDatabase.SegmentMembershipTable.SEGMENT_ID, SegmentDatabase.SegmentMembershipTable.MEMBERSHIP_ACTION }; - private final static String MEMBERSHIP_QUERY_SELECTION = SegmentDatabase.SegmentMembershipTable.SEGMENT_ID+ " in %s and " + SegmentDatabase.SegmentMembershipTable.TIMESTAMP + " < %d"; + private final static String MEMBERSHIP_QUERY_SELECTION = SegmentDatabase.SegmentMembershipTable.SEGMENT_ID + " in %s and " + SegmentDatabase.SegmentMembershipTable.TIMESTAMP + " < %d"; private void insertAudiences(JSONObject audiences) throws JSONException { SQLiteDatabase db = mAudienceDB.getWritableDatabase(); @@ -149,10 +149,10 @@ private void insertAudiences(JSONObject audiences) throws JSONException { } } success = true; - }catch (Exception e){ + } catch (Exception e) { Logger.debug("Failed to insert audiences: " + e.getMessage()); - }finally { - if (success){ + } finally { + if (success) { db.setTransactionSuccessful(); } db.endTransaction(); @@ -160,23 +160,26 @@ private void insertAudiences(JSONObject audiences) throws JSONException { } } + class SegmentTask extends AsyncTask { ExecutorService executor = Executors.newSingleThreadExecutor(); String endpointId; SegmentListener listener; long timeout; - SegmentTask(long timeout, String endpointId, SegmentListener listener){ + + SegmentTask(long timeout, String endpointId, SegmentListener listener) { this.timeout = timeout; this.endpointId = endpointId; this.listener = listener; } + @Override protected SegmentMembership doInBackground(Void... params) { FutureTask futureTask1 = new FutureTask(new Callable() { @Override public Boolean call() throws Exception { JSONObject audiences = mApiClient.fetchAudiences(); - if (audiences != null){ + if (audiences != null) { insertAudiences(audiences); } return audiences != null; diff --git a/android-core/src/main/java/com/mparticle/internal/UploadHandler.java b/android-core/src/main/java/com/mparticle/internal/UploadHandler.java index 2e2288fb4..790c8def4 100644 --- a/android-core/src/main/java/com/mparticle/internal/UploadHandler.java +++ b/android-core/src/main/java/com/mparticle/internal/UploadHandler.java @@ -1,8 +1,9 @@ package com.mparticle.internal; +import static com.mparticle.networking.NetworkConnection.HTTP_TOO_MANY_REQUESTS; + import android.content.Context; import android.content.SharedPreferences; -import android.os.Handler; import android.os.Looper; import android.os.Message; @@ -17,7 +18,6 @@ import com.mparticle.segmentation.SegmentListener; import org.json.JSONException; -import org.json.JSONObject; import java.io.IOException; import java.net.MalformedURLException; @@ -25,8 +25,6 @@ import javax.net.ssl.SSLHandshakeException; -import static com.mparticle.networking.NetworkConnection.HTTP_TOO_MANY_REQUESTS; - /** * Primary queue handler which is responsible for querying, packaging, and uploading data. */ @@ -77,7 +75,6 @@ public class UploadHandler extends BaseHandler { volatile boolean isNetworkConnected = true; /** - * * Only used for unit testing. */ UploadHandler(Context context, ConfigManager configManager, AppStateManager appStateManager, MessageManager messageManager, MParticleDBManager mparticleDBManager, @Nullable KitFrameworkWrapper kitFrameworkWrapper) { @@ -139,7 +136,7 @@ public void handleMessageImpl(Message msg) { long uploadInterval = mConfigManager.getUploadInterval(); if (isNetworkConnected) { if (uploadInterval > 0 || msg.arg1 == 1) { - while(mParticleDBManager.hasMessagesForUpload()) { + while (mParticleDBManager.hasMessagesForUpload()) { prepareMessageUploads(false); } boolean needsHistory = upload(false); @@ -162,7 +159,7 @@ public void handleMessageImpl(Message msg) { } } catch (MParticleApiClientImpl.MPConfigException e) { Logger.error("Bad API request - is the correct API key and secret configured?"); - } catch (Exception e){ + } catch (Exception e) { Logger.verbose("UploadHandler Exception while handling message: " + e.toString()); } catch (VerifyError ve) { Logger.verbose("UploadHandler VerifyError while handling message" + ve.toString()); @@ -320,14 +317,14 @@ void setApiClient(MParticleApiClient apiClient) { mApiClient = apiClient; } - public void setConnected(boolean connected){ + public void setConnected(boolean connected) { try { MParticle instance = MParticle.getInstance(); if (instance != null && !isNetworkConnected && connected && mConfigManager.isPushEnabled()) { instance.Messaging().enablePushNotifications(mConfigManager.getPushSenderId()); } - }catch (Exception e) { + } catch (Exception e) { } isNetworkConnected = connected; diff --git a/android-core/src/main/java/com/mparticle/internal/UserStorage.java b/android-core/src/main/java/com/mparticle/internal/UserStorage.java index 883d56da3..0190d89bb 100644 --- a/android-core/src/main/java/com/mparticle/internal/UserStorage.java +++ b/android-core/src/main/java/com/mparticle/internal/UserStorage.java @@ -1,5 +1,7 @@ package com.mparticle.internal; +import static com.mparticle.internal.ConfigManager.PREFERENCES_FILE; + import android.content.Context; import android.content.SharedPreferences; import android.net.UrlQuerySanitizer; @@ -15,8 +17,6 @@ import java.util.TreeSet; import java.util.UUID; -import static com.mparticle.internal.ConfigManager.PREFERENCES_FILE; - public class UserStorage { private static final String USER_CONFIG_COLLECTION = "mp::user_config_collection"; @@ -49,7 +49,7 @@ public class UserStorage { static List getAllUsers(Context context) { Set userMpIds = getMpIdSet(context); List userStorages = new ArrayList(); - for (Long mdId: userMpIds) { + for (Long mdId : userMpIds) { userStorages.add(new UserStorage(context, Long.valueOf(mdId))); } return userStorages; @@ -88,7 +88,7 @@ long getMpid() { return mpId; } - int getCurrentSessionCounter(){ + int getCurrentSessionCounter() { return getCurrentSessionCounter(0); } @@ -106,7 +106,7 @@ private boolean hasCurrentSessionCounter() { void incrementSessionCounter() { int nextCount = getCurrentSessionCounter() + 1; - if (nextCount >= (Integer.MAX_VALUE / 100)){ + if (nextCount >= (Integer.MAX_VALUE / 100)) { nextCount = 0; } mPreferences.edit().putInt(SESSION_COUNTER, nextCount).apply(); @@ -130,7 +130,7 @@ private boolean hasDeletedUserAttributes() { } int getBreadcrumbLimit() { - if (mPreferences != null){ + if (mPreferences != null) { return mPreferences.getInt(BREADCRUMB_LIMIT, DEFAULT_BREADCRUMB_LIMIT); } return DEFAULT_BREADCRUMB_LIMIT; @@ -343,13 +343,14 @@ static Set getMpIdSet(Context context) { JSONArray userConfigs = new JSONArray(); try { userConfigs = new JSONArray(getMParticleSharedPrefs(context).getString(USER_CONFIG_COLLECTION, new JSONArray().toString())); - } catch (JSONException ignore) {} + } catch (JSONException ignore) { + } Set mpIds = new TreeSet(); for (int i = 0; i < userConfigs.length(); i++) { try { mpIds.add(userConfigs.getLong(i)); + } catch (JSONException ignore) { } - catch (JSONException ignore) {} } return mpIds; } @@ -360,7 +361,7 @@ private void setMpIds(Set mpIds) { private static void setMpIds(Context context, Set mpIds) { JSONArray jsonArray = new JSONArray(); - for (Long mpId: mpIds) { + for (Long mpId : mpIds) { jsonArray.put(mpId); } getMParticleSharedPrefs(context).edit().putString(USER_CONFIG_COLLECTION, jsonArray.toString()).apply(); @@ -428,7 +429,6 @@ void merge(UserStorage userStorage) { * kept application-wide, to the current interface, which stores the values by MPID. The migration * process will associate all current values covered by UserStorage to the current MPID, which should * be passed into the parameter "currentMpId". - * **/ private static class SharedPreferencesMigrator { @@ -505,7 +505,7 @@ void migrate(UserStorage userStorage) { String dasParseString = jsonCookies.getJSONObject("uid").getString("c"); UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(dasParseString); das = sanitizer.getValue("g"); - }catch (Exception e) { + } catch (Exception e) { } userStorage.setCookies(cookies); @@ -525,8 +525,7 @@ void migrate(UserStorage userStorage) { if (userIdentities != null) { userStorage.setUserIdentities(userIdentities); } - } - catch (Exception ex) { + } catch (Exception ex) { //do nothing } } @@ -534,6 +533,7 @@ void migrate(UserStorage userStorage) { /** * Check if we have need to migrate from the old SharedPreferences schema. We will only need * to trigger a migration, if the flag is explicitly set to true. + * * @param context * @return */ diff --git a/android-core/src/main/java/com/mparticle/internal/database/MPDatabaseImpl.java b/android-core/src/main/java/com/mparticle/internal/database/MPDatabaseImpl.java index 8f328778c..2b8a95aff 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/MPDatabaseImpl.java +++ b/android-core/src/main/java/com/mparticle/internal/database/MPDatabaseImpl.java @@ -3,7 +3,6 @@ import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; -import android.os.Build; import android.provider.BaseColumns; import com.mparticle.internal.listeners.InternalListenerManager; @@ -13,9 +12,9 @@ import java.util.List; public class MPDatabaseImpl implements MPDatabase { - SQLiteDatabase sqLiteDatabase; + SQLiteDatabase sqLiteDatabase; - public MPDatabaseImpl(SQLiteDatabase database) { + public MPDatabaseImpl(SQLiteDatabase database) { this.sqLiteDatabase = database; } @@ -37,8 +36,8 @@ public Cursor rawQuery(String query, String... selectionArgs) { @Override public Cursor query(String table, String[] columns, String selection, - String[] selectionArgs, String groupBy, String having, - String orderBy, String limit) { + String[] selectionArgs, String groupBy, String having, + String orderBy, String limit) { if (InternalListenerManager.isEnabled()) { columns = getColumnsWithId(columns); } @@ -87,7 +86,7 @@ private String[] getColumnsWithId(String[] columns) { return columns; } boolean found = false; - for (String column: columns) { + for (String column : columns) { if (column.equals(BaseColumns._ID)) { found = true; } diff --git a/android-core/src/main/java/com/mparticle/internal/database/services/BreadcrumbService.java b/android-core/src/main/java/com/mparticle/internal/database/services/BreadcrumbService.java index aba53a481..e4cb60184 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/services/BreadcrumbService.java +++ b/android-core/src/main/java/com/mparticle/internal/database/services/BreadcrumbService.java @@ -7,7 +7,6 @@ import com.mparticle.internal.ConfigManager; import com.mparticle.internal.Constants; import com.mparticle.internal.Logger; -import com.mparticle.internal.MessageManager; import com.mparticle.internal.database.MPDatabase; import com.mparticle.internal.database.tables.BreadcrumbTable; import com.mparticle.internal.messages.BaseMPMessage; @@ -69,8 +68,7 @@ static int getBreadcrumbCount(MPDatabase db, Long mpid) { null, null); return rawIds.getCount(); - } - finally { + } finally { if (rawIds != null && !rawIds.isClosed()) { rawIds.close(); } diff --git a/android-core/src/main/java/com/mparticle/internal/database/services/MParticleDBManager.java b/android-core/src/main/java/com/mparticle/internal/database/services/MParticleDBManager.java index 290e64bc7..0135b9698 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/services/MParticleDBManager.java +++ b/android-core/src/main/java/com/mparticle/internal/database/services/MParticleDBManager.java @@ -65,6 +65,7 @@ public MParticleDBManager(Context context) { /** * Creates a new SQLiteDatabase instance, if the Database has not been opened yet, it returns * an instance. Each instance is a singleton, per thread. + * * @return */ public MPDatabase getDatabase() { @@ -81,18 +82,13 @@ public void updateMpId(long oldMpId, long newMpId) { new SessionService().updateMpId(db, oldMpId, newMpId); new UserAttributesService().updateMpId(db, oldMpId, newMpId); db.setTransactionSuccessful(); - } - finally { + } finally { db.endTransaction(); } } /** - * - * * Breadcumb Service Methods. - * - * */ @@ -108,11 +104,7 @@ public void appendBreadcrumbs(BaseMPMessage message) throws JSONException { } /** - * - * * Message Service Methods. - * - * */ public void cleanupMessages() { @@ -128,7 +120,7 @@ public void insertMessage(String apiKey, BaseMPMessage message, String dataplanI private static MessageListener sMessageListener; - static void setMessageListener(MessageListener messageListener){ + static void setMessageListener(MessageListener messageListener) { sMessageListener = messageListener; } @@ -141,15 +133,11 @@ public interface MessageListener { } /** - * - * * Prepare Messages for Upload. - * - * */ public void createSessionHistoryUploadMessage(ConfigManager configManager, DeviceAttributes deviceAttributes, String currentSessionId) throws JSONException { - MPDatabase db = getDatabase(); + MPDatabase db = getDatabase(); db.beginTransaction(); try { List readyMessages = MessageService.getSessionHistory(db, currentSessionId); @@ -166,8 +154,7 @@ public void createSessionHistoryUploadMessage(ConfigManager configManager, Devic } createUploads(uploadMessagesByBatchId, db, deviceAttributes, configManager, currentSessionId, true); db.setTransactionSuccessful(); - } - finally { + } finally { db.endTransaction(); } } @@ -178,7 +165,7 @@ public boolean hasMessagesForUpload() { } public void createMessagesForUploadMessage(ConfigManager configManager, DeviceAttributes deviceAttributes, String currentSessionId, boolean sessionHistoryEnabled) throws JSONException { - MPDatabase db = getDatabase(); + MPDatabase db = getDatabase(); db.beginTransaction(); try { List readyMessages = MessageService.getMessagesForUpload(db); @@ -224,23 +211,21 @@ public void createMessagesForUploadMessage(ConfigManager configManager, DeviceAt } createUploads(uploadMessagesByBatchId, db, deviceAttributes, configManager, currentSessionId, false, sessionHistoryEnabled); db.setTransactionSuccessful(); - } - finally { + } finally { db.endTransaction(); } } public void deleteMessagesAndSessions(String currentSessionId) { - MPDatabase db = getDatabase(); - try { - db.beginTransaction(); - MessageService.deleteOldMessages(db, currentSessionId); - SessionService.deleteSessions(db, currentSessionId); - db.setTransactionSuccessful(); - } - finally { - db.endTransaction(); - } + MPDatabase db = getDatabase(); + try { + db.beginTransaction(); + MessageService.deleteOldMessages(db, currentSessionId); + SessionService.deleteSessions(db, currentSessionId); + db.setTransactionSuccessful(); + } finally { + db.endTransaction(); + } } private HashMap getUploadMessageByBatchIdMap(List readyMessages, MPDatabase db, ConfigManager configManager, boolean isHistory) throws JSONException { @@ -248,7 +233,7 @@ private HashMap getUploadMessageByBatchIdMap(List getUploadMessageByBatchIdMap(List readyMessages, MPDatabase db, ConfigManager configManager, boolean isHistory, boolean markAsUpload) throws JSONException { - HashMap uploadMessagesByBatchId= new HashMap(); + HashMap uploadMessagesByBatchId = new HashMap(); int highestUploadedMessageId = -1; for (MessageService.ReadyMessage readyMessage : readyMessages) { BatchId batchId = new BatchId(readyMessage); @@ -339,6 +324,7 @@ private void createUploads(Map uploadMessagesByBatchId, M /** * remove Session entries that do not have Message entries referencing them, and * are not the current Session + * * @param currentSessionId */ void cleanSessions(String currentSessionId) { @@ -361,7 +347,8 @@ private JSONObject findUserAttributeState(JSONArray messages, long mpId) { messages.getJSONObject(i).remove(Constants.MessageKey.USER_ATTRIBUTES); } } catch (JSONException ignored) { - } catch (NullPointerException ignored) { } + } catch (NullPointerException ignored) { + } } } if (userAttributes == null) { @@ -384,7 +371,8 @@ private JSONArray findIdentityState(ConfigManager configManager, JSONArray messa messages.getJSONObject(i).remove(Constants.MessageKey.USER_IDENTITIES); } } catch (JSONException ignored) { - } catch (NullPointerException ignored) { } + } catch (NullPointerException ignored) { + } } } if (identities == null) { @@ -396,7 +384,7 @@ private JSONArray findIdentityState(ConfigManager configManager, JSONArray messa /** * Method that is responsible for building an upload message to be sent over the wire. - **/ + **/ private MessageBatch createUploadMessage(ConfigManager configManager, boolean history, BatchId batchId) throws JSONException { MessageBatch batchMessage = MessageBatch.create( history, @@ -439,15 +427,14 @@ public BaseMPMessage getSessionForSessionEndMessage(String sessionId, Location l endMessage.put(Constants.MessageKey.ID, UUID.randomUUID().toString()); } return endMessage; - } - finally { + } finally { if (selectCursor != null && !selectCursor.isClosed()) { selectCursor.close(); } } } - BaseMPMessage createMessageSessionEnd(String sessionId, long start, long end, long foregroundLength, JSONObject sessionAttributes, Location location, Set mpIds) throws JSONException{ + BaseMPMessage createMessageSessionEnd(String sessionId, long start, long end, long foregroundLength, JSONObject sessionAttributes, Location location, Set mpIds) throws JSONException { int eventCounter = mPreferences.getInt(Constants.PrefKeys.EVENT_COUNTER, 0); resetEventCounter(); InternalSession session = new InternalSession(); @@ -455,7 +442,7 @@ BaseMPMessage createMessageSessionEnd(String sessionId, long start, long end, lo session.mSessionStartTime = start; JSONArray spanningMpids = new JSONArray(); long storageMpid = Constants.TEMPORARY_MPID; - for (Long mpid: mpIds) { + for (Long mpid : mpIds) { //We do not need to associate a SessionEnd message with any particular MPID, as long as it is not == Constants.TEMPORARY_MPID. if (mpid != Constants.TEMPORARY_MPID) { spanningMpids.put(mpid); @@ -474,7 +461,7 @@ BaseMPMessage createMessageSessionEnd(String sessionId, long start, long end, lo return message; } - private void resetEventCounter(){ + private void resetEventCounter() { mPreferences.edit().putInt(Constants.PrefKeys.EVENT_COUNTER, 0).apply(); } @@ -492,11 +479,7 @@ public void insertSession(BaseMPMessage message, String apiKey, JSONObject appIn /** - * - * * Reporting Service Methods - * - * */ public void insertReportingMessages(List reportingMessages, long mpId) { @@ -515,13 +498,8 @@ public void insertReportingMessages(List reportingMessages } - /** - * - * * Upload Service Methods - * - * */ @@ -542,18 +520,14 @@ public void insertAliasRequest(String apiKey, JSONObject request) { } /** - * - * * UserAttribute Service Methods - * - * */ public Map getUserAttributeSingles(long mpId) { if (getDatabase() != null) { Map stringifiedAttributes = UserAttributesService.getUserAttributesSingles(getDatabase(), mpId); Map typedAttributes = new HashMap<>(); - for (Map.Entry stringifiedAttribute: stringifiedAttributes.entrySet()) { + for (Map.Entry stringifiedAttribute : stringifiedAttributes.entrySet()) { String key = stringifiedAttribute.getKey(); String value = stringifiedAttribute.getValue(); typedAttributes.put(key, MPUtility.toNumberOrString(value)); @@ -571,21 +545,22 @@ public TreeMap> getUserAttributeLists(long mpId) { } - public JSONObject getAllUserAttributesJson(long mpId) { + public JSONObject getAllUserAttributesJson(long mpId) { Map attributes = getUserAttributes(null, mpId); JSONObject jsonAttributes = new JSONObject(); for (Map.Entry entry : attributes.entrySet()) { Object value = entry.getValue(); if (entry.getValue() instanceof List) { - List attributeList = (List)value; + List attributeList = (List) value; JSONArray jsonArray = new JSONArray(); for (String attribute : attributeList) { jsonArray.put(attribute); } try { jsonAttributes.put(entry.getKey(), jsonArray); - } catch (JSONException ignored) { } - }else { + } catch (JSONException ignored) { + } + } else { try { Object entryValue = entry.getValue(); if (entryValue == null) { @@ -619,7 +594,7 @@ public Map getUserAttributes(final UserAttributeListenerWrapper allUserAttributes.putAll(userAttributeLists); } return allUserAttributes; - }else { + } else { MParticle instance = MParticle.getInstance(); if (instance != null) { instance.Internal().getMessageManager().getMessageHandler().post(new Runnable() { @@ -642,7 +617,7 @@ public void run() { public List setUserAttribute(UserAttributeResponse userAttribute) { List attributionChanges = new ArrayList(); - if (getDatabase() == null){ + if (getDatabase() == null) { return attributionChanges; } Map currentValues = getUserAttributes(null, userAttribute.mpId); @@ -684,7 +659,7 @@ public List setUserAttribute(UserAttributeResponse userAttrib } } db.setTransactionSuccessful(); - }catch (Exception e){ + } catch (Exception e) { Logger.error(e, "Error while adding user attributes: ", e.toString()); } finally { db.endTransaction(); diff --git a/android-core/src/main/java/com/mparticle/internal/database/services/MessageService.java b/android-core/src/main/java/com/mparticle/internal/database/services/MessageService.java index 85deabce3..8bc11d9e9 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/services/MessageService.java +++ b/android-core/src/main/java/com/mparticle/internal/database/services/MessageService.java @@ -20,7 +20,7 @@ public class MessageService extends MessageTable { private final static String[] prepareSelection = new String[]{"_id", MessageTableColumns.MESSAGE, MessageTableColumns.CREATED_AT, MessageTableColumns.STATUS, MessageTableColumns.SESSION_ID, MessageTableColumns.MP_ID, MessageTableColumns.DATAPLAN_ID, MessageTableColumns.DATAPLAN_VERSION}; - private final static String prepareOrderBy = MessageTableColumns._ID + " asc"; + private final static String prepareOrderBy = MessageTableColumns._ID + " asc"; private static String getSessionHistorySelection(boolean includesMpid) { return String.format( @@ -39,12 +39,11 @@ public static Set getSessionIds(MPDatabase database) { Cursor cursor = null; try { cursor = database.rawQuery("SELECT DISTINCT " + MessageTableColumns.SESSION_ID + " FROM " + MessageTableColumns.TABLE_NAME); // mobsf-ignore: sqlite_injection - while(cursor.moveToNext()) { + while (cursor.moveToNext()) { sessionIds.add(cursor.getString(0)); } return sessionIds; - } - finally { + } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } @@ -55,7 +54,7 @@ public static List getSessionHistory(MPDatabase database, String c return getSessionHistory(database, currentSessionId, false, Constants.TEMPORARY_MPID); } - static List getSessionHistory(MPDatabase database, String currentSessionId, boolean includes, long mpid){ + static List getSessionHistory(MPDatabase database, String currentSessionId, boolean includes, long mpid) { String[] selectionArgs = new String[]{currentSessionId, String.valueOf(mpid)}; Cursor readyMessagesCursor = null; List readyMessages = new ArrayList(); @@ -88,8 +87,7 @@ static List getSessionHistory(MPDatabase database, String currentS InternalListenerManager.getListener().onCompositeObjects(readyMessagesCursor, readyMessage); readyMessages.add(readyMessage); } - } - finally { + } finally { if (readyMessagesCursor != null && !readyMessagesCursor.isClosed()) { readyMessagesCursor.close(); } @@ -97,7 +95,7 @@ static List getSessionHistory(MPDatabase database, String currentS return readyMessages; } - public static int deleteOldMessages(MPDatabase database, String currentSessionId){ + public static int deleteOldMessages(MPDatabase database, String currentSessionId) { String[] selectionArgs = new String[]{currentSessionId, String.valueOf(Constants.TEMPORARY_MPID)}; return database.delete( MessageTableColumns.TABLE_NAME, @@ -116,8 +114,7 @@ public static boolean hasMessagesForUpload(MPDatabase database) { null, prepareOrderBy); return messageIds.getCount() > 0; - } - finally { + } finally { if (messageIds != null && !messageIds.isClosed()) { messageIds.close(); } @@ -132,7 +129,7 @@ public static List getMessagesForUpload(MPDatabase database) { return getMessagesForUpload(database, false, Constants.TEMPORARY_MPID); } - static List getMessagesForUpload(MPDatabase database, boolean includes, long mpid){ + static List getMessagesForUpload(MPDatabase database, boolean includes, long mpid) { Cursor readyMessagesCursor = null; List readyMessages = new ArrayList(); try { @@ -164,8 +161,7 @@ static List getMessagesForUpload(MPDatabase database, boolean incl InternalListenerManager.getListener().onCompositeObjects(readyMessagesCursor, readyMessage); readyMessages.add(readyMessage); } - } - finally { + } finally { if (readyMessagesCursor != null && !readyMessagesCursor.isClosed()) { readyMessagesCursor.close(); } diff --git a/android-core/src/main/java/com/mparticle/internal/database/services/SQLiteOpenHelperWrapper.java b/android-core/src/main/java/com/mparticle/internal/database/services/SQLiteOpenHelperWrapper.java index 2bb400c31..55b7a1e2e 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/services/SQLiteOpenHelperWrapper.java +++ b/android-core/src/main/java/com/mparticle/internal/database/services/SQLiteOpenHelperWrapper.java @@ -5,7 +5,9 @@ public interface SQLiteOpenHelperWrapper { void onCreate(SQLiteDatabase database); + void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion); + void onDowngrade(SQLiteDatabase database, int oldVersion, int newVersion); } diff --git a/android-core/src/main/java/com/mparticle/internal/database/services/SessionService.java b/android-core/src/main/java/com/mparticle/internal/database/services/SessionService.java index a66a79e39..8560e903e 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/services/SessionService.java +++ b/android-core/src/main/java/com/mparticle/internal/database/services/SessionService.java @@ -1,5 +1,9 @@ package com.mparticle.internal.database.services; +import static com.mparticle.internal.database.tables.SessionTable.SessionTableColumns.APP_INFO; +import static com.mparticle.internal.database.tables.SessionTable.SessionTableColumns.SESSION_ID; +import static com.mparticle.internal.database.tables.SessionTable.SessionTableColumns.TABLE_NAME; + import android.content.ContentValues; import android.database.Cursor; import android.text.TextUtils; @@ -20,27 +24,24 @@ import java.util.Map; import java.util.Set; -import static com.mparticle.internal.database.tables.SessionTable.SessionTableColumns.APP_INFO; -import static com.mparticle.internal.database.tables.SessionTable.SessionTableColumns.SESSION_ID; -import static com.mparticle.internal.database.tables.SessionTable.SessionTableColumns.TABLE_NAME; - public class SessionService extends SessionTable { public static String[] readyMessages = new String[]{Integer.toString(Constants.Status.UPLOADED)}; - public static int deleteSessions(MPDatabase database, String currentSessionId){ + public static int deleteSessions(MPDatabase database, String currentSessionId) { String[] selectionArgs = new String[]{currentSessionId}; return database.delete(TABLE_NAME, SessionTableColumns.SESSION_ID + "!=? ", selectionArgs); } /** * delete Session entries with session_id that are not a part of the Set + * * @param database * @param exceptSessionIds the session_id value for message that SHOULD NOT be deleted * @return the number of Session entries deleted */ public static int deleteSessions(MPDatabase database, Set exceptSessionIds) { List idsWrapped = new ArrayList(); - for (String id: exceptSessionIds) { + for (String id : exceptSessionIds) { idsWrapped.add("'" + id + "'"); } String idArgString = TextUtils.join(",", idsWrapped.toArray()); @@ -105,8 +106,7 @@ public static List getOrphanSessionIds(MPDatabase db, String apiKey) { sessionIds.add(selectCursor.getString(0)); } return sessionIds; - } - finally { + } finally { if (selectCursor != null && !selectCursor.isClosed()) { selectCursor.close(); } @@ -142,7 +142,7 @@ public static List processSessions(MPDatabase database, HashMap processSessions(MPDatabase database, HashMap processSessions(MPDatabase database, HashMap> flattenBySessionId(Map uploadMessagesByBatchId) { Map> uploadMessagesBySessionId = new HashMap>(); - for (Map.Entry batchEntry: uploadMessagesByBatchId.entrySet()) { + for (Map.Entry batchEntry : uploadMessagesByBatchId.entrySet()) { String sessionId = batchEntry.getKey().getSessionId(); List messageBatches = uploadMessagesBySessionId.get(sessionId); if (messageBatches == null) { diff --git a/android-core/src/main/java/com/mparticle/internal/database/services/UploadService.java b/android-core/src/main/java/com/mparticle/internal/database/services/UploadService.java index 202bf66fd..122b88df9 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/services/UploadService.java +++ b/android-core/src/main/java/com/mparticle/internal/database/services/UploadService.java @@ -4,7 +4,6 @@ import android.database.Cursor; import com.mparticle.internal.Constants; -import com.mparticle.internal.MessageBatch; import com.mparticle.internal.database.MPDatabase; import com.mparticle.internal.database.tables.UploadTable; import com.mparticle.internal.listeners.InternalListenerManager; @@ -50,8 +49,7 @@ public static List getReadyUploads(MPDatabase da readyUploads.add(readyUpload); InternalListenerManager.getListener().onCompositeObjects(readyUploadsCursor, readyUpload); } - } - finally { + } finally { if (readyUploadsCursor != null && !readyUploadsCursor.isClosed()) { readyUploadsCursor.close(); } diff --git a/android-core/src/main/java/com/mparticle/internal/database/services/UserAttributesService.java b/android-core/src/main/java/com/mparticle/internal/database/services/UserAttributesService.java index bc513a6c2..17d695172 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/services/UserAttributesService.java +++ b/android-core/src/main/java/com/mparticle/internal/database/services/UserAttributesService.java @@ -3,7 +3,6 @@ import android.content.ContentValues; import android.database.Cursor; -import com.mparticle.MParticle; import com.mparticle.internal.Logger; import com.mparticle.internal.database.MPDatabase; import com.mparticle.internal.database.tables.UserAttributesTable; @@ -33,15 +32,15 @@ public static TreeMap getUserAttributesSingles(MPDatabase db, lo TreeMap attributes = new TreeMap(String.CASE_INSENSITIVE_ORDER); Cursor cursor = null; try { - String[] args = {"1", String.valueOf(mpId)}; + String[] args = {"1", String.valueOf(mpId)}; - cursor = db.query(UserAttributesTableColumns.TABLE_NAME, null, UserAttributesTableColumns.IS_LIST + " != ? and " + UserAttributesTableColumns.MP_ID + " = ?", args, null, null, UserAttributesTableColumns.ATTRIBUTE_KEY + ", "+ UserAttributesTableColumns.CREATED_AT +" desc"); + cursor = db.query(UserAttributesTableColumns.TABLE_NAME, null, UserAttributesTableColumns.IS_LIST + " != ? and " + UserAttributesTableColumns.MP_ID + " = ?", args, null, null, UserAttributesTableColumns.ATTRIBUTE_KEY + ", " + UserAttributesTableColumns.CREATED_AT + " desc"); int keyIndex = cursor.getColumnIndexOrThrow(UserAttributesTableColumns.ATTRIBUTE_KEY); int valueIndex = cursor.getColumnIndexOrThrow(UserAttributesTableColumns.ATTRIBUTE_VALUE); while (cursor.moveToNext()) { attributes.put(cursor.getString(keyIndex), cursor.getString(valueIndex)); } - }catch (Exception e) { + } catch (Exception e) { Logger.error(e, "Error while querying user attributes: ", e.toString()); } finally { if (cursor != null && !cursor.isClosed()) { @@ -55,22 +54,22 @@ public static TreeMap> getUserAttributesLists(MPDatabase db TreeMap> attributes = new TreeMap>(String.CASE_INSENSITIVE_ORDER); Cursor cursor = null; try { - String[] args = {"1", String.valueOf(mpId)}; - cursor = db.query(UserAttributesTableColumns.TABLE_NAME, null, UserAttributesTableColumns.IS_LIST + " = ? and " + UserAttributesTableColumns.MP_ID + " = ?", args, null, null, UserAttributesTableColumns.ATTRIBUTE_KEY + ", "+ UserAttributesTableColumns.CREATED_AT +" desc"); + String[] args = {"1", String.valueOf(mpId)}; + cursor = db.query(UserAttributesTableColumns.TABLE_NAME, null, UserAttributesTableColumns.IS_LIST + " = ? and " + UserAttributesTableColumns.MP_ID + " = ?", args, null, null, UserAttributesTableColumns.ATTRIBUTE_KEY + ", " + UserAttributesTableColumns.CREATED_AT + " desc"); int keyIndex = cursor.getColumnIndexOrThrow(UserAttributesTableColumns.ATTRIBUTE_KEY); int valueIndex = cursor.getColumnIndexOrThrow(UserAttributesTableColumns.ATTRIBUTE_VALUE); String previousKey = null; List currentList = null; while (cursor.moveToNext()) { String currentKey = cursor.getString(keyIndex); - if (!currentKey.equals(previousKey)){ + if (!currentKey.equals(previousKey)) { previousKey = currentKey; currentList = new ArrayList(); attributes.put(currentKey, currentList); } attributes.get(currentKey).add(cursor.getString(valueIndex)); } - }catch (Exception e) { + } catch (Exception e) { Logger.error(e, "Error while querying user attribute lists: ", e.toString()); } finally { if (cursor != null && !cursor.isClosed()) { diff --git a/android-core/src/main/java/com/mparticle/internal/database/tables/MParticleDatabaseHelper.java b/android-core/src/main/java/com/mparticle/internal/database/tables/MParticleDatabaseHelper.java index 2a766e1dc..7c1ff65c8 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/tables/MParticleDatabaseHelper.java +++ b/android-core/src/main/java/com/mparticle/internal/database/tables/MParticleDatabaseHelper.java @@ -5,15 +5,12 @@ import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; -import android.os.Message; import androidx.annotation.VisibleForTesting; -import com.mparticle.MParticle; import com.mparticle.internal.ConfigManager; import com.mparticle.internal.Constants; import com.mparticle.internal.Logger; -import com.mparticle.internal.MPUtility; import com.mparticle.internal.database.services.SQLiteOpenHelperWrapper; import org.json.JSONException; @@ -25,6 +22,7 @@ public class MParticleDatabaseHelper implements SQLiteOpenHelperWrapper { private final Context mContext; public static final int DB_VERSION = 9; private static String DB_NAME = "mparticle.db"; + public static String getDbName() { return DB_NAME; } @@ -114,7 +112,7 @@ private void upgradeMpId(SQLiteDatabase db) { BreadcrumbTable.BreadcrumbTableColumns.TABLE_NAME, MessageTable.MessageTableColumns.TABLE_NAME }; - for (String tableName: tableNames) { + for (String tableName : tableNames) { SQLiteStatement statement = db.compileStatement(String.format(updateStatement, tableName, MpIdDependentTable.MP_ID, currentMpId)); statement.execute(); } @@ -156,8 +154,7 @@ private void upgradeUserAttributes(SQLiteDatabase db) { private void removeGcmTable(SQLiteDatabase db) { try { db.execSQL("DROP TABLE IF EXISTS gcm_messages"); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } diff --git a/android-core/src/main/java/com/mparticle/internal/database/tables/MpIdDependentTable.java b/android-core/src/main/java/com/mparticle/internal/database/tables/MpIdDependentTable.java index 00526afd6..04574662d 100644 --- a/android-core/src/main/java/com/mparticle/internal/database/tables/MpIdDependentTable.java +++ b/android-core/src/main/java/com/mparticle/internal/database/tables/MpIdDependentTable.java @@ -1,7 +1,7 @@ package com.mparticle.internal.database.tables; import android.content.ContentValues; -import android.database.sqlite.SQLiteDatabase; + import com.mparticle.internal.database.MPDatabase; public abstract class MpIdDependentTable { @@ -10,8 +10,8 @@ public abstract class MpIdDependentTable { public abstract String getTableName(); public void updateMpId(MPDatabase database, long oldMpId, long newMpId) { - ContentValues contentValues = new ContentValues(); - contentValues.put(MP_ID, newMpId); - database.update(getTableName(), contentValues, MP_ID + " = ?", new String[]{String.valueOf(oldMpId)}); + ContentValues contentValues = new ContentValues(); + contentValues.put(MP_ID, newMpId); + database.update(getTableName(), contentValues, MP_ID + " = ?", new String[]{String.valueOf(oldMpId)}); } } diff --git a/android-core/src/main/java/com/mparticle/internal/listeners/ApiClass.java b/android-core/src/main/java/com/mparticle/internal/listeners/ApiClass.java index 78e3969dd..0812efcf3 100644 --- a/android-core/src/main/java/com/mparticle/internal/listeners/ApiClass.java +++ b/android-core/src/main/java/com/mparticle/internal/listeners/ApiClass.java @@ -7,4 +7,5 @@ @Retention(RetentionPolicy.CLASS) @Target(ElementType.TYPE) -public @interface ApiClass { } +public @interface ApiClass { +} diff --git a/android-core/src/main/java/com/mparticle/internal/listeners/GraphListener.java b/android-core/src/main/java/com/mparticle/internal/listeners/GraphListener.java index 40fad3cb6..973a9fe94 100644 --- a/android-core/src/main/java/com/mparticle/internal/listeners/GraphListener.java +++ b/android-core/src/main/java/com/mparticle/internal/listeners/GraphListener.java @@ -1,10 +1,12 @@ package com.mparticle.internal.listeners; import android.os.Message; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; interface GraphListener { void onCompositeObjects(@Nullable Object child, @Nullable Object parent); + void onThreadMessage(@NonNull String handlerName, @Nullable Message msg, boolean onNewThread, @Nullable StackTraceElement[] stackTrace); } diff --git a/android-core/src/main/java/com/mparticle/internal/listeners/InternalListener.java b/android-core/src/main/java/com/mparticle/internal/listeners/InternalListener.java index 700b6ebf3..e7d546a84 100644 --- a/android-core/src/main/java/com/mparticle/internal/listeners/InternalListener.java +++ b/android-core/src/main/java/com/mparticle/internal/listeners/InternalListener.java @@ -3,6 +3,7 @@ import android.content.ContentValues; import android.os.Build; import android.os.Message; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; @@ -28,8 +29,9 @@ public interface InternalListener { * To be called when a Kit's API method is invoked. This overloaded variant should be used when * the name of the method containing this method's invocation (in KitManagerImpl) matches the name of the * Kit's method being invoked - * @param kitId the Id of the kit - * @param used whether the Kit's method returned ReportingMessages, or null if return type is void + * + * @param kitId the Id of the kit + * @param used whether the Kit's method returned ReportingMessages, or null if return type is void * @param objects the arguments supplied to the Kit */ void onKitApiCalled(int kitId, Boolean used, Object... objects); @@ -37,17 +39,19 @@ public interface InternalListener { /** * to be called when a Kit's API method is invoked, and the name of the Kit's method is different * then the method containing this method's invocation + * * @param methodName the name of the Kit's method being called - * @param kitId the Id of the kit - * @param used whether the Kit's method returned ReportingMessages, or null if return type is void - * @param objects the arguments supplied to the Kit + * @param kitId the Id of the kit + * @param used whether the Kit's method returned ReportingMessages, or null if return type is void + * @param objects the arguments supplied to the Kit */ void onKitApiCalled(String methodName, int kitId, Boolean used, Object... objects); /** * establishes a child-parent relationship between two objects. It is not necessary to call this * method for objects headed to the MessageHandler from the public API, or objects headed to kits - * @param child the child object + * + * @param child the child object * @param parent the parent object */ void onCompositeObjects(@Nullable Object child, @Nullable Object parent); @@ -58,14 +62,15 @@ public interface InternalListener { * and once as soon as it lands on the new Thread * * @param handlerName the Name of the Handler class, for example "com.mparticle.internal.MessageHandler" - * @param msg the Message object + * @param msg the Message object */ void onThreadMessage(@NonNull String handlerName, @NonNull Message msg, boolean onNewThread); /** * indicates that an entry has been stored in the Database - * @param rowId the rowId denoted by the "_id" column value - * @param tableName the name of the database table + * + * @param rowId the rowId denoted by the "_id" column value + * @param tableName the name of the database table * @param contentValues the ContentValues object to be inserted */ @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB) @@ -73,17 +78,19 @@ public interface InternalListener { /** * indicates that a Network Request has been started - * @param type the type of Request, should either be "CONFIG", "EVENTS" or "Identity.Login/Logout/Identify/Modify" - * @param url the request url - * @param body the request body + * + * @param type the type of Request, should either be "CONFIG", "EVENTS" or "Identity.Login/Logout/Identify/Modify" + * @param url the request url + * @param body the request body * @param objects any underlying objects that the request body is derived from, for example, an IdentityApiRequest instance */ void onNetworkRequestStarted(SdkListener.Endpoint type, String url, JSONObject body, Object... objects); /** * indicates that a NetworkRequest has been finished - * @param url the request url - * @param response the response body + * + * @param url the request url + * @param response the response body * @param responseCode the response code */ void onNetworkRequestFinished(SdkListener.Endpoint type, String url, JSONObject response, int responseCode); @@ -91,18 +98,21 @@ public interface InternalListener { /** * this should be called when the current Session changes, for example, it starts, stops or the * event count changes + * * @param internalSession */ void onSessionUpdated(InternalSession internalSession); /** * indicates that a Kit dependency is present + * * @param kitId */ void onKitDetected(int kitId); /** * indicates that we have received a configuration for a Kit + * * @param kitId * @param configuration */ @@ -112,6 +122,7 @@ public interface InternalListener { * indicates that a Kit was present, and a configuration was received for it, but it was not started, * or it was stopped. This could be because it crashed, or because a User's logged in status required * that we shut it down + * * @param kitId * @param reason */ @@ -119,6 +130,7 @@ public interface InternalListener { /** * indicates that a Kit successfully executed it's onKitCreate() method + * * @param kitId */ void onKitStarted(int kitId); @@ -127,19 +139,31 @@ public interface InternalListener { InternalListener EMPTY = new InternalListener() { public void onApiCalled(Object... objects) { /* stub */} + public void onKitApiCalled(int kitId, Boolean used, Object... objects) { /* stub */} + public void onKitApiCalled(String methodName, int kitId, Boolean used, Object... objects) { /* stub */} + public void onEntityStored(Long rowId, String tableName, ContentValues contentValues) { /* stub */} + public void onNetworkRequestStarted(SdkListener.Endpoint type, String url, JSONObject body, Object... objects) { /* stub */} + public void onNetworkRequestFinished(SdkListener.Endpoint type, String url, JSONObject response, int responseCode) { /* stub */} + public void onSessionUpdated(InternalSession internalSession) { /* stub */} + public void onKitDetected(int kitId) { /* stub */} + public void onKitConfigReceived(int kitId, String configuration) { /* stub */} + public void onKitExcluded(int kitId, String reason) { /* stub */} + public void onKitStarted(int kitId) { /* stub */} + public void onAliasRequestFinished(AliasResponse aliasResponse) { /* stub */} public void onCompositeObjects(Object child, Object parent) { /* stub */} + public void onThreadMessage(String handlerName, Message msg, boolean onNewThread) { /* stub */ } }; } diff --git a/android-core/src/main/java/com/mparticle/internal/listeners/InternalListenerManager.java b/android-core/src/main/java/com/mparticle/internal/listeners/InternalListenerManager.java index 3005d579d..4b8d456db 100644 --- a/android-core/src/main/java/com/mparticle/internal/listeners/InternalListenerManager.java +++ b/android-core/src/main/java/com/mparticle/internal/listeners/InternalListenerManager.java @@ -3,6 +3,7 @@ import android.content.ContentValues; import android.content.Context; import android.os.Message; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; diff --git a/android-core/src/main/java/com/mparticle/internal/messages/BaseMPMessage.java b/android-core/src/main/java/com/mparticle/internal/messages/BaseMPMessage.java index a69bc8cba..5ff009dec 100644 --- a/android-core/src/main/java/com/mparticle/internal/messages/BaseMPMessage.java +++ b/android-core/src/main/java/com/mparticle/internal/messages/BaseMPMessage.java @@ -1,6 +1,7 @@ package com.mparticle.internal.messages; import android.location.Location; + import androidx.annotation.Nullable; import com.mparticle.internal.Constants; @@ -13,7 +14,8 @@ public class BaseMPMessage extends JSONObject { private long mpId; - protected BaseMPMessage(){} + protected BaseMPMessage() { + } protected BaseMPMessage(BaseMPMessageBuilder builder, InternalSession session, @Nullable Location location, long mpId) throws JSONException { super(builder, builder.getKeys()); @@ -44,14 +46,14 @@ protected BaseMPMessage(BaseMPMessageBuilder builder, InternalSession session, @ } } - public JSONObject getAttributes(){ + public JSONObject getAttributes() { return optJSONObject(Constants.MessageKey.ATTRIBUTES); } - public long getTimestamp(){ + public long getTimestamp() { try { return getLong(Constants.MessageKey.TIMESTAMP); - }catch (JSONException jse){ + } catch (JSONException jse) { } return 0; diff --git a/android-core/src/main/java/com/mparticle/internal/messages/BaseMPMessageBuilder.java b/android-core/src/main/java/com/mparticle/internal/messages/BaseMPMessageBuilder.java index 5b7b0499c..a919b1d28 100644 --- a/android-core/src/main/java/com/mparticle/internal/messages/BaseMPMessageBuilder.java +++ b/android-core/src/main/java/com/mparticle/internal/messages/BaseMPMessageBuilder.java @@ -2,6 +2,7 @@ import android.location.Location; + import androidx.annotation.Nullable; import com.mparticle.internal.Constants; @@ -89,7 +90,7 @@ public BaseMPMessageBuilder dataConnection(String dataConnection) { public BaseMPMessageBuilder length(Double length) { mLength = length; - if (length != null){ + if (length != null) { try { put(Constants.MessageKey.EVENT_DURATION, length); addEventLengthAttributes(length); diff --git a/android-core/src/main/java/com/mparticle/internal/messages/MPAliasMessage.java b/android-core/src/main/java/com/mparticle/internal/messages/MPAliasMessage.java index 7c03894ac..1c5cc3b20 100644 --- a/android-core/src/main/java/com/mparticle/internal/messages/MPAliasMessage.java +++ b/android-core/src/main/java/com/mparticle/internal/messages/MPAliasMessage.java @@ -1,14 +1,5 @@ package com.mparticle.internal.messages; -import com.mparticle.MParticle; -import com.mparticle.identity.AliasRequest; -import com.mparticle.internal.ConfigManager; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.UUID; - import static com.mparticle.internal.Constants.MessageKey.ALIAS_REQUEST_TYPE; import static com.mparticle.internal.Constants.MessageKey.API_KEY; import static com.mparticle.internal.Constants.MessageKey.DATA; @@ -21,6 +12,15 @@ import static com.mparticle.internal.Constants.MessageKey.SOURCE_MPID; import static com.mparticle.internal.Constants.MessageKey.START_TIME; +import com.mparticle.MParticle; +import com.mparticle.identity.AliasRequest; +import com.mparticle.internal.ConfigManager; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.UUID; + public class MPAliasMessage extends JSONObject { public MPAliasMessage(String jsonString) throws JSONException { diff --git a/android-core/src/main/java/com/mparticle/internal/messages/MPCommerceMessage.java b/android-core/src/main/java/com/mparticle/internal/messages/MPCommerceMessage.java index b442512e4..6e01ad3b9 100644 --- a/android-core/src/main/java/com/mparticle/internal/messages/MPCommerceMessage.java +++ b/android-core/src/main/java/com/mparticle/internal/messages/MPCommerceMessage.java @@ -1,6 +1,7 @@ package com.mparticle.internal.messages; import android.location.Location; + import androidx.annotation.Nullable; import com.mparticle.commerce.CommerceEvent; diff --git a/android-core/src/main/java/com/mparticle/internal/messages/MPEventMessage.java b/android-core/src/main/java/com/mparticle/internal/messages/MPEventMessage.java index c0f6431c8..77dd81c98 100644 --- a/android-core/src/main/java/com/mparticle/internal/messages/MPEventMessage.java +++ b/android-core/src/main/java/com/mparticle/internal/messages/MPEventMessage.java @@ -1,6 +1,7 @@ package com.mparticle.internal.messages; import android.location.Location; + import androidx.annotation.Nullable; import com.mparticle.MParticle; diff --git a/android-core/src/main/java/com/mparticle/internal/package-info.java b/android-core/src/main/java/com/mparticle/internal/package-info.java index efc765484..c8d5ff3cb 100644 --- a/android-core/src/main/java/com/mparticle/internal/package-info.java +++ b/android-core/src/main/java/com/mparticle/internal/package-info.java @@ -1,2 +1 @@ - package com.mparticle.internal; \ No newline at end of file diff --git a/android-core/src/main/java/com/mparticle/media/MPMediaAPI.java b/android-core/src/main/java/com/mparticle/media/MPMediaAPI.java index 8a3c6d1f5..fdbb0617c 100644 --- a/android-core/src/main/java/com/mparticle/media/MPMediaAPI.java +++ b/android-core/src/main/java/com/mparticle/media/MPMediaAPI.java @@ -1,6 +1,7 @@ package com.mparticle.media; import android.content.Context; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -10,14 +11,13 @@ * Utility class to interact with the mParticle Media APIs. Do not directly instantiate this. * * @see com.mparticle.MParticle#Media() - * */ public class MPMediaAPI { private final MediaCallbacks mCallbacks; private final Context mContext; private AtomicBoolean mAudioPlaying = new AtomicBoolean(false); - private MPMediaAPI(){ + private MPMediaAPI() { mContext = null; mCallbacks = null; } @@ -36,11 +36,11 @@ public MPMediaAPI(@Nullable Context context, @NonNull MediaCallbacks callbacks) * * @param playing Is your app currently playing music for the user. */ - public void setAudioPlaying(boolean playing){ + public void setAudioPlaying(boolean playing) { mAudioPlaying.set(playing); - if (playing){ + if (playing) { mCallbacks.onAudioPlaying(); - }else{ + } else { mCallbacks.onAudioStopped(); } } diff --git a/android-core/src/main/java/com/mparticle/media/MediaCallbacks.java b/android-core/src/main/java/com/mparticle/media/MediaCallbacks.java index c6431e5fc..295698c38 100644 --- a/android-core/src/main/java/com/mparticle/media/MediaCallbacks.java +++ b/android-core/src/main/java/com/mparticle/media/MediaCallbacks.java @@ -1,8 +1,10 @@ package com.mparticle.media; /** + * */ public interface MediaCallbacks { public void onAudioPlaying(); + public void onAudioStopped(); } diff --git a/android-core/src/main/java/com/mparticle/media/package-info.java b/android-core/src/main/java/com/mparticle/media/package-info.java index a3ec090cf..5b393bb17 100644 --- a/android-core/src/main/java/com/mparticle/media/package-info.java +++ b/android-core/src/main/java/com/mparticle/media/package-info.java @@ -1,6 +1,4 @@ /** - * * Package containing the mParticle Media APIs. - * */ package com.mparticle.media; \ No newline at end of file diff --git a/android-core/src/main/java/com/mparticle/messaging/MPMessagingAPI.java b/android-core/src/main/java/com/mparticle/messaging/MPMessagingAPI.java index a33e880cb..a3e4e864a 100644 --- a/android-core/src/main/java/com/mparticle/messaging/MPMessagingAPI.java +++ b/android-core/src/main/java/com/mparticle/messaging/MPMessagingAPI.java @@ -15,22 +15,23 @@ /** * DO NOT DIRECTLY INSTANTIATE THIS CLASS! - * Utility class to enable and adjust push notification behavior. + * Utility class to enable and adjust push notification behavior. * * @see com.mparticle.MParticle#Messaging() - * */ public class MPMessagingAPI { private final Context mContext; - @NonNull public static final String CLOUD_MESSAGE_EXTRA = "mp-push-message"; + @NonNull + public static final String CLOUD_MESSAGE_EXTRA = "mp-push-message"; /** * Listen for this broadcast (as an Intent action) to detect when the device received a push. * * In the received Intent, you will have access to the entire payload of the push notification. */ - @NonNull public static final String BROADCAST_NOTIFICATION_RECEIVED = "com.mparticle.push.RECEIVE"; + @NonNull + public static final String BROADCAST_NOTIFICATION_RECEIVED = "com.mparticle.push.RECEIVE"; /** * Listen for this broadcast (as an Intent action) to detect when a user taps a push message in the * notification bar of their device. You may then navigate or otherwise adjust the user experience based on @@ -38,9 +39,10 @@ public class MPMessagingAPI { * * In the received Intent, you will have access to the entire payload of the push notification. */ - @NonNull public static final String BROADCAST_NOTIFICATION_TAPPED = "com.mparticle.push.TAP"; + @NonNull + public static final String BROADCAST_NOTIFICATION_TAPPED = "com.mparticle.push.TAP"; - private MPMessagingAPI(){ + private MPMessagingAPI() { mContext = null; } @@ -63,7 +65,7 @@ public void enablePushNotifications(@NonNull String senderId) { Logger.error("Push is enabled but Firebase Cloud Messaging library not found - you must add com.google.firebase:firebase-messaging:10.2.1 or later to your application."); } else if (!MPUtility.isServiceAvailable(mContext, MPService.class)) { Logger.error("Push is enabled but you have not added to the section of your AndroidManifest.xml."); - } else if (!MPUtility.checkPermission(mContext, "com.google.android.c2dm.permission.RECEIVE")){ + } else if (!MPUtility.checkPermission(mContext, "com.google.android.c2dm.permission.RECEIVE")) { Logger.error("Attempted to enable push notifications without required permission: ", "\"com.google.android.c2dm.permission.RECEIVE\"."); } else { PushRegistrationHelper.requestInstanceId(mContext, senderId); @@ -84,8 +86,8 @@ public void displayPushNotificationByDefault(@Nullable Boolean enabled) { /** * Register a custom implementation of PushAnalyticsReceiver, which will provide callbacks when * push messages are received. - * @param receiver the implementation of PushAnalyticsReceiver to be registered * + * @param receiver the implementation of PushAnalyticsReceiver to be registered * @see PushAnalyticsReceiver */ public void registerPushAnalyticsReceiver(@NonNull PushAnalyticsReceiver receiver) { @@ -100,7 +102,6 @@ public void registerPushAnalyticsReceiver(@NonNull PushAnalyticsReceiver receive * to have been registered, nothing will happen. * * @param receiver the previously registered implementation of PushAnalyticsReceiver to be unregistered - * * @see PushAnalyticsReceiver */ public void unregisterPushAnalyticsReceiver(@Nullable PushAnalyticsReceiver receiver) { diff --git a/android-core/src/main/java/com/mparticle/messaging/MPMessagingRouter.java b/android-core/src/main/java/com/mparticle/messaging/MPMessagingRouter.java index ce20337bf..8b3092449 100644 --- a/android-core/src/main/java/com/mparticle/messaging/MPMessagingRouter.java +++ b/android-core/src/main/java/com/mparticle/messaging/MPMessagingRouter.java @@ -3,7 +3,6 @@ import android.content.Context; import android.content.Intent; -import com.mparticle.MPService; import com.mparticle.MPServiceUtil; public class MPMessagingRouter { diff --git a/android-core/src/main/java/com/mparticle/messaging/PushAnalyticsReceiver.java b/android-core/src/main/java/com/mparticle/messaging/PushAnalyticsReceiver.java index a1b1953c3..faf2b325a 100644 --- a/android-core/src/main/java/com/mparticle/messaging/PushAnalyticsReceiver.java +++ b/android-core/src/main/java/com/mparticle/messaging/PushAnalyticsReceiver.java @@ -22,7 +22,6 @@ * * @see #onNotificationReceived(ProviderCloudMessage) * @see #onNotificationTapped(ProviderCloudMessage) - * */ public class PushAnalyticsReceiver extends BroadcastReceiver implements PushAnalyticsReceiverCallback { diff --git a/android-core/src/main/java/com/mparticle/messaging/PushAnalyticsReceiverCallback.java b/android-core/src/main/java/com/mparticle/messaging/PushAnalyticsReceiverCallback.java index 94e17f4c6..f63045440 100644 --- a/android-core/src/main/java/com/mparticle/messaging/PushAnalyticsReceiverCallback.java +++ b/android-core/src/main/java/com/mparticle/messaging/PushAnalyticsReceiverCallback.java @@ -4,7 +4,6 @@ public interface PushAnalyticsReceiverCallback { /** * Override this method to listen for when a notification has been received. * - * * @param message The message that was received. Depending on the push provider * @return True if you would like to handle this notification, False if you would like the mParticle to generate and show a {@link android.app.Notification}. */ @@ -13,7 +12,6 @@ public interface PushAnalyticsReceiverCallback { /** * Override this method to listen for when a notification has been tapped or acted on. * - * * @param message The message that was tapped. Depending on the push provider * @return True if you would like to consume this tap/action, False if the mParticle SDK should attempt to handle it. */ diff --git a/android-core/src/main/java/com/mparticle/messaging/package-info.java b/android-core/src/main/java/com/mparticle/messaging/package-info.java index 9971c534d..813bd30e7 100644 --- a/android-core/src/main/java/com/mparticle/messaging/package-info.java +++ b/android-core/src/main/java/com/mparticle/messaging/package-info.java @@ -1,6 +1,4 @@ /** - * * Package containing the mParticle messaging and push APIs. - * */ package com.mparticle.messaging; \ No newline at end of file diff --git a/android-core/src/main/java/com/mparticle/networking/Certificate.java b/android-core/src/main/java/com/mparticle/networking/Certificate.java index 323b0cc72..176e4bda7 100644 --- a/android-core/src/main/java/com/mparticle/networking/Certificate.java +++ b/android-core/src/main/java/com/mparticle/networking/Certificate.java @@ -9,7 +9,7 @@ import org.json.JSONException; import org.json.JSONObject; -public final class Certificate{ +public final class Certificate { private String alias; private String certificate; @@ -60,8 +60,7 @@ JSONObject toJson() { return new JSONObject() .put("alias", getAlias()) .put("certificate", getCertificate()); - } - catch (JSONException jse) { + } catch (JSONException jse) { Logger.error(jse); } return jsonObject; diff --git a/android-core/src/main/java/com/mparticle/networking/DomainMapping.java b/android-core/src/main/java/com/mparticle/networking/DomainMapping.java index 2a79db5da..0b123986c 100644 --- a/android-core/src/main/java/com/mparticle/networking/DomainMapping.java +++ b/android-core/src/main/java/com/mparticle/networking/DomainMapping.java @@ -1,5 +1,7 @@ package com.mparticle.networking; +import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -14,8 +16,6 @@ import java.util.LinkedList; import java.util.List; -import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint; - public class DomainMapping { private Endpoint mType; private String mUrl; @@ -39,7 +39,6 @@ private DomainMapping(Builder builder) { * Override the url of outbound Config requests * * @param newUrl the new domain portion of the url - * * @return the Builder instance */ @NonNull @@ -51,9 +50,8 @@ public static Builder configMapping(@Nullable String newUrl) { * Override the url of outbound Config requests. The subdirectory of the url will also be * overridden if {@param overridesSubdirectory} is true * - * @param newUrl the new domain portion of the url + * @param newUrl the new domain portion of the url * @param overridesSubdirectory indicate whether the new domain includes the subdirectory - * * @return the Builder instance */ public static Builder configMapping(@Nullable String newUrl, boolean overridesSubdirectory) { @@ -64,7 +62,6 @@ public static Builder configMapping(@Nullable String newUrl, boolean overridesSu * Override the url of outbound Events requests, including Alias events * * @param newUrl the new domain portion of the url - * * @return the Builder instance */ @NonNull @@ -76,9 +73,8 @@ public static Builder eventsMapping(@Nullable String newUrl) { * Override the url of outbound Events requests, including Alias events. The subdirectory of the url will also be * overridden if {@param overridesSubdirectory} is true * - * @param newUrl the new domain portion of the url + * @param newUrl the new domain portion of the url * @param overridesSubdirectory indicate whether the new domain includes the subdirectory - * * @return the Builder instance */ public static Builder eventsMapping(@Nullable String newUrl, boolean overridesSubdirectory) { @@ -90,10 +86,9 @@ public static Builder eventsMapping(@Nullable String newUrl, boolean overridesSu * overridden if {@param overridesSubdirectory} is true. {@param eventsOnly} with indicate if * this mapping should only be applied to Events requests, and specifically not Alias events * - * @param newUrl the new domain portion of the url + * @param newUrl the new domain portion of the url * @param overridesSubdirectory indicate whether the new domain includes the subdirectory - * @param eventsOnly indicates whether this mapping should only apply to core, non-alias events - * + * @param eventsOnly indicates whether this mapping should only apply to core, non-alias events * @return the Builder instance */ public static Builder eventsMapping(@Nullable String newUrl, boolean overridesSubdirectory, boolean eventsOnly) { @@ -105,7 +100,6 @@ public static Builder eventsMapping(@Nullable String newUrl, boolean overridesSu * Override the url of outbound Alias events requests. * * @param newUrl the new domain portion of the url - * * @return the Builder instance */ public static Builder aliasMapping(@Nullable String newUrl) { @@ -116,9 +110,8 @@ public static Builder aliasMapping(@Nullable String newUrl) { * Override the url of outbound Alias events requests. The subdirectory of the url will also be * overridden if {@param overridesSubdirectory} is true * - * @param newUrl the new domain portion of the url + * @param newUrl the new domain portion of the url * @param overridesSubdirectory indicate whether the new domain includes the subdirectory - * * @return the Builder instance */ public static Builder aliasMapping(@Nullable String newUrl, boolean overridesSubdirectory) { @@ -130,7 +123,6 @@ public static Builder aliasMapping(@Nullable String newUrl, boolean overridesSub * Override the url of outbound Identity requests * * @param newUrl the new domain portion of the url - * * @return the Builder instance */ @NonNull @@ -142,9 +134,8 @@ public static Builder identityMapping(@Nullable String newUrl) { * Override the url of outbound Identity requests. The subdirectory of the url will also be * overridden if {@param overridesSubdirectory} is true * - * @param newUrl the new domain portion of the url + * @param newUrl the new domain portion of the url * @param overridesSubdirectory indicate whether the new domain includes the subdirectory - * * @return the Builder instance */ public static Builder identityMapping(@Nullable String newUrl, boolean overridesSubdirectory) { @@ -155,7 +146,6 @@ public static Builder identityMapping(@Nullable String newUrl, boolean overrides * Override the url of outbound Audience requests * * @param newUrl the new domain portion of the url - * * @return the Builder instance */ @NonNull @@ -167,9 +157,8 @@ public static Builder audienceMapping(@Nullable String newUrl) { * Override the url of outbound Audience requests. The subdirectory of the url will also be * overridden if {@param overridesSubdirectory} is true * - * @param newUrl the new domain portion of the url + * @param newUrl the new domain portion of the url * @param overridesSubdirectory indicate whether the new domain includes the subdirectory - * * @return the Builder instance */ public static Builder audienceMapping(@Nullable String newUrl, boolean overridesSubdirectory) { @@ -238,8 +227,7 @@ JSONObject toJson() { .put("mType", mType.value) .put("url", mUrl) .put("mCertificates", certificatesJson); - } - catch (JSONException jse) { + } catch (JSONException jse) { Logger.error(jse); } return jsonObject; @@ -314,7 +302,7 @@ public Builder addCertificate(@NonNull String alias, @NonNull String certificate @NonNull public Builder setCertificates(@Nullable List certificates) { this.certificates = new ArrayList(); - for (Certificate certificate: certificates) { + for (Certificate certificate : certificates) { if (certificate != null) { addCertificate(certificate); } @@ -343,8 +331,7 @@ private static Builder withJson(String jsonString) { builder.addCertificate(Certificate.withCertificate(certificatesJsonArray.getJSONObject(i))); } return builder; - } - catch (JSONException jse) { + } catch (JSONException jse) { Logger.error(jse); } return null; diff --git a/android-core/src/main/java/com/mparticle/networking/MPConnection.java b/android-core/src/main/java/com/mparticle/networking/MPConnection.java index 78713b6ad..03759fad5 100644 --- a/android-core/src/main/java/com/mparticle/networking/MPConnection.java +++ b/android-core/src/main/java/com/mparticle/networking/MPConnection.java @@ -14,23 +14,34 @@ public interface MPConnection { void setRequestMethod(String method) throws ProtocolException; + void setDoOutput(Boolean doOutput); + void setConnectTimeout(Integer timeout); + void setReadTimeout(Integer readTimeout); + void setRequestProperty(String key, String value); MPUrl getURL(); + String getRequestMethod(); + String getHeaderField(String key); + Map> getHeaderFields(); OutputStream getOutputStream() throws IOException; + InputStream getInputStream() throws IOException; + InputStream getErrorStream(); int getResponseCode() throws IOException; + String getResponseMessage() throws IOException; void setSSLSocketFactory(SSLSocketFactory factory); + SSLSocketFactory getSSLSocketFactory(); } diff --git a/android-core/src/main/java/com/mparticle/networking/MPConnectionImpl.java b/android-core/src/main/java/com/mparticle/networking/MPConnectionImpl.java index 0c7339115..1761a4573 100644 --- a/android-core/src/main/java/com/mparticle/networking/MPConnectionImpl.java +++ b/android-core/src/main/java/com/mparticle/networking/MPConnectionImpl.java @@ -103,11 +103,11 @@ public String getResponseMessage() throws IOException { @Override public void setSSLSocketFactory(SSLSocketFactory factory) { - ((HttpsURLConnection)httpURLConnection).setSSLSocketFactory(factory); + ((HttpsURLConnection) httpURLConnection).setSSLSocketFactory(factory); } @Override public SSLSocketFactory getSSLSocketFactory() { - return ((HttpsURLConnection)httpURLConnection).getSSLSocketFactory(); + return ((HttpsURLConnection) httpURLConnection).getSSLSocketFactory(); } } diff --git a/android-core/src/main/java/com/mparticle/networking/MPUrl.java b/android-core/src/main/java/com/mparticle/networking/MPUrl.java index 315509765..1ef6597eb 100644 --- a/android-core/src/main/java/com/mparticle/networking/MPUrl.java +++ b/android-core/src/main/java/com/mparticle/networking/MPUrl.java @@ -34,13 +34,17 @@ public String toString() { } public abstract MPConnection openConnection() throws IOException; + public abstract String getFile(); + public abstract String getAuthority(); + public abstract String getPath(); /** * returns an instance of the Default URL, if NetworkOptions is being used to override it. Otherwise, * a reference to itself will be returned + * * @return an MPUrl instance with the the default URL */ @NonNull diff --git a/android-core/src/main/java/com/mparticle/networking/MPUrlImpl.java b/android-core/src/main/java/com/mparticle/networking/MPUrlImpl.java index 204551a54..81f1a7113 100644 --- a/android-core/src/main/java/com/mparticle/networking/MPUrlImpl.java +++ b/android-core/src/main/java/com/mparticle/networking/MPUrlImpl.java @@ -18,7 +18,7 @@ class MPUrlImpl extends MPUrl { @Override public MPConnection openConnection() throws IOException { - return new MPConnectionImpl((HttpURLConnection)url.openConnection(), this); + return new MPConnectionImpl((HttpURLConnection) url.openConnection(), this); } @Override @@ -44,7 +44,7 @@ public String toString() { @Override public boolean equals(Object obj) { if (obj instanceof MPUrlImpl) { - return url.equals(((MPUrlImpl)obj).url); + return url.equals(((MPUrlImpl) obj).url); } return url.equals(obj); } diff --git a/android-core/src/main/java/com/mparticle/networking/MParticleBaseClient.java b/android-core/src/main/java/com/mparticle/networking/MParticleBaseClient.java index 722a5f4c5..0bc0916c8 100644 --- a/android-core/src/main/java/com/mparticle/networking/MParticleBaseClient.java +++ b/android-core/src/main/java/com/mparticle/networking/MParticleBaseClient.java @@ -2,5 +2,6 @@ public interface MParticleBaseClient { BaseNetworkConnection getRequestHandler(); + void setRequestHandler(BaseNetworkConnection handler); } diff --git a/android-core/src/main/java/com/mparticle/networking/MParticleBaseClientImpl.java b/android-core/src/main/java/com/mparticle/networking/MParticleBaseClientImpl.java index 26aad57cf..5615fe927 100644 --- a/android-core/src/main/java/com/mparticle/networking/MParticleBaseClientImpl.java +++ b/android-core/src/main/java/com/mparticle/networking/MParticleBaseClientImpl.java @@ -3,6 +3,7 @@ import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; + import androidx.annotation.Nullable; import com.mparticle.BuildConfig; diff --git a/android-core/src/main/java/com/mparticle/networking/NetworkConnection.java b/android-core/src/main/java/com/mparticle/networking/NetworkConnection.java index 5f214c6c7..e1e1b1d97 100644 --- a/android-core/src/main/java/com/mparticle/networking/NetworkConnection.java +++ b/android-core/src/main/java/com/mparticle/networking/NetworkConnection.java @@ -34,8 +34,8 @@ public class NetworkConnection extends BaseNetworkConnection { * Default throttle time - in the worst case scenario if the server is busy, the soonest * the SDK will attempt to contact the server again will be after this 2 hour window. */ - static final long DEFAULT_THROTTLE_MILLIS = 1000*60*60*2; - static final long MAX_THROTTLE_MILLIS = 1000*60*60*24; + static final long DEFAULT_THROTTLE_MILLIS = 1000 * 60 * 60 * 2; + static final long MAX_THROTTLE_MILLIS = 1000 * 60 * 60 * 24; NetworkConnection(ConfigManager configManager, SharedPreferences sharedPreferences) { super(sharedPreferences); @@ -74,8 +74,7 @@ public MPConnection makeUrlRequest(MParticleBaseClientImpl.Endpoint endpoint, MP setNextAllowedRequestTime(connection, endpoint); } } - } - catch (IOException ex) { + } catch (IOException ex) { throw ex; } return connection; @@ -92,8 +91,8 @@ protected OutputStream getOutputStream(MPConnection connection) throws IOExcepti /** * Custom socket factory used for certificate pinning. */ - protected SSLSocketFactory getSocketFactory(MParticleBaseClientImpl.Endpoint endpoint) throws Exception{ - if (mSocketFactory == null){ + protected SSLSocketFactory getSocketFactory(MParticleBaseClientImpl.Endpoint endpoint) throws Exception { + if (mSocketFactory == null) { String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); @@ -101,7 +100,7 @@ protected SSLSocketFactory getSocketFactory(MParticleBaseClientImpl.Endpoint end CertificateFactory cf = CertificateFactory.getInstance("X.509"); NetworkOptions networkOptions = mConfigManager.getNetworkOptions(); DomainMapping domainMapping = networkOptions.getDomain(endpoint); - for (com.mparticle.networking.Certificate certificate: domainMapping != null ? domainMapping.getCertificates() : NetworkOptionsManager.getDefaultCertificates()) { + for (com.mparticle.networking.Certificate certificate : domainMapping != null ? domainMapping.getCertificates() : NetworkOptionsManager.getDefaultCertificates()) { keyStore.setCertificateEntry(certificate.getAlias(), generateCertificate(cf, certificate.getCertificate())); } String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); @@ -119,10 +118,10 @@ protected SSLSocketFactory getSocketFactory(MParticleBaseClientImpl.Endpoint end private static Certificate generateCertificate(CertificateFactory certificateFactory, String encodedCertificate) throws IOException, CertificateException { Certificate certificate = null; - InputStream inputStream = new ByteArrayInputStream( encodedCertificate.getBytes() ); + InputStream inputStream = new ByteArrayInputStream(encodedCertificate.getBytes()); try { certificate = certificateFactory.generateCertificate(inputStream); - }finally { + } finally { inputStream.close(); } return certificate; diff --git a/android-core/src/main/java/com/mparticle/networking/NetworkOptions.java b/android-core/src/main/java/com/mparticle/networking/NetworkOptions.java index 7003007dd..a2320dc38 100644 --- a/android-core/src/main/java/com/mparticle/networking/NetworkOptions.java +++ b/android-core/src/main/java/com/mparticle/networking/NetworkOptions.java @@ -1,5 +1,11 @@ package com.mparticle.networking; +import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint; +import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.ALIAS; +import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.CONFIG; +import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.EVENTS; +import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.IDENTITY; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -15,18 +21,13 @@ import java.util.List; import java.util.Map; -import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint; -import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.ALIAS; -import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.CONFIG; -import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.EVENTS; -import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.IDENTITY; - public class NetworkOptions { Map domainMappings = new HashMap(); boolean pinningDisabledInDevelopment = false; - private NetworkOptions() {} + private NetworkOptions() { + } private NetworkOptions(Builder builder) { if (builder.domainMappings != null) { @@ -109,11 +110,10 @@ private JSONObject toJson() { JSONArray domainMappingsJson = new JSONArray(); networkOptions.put("disableDevPinning", pinningDisabledInDevelopment); networkOptions.put("domainMappings", domainMappingsJson); - for (DomainMapping domainMapping: domainMappings.values()) { + for (DomainMapping domainMapping : domainMappings.values()) { domainMappingsJson.put(domainMapping.toString()); } - } - catch (JSONException jse) { + } catch (JSONException jse) { Logger.error(jse); } return networkOptions; @@ -151,7 +151,7 @@ public Builder setDomainMappings(@Nullable List domainMappingsLis domainMappings = new HashMap(); return this; } - for (DomainMapping domainMapping: domainMappingsList) { + for (DomainMapping domainMapping : domainMappingsList) { addDomainMapping(domainMapping); } return this; diff --git a/android-core/src/main/java/com/mparticle/networking/NetworkOptionsManager.java b/android-core/src/main/java/com/mparticle/networking/NetworkOptionsManager.java index 762909b23..994aca1bf 100644 --- a/android-core/src/main/java/com/mparticle/networking/NetworkOptionsManager.java +++ b/android-core/src/main/java/com/mparticle/networking/NetworkOptionsManager.java @@ -1,5 +1,7 @@ package com.mparticle.networking; +import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint; + import com.mparticle.BuildConfig; import com.mparticle.internal.Constants; import com.mparticle.internal.MPUtility; @@ -7,8 +9,6 @@ import java.util.LinkedList; import java.util.List; -import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint; - public class NetworkOptionsManager { public static String MP_CONFIG_URL = "config2.mparticle.com"; public static String MP_IDENTITY_URL = "identity.mparticle.com"; @@ -19,7 +19,7 @@ public static NetworkOptions validateAndResolve(NetworkOptions networkOptions) { return defaultNetworkOptions(); } //Only take the endpoints we care about. - for (Endpoint endpoint: Endpoint.values()) { + for (Endpoint endpoint : Endpoint.values()) { DomainMapping domainMapping = networkOptions.domainMappings.get(endpoint); if (domainMapping == null) { networkOptions.domainMappings.put(endpoint, DomainMapping.withEndpoint(endpoint) diff --git a/android-core/src/main/java/com/mparticle/package-info.java b/android-core/src/main/java/com/mparticle/package-info.java index fa00c47db..19efe7d38 100644 --- a/android-core/src/main/java/com/mparticle/package-info.java +++ b/android-core/src/main/java/com/mparticle/package-info.java @@ -1,6 +1,4 @@ /** - * * The primary package for the mParticle SDK where most of the public APIs reside - start here. - * */ package com.mparticle; \ No newline at end of file diff --git a/android-core/src/main/java/com/mparticle/segmentation/Segment.java b/android-core/src/main/java/com/mparticle/segmentation/Segment.java index 287ca926d..125fbaf6a 100644 --- a/android-core/src/main/java/com/mparticle/segmentation/Segment.java +++ b/android-core/src/main/java/com/mparticle/segmentation/Segment.java @@ -22,10 +22,10 @@ public Segment(int id, @NonNull String name, @NonNull String endpointBlob) { try { JSONArray endpointJson = new JSONArray(endpointBlob); endpoints = new String[endpointJson.length()]; - for (int i = 0; i < endpointJson.length(); i++){ + for (int i = 0; i < endpointJson.length(); i++) { endpoints[i] = endpointJson.getString(i); } - }catch (JSONException jse){ + } catch (JSONException jse) { } @@ -36,7 +36,7 @@ public Segment(int id, @NonNull String name, @NonNull String endpointBlob) { * * @return an integer ID */ - public int getId(){ + public int getId() { return id; } @@ -46,7 +46,7 @@ public int getId(){ * @return */ @Nullable - public String getName(){ + public String getName() { return name; } @@ -56,10 +56,10 @@ public String getName(){ * @return an array of IDs */ @NonNull - public String[] getEndpoints(){ + public String[] getEndpoints() { if (endpoints != null) { return endpoints; - }else{ + } else { return new String[]{}; } } @@ -73,7 +73,7 @@ public String[] getEndpoints(){ @NonNull public String toString() { return "Segment ID: " + id + ", " + - "Name: " + name + ", " + - "Endpoints: " + ((endpoints != null && endpoints.length > 0) ? Arrays.toString(endpoints) : "None specified."); + "Name: " + name + ", " + + "Endpoints: " + ((endpoints != null && endpoints.length > 0) ? Arrays.toString(endpoints) : "None specified."); } } diff --git a/android-core/src/main/java/com/mparticle/segmentation/SegmentMembership.java b/android-core/src/main/java/com/mparticle/segmentation/SegmentMembership.java index 0df14a639..9e4678ef6 100644 --- a/android-core/src/main/java/com/mparticle/segmentation/SegmentMembership.java +++ b/android-core/src/main/java/com/mparticle/segmentation/SegmentMembership.java @@ -5,7 +5,7 @@ import java.util.ArrayList; /** - This class is returned as response from a user segments call. It contains segment ids, expiration, and a flag indicating whether it is expired. + * This class is returned as response from a user segments call. It contains segment ids, expiration, and a flag indicating whether it is expired. */ public class SegmentMembership { private ArrayList segments; @@ -17,7 +17,7 @@ public SegmentMembership(@NonNull ArrayList ids) { } /** - The list of user segment IDs. + * The list of user segment IDs. */ @NonNull public ArrayList getSegments() { @@ -25,16 +25,16 @@ public ArrayList getSegments() { } /** - Returns a String with a comma separated list of user segment IDs. + * Returns a String with a comma separated list of user segment IDs. */ @Override @NonNull - public String toString(){ + public String toString() { return getCommaSeparatedIds(); } /** - Returns a String with a comma separated list of user segment IDs. + * Returns a String with a comma separated list of user segment IDs. */ @NonNull public String getCommaSeparatedIds() { diff --git a/android-core/src/main/java/com/mparticle/segmentation/package-info.java b/android-core/src/main/java/com/mparticle/segmentation/package-info.java index c0185ecb3..da6ae02a7 100644 --- a/android-core/src/main/java/com/mparticle/segmentation/package-info.java +++ b/android-core/src/main/java/com/mparticle/segmentation/package-info.java @@ -1,6 +1,4 @@ /** - * * Package containing the mParticle Segmentation APIs. - * */ package com.mparticle.segmentation; \ No newline at end of file diff --git a/android-core/src/main/kotlin/com.mparticle/TypedUserAttributeListener.kt b/android-core/src/main/kotlin/com.mparticle/TypedUserAttributeListener.kt index cc75b21d2..49d6f0d71 100644 --- a/android-core/src/main/kotlin/com.mparticle/TypedUserAttributeListener.kt +++ b/android-core/src/main/kotlin/com.mparticle/TypedUserAttributeListener.kt @@ -1,6 +1,6 @@ package com.mparticle -interface TypedUserAttributeListener: UserAttributeListenerType { +interface TypedUserAttributeListener : UserAttributeListenerType { fun onUserAttributesReceived( userAttributes: Map, userAttributeLists: Map?>, diff --git a/android-core/src/main/kotlin/com/mparticle/identity/UserAttributeListenerWrapper.kt b/android-core/src/main/kotlin/com/mparticle/identity/UserAttributeListenerWrapper.kt index 691383ed7..dcb907e56 100644 --- a/android-core/src/main/kotlin/com/mparticle/identity/UserAttributeListenerWrapper.kt +++ b/android-core/src/main/kotlin/com/mparticle/identity/UserAttributeListenerWrapper.kt @@ -5,13 +5,21 @@ import com.mparticle.UserAttributeListener import com.mparticle.UserAttributeListenerType class UserAttributeListenerWrapper(val listener: UserAttributeListenerType) { - fun onUserAttributesReceived(singles: Map?, lists: Map?>?, mpid: Long?) { + fun onUserAttributesReceived( + singles: Map?, + lists: Map?>?, + mpid: Long? + ) { when (listener) { is UserAttributeListener -> (singles ?: mutableMapOf()) .entries .associate { it.key to it.value?.toString() } .let { listener.onUserAttributesReceived(it, lists, mpid) } - is TypedUserAttributeListener -> mpid?.let { listener.onUserAttributesReceived(singles ?: mutableMapOf(), lists ?: mutableMapOf(), it) } + is TypedUserAttributeListener -> mpid?.let { + listener.onUserAttributesReceived( + singles ?: mutableMapOf(), lists ?: mutableMapOf(), it + ) + } } } } \ No newline at end of file diff --git a/android-core/src/test/java/com/mparticle/networking/MParticleBaseClientImplTest.java b/android-core/src/test/java/com/mparticle/networking/MParticleBaseClientImplTest.java index 7c9fa29a1..8e3f0e675 100644 --- a/android-core/src/test/java/com/mparticle/networking/MParticleBaseClientImplTest.java +++ b/android-core/src/test/java/com/mparticle/networking/MParticleBaseClientImplTest.java @@ -1,5 +1,8 @@ package com.mparticle.networking; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import androidx.annotation.NonNull; import com.mparticle.internal.ConfigManager; @@ -14,9 +17,6 @@ import javax.net.ssl.SSLSocketFactory; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - public class MParticleBaseClientImplTest { @@ -63,7 +63,7 @@ public void write(@NonNull byte[] b) throws IOException { MPConnection mockConnection = Mockito.mock(MPConnection.class); Mockito.when(mockConnection.isHttps()).thenReturn(true); - client.makeUrlRequest(null, mockConnection, "message" , true); + client.makeUrlRequest(null, mockConnection, "message", true); assertTrue(getSocketFactoryCalled[0]); assertTrue(writeCalled[0]); } diff --git a/android-core/src/test/kotlin/com/mparticle/commerce/CommerceEventTest.kt b/android-core/src/test/kotlin/com/mparticle/commerce/CommerceEventTest.kt index dd6721a62..5c74cb92d 100644 --- a/android-core/src/test/kotlin/com/mparticle/commerce/CommerceEventTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/commerce/CommerceEventTest.kt @@ -163,7 +163,8 @@ class CommerceEventTest { var event = builder.build() Assert.assertNull(event.customFlags) - val attributes = RandomUtils.getInstance().getRandomCustomFlags(RandomUtils.getInstance().randomInt(1, 10)) + val attributes = RandomUtils.getInstance() + .getRandomCustomFlags(RandomUtils.getInstance().randomInt(1, 10)) for (attribute in attributes.entries) { for (value in attribute.value) { builder.addCustomFlag(attribute.key, value) diff --git a/android-core/src/test/kotlin/com/mparticle/commerce/ProductTest.kt b/android-core/src/test/kotlin/com/mparticle/commerce/ProductTest.kt index 64ac875c3..2ca42375e 100644 --- a/android-core/src/test/kotlin/com/mparticle/commerce/ProductTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/commerce/ProductTest.kt @@ -16,7 +16,8 @@ class ProductTest { fun testDefaultEqualityComparator() { Product.setEqualityComparator(null) val product1 = Product.Builder("name", "sku", 2.0).brand("cool brand!").build() - val product2 = Product.Builder("cool brand!", "sku", 2.0).brand("cool brand!adsflkjh").build() + val product2 = + Product.Builder("cool brand!", "sku", 2.0).brand("cool brand!adsflkjh").build() val product2Copy = Product.Builder(product2).build() product2Copy.mTimeAdded = product2.mTimeAdded Assert.assertNotEquals(product2, product1) @@ -30,7 +31,8 @@ class ProductTest { fun testEqualityComparator() { Product.setEqualityComparator { product1, product2 -> product1?.name == product2?.brand } val product1 = Product.Builder("name", "sku", 2.0).brand("cool brand!").build() - val product2 = Product.Builder("cool brand!", "sku", 2.0).brand("cool brand!adsflkjh").build() + val product2 = + Product.Builder("cool brand!", "sku", 2.0).brand("cool brand!adsflkjh").build() Assert.assertEquals(product2, product1) } diff --git a/android-core/src/test/kotlin/com/mparticle/identity/IdentityApiTest.kt b/android-core/src/test/kotlin/com/mparticle/identity/IdentityApiTest.kt index 923ff6e73..c46fca4be 100644 --- a/android-core/src/test/kotlin/com/mparticle/identity/IdentityApiTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/identity/IdentityApiTest.kt @@ -6,7 +6,6 @@ import com.mparticle.testutils.AndroidUtils import org.junit.Assert import org.junit.Test import java.util.Random -import kotlin.collections.ArrayList class IdentityApiTest { private var ran = Random() diff --git a/android-core/src/test/kotlin/com/mparticle/internal/DeviceAttributesTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/DeviceAttributesTest.kt index 38e8d24ce..8737eb104 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/DeviceAttributesTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/DeviceAttributesTest.kt @@ -57,7 +57,18 @@ class DeviceAttributesTest { fun testAppInfoLaunchCount() { val context: Context = MockContext() // Clear out the stored data for the current user, so we don't get any launches from previous tests. - ConfigManager(context, null, null, null, null, null, null, null, null, null).deleteUserStorage( + ConfigManager( + context, + null, + null, + null, + null, + null, + null, + null, + null, + null + ).deleteUserStorage( context, ConfigManager.getMpid(context) ) diff --git a/android-core/src/test/kotlin/com/mparticle/internal/InstallReceiverHelperTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/InstallReceiverHelperTest.kt index 2fb79a501..3adae7b33 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/InstallReceiverHelperTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/InstallReceiverHelperTest.kt @@ -4,7 +4,6 @@ import android.content.Context import com.mparticle.InstallReferrerHelper import com.mparticle.mock.MockContext import org.junit.Test -import java.lang.Exception class InstallReceiverHelperTest { @Test diff --git a/android-core/src/test/kotlin/com/mparticle/internal/KitFrameworkWrapperTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/KitFrameworkWrapperTest.kt index da67755c1..84e969512 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/KitFrameworkWrapperTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/KitFrameworkWrapperTest.kt @@ -22,8 +22,6 @@ import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner import java.lang.ref.WeakReference import java.util.Random -import kotlin.collections.ArrayList -import kotlin.collections.HashSet @RunWith(PowerMockRunner::class) class KitFrameworkWrapperTest { diff --git a/android-core/src/test/kotlin/com/mparticle/internal/LoggerTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/LoggerTest.kt index 311890673..9c56d0063 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/LoggerTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/LoggerTest.kt @@ -6,7 +6,6 @@ import com.mparticle.internal.Logger.DefaultLogHandler import com.mparticle.mock.MockContext import org.junit.Assert import org.junit.Test -import java.lang.Exception /** * Created by wpassidomo on 3/1/17. diff --git a/android-core/src/test/kotlin/com/mparticle/internal/MessageBatchTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/MessageBatchTest.kt index e87234848..48b11ce3b 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/MessageBatchTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/MessageBatchTest.kt @@ -9,7 +9,6 @@ import org.json.JSONObject import org.junit.Assert import org.junit.Test import org.mockito.Mockito -import java.lang.Exception class MessageBatchTest { @Test diff --git a/android-core/src/test/kotlin/com/mparticle/networking/CustomAttributesTests.kt b/android-core/src/test/kotlin/com/mparticle/networking/CustomAttributesTests.kt index f001dec23..9e665f715 100644 --- a/android-core/src/test/kotlin/com/mparticle/networking/CustomAttributesTests.kt +++ b/android-core/src/test/kotlin/com/mparticle/networking/CustomAttributesTests.kt @@ -11,7 +11,8 @@ class CustomAttributesTests { @Test fun testListSerialization() { - val customAttributesList = mutableMapOf("list" to listOf("foo", "bar", "this", "that")) + val customAttributesList = + mutableMapOf("list" to listOf("foo", "bar", "this", "that")) val serialized = "[foo, bar, this, that]" MPEvent.Builder("Test Event") .customAttributes(customAttributesList) @@ -21,7 +22,8 @@ class CustomAttributesTests { assertEquals(serialized, stringifiedCustomAttributes!!["list"]) } - val customAttributesArrayList = mutableMapOf("list" to arrayListOf("foo", "bar", "this", "that")) + val customAttributesArrayList = + mutableMapOf("list" to arrayListOf("foo", "bar", "this", "that")) MPEvent.Builder("Test Event") .customAttributes(customAttributesArrayList) @@ -47,7 +49,9 @@ class CustomAttributesTests { assertEquals("{,}", it) } } - val customAttributesMap = mutableMapOf("list" to mapOf("foo" to "bar", "this" to "that")) + + val customAttributesMap = + mutableMapOf("list" to mapOf("foo" to "bar", "this" to "that")) MPEvent.Builder("Test Event") .customAttributes(customAttributesMap) .build() @@ -55,7 +59,8 @@ class CustomAttributesTests { test(it.customAttributeStrings) } - val customAttributesHashMap = mutableMapOf("list" to hashMapOf("foo" to "bar", "this" to "that")) + val customAttributesHashMap = + mutableMapOf("list" to hashMapOf("foo" to "bar", "this" to "that")) MPEvent.Builder("Test Event") .customAttributes(customAttributesHashMap) @@ -67,7 +72,12 @@ class CustomAttributesTests { @Test fun testJSONSerialization() { - val customAttributesMap = mutableMapOf("list" to mapOf("foo" to "bar", "this" to "that").let { JSONObject(it.toMap()) }) + val customAttributesMap = mutableMapOf( + "list" to mapOf( + "foo" to "bar", + "this" to "that" + ).let { JSONObject(it.toMap()) } + ) val serialized = "{\"foo\":\"bar\",\"this\":\"that\"}" MPEvent.Builder("Test Event") .customAttributes(customAttributesMap) diff --git a/android-core/src/test/kotlin/com/mparticle/networking/DomainMappingTest.kt b/android-core/src/test/kotlin/com/mparticle/networking/DomainMappingTest.kt index 38edd5d15..f3102a803 100644 --- a/android-core/src/test/kotlin/com/mparticle/networking/DomainMappingTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/networking/DomainMappingTest.kt @@ -4,8 +4,6 @@ import com.mparticle.testutils.RandomUtils import org.junit.Assert import org.junit.Test import java.util.Random -import kotlin.collections.ArrayList -import kotlin.collections.HashMap class DomainMappingTest { private var random = Random() diff --git a/android-kit-base/build.gradle b/android-kit-base/build.gradle index 269ab14fe..2bfc817e3 100644 --- a/android-kit-base/build.gradle +++ b/android-kit-base/build.gradle @@ -70,7 +70,7 @@ dependencies { api 'androidx.annotation:annotation:[1.0.0,)' testImplementation 'junit:junit:4.13.2' - testImplementation files('libs/java-json.jar') + testImplementation files('libs/java-json.jar') testImplementation 'org.powermock:powermock-module-junit4:2.0.7' testImplementation 'org.powermock:powermock-api-mockito2:2.0.2' testImplementation 'org.powermock:powermock-core:2.0.7' diff --git a/android-kit-base/src/androidTest/AndroidManifest.xml b/android-kit-base/src/androidTest/AndroidManifest.xml index f567c2461..cf70d191e 100644 --- a/android-kit-base/src/androidTest/AndroidManifest.xml +++ b/android-kit-base/src/androidTest/AndroidManifest.xml @@ -1,10 +1,13 @@ - + + - - + + diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/BaseKitOptionsTest.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/BaseKitOptionsTest.kt index 47a0b142d..261c339d6 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/BaseKitOptionsTest.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/BaseKitOptionsTest.kt @@ -68,11 +68,12 @@ open class BaseKitOptionsTest : BaseCleanInstallEachTest() { protected fun waitForKitToStart(kitId: Int) { val latch = MPLatch(1) // wait for kit to start/reload - com.mparticle.internal.AccessUtils.getKitManager().addKitsLoadedListener { kits, previousKits, kitConfigs -> - if (kits.containsKey(kitId)) { - latch.countDown() + com.mparticle.internal.AccessUtils.getKitManager() + .addKitsLoadedListener { kits, previousKits, kitConfigs -> + if (kits.containsKey(kitId)) { + latch.countDown() + } } - } // check if the kit has already been started and short-circut if it has if (MParticle.getInstance()?.isKitActive(kitId) == true) { latch.countDown() diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/ConfiguredKitOptions.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/ConfiguredKitOptions.kt index 103c41383..290627208 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/ConfiguredKitOptions.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/ConfiguredKitOptions.kt @@ -9,7 +9,11 @@ class ConfiguredKitOptions : KitOptions() { return addKit(kitId, type, JSONObject().put("id", kitId)) } - fun addKit(kitId: Int, type: Class, config: JSONObject?): ConfiguredKitOptions { + fun addKit( + kitId: Int, + type: Class, + config: JSONObject? + ): ConfiguredKitOptions { testingConfiguration[kitId] = config?.put("id", kitId) super.addKit(kitId, type) return this diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/DataplanBlockingUserTests.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/DataplanBlockingUserTests.kt index ebf5086ec..9a4e20328 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/DataplanBlockingUserTests.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/DataplanBlockingUserTests.kt @@ -42,10 +42,14 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { ).let { startMParticle(it) } - attributeListenerKitKit = MParticle.getInstance()?.getKitInstance(-1) as AttributeListenerTestKit - identityListenerKitKit = MParticle.getInstance()?.getKitInstance(-2) as IdentityListenerTestKit - userAttributeListenerKitKit = MParticle.getInstance()?.getKitInstance(-3) as UserAttributeListenerTestKit - kitIntegrationTestKits = listOf(attributeListenerKitKit, identityListenerKitKit, userAttributeListenerKitKit) + attributeListenerKitKit = + MParticle.getInstance()?.getKitInstance(-1) as AttributeListenerTestKit + identityListenerKitKit = + MParticle.getInstance()?.getKitInstance(-2) as IdentityListenerTestKit + userAttributeListenerKitKit = + MParticle.getInstance()?.getKitInstance(-3) as UserAttributeListenerTestKit + kitIntegrationTestKits = + listOf(attributeListenerKitKit, identityListenerKitKit, userAttributeListenerKitKit) assertTrue(randomAttributes().isNotEmpty()) assertTrue(randomIdentities().isNotEmpty()) } @@ -58,7 +62,15 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { assertTrue(blockedAttributes.isNotEmpty()) datapoints[DataplanFilterImpl.USER_ATTRIBUTES_KEY] = allowedAttributes.keys.toHashSet() - AccessUtils.getKitManager().setDataplanFilter(DataplanFilterImpl(datapoints, Random.nextBoolean(), Random.nextBoolean(), true, Random.nextBoolean())) + AccessUtils.getKitManager().setDataplanFilter( + DataplanFilterImpl( + datapoints, + Random.nextBoolean(), + Random.nextBoolean(), + true, + Random.nextBoolean() + ) + ) userAttributeListenerKitKit.onSetUserAttribute = { key, _, _ -> assertTrue(allowedAttributes.containsKey(key)) @@ -68,14 +80,18 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { assertTrue(allowedAttributes.containsKey(key)) assertFalse(blockedAttributes.containsKey(key)) } - MParticle.getInstance()?.Identity()?.currentUser?.userAttributes = allowedAttributes + blockedAttributes + MParticle.getInstance()?.Identity()?.currentUser?.userAttributes = + allowedAttributes + blockedAttributes AccessUtils.awaitMessageHandler() kitIntegrationTestKits.forEach { kit -> assertEquals(kit.name, allowedAttributes, kit.allUserAttributes) } // sanity check to make sure the non-filtered User has the blocked identities - assertEquals(allowedAttributes + blockedAttributes, MParticle.getInstance()?.Identity()?.currentUser?.userAttributes) + assertEquals( + allowedAttributes + blockedAttributes, + MParticle.getInstance()?.Identity()?.currentUser?.userAttributes + ) } @Test @@ -86,7 +102,15 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { assertTrue(blockedAttributes.isNotEmpty()) datapoints[DataplanFilterImpl.USER_ATTRIBUTES_KEY] = allowedAttributes.keys.toHashSet() - AccessUtils.getKitManager().setDataplanFilter(DataplanFilterImpl(datapoints, Random.nextBoolean(), Random.nextBoolean(), blockUserAttributes = true, blockUserIdentities = false)) + AccessUtils.getKitManager().setDataplanFilter( + DataplanFilterImpl( + datapoints, + Random.nextBoolean(), + Random.nextBoolean(), + blockUserAttributes = true, + blockUserIdentities = false + ) + ) kitIntegrationTestKits.forEach { kit -> kit.onAttributeReceived = { key, _ -> @@ -94,7 +118,9 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { assertFalse(blockedAttributes.containsKey(key)) } } - (allowedAttributes + blockedAttributes).entries.forEach { MParticle.getInstance()?.Identity()?.currentUser?.setUserAttribute(it.key, it.value) } + (allowedAttributes + blockedAttributes).entries.forEach { + MParticle.getInstance()?.Identity()?.currentUser?.setUserAttribute(it.key, it.value) + } AccessUtils.awaitMessageHandler() var count = 0 @@ -118,7 +144,9 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { assertFalse(blockedAttributes.containsKey(it)) count++ } - (allowedAttributes + blockedAttributes).keys.forEach { MParticle.getInstance()?.Identity()?.currentUser?.removeUserAttribute(it) } + (allowedAttributes + blockedAttributes).keys.forEach { + MParticle.getInstance()?.Identity()?.currentUser?.removeUserAttribute(it) + } MParticle.getInstance()?.Identity()?.currentUser?.userAttributes = mapOf() AccessUtils.awaitMessageHandler() @@ -138,11 +166,20 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { val datapoints = getRandomDataplanPoints() val allowedAttributes = randomAttributes().map { it.key to listOf(it.value) }.toMap() - val blockedAttributes = randomAttributes().map { it.key to listOf(it.value) }.toMap().filterKeys { !allowedAttributes.containsKey(it) } + val blockedAttributes = randomAttributes().map { it.key to listOf(it.value) }.toMap() + .filterKeys { !allowedAttributes.containsKey(it) } assertTrue(blockedAttributes.isNotEmpty()) datapoints[DataplanFilterImpl.USER_ATTRIBUTES_KEY] = allowedAttributes.keys.toHashSet() - AccessUtils.getKitManager().setDataplanFilter(DataplanFilterImpl(datapoints, Random.nextBoolean(), Random.nextBoolean(), true, Random.nextBoolean())) + AccessUtils.getKitManager().setDataplanFilter( + DataplanFilterImpl( + datapoints, + Random.nextBoolean(), + Random.nextBoolean(), + true, + Random.nextBoolean() + ) + ) var count = 0 kitIntegrationTestKits.forEach { kit -> @@ -162,7 +199,8 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { assertFalse(blockedAttributes.containsKey(key)) count++ } - MParticle.getInstance()?.Identity()?.currentUser?.userAttributes = allowedAttributes + blockedAttributes + MParticle.getInstance()?.Identity()?.currentUser?.userAttributes = + allowedAttributes + blockedAttributes AccessUtils.awaitMessageHandler() assertEquals(count, allowedAttributes.size * 4) @@ -171,7 +209,10 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { assertEquals(allowedAttributes.keys, kit.allUserAttributes.keys) } // sanity check to make sure the non-filtered User has the blocked attributes - assertEquals(allowedAttributes + blockedAttributes, MParticle.getInstance()?.Identity()?.currentUser?.userAttributes) + assertEquals( + allowedAttributes + blockedAttributes, + MParticle.getInstance()?.Identity()?.currentUser?.userAttributes + ) } @Test @@ -180,8 +221,17 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { val allowedIdentities = randomIdentities() val blockIdentities = randomIdentities().filterKeys { !allowedIdentities.containsKey(it) } - datapoints[DataplanFilterImpl.USER_IDENTITIES_KEY] = allowedIdentities.keys.map { it.getEventsApiName() }.toHashSet() - AccessUtils.getKitManager().setDataplanFilter(DataplanFilterImpl(datapoints, Random.nextBoolean(), Random.nextBoolean(), Random.nextBoolean(), true)) + datapoints[DataplanFilterImpl.USER_IDENTITIES_KEY] = + allowedIdentities.keys.map { it.getEventsApiName() }.toHashSet() + AccessUtils.getKitManager().setDataplanFilter( + DataplanFilterImpl( + datapoints, + Random.nextBoolean(), + Random.nextBoolean(), + Random.nextBoolean(), + true + ) + ) MParticle.getInstance()?.Identity()?.login( IdentityApiRequest.withEmptyUser() @@ -204,7 +254,10 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { assertEquals(allowedIdentities, kit.userIdentities) } // sanity check to make sure the non-filtered User has the blocked identities - assertEquals(allowedIdentities + blockIdentities, MParticle.getInstance()?.Identity()?.currentUser?.userIdentities) + assertEquals( + allowedIdentities + blockIdentities, + MParticle.getInstance()?.Identity()?.currentUser?.userIdentities + ) } // @Test @@ -242,10 +295,20 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { private fun getRandomDataplanEventKey(): DataplanFilterImpl.DataPoint { return when (Random.Default.nextInt(0, 5)) { - 0 -> DataplanFilterImpl.DataPoint(DataplanFilterImpl.CUSTOM_EVENT_KEY, randomString(5), randomEventType().ordinal.toString()) + 0 -> DataplanFilterImpl.DataPoint( + DataplanFilterImpl.CUSTOM_EVENT_KEY, + randomString(5), + randomEventType().ordinal.toString() + ) 1 -> DataplanFilterImpl.DataPoint(DataplanFilterImpl.SCREEN_EVENT_KEY, randomString(8)) - 2 -> DataplanFilterImpl.DataPoint(DataplanFilterImpl.PRODUCT_ACTION_KEY, randomProductAction()) - 3 -> DataplanFilterImpl.DataPoint(DataplanFilterImpl.PROMOTION_ACTION_KEY, randomPromotionAction()) + 2 -> DataplanFilterImpl.DataPoint( + DataplanFilterImpl.PRODUCT_ACTION_KEY, + randomProductAction() + ) + 3 -> DataplanFilterImpl.DataPoint( + DataplanFilterImpl.PROMOTION_ACTION_KEY, + randomPromotionAction() + ) 4 -> DataplanFilterImpl.DataPoint(DataplanFilterImpl.PRODUCT_IMPRESSION_KEY) else -> throw IllegalArgumentException("messed this implementation up :/") } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/GCMPushMessageForwardingTest.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/GCMPushMessageForwardingTest.kt index d2cae47f3..07d0f073b 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/GCMPushMessageForwardingTest.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/GCMPushMessageForwardingTest.kt @@ -30,9 +30,10 @@ class GCMPushMessageForwardingTest : BaseKitOptionsTest() { data = Uri.EMPTY putExtras(Bundle()) } - (MParticle.getInstance()?.getKitInstance(1) as PushListenerTestKit).onPushMessageReceived = { context, intent -> - receivedIntent = intent - } + (MParticle.getInstance()?.getKitInstance(1) as PushListenerTestKit).onPushMessageReceived = + { context, intent -> + receivedIntent = intent + } MPServiceUtil(mContext).onHandleIntent(intent) assertNotNull(receivedIntent) diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KitManagerImplTests.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KitManagerImplTests.kt index 53eed34f0..f50d63592 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KitManagerImplTests.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/KitManagerImplTests.kt @@ -94,7 +94,10 @@ class KitManagerImplTests : BaseKitOptionsTest() { // double check that ConfigManager is generating the right string val expectedActiveKits = "-6,-4,-3,-1" val expectedBundledKits = "-6,-5,-4,-3,-2.-1" - assertEquals(expectedActiveKits, MParticle.getInstance()?.Internal()?.configManager?.activeModuleIds) + assertEquals( + expectedActiveKits, + MParticle.getInstance()?.Internal()?.configManager?.activeModuleIds + ) // check that the active kits value is sent to the server MParticle.getInstance()?.apply { diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/AttributeListenerTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/AttributeListenerTestKit.kt index c49ea9c1c..644c9ecd9 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/AttributeListenerTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/AttributeListenerTestKit.kt @@ -6,22 +6,31 @@ import com.mparticle.kits.ReportingMessage open class AttributeListenerTestKit : ListenerTestKit(), KitIntegration.AttributeListener { var setUserAttribute: ((attributeKey: String?, attributeValue: String?) -> Unit)? = null - var setUserAttributeList: ((attributeKey: String?, attributeValueList: List?) -> Unit)? = null + var setUserAttributeList: ((attributeKey: String?, attributeValueList: List?) -> Unit)? = + null var supportsAttributeLists: (() -> Boolean)? = null - var setAllUserAttributes: ((userAttributes: Map?, userAttributeLists: Map>?) -> Unit)? = null + var setAllUserAttributes: ((userAttributes: Map?, userAttributeLists: Map>?) -> Unit)? = + null var removeUserAttribute: ((key: String?) -> Unit)? = null - var setUserIdentity: ((identityType: MParticle.IdentityType?, identity: String?) -> Unit)? = null + var setUserIdentity: ((identityType: MParticle.IdentityType?, identity: String?) -> Unit)? = + null var removeUserIdentity: ((identityType: MParticle.IdentityType?) -> Unit)? = null var logout: (() -> List)? = null override fun supportsAttributeLists() = supportsAttributeLists?.invoke() ?: true - override fun setUserAttributeList(attributeKey: String, attributeValueList: MutableList) { + override fun setUserAttributeList( + attributeKey: String, + attributeValueList: MutableList + ) { setUserAttributeList?.invoke(attributeKey, attributeValueList) onAttributeReceived?.invoke(attributeKey, attributeValueList) } - override fun setAllUserAttributes(userAttributes: Map, userAttributeLists: Map>) { + override fun setAllUserAttributes( + userAttributes: Map, + userAttributeLists: Map> + ) { setAllUserAttributes?.invoke(userAttributes, userAttributeLists) userAttributes.forEach { onAttributeReceived?.invoke(it.key, it.value) } userAttributeLists.forEach { onAttributeReceived?.invoke(it.key, it.value) } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/BaseTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/BaseTestKit.kt index 14442dadc..821fb50f8 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/BaseTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/BaseTestKit.kt @@ -5,7 +5,10 @@ import com.mparticle.kits.KitIntegration import com.mparticle.kits.ReportingMessage open class BaseTestKit : KitIntegration() { - open override fun onKitCreate(settings: Map?, context: Context): List { + open override fun onKitCreate( + settings: Map?, + context: Context + ): List { return listOf() } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/CommerceListenerTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/CommerceListenerTestKit.kt index 352ddd066..e38a6d7b2 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/CommerceListenerTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/CommerceListenerTestKit.kt @@ -7,13 +7,20 @@ import java.math.BigDecimal class CommerceListenerTestKit : ListenerTestKit(), KitIntegration.CommerceListener { var logEvent: ((CommerceEvent?) -> List)? = null - var logLtvIncrease: ((BigDecimal?, BigDecimal?, String?, Map?) -> List)? = null + var logLtvIncrease: ((BigDecimal?, BigDecimal?, String?, Map?) -> List)? = + null override fun logEvent(event: CommerceEvent?): List { return logEvent?.invoke(event) ?: listOf() } - override fun logLtvIncrease(valueIncreased: BigDecimal?, valueTotal: BigDecimal?, eventName: String?, contextInfo: Map?): List { - return logLtvIncrease?.invoke(valueIncreased, valueTotal, eventName, contextInfo) ?: listOf() + override fun logLtvIncrease( + valueIncreased: BigDecimal?, + valueTotal: BigDecimal?, + eventName: String?, + contextInfo: Map? + ): List { + return logLtvIncrease?.invoke(valueIncreased, valueTotal, eventName, contextInfo) + ?: listOf() } } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/EventTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/EventTestKit.kt index b6a2567fe..11a0ae7a6 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/EventTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/EventTestKit.kt @@ -10,6 +10,7 @@ class EventTestKit : ListenerTestKit(), KitIntegration.EventListener { override fun logEvent(baseEvent: MPEvent): MutableList? { return onLogEvent(baseEvent) } + override fun leaveBreadcrumb(breadcrumb: String?): MutableList { TODO("Not yet implemented") } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/IdentityListenerTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/IdentityListenerTestKit.kt index 3db28c174..000d2e743 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/IdentityListenerTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/IdentityListenerTestKit.kt @@ -5,28 +5,44 @@ import com.mparticle.kits.FilteredIdentityApiRequest import com.mparticle.kits.KitIntegration open class IdentityListenerTestKit : ListenerTestKit(), KitIntegration.IdentityListener { - var onIdentifyCompleted: ((mParticleUser: MParticleUser?, identityApiRequest: FilteredIdentityApiRequest?) -> Unit)? = null - var onLoginCompleted: ((mParticleUser: MParticleUser?, identityApiRequest: FilteredIdentityApiRequest?) -> Unit)? = null - var onLogoutCompleted: ((mParticleUser: MParticleUser?, identityApiRequest: FilteredIdentityApiRequest?) -> Unit)? = null - var onModifyCompleted: ((mParticleUser: MParticleUser?, identityApiRequest: FilteredIdentityApiRequest?) -> Unit)? = null + var onIdentifyCompleted: ((mParticleUser: MParticleUser?, identityApiRequest: FilteredIdentityApiRequest?) -> Unit)? = + null + var onLoginCompleted: ((mParticleUser: MParticleUser?, identityApiRequest: FilteredIdentityApiRequest?) -> Unit)? = + null + var onLogoutCompleted: ((mParticleUser: MParticleUser?, identityApiRequest: FilteredIdentityApiRequest?) -> Unit)? = + null + var onModifyCompleted: ((mParticleUser: MParticleUser?, identityApiRequest: FilteredIdentityApiRequest?) -> Unit)? = + null var onUserIdentified: ((mParticleUser: MParticleUser?) -> Unit)? = null - override fun onLogoutCompleted(mParticleUser: MParticleUser?, identityApiRequest: FilteredIdentityApiRequest?) { + override fun onLogoutCompleted( + mParticleUser: MParticleUser?, + identityApiRequest: FilteredIdentityApiRequest? + ) { onLogoutCompleted?.invoke(mParticleUser, identityApiRequest) onUserReceived?.invoke(mParticleUser) } - override fun onLoginCompleted(mParticleUser: MParticleUser?, identityApiRequest: FilteredIdentityApiRequest?) { + override fun onLoginCompleted( + mParticleUser: MParticleUser?, + identityApiRequest: FilteredIdentityApiRequest? + ) { onLoginCompleted?.invoke(mParticleUser, identityApiRequest) onUserReceived?.invoke(mParticleUser) } - override fun onIdentifyCompleted(mParticleUser: MParticleUser?, identityApiRequest: FilteredIdentityApiRequest?) { + override fun onIdentifyCompleted( + mParticleUser: MParticleUser?, + identityApiRequest: FilteredIdentityApiRequest? + ) { onIdentifyCompleted?.invoke(mParticleUser, identityApiRequest) onUserReceived?.invoke(mParticleUser) } - override fun onModifyCompleted(mParticleUser: MParticleUser?, identityApiRequest: FilteredIdentityApiRequest?) { + override fun onModifyCompleted( + mParticleUser: MParticleUser?, + identityApiRequest: FilteredIdentityApiRequest? + ) { onModifyCompleted?.invoke(mParticleUser, identityApiRequest) onUserReceived?.invoke(mParticleUser) } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/ListenerTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/ListenerTestKit.kt index 14882c6d6..0b7979d36 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/ListenerTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/ListenerTestKit.kt @@ -10,7 +10,8 @@ abstract class ListenerTestKit : BaseTestKit() { var onIdentityReceived: ((MParticle.IdentityType, String?) -> Unit)? = null var onAttributeReceived: ((String?, Any?) -> Unit)? = null - var onKitCreate: ((settings: Map?, context: Context) -> List)? = null + var onKitCreate: ((settings: Map?, context: Context) -> List)? = + null var setOptOut: ((optedOut: Boolean) -> List)? = null var getName: (() -> String)? = null @@ -18,6 +19,9 @@ abstract class ListenerTestKit : BaseTestKit() { override fun setOptOut(optedOut: Boolean) = setOptOut?.invoke(optedOut) ?: listOf() - override fun onKitCreate(settings: Map?, context: Context): List = onKitCreate?.invoke(settings, context) + override fun onKitCreate( + settings: Map?, + context: Context + ): List = onKitCreate?.invoke(settings, context) ?: listOf() } diff --git a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt index e8869695c..ab59245b4 100644 --- a/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt +++ b/android-kit-base/src/androidTest/kotlin/com/mparticle/kits/testkits/UserAttributeListenerTestKit.kt @@ -5,20 +5,33 @@ import com.mparticle.kits.FilteredMParticleUser import com.mparticle.kits.KitIntegration open class UserAttributeListenerTestKit : ListenerTestKit(), KitIntegration.UserAttributeListener { - var onIncrementUserAttribute: ((key: String?, incrementedBy: Number, value: String?, user: FilteredMParticleUser?) -> Unit)? = null + var onIncrementUserAttribute: ((key: String?, incrementedBy: Number, value: String?, user: FilteredMParticleUser?) -> Unit)? = + null var onRemoveUserAttribute: ((key: String?, user: FilteredMParticleUser?) -> Unit)? = null - var onSetUserAttribute: ((key: String?, value: Any?, user: FilteredMParticleUser?) -> Unit)? = null + var onSetUserAttribute: ((key: String?, value: Any?, user: FilteredMParticleUser?) -> Unit)? = + null var onSetUserTag: ((key: String?, user: FilteredMParticleUser?) -> Unit)? = null - var onSetUserAttributeList: ((attributeKey: String?, attributeValueList: List?, user: FilteredMParticleUser?) -> Unit)? = null - var onSetAllUserAttributes: ((userAttributes: Map?, userAttributeLists: Map?>?, user: FilteredMParticleUser?) -> Unit)? = null + var onSetUserAttributeList: ((attributeKey: String?, attributeValueList: List?, user: FilteredMParticleUser?) -> Unit)? = + null + var onSetAllUserAttributes: ((userAttributes: Map?, userAttributeLists: Map?>?, user: FilteredMParticleUser?) -> Unit)? = + null var supportsAttributeLists: (() -> Boolean)? = null - var onConsentStateUpdated: ((oldState: ConsentState?, newState: ConsentState?, user: FilteredMParticleUser?) -> Unit)? = null + var onConsentStateUpdated: ((oldState: ConsentState?, newState: ConsentState?, user: FilteredMParticleUser?) -> Unit)? = + null - override fun onConsentStateUpdated(oldState: ConsentState?, newState: ConsentState?, user: FilteredMParticleUser?) { + override fun onConsentStateUpdated( + oldState: ConsentState?, + newState: ConsentState?, + user: FilteredMParticleUser? + ) { onConsentStateUpdated?.invoke(oldState, newState, user) } - override fun onSetAllUserAttributes(userAttributes: Map?, userAttributeLists: Map>?, user: FilteredMParticleUser?) { + override fun onSetAllUserAttributes( + userAttributes: Map?, + userAttributeLists: Map>?, + user: FilteredMParticleUser? + ) { onSetAllUserAttributes?.invoke(userAttributes, userAttributeLists, user) userAttributes?.forEach { onAttributeReceived?.invoke(it.key, it.value) } } @@ -35,13 +48,22 @@ open class UserAttributeListenerTestKit : ListenerTestKit(), KitIntegration.User onUserReceived?.invoke(user) } - override fun onIncrementUserAttribute(key: String?, incrementedBy: Number, value: String?, user: FilteredMParticleUser?) { + override fun onIncrementUserAttribute( + key: String?, + incrementedBy: Number, + value: String?, + user: FilteredMParticleUser? + ) { onIncrementUserAttribute?.invoke(key, incrementedBy, value, user) onAttributeReceived?.invoke(key, value) onUserReceived?.invoke(user) } - override fun onSetUserAttributeList(attributeKey: String?, attributeValueList: MutableList?, user: FilteredMParticleUser?) { + override fun onSetUserAttributeList( + attributeKey: String?, + attributeValueList: MutableList?, + user: FilteredMParticleUser? + ) { onSetUserAttributeList?.invoke(attributeKey, attributeValueList, user) onAttributeReceived?.invoke(attributeKey, attributeValueList) onUserReceived?.invoke(user) diff --git a/android-kit-base/src/main/java/com/mparticle/kits/CommerceEventUtils.java b/android-kit-base/src/main/java/com/mparticle/kits/CommerceEventUtils.java index e3c1ea25c..883d99cee 100644 --- a/android-kit-base/src/main/java/com/mparticle/kits/CommerceEventUtils.java +++ b/android-kit-base/src/main/java/com/mparticle/kits/CommerceEventUtils.java @@ -417,8 +417,11 @@ public void onAttributeExtracted(Map customAttributes) { public interface OnAttributeExtracted { void onAttributeExtracted(String key, String value); + void onAttributeExtracted(String key, double value); + void onAttributeExtracted(String key, int value); + void onAttributeExtracted(Map attributes); } } \ No newline at end of file diff --git a/android-kit-base/src/main/java/com/mparticle/kits/FilteredIdentityApiRequest.java b/android-kit-base/src/main/java/com/mparticle/kits/FilteredIdentityApiRequest.java index d607d441b..346f2c7c4 100644 --- a/android-kit-base/src/main/java/com/mparticle/kits/FilteredIdentityApiRequest.java +++ b/android-kit-base/src/main/java/com/mparticle/kits/FilteredIdentityApiRequest.java @@ -9,11 +9,11 @@ public class FilteredIdentityApiRequest { KitIntegration provider; Map userIdentities = new HashMap<>(); - + FilteredIdentityApiRequest(IdentityApiRequest identityApiRequest, KitIntegration provider) { if (identityApiRequest != null) { userIdentities = new HashMap<>(identityApiRequest.getUserIdentities()); - if (provider.getKitManager()!= null) { + if (provider.getKitManager() != null) { userIdentities = provider.getKitManager().getDataplanFilter().transformIdentities(userIdentities); } } diff --git a/android-kit-base/src/main/java/com/mparticle/kits/KitConfiguration.java b/android-kit-base/src/main/java/com/mparticle/kits/KitConfiguration.java index f28483f4f..aeef9c910 100644 --- a/android-kit-base/src/main/java/com/mparticle/kits/KitConfiguration.java +++ b/android-kit-base/src/main/java/com/mparticle/kits/KitConfiguration.java @@ -432,7 +432,7 @@ private static JSONObject convertSparseMapToJsonObject(Map map) JSONObject obj = new JSONObject(); for (Map.Entry entry : map.entrySet()) { try { - obj.put(Integer.toString(entry.getKey()), entry.getValue()); + obj.put(Integer.toString(entry.getKey()), entry.getValue()); } catch (JSONException jse) { Logger.error("Issue while parsing kit configuration: " + jse.getMessage()); } @@ -448,7 +448,7 @@ public static JSONObject convertSparseArrayToJsonObject(SparseBooleanArray array for (int i = 0; i < array.size(); i++) { int key = array.keyAt(i); try { - object.put(Integer.toString(key), array.get(key)); + object.put(Integer.toString(key), array.get(key)); } catch (JSONException jse) { Logger.error("Issue while parsing kit configuration: " + jse.getMessage()); } diff --git a/android-kit-base/src/main/java/com/mparticle/kits/KitIntegration.java b/android-kit-base/src/main/java/com/mparticle/kits/KitIntegration.java index 89a18f16a..929c93a8e 100644 --- a/android-kit-base/src/main/java/com/mparticle/kits/KitIntegration.java +++ b/android-kit-base/src/main/java/com/mparticle/kits/KitIntegration.java @@ -17,10 +17,7 @@ import com.mparticle.commerce.CommerceEvent; import com.mparticle.consent.ConsentState; import com.mparticle.identity.MParticleUser; -import com.mparticle.internal.SideloadedKit; -import org.jetbrains.annotations.NotNull; -import org.json.JSONException; import org.json.JSONObject; import java.lang.ref.WeakReference; @@ -81,7 +78,7 @@ public KitConfiguration getConfiguration() { } public JSONObject getJsonConfig() { - if(mKitConfiguration!=null){ + if (mKitConfiguration != null) { return mKitConfiguration.convertToJsonObject(); } return null; @@ -413,7 +410,7 @@ public interface AttributeListener { /** * Indicate to the mParticle Kit framework if this AttributeListener supports attribute-values as lists. - * + * * If an AttributeListener returns false, the setUserAttributeList method will never be called. Instead, setUserAttribute * will be called with the attribute-value lists combined as a csv. * diff --git a/android-kit-base/src/main/java/com/mparticle/kits/KitManagerImpl.java b/android-kit-base/src/main/java/com/mparticle/kits/KitManagerImpl.java index 1c14aa5d4..f4af5a035 100644 --- a/android-kit-base/src/main/java/com/mparticle/kits/KitManagerImpl.java +++ b/android-kit-base/src/main/java/com/mparticle/kits/KitManagerImpl.java @@ -9,7 +9,6 @@ import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; -import android.util.Log; import androidx.annotation.MainThread; import androidx.annotation.NonNull; @@ -29,9 +28,9 @@ import com.mparticle.identity.IdentityApiRequest; import com.mparticle.identity.IdentityStateListener; import com.mparticle.identity.MParticleUser; -import com.mparticle.internal.KitsLoadedCallback; import com.mparticle.internal.CoreCallbacks; import com.mparticle.internal.KitManager; +import com.mparticle.internal.KitsLoadedCallback; import com.mparticle.internal.Logger; import com.mparticle.internal.MPUtility; import com.mparticle.internal.ReportingManager; diff --git a/android-kit-base/src/main/java/com/mparticle/kits/KitUtils.java b/android-kit-base/src/main/java/com/mparticle/kits/KitUtils.java index f058722ee..6b7cb4834 100644 --- a/android-kit-base/src/main/java/com/mparticle/kits/KitUtils.java +++ b/android-kit-base/src/main/java/com/mparticle/kits/KitUtils.java @@ -23,7 +23,6 @@ */ public final class KitUtils { /** - * * mParticle attribute keys defined by the `MParticle.UserAttributes` interface are * preceded by a dollar-sign ie `"$FirstName"`. This method just removes the dollar-sign if present. * @@ -47,7 +46,7 @@ public static String sanitizeAttributeKey(String key) { * send server-to-server, or via a Kit. * * @param bytes - * @return returns the hashed bytes + * @return returns the hashed bytes */ public static BigInteger hashFnv1a(byte[] bytes) { return MPUtility.hashFnv1A(bytes); @@ -77,6 +76,7 @@ public static int hashForFiltering(String input) { public static boolean isEmpty(CharSequence str) { return MPUtility.isEmpty(str); } + /** * Combine the given list into a single string separated by a comma. * @@ -135,8 +135,8 @@ public static boolean isServiceAvailable(Context context, Class service) { * will return "True" and "False" (rather than "true") which trips up Boolean.valueOf * so this provides a consistent way for kits to handle such settings. * - * @param settings the Map of settings given to a kit. - * @param key the key of the setting to parse + * @param settings the Map of settings given to a kit. + * @param key the key of the setting to parse * @param defaultValue the default value if the setting is not found * @return the parsed boolean value of the setting. */ @@ -156,11 +156,11 @@ public static boolean parseBooleanSetting(Map settings, String k * so this provides a consistent way for kits to handle such settings. * * @param settings the Map of settings given to a kit. - * @param key the key of the setting to parse + * @param key the key of the setting to parse * @return the parsed boolean value of the setting, or false if the setting is not found. */ public static boolean parseBooleanSetting(Map settings, String key) { - return parseBooleanSetting(settings, key, false); + return parseBooleanSetting(settings, key, false); } @TargetApi(Build.VERSION_CODES.CUPCAKE) diff --git a/android-kit-base/src/main/java/com/mparticle/kits/ReportingMessage.java b/android-kit-base/src/main/java/com/mparticle/kits/ReportingMessage.java index 0ffc79fc9..22e08cfcd 100644 --- a/android-kit-base/src/main/java/com/mparticle/kits/ReportingMessage.java +++ b/android-kit-base/src/main/java/com/mparticle/kits/ReportingMessage.java @@ -91,11 +91,11 @@ public ReportingMessage setScreenName(String screenName) { public static ReportingMessage fromEvent(KitIntegration provider, BaseEvent event) { ReportingMessage message = new ReportingMessage(provider, event.getType().getMessageType(), System.currentTimeMillis(), event.getCustomAttributeStrings()); if (event instanceof MPEvent) { - MPEvent mpEvent = (MPEvent)event; + MPEvent mpEvent = (MPEvent) event; message.eventType = mpEvent.getEventType().name(); message.eventName = mpEvent.getEventName(); } else if (event instanceof CommerceEvent) { - CommerceEvent commerceEvent = (CommerceEvent)event; + CommerceEvent commerceEvent = (CommerceEvent) event; message.eventType = CommerceEventUtils.getEventTypeString(commerceEvent); } return message; @@ -155,7 +155,8 @@ public JSONObject toJson() { jsonObject.put("et", eventType); } } - } catch (JSONException ignored) { } + } catch (JSONException ignored) { + } return jsonObject; } diff --git a/android-kit-base/src/main/java/com/mparticle/kits/mappings/CustomMapping.java b/android-kit-base/src/main/java/com/mparticle/kits/mappings/CustomMapping.java index 9dcb73e3d..261bce501 100644 --- a/android-kit-base/src/main/java/com/mparticle/kits/mappings/CustomMapping.java +++ b/android-kit-base/src/main/java/com/mparticle/kits/mappings/CustomMapping.java @@ -5,8 +5,8 @@ import com.mparticle.commerce.CommerceEvent; import com.mparticle.commerce.Product; import com.mparticle.commerce.Promotion; -import com.mparticle.kits.CommerceEventUtils; import com.mparticle.internal.MPUtility; +import com.mparticle.kits.CommerceEventUtils; import org.json.JSONArray; import org.json.JSONException; diff --git a/android-kit-base/src/main/kotlin/com/mparticle/kits/DataplanFilter.kt b/android-kit-base/src/main/kotlin/com/mparticle/kits/DataplanFilter.kt index 9a8033da9..7a4525e71 100644 --- a/android-kit-base/src/main/kotlin/com/mparticle/kits/DataplanFilter.kt +++ b/android-kit-base/src/main/kotlin/com/mparticle/kits/DataplanFilter.kt @@ -69,12 +69,22 @@ Data Plan parsed for Kit Filtering: event is MPEvent -> when { event.isScreenEvent -> DataPoint(SCREEN_EVENT_KEY, event.eventName) - else -> DataPoint(CUSTOM_EVENT_KEY, event.eventName, event.eventType.getEventsApiName()) + else -> DataPoint( + CUSTOM_EVENT_KEY, + event.eventName, + event.eventType.getEventsApiName() + ) } event is CommerceEvent -> when { - !event.productAction.isNullOrBlank() -> DataPoint(PRODUCT_ACTION_KEY, event.productAction) - !event.promotionAction.isNullOrBlank() -> DataPoint(PROMOTION_ACTION_KEY, event.promotionAction) + !event.productAction.isNullOrBlank() -> DataPoint( + PRODUCT_ACTION_KEY, + event.productAction + ) + !event.promotionAction.isNullOrBlank() -> DataPoint( + PROMOTION_ACTION_KEY, + event.promotionAction + ) !event.impressions.isNullOrEmpty() -> DataPoint(PRODUCT_IMPRESSION_KEY) else -> null } @@ -99,7 +109,8 @@ Data Plan parsed for Kit Filtering: } } if (event is CommerceEvent) { - val productActionDatapoint = dataPoints["$dataPointKey.$PRODUCT_ACTION_PRODUCTS"] + val productActionDatapoint = + dataPoints["$dataPointKey.$PRODUCT_ACTION_PRODUCTS"] event.products?.iterator()?.forEach { product -> product?.customAttributes?.toMutableMap()?.apply { val filteredAttributes = filterKeys { @@ -109,7 +120,8 @@ Data Plan parsed for Kit Filtering: putAll(filteredAttributes) } } - val productImpressionDatapoint = dataPoints["$dataPointKey.$PRODUCT_IMPRESSION_PRODUCTS"] + val productImpressionDatapoint = + dataPoints["$dataPointKey.$PRODUCT_IMPRESSION_PRODUCTS"] if ((event.impressions?.size ?: 0) > 0) { event.impressions?.iterator()?.forEach { it.products.forEach { product -> @@ -284,7 +296,8 @@ Data Plan parsed for Kit Filtering: ?.optJSONObject("data") ?: return null if (datapoint.productAttributeType == null) { data.let { - val customAttributes = it.getConstrainedPropertiesJSONObject("custom_attributes") + val customAttributes = + it.getConstrainedPropertiesJSONObject("custom_attributes") if (customAttributes == null) { return null } else { @@ -296,15 +309,17 @@ Data Plan parsed for Kit Filtering: data.let { val products = when (datapoint.productAttributeType) { PRODUCT_ACTION_PRODUCTS -> { - val productBlock = it.getConstrainedPropertiesJSONObject("product_action") - ?.getConstrainedPropertiesJSONObject("products") + val productBlock = + it.getConstrainedPropertiesJSONObject("product_action") + ?.getConstrainedPropertiesJSONObject("products") if (productBlock == emptyJSONObject) { return hashSetOf() } productBlock } PRODUCT_IMPRESSION_PRODUCTS -> { - var productBlock = it.getConstrainedPropertiesJSONObject("product_impressions") + var productBlock = + it.getConstrainedPropertiesJSONObject("product_impressions") if (productBlock == emptyJSONObject) { return hashSetOf() } @@ -416,7 +431,11 @@ Data Plan parsed for Kit Filtering: } class DataPoint(val type: String, val name: String? = null, val eventType: String? = null) { - constructor(datapoint: DataPoint) : this(datapoint.type, datapoint.name, datapoint.eventType) + constructor(datapoint: DataPoint) : this( + datapoint.type, + datapoint.name, + datapoint.eventType + ) var productAttributeType: String? = null private set @@ -430,12 +449,15 @@ Data Plan parsed for Kit Filtering: else -> null } - override fun toString() = "$type${if (name != null) ".$name" else ""}${if (eventType != null) ".$eventType" else ""}${productAttributeType?.let { ".$it" } ?: ""}" + override fun toString() = + "$type${if (name != null) ".$name" else ""}${if (eventType != null) ".$eventType" else ""}${productAttributeType?.let { ".$it" } ?: ""}" } class EmptyDataplanFilter : DataplanFilter { override fun transformEventForEvent(event: T?) = event - override fun transformIdentities(identities: Map?) = identities + override fun transformIdentities(identities: Map?) = + identities + override fun transformUserAttributes(attributes: Map?) = attributes override fun isUserAttributeBlocked(key: String?) = false override fun isUserIdentityBlocked(key: MParticle.IdentityType?) = false diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/DataplanFilterImplTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/DataplanFilterImplTest.kt index bf9177e27..a74886571 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/DataplanFilterImplTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/DataplanFilterImplTest.kt @@ -49,11 +49,21 @@ class DataplanFilterImplTest { assertEquals(it, hashSetOf("foo number", "foo", "foo foo")) } dataPoints.getValue("$PRODUCT_ACTION_KEY.add_to_cart").also { - assertEquals(it, hashSetOf("attributeNumEnum", "attributeEmail", "attributeStringAlpha", "attributeBoolean", "attributeNumMinMax")) - } - dataPoints.getValue("$PRODUCT_ACTION_KEY.add_to_cart.$PRODUCT_IMPRESSION_PRODUCTS").also { - assertNull(it) + assertEquals( + it, + hashSetOf( + "attributeNumEnum", + "attributeEmail", + "attributeStringAlpha", + "attributeBoolean", + "attributeNumMinMax" + ) + ) } + dataPoints.getValue("$PRODUCT_ACTION_KEY.add_to_cart.$PRODUCT_IMPRESSION_PRODUCTS") + .also { + assertNull(it) + } dataPoints.getValue("$PRODUCT_ACTION_KEY.add_to_cart.$PRODUCT_ACTION_PRODUCTS").also { assertNull(it) } @@ -67,7 +77,10 @@ class DataplanFilterImplTest { assertEquals(it, hashSetOf()) } dataPoints.getValue(USER_ATTRIBUTES_KEY).also { - assertEquals(it, hashSetOf("a third attribute", "my attribute", "my other attribute")) + assertEquals( + it, + hashSetOf("a third attribute", "my attribute", "my other attribute") + ) } dataPoints.getValue(USER_IDENTITIES_KEY).also { assertNull(it) @@ -116,9 +129,10 @@ class DataplanFilterImplTest { dataPoints.getValue("$PRODUCT_ACTION_KEY.add_to_cart.$PRODUCT_ACTION_PRODUCTS").also { assertNull(it) } - dataPoints.getValue("$PRODUCT_ACTION_KEY.add_to_cart.$PRODUCT_IMPRESSION_PRODUCTS").also { - assertNull(it) - } + dataPoints.getValue("$PRODUCT_ACTION_KEY.add_to_cart.$PRODUCT_IMPRESSION_PRODUCTS") + .also { + assertNull(it) + } dataPoints.getValue("$PROMOTION_ACTION_KEY.view").also { assertEquals(hashSetOf("not required", "required"), it) } @@ -135,7 +149,10 @@ class DataplanFilterImplTest { assertNull(it) } dataPoints.getValue(USER_ATTRIBUTES_KEY).also { - assertEquals(hashSetOf("my attribute", "my other attribute", "a third attribute"), it) + assertEquals( + hashSetOf("my attribute", "my other attribute", "a third attribute"), + it + ) } dataPoints.getValue(USER_IDENTITIES_KEY).also { assertNull(it) } dataPoints.getValue("$CUSTOM_EVENT_KEY.SocialEvent.social").also { @@ -181,7 +198,8 @@ class DataplanFilterImplTest { customAttributes = randomAttributes() } - val dataplanFilter = DataplanFilterImpl(dataplanPoints, true, Random.nextBoolean(), false, false) + val dataplanFilter = + DataplanFilterImpl(dataplanPoints, true, Random.nextBoolean(), false, false) assertNull(dataplanFilter.transformEventForEvent(event)?.toString()) diversity.remove(datapoint.type) } @@ -199,7 +217,8 @@ class DataplanFilterImplTest { dataplanPoints[datapoint.toString()] = null - val dataplanFilter = DataplanFilterImpl(dataplanPoints, true, Random.nextBoolean(), false, false) + val dataplanFilter = + DataplanFilterImpl(dataplanPoints, true, Random.nextBoolean(), false, false) assertEquals(event.toString(), dataplanFilter.transformEventForEvent(event)?.toString()) diversity.remove(datapoint.type) } @@ -216,7 +235,8 @@ class DataplanFilterImplTest { customAttributes = randomAttributes() } - val dataplanFilter = DataplanFilterImpl(dataplanPoints, false, Random.nextBoolean(), false, false) + val dataplanFilter = + DataplanFilterImpl(dataplanPoints, false, Random.nextBoolean(), false, false) assertEquals(event.toString(), dataplanFilter.transformEventForEvent(event)?.toString()) diversity.remove(datapoint.type) } @@ -234,8 +254,12 @@ class DataplanFilterImplTest { } dataplanPoints[datapoint.toString()] = allowedAttributes.keys.toHashSet() - val dataplanFilter = DataplanFilterImpl(dataplanPoints, true, Random.nextBoolean(), false, false) - assertEquals(allowedAttributes, dataplanFilter.transformEventForEvent(event)?.customAttributeStrings) + val dataplanFilter = + DataplanFilterImpl(dataplanPoints, true, Random.nextBoolean(), false, false) + assertEquals( + allowedAttributes, + dataplanFilter.transformEventForEvent(event)?.customAttributeStrings + ) diversity.remove(datapoint.type) } } @@ -251,7 +275,8 @@ class DataplanFilterImplTest { customAttributes = allowedAttributes } - val dataplanFilter = DataplanFilterImpl(dataplanPoints, false, Random.nextBoolean(), false, false) + val dataplanFilter = + DataplanFilterImpl(dataplanPoints, false, Random.nextBoolean(), false, false) assertEquals(event, dataplanFilter.transformEventForEvent(event)) diversity.remove(datapoint.type) } @@ -271,8 +296,12 @@ class DataplanFilterImplTest { } dataplanPoints[datapoint.toString()] = allowedAttributes.keys.toHashSet() - val dataplanFilter = DataplanFilterImpl(dataplanPoints, Random.Default.nextBoolean(), true, false, false) - assertEquals(allowedAttributes, dataplanFilter.transformEventForEvent(event)?.customAttributeStrings) + val dataplanFilter = + DataplanFilterImpl(dataplanPoints, Random.Default.nextBoolean(), true, false, false) + assertEquals( + allowedAttributes, + dataplanFilter.transformEventForEvent(event)?.customAttributeStrings + ) diversity.remove(datapoint.type) } } @@ -292,22 +321,45 @@ class DataplanFilterImplTest { } } - private val types = setOf(CUSTOM_EVENT_KEY, PRODUCT_ACTION_KEY, PROMOTION_ACTION_KEY, PRODUCT_IMPRESSION_KEY, SCREEN_EVENT_KEY) + private val types = setOf( + CUSTOM_EVENT_KEY, + PRODUCT_ACTION_KEY, + PROMOTION_ACTION_KEY, + PRODUCT_IMPRESSION_KEY, + SCREEN_EVENT_KEY + ) fun getRandomEvent(datapoint: DataplanPoint): BaseEvent { return when (datapoint.type) { - CUSTOM_EVENT_KEY -> MPEvent.Builder(datapoint.name!!, MParticle.EventType.values().first { it.getEventsApiName() == datapoint.eventType }).build() - SCREEN_EVENT_KEY -> ScreenEventBuilder(datapoint.name!!).build().also { assertTrue(it.isScreenEvent) } - PRODUCT_ACTION_KEY -> CommerceEvent.Builder(datapoint.name!!, Product.Builder("a", "b", 1.0).build()).build() + CUSTOM_EVENT_KEY -> MPEvent.Builder( + datapoint.name!!, + MParticle.EventType.values().first { it.getEventsApiName() == datapoint.eventType } + ) + .build() + SCREEN_EVENT_KEY -> ScreenEventBuilder(datapoint.name!!).build() + .also { assertTrue(it.isScreenEvent) } + PRODUCT_ACTION_KEY -> CommerceEvent.Builder( + datapoint.name!!, + Product.Builder("a", "b", 1.0).build() + ).build() PROMOTION_ACTION_KEY -> CommerceEvent.Builder(datapoint.name!!, Promotion()).build() - PRODUCT_IMPRESSION_KEY -> CommerceEvent.Builder(Impression("impressionname", Product.Builder("a", "b", 1.0).build())).build() + PRODUCT_IMPRESSION_KEY -> CommerceEvent.Builder( + Impression( + "impressionname", + Product.Builder("a", "b", 1.0).build() + ) + ).build() else -> throw IllegalArgumentException(datapoint.type + ": messed this implementation up :/") } } fun getRandomDataplanEventKey(): DataplanPoint { return when (Random.Default.nextInt(0, 5)) { - 0 -> DataplanPoint(CUSTOM_EVENT_KEY, randomString(5), randomEventType().getEventsApiName()) + 0 -> DataplanPoint( + CUSTOM_EVENT_KEY, + randomString(5), + randomEventType().getEventsApiName() + ) 1 -> DataplanPoint(SCREEN_EVENT_KEY, randomString(8)) 2 -> DataplanPoint(PRODUCT_ACTION_KEY, randomProductAction()) 3 -> DataplanPoint(PROMOTION_ACTION_KEY, randomPromotionAction()) @@ -339,7 +391,12 @@ class DataplanFilterImplTest { } fun randomEventType(): MParticle.EventType { - return MParticle.EventType.values()[Random.Default.nextInt(0, MParticle.EventType.values().size - 1)] + return MParticle.EventType.values()[ + Random.Default.nextInt( + 0, + MParticle.EventType.values().size - 1 + ) + ] } fun randomProductAction(): String { @@ -367,6 +424,7 @@ class DataplanFilterImplTest { isScreenEvent = true } } + class ScreenEventBuilder(name: String) : MPEvent.Builder(name, MParticle.EventType.Other) { override fun build(): MPEvent { return ScreenEvent(super.build()) @@ -374,6 +432,7 @@ class DataplanFilterImplTest { } class DataplanPoint(val type: String, val name: String? = null, val eventType: String? = null) { - override fun toString() = "$type${if (name != null) ".$name" else ""}${if (eventType != null) ".$eventType" else ""}" + override fun toString() = + "$type${if (name != null) ".$name" else ""}${if (eventType != null) ".$eventType" else ""}" } } diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitConfigurationTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitConfigurationTest.kt index 265fc57e6..d911874a4 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitConfigurationTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitConfigurationTest.kt @@ -396,8 +396,17 @@ class KitConfigurationTest { fun testScreenAttributeFiltering() { val configuration = MockKitConfiguration.createKitConfiguration(JSONObject(" {\"id\":56, \"as\":{\"secretKey\":\"testappkey\", \"eventList\":\"[\\\"test1\\\",\\\"test2\\\",\\\"test3\\\"]\", \"sendTransactionData\":\"True\", \"eventAttributeList\":null }, \"hs\":{\"svea\":{\"1689004688\":0, \"1198002448\":1 } }, }")) - val testAttributes = mapOf("screen attribute should not forward" to "testVal", "screen attribute should forward" to "testVal", "screen attribute should also forward" to "testVal") - val filterdScreenAttributes = KitConfiguration.filterEventAttributes(null, "testScreenView", configuration.screenAttributeFilters, testAttributes) + val testAttributes = mapOf( + "screen attribute should not forward" to "testVal", + "screen attribute should forward" to "testVal", + "screen attribute should also forward" to "testVal" + ) + val filterdScreenAttributes = KitConfiguration.filterEventAttributes( + null, + "testScreenView", + configuration.screenAttributeFilters, + testAttributes + ) Assert.assertFalse( filterdScreenAttributes.containsKey("screen attribute should not forward") ) diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitIntegrationTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitIntegrationTest.kt index 635a5ba17..6e80af26c 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitIntegrationTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitIntegrationTest.kt @@ -208,7 +208,7 @@ class KitIntegrationTest { return null } - override fun setOptOut(optedOut: Boolean): List ? { + override fun setOptOut(optedOut: Boolean): List? { return null } } diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerImplTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerImplTest.kt index c6c077386..db47f3b43 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerImplTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/KitManagerImplTest.kt @@ -51,7 +51,10 @@ class KitManagerImplTest { Assert.assertEquals(factory, manager.mKitIntegrationFactory) } - private fun createKitsMap(ids: List, type: Class<*> = KitIntegration::class.java): HashMap> { + private fun createKitsMap( + ids: List, + type: Class<*> = KitIntegration::class.java + ): HashMap> { val map = hashMapOf>() ids.forEach { map.put(it, type) } return map @@ -534,7 +537,8 @@ class KitManagerImplTest { .sideloadedKits(mutableListOf(sideloadedKit) as List).build() val manager: KitManagerImpl = MockKitManagerImpl(options) val factory = Mockito.mock(KitIntegrationFactory::class.java) - Mockito.`when`(factory.getSupportedKits()).thenReturn(createKitsMap(listOf(kitId), MPSideloadedKit::class.java).keys) + Mockito.`when`(factory.getSupportedKits()) + .thenReturn(createKitsMap(listOf(kitId), MPSideloadedKit::class.java).keys) manager.setKitFactory(factory) Mockito.`when`(factory.isSupported(Mockito.anyInt())).thenReturn(true) @@ -574,7 +578,8 @@ class KitManagerImplTest { KitIntegrationFactory::class.java ) manager.setKitFactory(factory) - Mockito.`when`(factory.getSupportedKits()).thenReturn(createKitsMap(listOf(1, idOne, idTwo), MPSideloadedKit::class.java).keys) + Mockito.`when`(factory.getSupportedKits()) + .thenReturn(createKitsMap(listOf(1, idOne, idTwo), MPSideloadedKit::class.java).keys) Mockito.`when`(factory.isSupported(Mockito.anyInt())).thenReturn(true) val sideloadedKit = Mockito.mock(KitIntegration::class.java) Mockito.`when`(sideloadedKit.isDisabled).thenReturn(false) diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/sample_dataplan2.json b/android-kit-base/src/test/kotlin/com/mparticle/kits/sample_dataplan2.json index d631aaa89..cda540a32 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/sample_dataplan2.json +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/sample_dataplan2.json @@ -1,722 +1,696 @@ { - "version_document":{ - "data_points":[ + "version_document": { + "data_points": [ { - "description":"a search event with a basic name", - "match":{ - "type":"custom_event", - "criteria":{ - "event_name":"Search Event", - "custom_event_type":"search" + "description": "a search event with a basic name", + "match": { + "type": "custom_event", + "criteria": { + "event_name": "Search Event", + "custom_event_type": "search" } }, - "validator":{ - "type":"json_schema", - "definition":{ - "properties":{ - "data":{ - "additionalProperties":true, - "properties":{ - "custom_event_type":{ - "description":"", - "type":"string" + "validator": { + "type": "json_schema", + "definition": { + "properties": { + "data": { + "additionalProperties": true, + "properties": { + "custom_event_type": { + "description": "", + "type": "string" }, - "event_name":{ - "description":"", - "type":"string" + "event_name": { + "description": "", + "type": "string" }, - "custom_attributes":{ - "additionalProperties":true, - "description":"", - "properties":{ - "hello":{ - "description":"", - "type":"string" + "custom_attributes": { + "additionalProperties": true, + "description": "", + "properties": { + "hello": { + "description": "", + "type": "string" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" } }, - "required":[ + "required": [ "custom_event_type", "event_name" ], - "type":"object" + "type": "object" } } } } }, { - "description":"no description for this location event", - "match":{ - "type":"custom_event", - "criteria":{ - "event_name":"locationEvent", - "custom_event_type":"location" + "description": "no description for this location event", + "match": { + "type": "custom_event", + "criteria": { + "event_name": "locationEvent", + "custom_event_type": "location" } }, - "validator":{ - "type":"json_schema", - "definition":{ - "properties":{ - "data":{ - "additionalProperties":true, - "properties":{ - "custom_event_type":{ - "description":"", - "type":"string" + "validator": { + "type": "json_schema", + "definition": { + "properties": { + "data": { + "additionalProperties": true, + "properties": { + "custom_event_type": { + "description": "", + "type": "string" }, - "event_name":{ - "description":"", - "type":"string" + "event_name": { + "description": "", + "type": "string" }, - "custom_attributes":{ - "additionalProperties":false, - "description":"", - "properties":{ - "foo":{ - "description":"", - "enum":[ + "custom_attributes": { + "additionalProperties": false, + "description": "", + "properties": { + "foo": { + "description": "", + "enum": [ "bar", "barr", "bar bar" ], - "type":"string" + "type": "string" }, - "foo foo":{ - "description":"", - "maximum":5, - "minimum":0, - "type":"number" + "foo foo": { + "description": "", + "maximum": 5, + "minimum": 0, + "type": "number" }, - "foo number":{ - "description":"", - "enum":[ + "foo number": { + "description": "", + "enum": [ "10", "20", "30" ], - "type":"number" + "type": "number" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" } }, - "required":[ + "required": [ "custom_event_type", "event_name" ], - "type":"object" + "type": "object" } } } } }, { - "description":"this commerce event has product attributes and allow additional attributes for event custom attributes and product custom attributes", - "match":{ - "type":"product_action", - "criteria":{ - "action":"add_to_cart" + "description": "this commerce event has product attributes and allow additional attributes for event custom attributes and product custom attributes", + "match": { + "type": "product_action", + "criteria": { + "action": "add_to_cart" } }, - "validator":{ - "type":"json_schema", - "definition":{ - "properties":{ - "data":{ - "additionalProperties":true, - "properties":{ - "currency_code":{ - "description":"", - "enum":[ + "validator": { + "type": "json_schema", + "definition": { + "properties": { + "data": { + "additionalProperties": true, + "properties": { + "currency_code": { + "description": "", + "enum": [ "USD", "CAD", "AUS" ], - "type":"string" + "type": "string" }, - "custom_attributes":{ - "additionalProperties":false, - "description":"", - "properties":{ - "attributeNumMinMax":{ - "description":"", - "maximum":17, - "minimum":9, - "type":"number" + "custom_attributes": { + "additionalProperties": false, + "description": "", + "properties": { + "attributeNumMinMax": { + "description": "", + "maximum": 17, + "minimum": 9, + "type": "number" }, - "attributeEmail":{ - "description":"", - "format":"email", - "type":"string" + "attributeEmail": { + "description": "", + "format": "email", + "type": "string" }, - "attributeNumEnum":{ - "description":"", - "enum":[ + "attributeNumEnum": { + "description": "", + "enum": [ "2", "7", "9" ], - "type":"number" + "type": "number" }, - "attributeStringAlpha":{ - "description":"", - "pattern":"[AZ]", - "type":"string" + "attributeStringAlpha": { + "description": "", + "pattern": "[AZ]", + "type": "string" }, - "attributeBoolean":{ - "description":"", - "type":"boolean" + "attributeBoolean": { + "description": "", + "type": "boolean" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" }, - "product_action":{ - "additionalProperties":false, - "description":"", - "properties":{ - "products":{ - "description":"", - "items":{ - "additionalProperties":true, - "description":"", - "properties":{ - "custom_attributes":{ - "additionalProperties":true, - "description":"", - "properties":{ - "plannedAttr2":{ - "description":"", - "type":"string" + "product_action": { + "additionalProperties": false, + "description": "", + "properties": { + "products": { + "description": "", + "items": { + "additionalProperties": true, + "description": "", + "properties": { + "custom_attributes": { + "additionalProperties": true, + "description": "", + "properties": { + "plannedAttr2": { + "description": "", + "type": "string" }, - "plannedAttr1":{ - "description":"", - "type":"string" + "plannedAttr1": { + "description": "", + "type": "string" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" }, - "type":"array" + "type": "array" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" } } } } }, { - "description":"view.a product", - "match":{ - "type":"promotion_action", - "criteria":{ - "action":"view" + "description": "view.a product", + "match": { + "type": "promotion_action", + "criteria": { + "action": "view" } }, - "validator":{ - "type":"json_schema", - "definition":{ - "properties":{ - "data":{ - "additionalProperties":true, - "properties":{ - "custom_attributes":{ - "additionalProperties":false, - "description":"", - "properties":{ - "not required":{ - "description":"", - "type":"string" + "validator": { + "type": "json_schema", + "definition": { + "properties": { + "data": { + "additionalProperties": true, + "properties": { + "custom_attributes": { + "additionalProperties": false, + "description": "", + "properties": { + "not required": { + "description": "", + "type": "string" }, - "required":{ - "description":"", - "type":"string" + "required": { + "description": "", + "type": "string" } }, - "required":[ + "required": [ "required" ], - "type":"object" + "type": "object" } }, - "required":[ + "required": [ "custom_attributes" ], - "type":"object" + "type": "object" } } } } }, { - "description":"", - "match":{ - "type":"custom_event", - "criteria":{ - "event_name":"TestEvent", - "custom_event_type":"navigation" + "description": "", + "match": { + "type": "custom_event", + "criteria": { + "event_name": "TestEvent", + "custom_event_type": "navigation" } }, - "validator":{ - "type":"json_schema", - "definition":{ - "properties":{ - "data":{ - "additionalProperties":true, - "properties":{ - "canonical_name":{ - "description":"", - "enum":[ + "validator": { + "type": "json_schema", + "definition": { + "properties": { + "data": { + "additionalProperties": true, + "properties": { + "canonical_name": { + "description": "", + "enum": [ "This", "That" ], - "type":"string" + "type": "string" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" } } } } }, { - "description":"", - "match":{ - "type":"product_impression", - "criteria":{ - + "description": "", + "match": { + "type": "product_impression", + "criteria": { } }, - "validator":{ - "type":"json_schema", - "definition":{ - "properties":{ - "data":{ - "additionalProperties":true, - "properties":{ - "custom_flags":{ - "additionalProperties":false, - "description":"", - "properties":{ - "NotSoCustomFlag":{ - "description":"", - "type":"boolean" + "validator": { + "type": "json_schema", + "definition": { + "properties": { + "data": { + "additionalProperties": true, + "properties": { + "custom_flags": { + "additionalProperties": false, + "description": "", + "properties": { + "NotSoCustomFlag": { + "description": "", + "type": "boolean" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" }, - "custom_attributes":{ - "additionalProperties":false, - "description":"", - "properties":{ - "thing1":{ - "description":"", - "type":"string" + "custom_attributes": { + "additionalProperties": false, + "description": "", + "properties": { + "thing1": { + "description": "", + "type": "string" } }, - "required":[ + "required": [ "thing1" ], - "type":"object" + "type": "object" } }, - "required":[ + "required": [ "custom_attributes" ], - "type":"object" + "type": "object" } } } } }, { - "description":"", - "match":{ - "type":"screen_view", - "criteria":{ - "screen_name":"A New ScreenViewEvent" + "description": "", + "match": { + "type": "screen_view", + "criteria": { + "screen_name": "A New ScreenViewEvent" } }, - "validator":{ - "type":"json_schema", - "definition":{ - "properties":{ - "data":{ - "additionalProperties":true, - "properties":{ - "activity_type":{ - "description":"", - "pattern":"[a-z]", - "type":"string" + "validator": { + "type": "json_schema", + "definition": { + "properties": { + "data": { + "additionalProperties": true, + "properties": { + "activity_type": { + "description": "", + "pattern": "[a-z]", + "type": "string" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" } } } } }, { - "description":"", - "match":{ - "type":"screen_view", - "criteria":{ - "screen_name":"my screeeen" + "description": "", + "match": { + "type": "screen_view", + "criteria": { + "screen_name": "my screeeen" } }, - "validator":{ - "type":"json_schema", - "definition":{ - "properties":{ - "data":{ - "additionalProperties":true, - "properties":{ - "custom_attributes":{ - "additionalProperties":false, - "description":"", - "properties":{ - "test2key":{ - "description":"", - "type":"string" + "validator": { + "type": "json_schema", + "definition": { + "properties": { + "data": { + "additionalProperties": true, + "properties": { + "custom_attributes": { + "additionalProperties": false, + "description": "", + "properties": { + "test2key": { + "description": "", + "type": "string" }, - "test1key":{ - "description":"", - "type":"string" + "test1key": { + "description": "", + "type": "string" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" } } } } }, { - "description":"", - "match":{ - "type":"custom_event", - "criteria":{ - "event_name":"something something something", - "custom_event_type":"navigation" + "description": "", + "match": { + "type": "custom_event", + "criteria": { + "event_name": "something something something", + "custom_event_type": "navigation" } }, - "validator":{ - "type":"json_schema", - "definition":{ - "properties":{ - "data":{ - "additionalProperties":true, - "properties":{ - "custom_attributes":{ - "additionalProperties":true, - "description":"", - "type":"object" + "validator": { + "type": "json_schema", + "definition": { + "properties": { + "data": { + "additionalProperties": true, + "properties": { + "custom_attributes": { + "additionalProperties": true, + "description": "", + "type": "object" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" } } } } }, { - "description":"User Attributes", - "match":{ - "type":"user_attributes", - "criteria":{ - + "description": "User Attributes", + "match": { + "type": "user_attributes", + "criteria": { } }, - "validator":{ - "type":"json_schema", - "definition":{ - "additionalProperties":false, - "properties":{ - "my attribute":{ - "description":"", - "type":"string" + "validator": { + "type": "json_schema", + "definition": { + "additionalProperties": false, + "properties": { + "my attribute": { + "description": "", + "type": "string" }, - "my other attribute":{ - "description":"", - "type":"string" + "my other attribute": { + "description": "", + "type": "string" }, - "a third attribute":{ - "description":"", - "type":"string" + "a third attribute": { + "description": "", + "type": "string" } }, - "required":[ + "required": [ "my other attribute" ] } }, - "active_transformation_ids":[ - + "active_transformation_ids": [ ] }, { - "description":"User Identities", - "match":{ - "type":"user_identities", - "criteria":{ - + "description": "User Identities", + "match": { + "type": "user_identities", + "criteria": { } }, - "validator":{ - "type":"json_schema", - "definition":{ - "additionalProperties":true, - "properties":{ - "customerid":{ - "description":"", - "type":"string" + "validator": { + "type": "json_schema", + "definition": { + "additionalProperties": true, + "properties": { + "customerid": { + "description": "", + "type": "string" }, - "amp_id":{ - "description":"", - "type":"string" + "amp_id": { + "description": "", + "type": "string" }, - "email":{ - "description":"", - "type":"string" + "email": { + "description": "", + "type": "string" } }, - "required":[ + "required": [ "email" ], - "type":"object" + "type": "object" } } }, { - "description":"", - "match":{ - "type":"custom_event", - "criteria":{ - "event_name":"SocialEvent", - "custom_event_type":"social" + "description": "", + "match": { + "type": "custom_event", + "criteria": { + "event_name": "SocialEvent", + "custom_event_type": "social" } }, - "validator":{ - "type":"json_schema", - "definition":{ - "properties":{ - "data":{ - "additionalProperties":true, - "properties":{ - "custom_attributes":{ - "additionalProperties":false, - "description":"", - "type":"object" + "validator": { + "type": "json_schema", + "definition": { + "properties": { + "data": { + "additionalProperties": true, + "properties": { + "custom_attributes": { + "additionalProperties": false, + "description": "", + "type": "object" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" } } } } }, { - "description":"this commerce event has product attributes and not allowing additional product attributes for event custom attributes and product custom attributes", - "match":{ - "type":"product_action", - "criteria":{ - "action":"purchase" + "description": "this commerce event has product attributes and not allowing additional product attributes for event custom attributes and product custom attributes", + "match": { + "type": "product_action", + "criteria": { + "action": "purchase" } }, - "validator":{ - "type":"json_schema", - "definition":{ - "properties":{ - "data":{ - "additionalProperties":true, - "properties":{ - "product_action":{ - "additionalProperties":false, - "description":"", - "properties":{ - "products":{ - "description":"", - "items":{ - "additionalProperties":false, - "description":"", - "properties":{ - "custom_attributes":{ - "additionalProperties":false, - "description":"", - "properties":{ - "plannedAttr1":{ - "description":"", - "type":"string" + "validator": { + "type": "json_schema", + "definition": { + "properties": { + "data": { + "additionalProperties": true, + "properties": { + "product_action": { + "additionalProperties": false, + "description": "", + "properties": { + "products": { + "description": "", + "items": { + "additionalProperties": false, + "description": "", + "properties": { + "custom_attributes": { + "additionalProperties": false, + "description": "", + "properties": { + "plannedAttr1": { + "description": "", + "type": "string" }, - "plannedAttr2":{ - "description":"", - "type":"string" + "plannedAttr2": { + "description": "", + "type": "string" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" }, - "position":{ - "description":"", - "type":"number" + "position": { + "description": "", + "type": "number" }, - "name":{ - "description":"", - "type":"string" + "name": { + "description": "", + "type": "string" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" }, - "type":"array" + "type": "array" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" }, - "custom_attributes":{ - "additionalProperties":false, - "description":"", - "properties":{ - "eventAttribute2":{ - "description":"", - "type":"string" + "custom_attributes": { + "additionalProperties": false, + "description": "", + "properties": { + "eventAttribute2": { + "description": "", + "type": "string" }, - "eventAttribute1":{ - "description":"", - "type":"string" + "eventAttribute1": { + "description": "", + "type": "string" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" } } } } }, { - "description":"", - "match":{ - "type":"promotion_action", - "criteria":{ - "action":"click" + "description": "", + "match": { + "type": "promotion_action", + "criteria": { + "action": "click" } }, - "validator":{ - "type":"json_schema", - "definition":{ - "properties":{ - "data":{ - "additionalProperties":true, - "properties":{ - "product_action":{ - "additionalProperties":true, - "description":"", - "properties":{ - "products":{ - "description":"", - "items":{ - "additionalProperties":false, - "description":"", - "type":"object" + "validator": { + "type": "json_schema", + "definition": { + "properties": { + "data": { + "additionalProperties": true, + "properties": { + "product_action": { + "additionalProperties": true, + "description": "", + "properties": { + "products": { + "description": "", + "items": { + "additionalProperties": false, + "description": "", + "type": "object" }, - "type":"array" + "type": "array" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" }, - "custom_attributes":{ - "additionalProperties":false, - "description":"", - "properties":{ - "eventAttribute2":{ - "description":"", - "type":"string" + "custom_attributes": { + "additionalProperties": false, + "description": "", + "properties": { + "eventAttribute2": { + "description": "", + "type": "string" }, - "eventAttribute1":{ - "description":"", - "type":"string" + "eventAttribute1": { + "description": "", + "type": "string" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" } }, - "required":[ - + "required": [ ], - "type":"object" + "type": "object" } } } diff --git a/kit-plugin/src/main/groovy/com/mparticle/kits/KitPlugin.groovy b/kit-plugin/src/main/groovy/com/mparticle/kits/KitPlugin.groovy index c0139075a..79a345a98 100644 --- a/kit-plugin/src/main/groovy/com/mparticle/kits/KitPlugin.groovy +++ b/kit-plugin/src/main/groovy/com/mparticle/kits/KitPlugin.groovy @@ -147,8 +147,8 @@ class KitPlugin implements Plugin { } //Publishing task aliases for simpler local development - target.task("publishLocal") { dependsOn "publishDebugPublicationToMavenLocal"} - target.task("publishReleaseLocal") { dependsOn "publishReleasePublicationToMavenLocal"} + target.task("publishLocal") { dependsOn "publishDebugPublicationToMavenLocal" } + target.task("publishReleaseLocal") { dependsOn "publishReleasePublicationToMavenLocal" } } } diff --git a/testutils/src/androidTest/AndroidManifest.xml b/testutils/src/androidTest/AndroidManifest.xml index 60c7575c4..1eee63b2b 100644 --- a/testutils/src/androidTest/AndroidManifest.xml +++ b/testutils/src/androidTest/AndroidManifest.xml @@ -1,7 +1,7 @@ - - - - + + + + + diff --git a/testutils/src/androidTest/java/com/mparticle/LegacyStartupTest.java b/testutils/src/androidTest/java/com/mparticle/LegacyStartupTest.java index 78edb110b..bade6901d 100644 --- a/testutils/src/androidTest/java/com/mparticle/LegacyStartupTest.java +++ b/testutils/src/androidTest/java/com/mparticle/LegacyStartupTest.java @@ -1,6 +1,9 @@ package com.mparticle; import android.Manifest; +import android.content.Context; + +import androidx.test.rule.GrantPermissionRule; import com.mparticle.internal.Logger; @@ -9,10 +12,6 @@ import org.junit.Before; import org.junit.Rule; -import android.content.Context; -import androidx.test.rule.GrantPermissionRule; - - import java.lang.reflect.Method; @LegacyOnly @@ -41,8 +40,8 @@ public void before() throws InterruptedException { public void after() { try { Logger.debug("Startup times = " + readFile()); + } catch (Exception ex) { } - catch (Exception ex) {} } @Override @@ -52,6 +51,6 @@ protected String fileName() { @Override protected void startup() throws Exception { - mParticleStart.invoke(null,mContext, "key", "secret"); + mParticleStart.invoke(null, mContext, "key", "secret"); } } diff --git a/testutils/src/main/AndroidManifest.xml b/testutils/src/main/AndroidManifest.xml index 8db18d189..f361d453d 100644 --- a/testutils/src/main/AndroidManifest.xml +++ b/testutils/src/main/AndroidManifest.xml @@ -1,5 +1,8 @@ - - + + + diff --git a/testutils/src/main/java/com/mparticle/AccessUtils.java b/testutils/src/main/java/com/mparticle/AccessUtils.java index 75f775240..1ef17d501 100644 --- a/testutils/src/main/java/com/mparticle/AccessUtils.java +++ b/testutils/src/main/java/com/mparticle/AccessUtils.java @@ -25,6 +25,7 @@ public static void reset(Context context, boolean deleteDatabase) { * This method returns an ordered list of the pending Messages in the UploadHandler queue. This * gives us the ability to test the UploadHandler's true "state" when looking closely at how * our Upload loop is performing + * * @return */ @RequiresApi(api = Build.VERSION_CODES.M) diff --git a/testutils/src/main/java/com/mparticle/BaseStartupTest.java b/testutils/src/main/java/com/mparticle/BaseStartupTest.java index 34917abe3..500b20795 100644 --- a/testutils/src/main/java/com/mparticle/BaseStartupTest.java +++ b/testutils/src/main/java/com/mparticle/BaseStartupTest.java @@ -1,10 +1,15 @@ package com.mparticle; +import static org.junit.Assert.fail; + import android.Manifest; import android.content.Context; import android.os.Environment; import android.os.Looper; +import androidx.test.platform.app.InstrumentationRegistry; +import androidx.test.rule.GrantPermissionRule; + import com.mparticle.internal.Logger; import com.mparticle.internal.MPUtility; @@ -25,11 +30,6 @@ import java.util.ArrayList; import java.util.List; -import androidx.test.platform.app.InstrumentationRegistry; -import androidx.test.rule.GrantPermissionRule; - -import static org.junit.Assert.fail; - @OrchestratorOnly @FixMethodOrder(MethodSorters.NAME_ASCENDING) public abstract class BaseStartupTest { @@ -130,27 +130,29 @@ public static void testStartupTimeAcceptable() throws Exception { List legacyResults = new ArrayList<>(); List currentResults = new ArrayList<>(); - for (String resultString: legacyFile.split(":")) { + for (String resultString : legacyFile.split(":")) { try { legacyResults.add(Long.parseLong(resultString)); - } catch (NumberFormatException ex) { } + } catch (NumberFormatException ex) { + } } - for (String resultString: currentFile.split(":")) { + for (String resultString : currentFile.split(":")) { try { currentResults.add(Long.parseLong(resultString)); - } catch (NumberFormatException ex) { } + } catch (NumberFormatException ex) { + } } Assume.assumeTrue(legacyResults.size() == currentResults.size()); Assume.assumeTrue(legacyResults.size() == 10); Long legacySum = 0L; - for (Long result: currentResults) { + for (Long result : currentResults) { legacySum += result; } Long currentSum = 0L; - for (Long result: currentResults) { + for (Long result : currentResults) { currentSum += result; } @@ -182,8 +184,7 @@ private static String readFile(String fileName) throws IOException { byte[] bytes = new byte[inputStream.read()]; inputStream.read(bytes); return new String(bytes); - } - catch (FileNotFoundException ex) { + } catch (FileNotFoundException ex) { return ""; } } diff --git a/testutils/src/main/java/com/mparticle/OrchestratorOnly.java b/testutils/src/main/java/com/mparticle/OrchestratorOnly.java index 26b6c8826..e375f3c1a 100644 --- a/testutils/src/main/java/com/mparticle/OrchestratorOnly.java +++ b/testutils/src/main/java/com/mparticle/OrchestratorOnly.java @@ -7,4 +7,5 @@ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) -public @interface OrchestratorOnly { } \ No newline at end of file +public @interface OrchestratorOnly { +} \ No newline at end of file diff --git a/testutils/src/main/java/com/mparticle/identity/AccessUtils.java b/testutils/src/main/java/com/mparticle/identity/AccessUtils.java index 52e01a75f..a1e272427 100644 --- a/testutils/src/main/java/com/mparticle/identity/AccessUtils.java +++ b/testutils/src/main/java/com/mparticle/identity/AccessUtils.java @@ -1,6 +1,7 @@ package com.mparticle.identity; import android.content.Context; + import androidx.test.platform.app.InstrumentationRegistry; import com.mparticle.MParticle; @@ -20,7 +21,7 @@ public class AccessUtils { public static String IDENTIFY_PATH = MParticleIdentityClientImpl.IDENTIFY_PATH; public static String LOGIN_PATH = MParticleIdentityClientImpl.LOGIN_PATH; public static String LOGOUT_PATH = MParticleIdentityClientImpl.LOGOUT_PATH; - public static String MODIFY_PATH = MParticleIdentityClientImpl.MODIFY_PATH; + public static String MODIFY_PATH = MParticleIdentityClientImpl.MODIFY_PATH; public static MPUrl getUrl(String endpoint) { MParticleIdentityClientImpl identityClient = getIdentityApiClient(); @@ -56,7 +57,7 @@ public static MParticleIdentityClientImpl getIdentityApiClient() { } return getIdentityClient(context, configManager); } - return (MParticleIdentityClientImpl)identityClient; + return (MParticleIdentityClientImpl) identityClient; } private static MParticleIdentityClientImpl getIdentityClient(Context context, ConfigManager configManager) { @@ -76,24 +77,41 @@ public static void setUserIdentity(String value, MParticle.IdentityType identity } public static void setUserIdentities(Map userIdentities, long mpid) { - for (Map.Entry entry: userIdentities.entrySet()) { + for (Map.Entry entry : userIdentities.entrySet()) { MParticle.getInstance().Identity().mUserDelegate.setUserIdentity(entry.getValue(), entry.getKey(), mpid); } } public static class IdentityApiClient implements MParticleIdentityClient { - @Override public IdentityHttpResponse login(IdentityApiRequest request) throws Exception { return null; } + @Override + public IdentityHttpResponse login(IdentityApiRequest request) throws Exception { + return null; + } - @Override public IdentityHttpResponse logout(IdentityApiRequest request) throws Exception { return null; } + @Override + public IdentityHttpResponse logout(IdentityApiRequest request) throws Exception { + return null; + } - @Override public IdentityHttpResponse identify(IdentityApiRequest request) throws Exception { return null;} + @Override + public IdentityHttpResponse identify(IdentityApiRequest request) throws Exception { + return null; + } - @Override public IdentityHttpResponse modify(IdentityApiRequest request) throws Exception { return null;} + @Override + public IdentityHttpResponse modify(IdentityApiRequest request) throws Exception { + return null; + } - @Override public BaseNetworkConnection getRequestHandler() { return null; } + @Override + public BaseNetworkConnection getRequestHandler() { + return null; + } - @Override public void setRequestHandler(BaseNetworkConnection handler) {} + @Override + public void setRequestHandler(BaseNetworkConnection handler) { + } } public static void clearUserIdentities(MParticleUserImpl user) { diff --git a/testutils/src/main/java/com/mparticle/internal/AccessUtils.java b/testutils/src/main/java/com/mparticle/internal/AccessUtils.java index 727df127b..178378f2c 100644 --- a/testutils/src/main/java/com/mparticle/internal/AccessUtils.java +++ b/testutils/src/main/java/com/mparticle/internal/AccessUtils.java @@ -2,6 +2,7 @@ import android.content.Context; import android.os.Handler; + import androidx.annotation.NonNull; import androidx.test.platform.app.InstrumentationRegistry; @@ -84,6 +85,7 @@ public static void awaitMessageHandler() throws InterruptedException { * * the fact that these messages are tied into an MPID is an artifact from a defunct implementation * of the UploadHandler, but it is really useful for this use case. + * * @throws InterruptedException */ public static void awaitUploadHandler() throws InterruptedException { @@ -150,7 +152,7 @@ public static KitManagerImpl getKitManager() { public static void setKitManager(final KitManager kitManager) throws InterruptedException { final KitFrameworkWrapper kitFrameworkWrapper = MParticle.getInstance().Internal().getKitManager(); kitFrameworkWrapper.loadKitLibrary(); - MParticle.getInstance().Identity().removeIdentityStateListener((IdentityStateListener)kitFrameworkWrapper.mKitManager); + MParticle.getInstance().Identity().removeIdentityStateListener((IdentityStateListener) kitFrameworkWrapper.mKitManager); final CountDownLatch kitManagerLoadedLatch = new MPLatch(1); //Need to do this since the KitManager instance in KitFrameworkWrapper is not threadsafe. If //it is in mid-loadKitLibrary, then the instance you set could be overwritten. diff --git a/testutils/src/main/java/com/mparticle/mock/MockApplication.java b/testutils/src/main/java/com/mparticle/mock/MockApplication.java index fba363e20..87e66184f 100644 --- a/testutils/src/main/java/com/mparticle/mock/MockApplication.java +++ b/testutils/src/main/java/com/mparticle/mock/MockApplication.java @@ -31,7 +31,7 @@ public Context getApplicationContext() { return this; } - public void setSharedPreferences(SharedPreferences prefs){ + public void setSharedPreferences(SharedPreferences prefs) { mContext.setSharedPreferences(prefs); } @@ -47,7 +47,7 @@ public SharedPreferences getSharedPreferences(String name, int mode) { @Override public PackageManager getPackageManager() { - return mContext.getPackageManager(); + return mContext.getPackageManager(); } @Override diff --git a/testutils/src/main/java/com/mparticle/mock/MockConfigManager.java b/testutils/src/main/java/com/mparticle/mock/MockConfigManager.java index 4cc2975b0..de8748e0f 100644 --- a/testutils/src/main/java/com/mparticle/mock/MockConfigManager.java +++ b/testutils/src/main/java/com/mparticle/mock/MockConfigManager.java @@ -6,6 +6,6 @@ public class MockConfigManager extends ConfigManager { public MockConfigManager() { - super(new MockContext(), MParticle.Environment.Production, null, null, null, null, null, null,null, null); + super(new MockContext(), MParticle.Environment.Production, null, null, null, null, null, null, null, null); } } diff --git a/testutils/src/main/java/com/mparticle/mock/MockContext.java b/testutils/src/main/java/com/mparticle/mock/MockContext.java index cfd4ec47f..796508fe2 100644 --- a/testutils/src/main/java/com/mparticle/mock/MockContext.java +++ b/testutils/src/main/java/com/mparticle/mock/MockContext.java @@ -1,5 +1,7 @@ package com.mparticle.mock; +import static junit.framework.Assert.fail; + import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; @@ -24,11 +26,12 @@ import android.os.Handler; import android.os.Looper; import android.os.UserHandle; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; import android.telephony.TelephonyManager; import android.view.Display; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + import org.mockito.Mockito; import java.io.File; @@ -38,8 +41,6 @@ import java.io.IOException; import java.io.InputStream; -import static junit.framework.Assert.fail; - public class MockContext extends Context { @@ -47,13 +48,13 @@ public class MockContext extends Context { Resources resources = new MockResources(); MockApplication application = null; - public void setSharedPreferences(SharedPreferences prefs){ + public void setSharedPreferences(SharedPreferences prefs) { sharedPreferences = prefs; } @Override public Context getApplicationContext() { - if (application == null){ + if (application == null) { application = new MockApplication(this); } return application; @@ -78,7 +79,7 @@ public Resources getResources() { @Override public Object getSystemService(String name) { - if (name.equals(Context.TELEPHONY_SERVICE)){ + if (name.equals(Context.TELEPHONY_SERVICE)) { return Mockito.mock(TelephonyManager.class); } return null; @@ -98,7 +99,7 @@ public PackageManager getPackageManager() { Mockito.when(manager.getApplicationInfo(Mockito.anyString(), Mockito.anyInt())).thenReturn(appInfo); Mockito.when(manager.getApplicationLabel(appInfo)).thenReturn("test label"); - }catch (Exception e){ + } catch (Exception e) { fail(e.toString()); } return manager; diff --git a/testutils/src/main/java/com/mparticle/mock/MockKit.java b/testutils/src/main/java/com/mparticle/mock/MockKit.java index db59f4185..ced4178ac 100644 --- a/testutils/src/main/java/com/mparticle/mock/MockKit.java +++ b/testutils/src/main/java/com/mparticle/mock/MockKit.java @@ -16,7 +16,9 @@ public String getName() { } @Override - protected List onKitCreate(Map settings, Context context) {return null;} + protected List onKitCreate(Map settings, Context context) { + return null; + } @Override public List setOptOut(boolean optedOut) { diff --git a/testutils/src/main/java/com/mparticle/mock/MockKitConfiguration.java b/testutils/src/main/java/com/mparticle/mock/MockKitConfiguration.java index deeaf0764..6e9beaf0b 100644 --- a/testutils/src/main/java/com/mparticle/mock/MockKitConfiguration.java +++ b/testutils/src/main/java/com/mparticle/mock/MockKitConfiguration.java @@ -31,11 +31,11 @@ public KitConfiguration parseConfiguration(JSONObject json) throws JSONException return super.parseConfiguration(json); } - public static KitConfiguration createKitConfiguration(JSONObject json) throws JSONException{ + public static KitConfiguration createKitConfiguration(JSONObject json) throws JSONException { return new MockKitConfiguration().parseConfiguration(json); } - public static KitConfiguration createKitConfiguration() throws JSONException{ + public static KitConfiguration createKitConfiguration() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("id", 42); return new MockKitConfiguration().parseConfiguration(jsonObject); @@ -44,16 +44,17 @@ public static KitConfiguration createKitConfiguration() throws JSONException{ @Override protected SparseBooleanArray convertToSparseArray(JSONObject json) { SparseBooleanArray map = new MockSparseBooleanArray(); - for (Iterator iterator = json.keys(); iterator.hasNext();) { + for (Iterator iterator = json.keys(); iterator.hasNext(); ) { try { String key = iterator.next(); map.put(Integer.parseInt(key), json.getInt(key) == 1); - }catch (JSONException jse){ + } catch (JSONException jse) { Logger.error("Issue while parsing kit configuration: " + jse.getMessage()); } } return map; } + class MockSparseBooleanArray extends SparseBooleanArray { @Override public boolean get(int key) { @@ -65,12 +66,13 @@ public boolean get(int key, boolean valueIfKeyNotFound) { System.out.print("SparseArray getting: " + key); if (map.containsKey(key)) { return map.get(key); - }else{ + } else { return valueIfKeyNotFound; } } Map map = new HashMap(); + @Override public void put(int key, boolean value) { map.put(key, value); diff --git a/testutils/src/main/java/com/mparticle/mock/MockKitManagerImpl.java b/testutils/src/main/java/com/mparticle/mock/MockKitManagerImpl.java index 1e25a5ef1..ec86e2155 100644 --- a/testutils/src/main/java/com/mparticle/mock/MockKitManagerImpl.java +++ b/testutils/src/main/java/com/mparticle/mock/MockKitManagerImpl.java @@ -2,7 +2,6 @@ import android.content.Context; -import com.mparticle.MParticle; import com.mparticle.MParticleOptions; import com.mparticle.internal.CoreCallbacks; import com.mparticle.internal.ReportingManager; @@ -24,7 +23,7 @@ public MockKitManagerImpl(Context context, ReportingManager reportingManager, Co super(context, reportingManager, coreCallbacks, Mockito.mock(MParticleOptions.class)); } - public MockKitManagerImpl( MParticleOptions options) { + public MockKitManagerImpl(MParticleOptions options) { super(new MockContext(), Mockito.mock(ReportingManager.class), Mockito.mock(CoreCallbacks.class), options); Mockito.when(mCoreCallbacks.getKitListener()).thenReturn(CoreCallbacks.KitListener.EMPTY); } diff --git a/testutils/src/main/java/com/mparticle/mock/MockMParticle.java b/testutils/src/main/java/com/mparticle/mock/MockMParticle.java index f240ec83f..31c88db10 100644 --- a/testutils/src/main/java/com/mparticle/mock/MockMParticle.java +++ b/testutils/src/main/java/com/mparticle/mock/MockMParticle.java @@ -2,7 +2,6 @@ import com.mparticle.MParticle; import com.mparticle.identity.IdentityApi; -import com.mparticle.internal.AppStateManager; import com.mparticle.internal.ConfigManager; import com.mparticle.internal.KitFrameworkWrapper; import com.mparticle.internal.MessageManager; diff --git a/testutils/src/main/java/com/mparticle/mock/MockResources.java b/testutils/src/main/java/com/mparticle/mock/MockResources.java index d8edcb4b1..ea293ccd1 100644 --- a/testutils/src/main/java/com/mparticle/mock/MockResources.java +++ b/testutils/src/main/java/com/mparticle/mock/MockResources.java @@ -16,9 +16,9 @@ public MockResources() { @Override public int getIdentifier(String name, String defType, String defPackage) { - if (name.equals("mp_key")){ + if (name.equals("mp_key")) { return 1; - }else if (name.equals("mp_secret")){ + } else if (name.equals("mp_secret")) { return 2; } @@ -27,7 +27,7 @@ public int getIdentifier(String name, String defType, String defPackage) { @Override public String getString(int id) throws NotFoundException { - switch (id){ + switch (id) { case 1: return TEST_APP_KEY; case 2: diff --git a/testutils/src/main/java/com/mparticle/mock/MockSharedPreferences.java b/testutils/src/main/java/com/mparticle/mock/MockSharedPreferences.java index abda35907..9f3430c71 100644 --- a/testutils/src/main/java/com/mparticle/mock/MockSharedPreferences.java +++ b/testutils/src/main/java/com/mparticle/mock/MockSharedPreferences.java @@ -29,35 +29,35 @@ public boolean contains(String key) { public boolean getBoolean(String key, boolean defValue) { if (mValues.containsKey(key)) { - return ((Boolean)mValues.get(key)).booleanValue(); + return ((Boolean) mValues.get(key)).booleanValue(); } return defValue; } public float getFloat(String key, float defValue) { if (mValues.containsKey(key)) { - return ((Float)mValues.get(key)).floatValue(); + return ((Float) mValues.get(key)).floatValue(); } return defValue; } public int getInt(String key, int defValue) { if (mValues.containsKey(key)) { - return ((Integer)mValues.get(key)).intValue(); + return ((Integer) mValues.get(key)).intValue(); } return defValue; } public long getLong(String key, long defValue) { if (mValues.containsKey(key)) { - return ((Long)mValues.get(key)).longValue(); + return ((Long) mValues.get(key)).longValue(); } return defValue; } public String getString(String key, String defValue) { if (mValues.containsKey(key)) - return (String)mValues.get(key); + return (String) mValues.get(key); return defValue; } @@ -121,7 +121,7 @@ public Editor clear() { @SuppressWarnings("unchecked") public boolean commit() { - mValues = (HashMap)mTempValues.clone(); + mValues = (HashMap) mTempValues.clone(); return true; } diff --git a/testutils/src/main/java/com/mparticle/mock/utils/RandomUtils.java b/testutils/src/main/java/com/mparticle/mock/utils/RandomUtils.java index 3a998eebf..6e3e2b439 100644 --- a/testutils/src/main/java/com/mparticle/mock/utils/RandomUtils.java +++ b/testutils/src/main/java/com/mparticle/mock/utils/RandomUtils.java @@ -1,5 +1,7 @@ package com.mparticle.mock.utils; +import static org.junit.Assert.assertTrue; + import com.mparticle.MParticle; import org.junit.Test; @@ -12,8 +14,6 @@ import java.util.Set; import java.util.TreeSet; -import static org.junit.Assert.assertTrue; - /** * Utilities for generating tests with Randomness. */ @@ -25,7 +25,7 @@ public class RandomUtils { private static RandomUtils instance; public static RandomUtils getInstance() { - if (instance == null) { + if (instance == null) { instance = new RandomUtils(); } return instance; @@ -37,7 +37,7 @@ public Map getRandomUserIdentities() { int identityTypeLength = MParticle.IdentityType.values().length; int numIdentities = randomInt(1, identityTypeLength); Set identityIndices = randomIntSet(0, identityTypeLength, numIdentities); - for (Integer identityIndex: identityIndices) { + for (Integer identityIndex : identityIndices) { randomIdentities.put(MParticle.IdentityType.values()[identityIndex], getAlphaNumericString(randomInt(1, 55))); } randomIdentities.remove(MParticle.IdentityType.Alias); @@ -46,7 +46,7 @@ public Map getRandomUserIdentities() { public Map> getRandomCustomFlags(int count) { Map> customFlags = new HashMap<>(); - for (Map.Entry entry: getRandomAttributes(count).entrySet()) { + for (Map.Entry entry : getRandomAttributes(count).entrySet()) { List flags = new ArrayList<>(); if (entry.getValue() != null) { flags.add(entry.getValue()); @@ -89,7 +89,7 @@ public String getAlphaNumericString(int lengthLowerBound, int lengthUpperBound) public String getAlphaNumericString(int length) { String characters = getAlphNumeric(); StringBuilder builder = new StringBuilder(); - for (int i = 0; i < length; i++){ + for (int i = 0; i < length; i++) { builder.append(characters.charAt(randomInt(0, characters.length() - 1))); } return builder.toString(); diff --git a/testutils/src/main/java/com/mparticle/networking/Matcher.java b/testutils/src/main/java/com/mparticle/networking/Matcher.java index b9c5f4845..f8b683b7f 100644 --- a/testutils/src/main/java/com/mparticle/networking/Matcher.java +++ b/testutils/src/main/java/com/mparticle/networking/Matcher.java @@ -1,11 +1,11 @@ package com.mparticle.networking; -import org.json.JSONException; import org.json.JSONObject; public class Matcher { - public Matcher() {} + public Matcher() { + } public Matcher(MPUrl url) { this.url = url.getFile(); @@ -53,7 +53,7 @@ public Matcher urlMatcher(MockServer.UrlMatcher urlMatcher) { @Override public boolean equals(Object obj) { if (obj instanceof Matcher) { - Matcher matcher = (Matcher)obj; + Matcher matcher = (Matcher) obj; if (matcher.bodyMatch == bodyMatch && matcher.url == url && diff --git a/testutils/src/main/java/com/mparticle/networking/MockServer.java b/testutils/src/main/java/com/mparticle/networking/MockServer.java index f9d2957d9..d83435e28 100644 --- a/testutils/src/main/java/com/mparticle/networking/MockServer.java +++ b/testutils/src/main/java/com/mparticle/networking/MockServer.java @@ -1,5 +1,11 @@ package com.mparticle.networking; +import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.ALIAS; +import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.AUDIENCE; +import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.CONFIG; +import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.EVENTS; +import static org.junit.Assert.fail; + import android.content.Context; import com.mparticle.MParticle; @@ -24,12 +30,6 @@ import java.util.Random; import java.util.concurrent.CountDownLatch; -import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.ALIAS; -import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.AUDIENCE; -import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.CONFIG; -import static com.mparticle.networking.MParticleBaseClientImpl.Endpoint.EVENTS; -import static org.junit.Assert.fail; - public class MockServer { private static MockServer instance; @@ -61,7 +61,8 @@ public static MockServer getInstance() { return instance; } - private MockServer() {} + private MockServer() { + } private MockServer(Context context) { this.context = context; @@ -105,52 +106,52 @@ public ReceivedRequests Requests() { void onRequestMade(MPConnectionTestImpl mockConnection) { try { Thread.sleep(50); - requests.add(mockConnection); - - List> logicList = new ArrayList<>(serverLogic.entrySet()); - //try to get a match FILO style - reverseAndUpdateKey(logicList); - long delay = 0; - boolean found = false; - for (Map.Entry entry: logicList) { - if (entry.getKey().isMatch(mockConnection)) { - if (entry.getValue() instanceof Response) { - Response response = (Response) entry.getValue(); - response.setRequest(mockConnection); - mockConnection.response = response.responseBody; - mockConnection.responseCode = response.responseCode; - if (!entry.getKey().keepAfterMatch) { - serverLogic.remove(entry.getKey()); + requests.add(mockConnection); + + List> logicList = new ArrayList<>(serverLogic.entrySet()); + //try to get a match FILO style + reverseAndUpdateKey(logicList); + long delay = 0; + boolean found = false; + for (Map.Entry entry : logicList) { + if (entry.getKey().isMatch(mockConnection)) { + if (entry.getValue() instanceof Response) { + Response response = (Response) entry.getValue(); + response.setRequest(mockConnection); + mockConnection.response = response.responseBody; + mockConnection.responseCode = response.responseCode; + if (!entry.getKey().keepAfterMatch) { + serverLogic.remove(entry.getKey()); + } + delay = response.delay; + found = true; + break; } - delay = response.delay; - found = true; - break; - } - if (entry.getValue() instanceof CallbackResponse) { - CallbackResponse callbackResponse = (CallbackResponse) entry.getValue(); - callbackResponse.invokeCallback(mockConnection); - if (!entry.getKey().keepAfterMatch) { - serverLogic.remove(entry.getKey()); + if (entry.getValue() instanceof CallbackResponse) { + CallbackResponse callbackResponse = (CallbackResponse) entry.getValue(); + callbackResponse.invokeCallback(mockConnection); + if (!entry.getKey().keepAfterMatch) { + serverLogic.remove(entry.getKey()); + } } } } - } - if (!found) { - Logger.error("response not found for request: " + mockConnection.url.toString()); - } + if (!found) { + Logger.error("response not found for request: " + mockConnection.url.toString()); + } - for (Map.Entry entry: new HashSet<>(blockers.entrySet())) { - if (entry.getKey().isMatch(mockConnection)) { - blockers.remove(entry.getKey()).countDown(); + for (Map.Entry entry : new HashSet<>(blockers.entrySet())) { + if (entry.getKey().isMatch(mockConnection)) { + blockers.remove(entry.getKey()).countDown(); + } } - } - if (delay > 0) { - try { - Thread.sleep(delay); - } catch (InterruptedException e) { - e.printStackTrace(); + if (delay > 0) { + try { + Thread.sleep(delay); + } catch (InterruptedException e) { + e.printStackTrace(); + } } - } } catch (InterruptedException e) { fail(e.getMessage()); Thread.currentThread().interrupt(); @@ -163,7 +164,7 @@ interface OnRequestCallback { void onRequest(Response response, MPConnectionTestImpl connection); } - + public MockServer setUpHappyConfig() { Matcher match = new Matcher().urlMatcher(new UrlMatcher() { @Override @@ -179,12 +180,12 @@ public boolean isMatch(MPUrl url) { return this; } - + public MockServer setupConfigResponse(String responseString) { return setupConfigResponse(responseString, 0); } - + public MockServer setupConfigResponse(String responseString, int delay) { Matcher match = new Matcher(getUrl(CONFIG)); match.keepAfterMatch = true; @@ -205,7 +206,7 @@ public MockServer setupConfigDeferred() { serverLogic.put(match, response); return this; } - + public MockServer setupHappyEvents() { Matcher match = new Matcher(getUrl(EVENTS)); match.keepAfterMatch = true; @@ -216,7 +217,7 @@ public MockServer setupHappyEvents() { return this; } - + private MockServer setupHappyIdentify() { Matcher match = new Matcher(getUrl(IDENTIFY)); match.keepAfterMatch = true; @@ -226,12 +227,12 @@ private MockServer setupHappyIdentify() { return this; } - + public MockServer setupHappyIdentify(long mpid) { return setupHappyIdentify(mpid, 0); } - + public MockServer setupHappyIdentify(long mpid, int delay) { Matcher match = new Matcher(getUrl(IDENTIFY)); Response response = new Response(getIdentityResponse(mpid, ran.nextBoolean())); @@ -249,7 +250,7 @@ private MockServer setupHappyLogin() { return this; } - + public MockServer setupHappyLogin(long mpid) { Matcher match = new Matcher(getUrl(LOGIN)); Response response = new Response(getIdentityResponse(mpid, ran.nextBoolean())); @@ -266,7 +267,7 @@ private MockServer setupHappyLogout() { return this; } - + public MockServer setupHappyLogout(long mpid) { Matcher match = new Matcher(getUrl(LOGOUT)); Response response = new Response(getIdentityResponse(mpid, ran.nextBoolean())); @@ -274,7 +275,7 @@ public MockServer setupHappyLogout(long mpid) { return this; } - + public MockServer setupHappyModify() { return setupHappyModify(0); } @@ -323,7 +324,7 @@ public MockServer setEventsResponseLogic(int responseCode) { serverLogic.put(matcher, response); return this; } - + public MockServer addConditionalIdentityResponse(long ifMpid, long thenMpid) { return addConditionalIdentityResponse(ifMpid, thenMpid, ran.nextBoolean(), 0); } @@ -331,7 +332,7 @@ public MockServer addConditionalIdentityResponse(long ifMpid, long thenMpid) { public MockServer addConditionalIdentityResponse(long ifMpid, long thenMpid, boolean isLoggedIn) { return addConditionalIdentityResponse(ifMpid, thenMpid, isLoggedIn, 0); } - + public MockServer addConditionalIdentityResponse(long ifMpid, long thenMpid, boolean isLoggedIn, int delay) { Matcher match = new Matcher(getUrl(IDENTIFY)); match.bodyMatch = getIdentityMpidMatch(ifMpid); @@ -344,12 +345,12 @@ public MockServer addConditionalIdentityResponse(long ifMpid, long thenMpid, boo public MockServer addConditionalLoginResponse(long ifMpid, long thenMpid) { return addConditionalLoginResponse(ifMpid, thenMpid, ran.nextBoolean(), 0); } - + public MockServer addConditionalLoginResponse(long ifMpid, long thenMpid, boolean isLoggedIn) { return addConditionalLoginResponse(ifMpid, thenMpid, isLoggedIn, 0); } - + public MockServer addConditionalLoginResponse(long ifMpid, long thenMpid, boolean isLoggedIn, int delay) { Matcher match = new Matcher(getUrl(LOGIN)); match.bodyMatch = getIdentityMpidMatch(ifMpid); @@ -359,15 +360,15 @@ public MockServer addConditionalLoginResponse(long ifMpid, long thenMpid, boolea return this; } - + public MockServer addConditionalLogoutResponse(long ifMpid, long thenMpid) { - return addConditionalLogoutResponse(ifMpid, thenMpid, ran.nextBoolean(),0); + return addConditionalLogoutResponse(ifMpid, thenMpid, ran.nextBoolean(), 0); } public MockServer addConditionalLogoutResponse(long ifMpid, long thenMpid, boolean isLoggedIn) { return addConditionalLogoutResponse(ifMpid, thenMpid, isLoggedIn, 0); } - + public MockServer addConditionalLogoutResponse(long ifMpid, long thenMpid, boolean isLoggedIn, int delay) { Matcher match = new Matcher(getUrl(LOGOUT)); match.bodyMatch = getIdentityMpidMatch(ifMpid); @@ -444,14 +445,13 @@ private MParticleBaseClientImpl getClient() { private OnRequestCallback getHappyIdentityRequestCallback() { return new OnRequestCallback() { - + public void onRequest(Response response, MPConnectionTestImpl connection) { try { IdentityRequest.IdentityRequestBody request = new IdentityRequest(connection).getBody(); response.responseCode = 200; response.responseBody = getIdentityResponse(request.previousMpid != null && request.previousMpid != 0 ? request.previousMpid : ran.nextLong(), ran.nextBoolean()); - } - catch (Exception ex) { + } catch (Exception ex) { throw new RuntimeException(ex); } } @@ -511,8 +511,7 @@ public int compare(Map.Entry o1, Map.Entry o2) } } } - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } @@ -561,7 +560,7 @@ public List getLogout() { public List getModify() { List matchingRequests = new ArrayList<>(); - for (MPConnectionTestImpl request: requests) { + for (MPConnectionTestImpl request : requests) { String url = request.getURL().getFile(); if (url.endsWith(MODIFY)) { matchingRequests.add(new IdentityRequest(request)); @@ -592,7 +591,7 @@ private List get(MParticleBaseClientImpl.Endpoint endpoint) { private List get(MParticleBaseClientImpl.Endpoint endpoint, MPUrl url) { List matchingRequests = new ArrayList<>(); - for (MPConnectionTestImpl request: requests) { + for (MPConnectionTestImpl request : requests) { if (request.getURL().getFile().equals(url.getFile())) { switch (endpoint) { case IDENTITY: @@ -616,7 +615,8 @@ public interface JSONMatch { public class Endpoints { - private Endpoints() {} + private Endpoints() { + } public MPUrl getIdentifyUrl() { return getUrl(IDENTIFY); diff --git a/testutils/src/main/java/com/mparticle/networking/Response.java b/testutils/src/main/java/com/mparticle/networking/Response.java index 46c367489..044bd98dc 100644 --- a/testutils/src/main/java/com/mparticle/networking/Response.java +++ b/testutils/src/main/java/com/mparticle/networking/Response.java @@ -6,7 +6,8 @@ class Response { String responseBody = ""; long delay; - Response() { } + Response() { + } Response(String responseBody) { this(200, responseBody); diff --git a/testutils/src/main/java/com/mparticle/testutils/AndroidUtils.java b/testutils/src/main/java/com/mparticle/testutils/AndroidUtils.java index 925cbbdbb..1bff4fc57 100644 --- a/testutils/src/main/java/com/mparticle/testutils/AndroidUtils.java +++ b/testutils/src/main/java/com/mparticle/testutils/AndroidUtils.java @@ -37,6 +37,7 @@ public ApplicationInfo getApplicationInfo() { public static class Mutable { public T value; + public Mutable(T value) { this.value = value; } diff --git a/testutils/src/main/java/com/mparticle/testutils/AssertTrue.java b/testutils/src/main/java/com/mparticle/testutils/AssertTrue.java index 2e0d6c36a..fd55332db 100644 --- a/testutils/src/main/java/com/mparticle/testutils/AssertTrue.java +++ b/testutils/src/main/java/com/mparticle/testutils/AssertTrue.java @@ -2,5 +2,6 @@ public abstract class AssertTrue implements StreamAssert.Assert { @Override - public void assertObject(T object) {} + public void assertObject(T object) { + } } diff --git a/testutils/src/main/java/com/mparticle/testutils/BaseAbstractTest.java b/testutils/src/main/java/com/mparticle/testutils/BaseAbstractTest.java index 718588be6..83d74b53c 100644 --- a/testutils/src/main/java/com/mparticle/testutils/BaseAbstractTest.java +++ b/testutils/src/main/java/com/mparticle/testutils/BaseAbstractTest.java @@ -15,10 +15,6 @@ import com.mparticle.MParticle; import com.mparticle.MParticleOptions; import com.mparticle.identity.BaseIdentityTask; -import com.mparticle.identity.IdentityApiResult; -import com.mparticle.identity.IdentityHttpResponse; -import com.mparticle.identity.TaskFailureListener; -import com.mparticle.identity.TaskSuccessListener; import com.mparticle.internal.AccessUtils; import com.mparticle.internal.AppStateManager; import com.mparticle.internal.ConfigManager; @@ -135,7 +131,7 @@ protected void clearStorage() { com.mparticle.AccessUtils.reset(mContext, false); MPDatabase database = new MParticleDBManager(mContext).getDatabase(); List tableNames = getAllTables(database); - for (String tableName: tableNames) { + for (String tableName : tableNames) { database.delete(tableName, "1 = 1", null); } } @@ -154,7 +150,7 @@ protected JSONObject getDatabaseContents(List tableNames) throws JSONExc protected JSONObject getDatabaseContents(MPDatabase database, List tableNames) throws JSONException { JSONObject databaseJson = new JSONObject(); - for (String tableName: tableNames) { + for (String tableName : tableNames) { JSONArray data = getData(database.query(tableName, null, null, null, null, null, null)); databaseJson.put(tableName, data); } @@ -163,10 +159,10 @@ protected JSONObject getDatabaseContents(MPDatabase database, List table protected JSONObject getDatabaseSchema(SQLiteDatabase database) throws JSONException { JSONObject databaseJson = new JSONObject(); - for (String tableName: getAllTables(new MPDatabaseImpl(database))) { + for (String tableName : getAllTables(new MPDatabaseImpl(database))) { Cursor cursor = database.query(tableName, null, null, null, null, null, null); JSONObject columnNames = new JSONObject(); - for (String columnName: cursor.getColumnNames()) { + for (String columnName : cursor.getColumnNames()) { columnNames.put(columnName, true); } databaseJson.put(tableName, columnNames); @@ -190,8 +186,7 @@ protected List getAllTables(MPDatabase database) { } cursor.moveToNext(); } - } - finally { + } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } @@ -221,8 +216,7 @@ private JSONArray getData(Cursor cursor) throws JSONException { jsonArray.put(jsonObject); cursor.moveToNext(); } - } - finally { + } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } diff --git a/testutils/src/main/java/com/mparticle/testutils/BaseCleanStartedEachTest.java b/testutils/src/main/java/com/mparticle/testutils/BaseCleanStartedEachTest.java index 71eddb2d4..610586ea7 100644 --- a/testutils/src/main/java/com/mparticle/testutils/BaseCleanStartedEachTest.java +++ b/testutils/src/main/java/com/mparticle/testutils/BaseCleanStartedEachTest.java @@ -21,7 +21,8 @@ */ public class BaseCleanStartedEachTest extends BaseAbstractTest { - public void beforeSetup() { } + public void beforeSetup() { + } @Before public final void beforeBase() throws InterruptedException { diff --git a/testutils/src/main/java/com/mparticle/testutils/CaptureLogcatOnFailingTest.java b/testutils/src/main/java/com/mparticle/testutils/CaptureLogcatOnFailingTest.java index 4316976d2..e15a9a9e5 100644 --- a/testutils/src/main/java/com/mparticle/testutils/CaptureLogcatOnFailingTest.java +++ b/testutils/src/main/java/com/mparticle/testutils/CaptureLogcatOnFailingTest.java @@ -81,8 +81,7 @@ private String getReleventLogsAfterTestStart(String testName) { } } catch (IOException e) { Logger.error(e); - } - finally { + } finally { if (reader != null) { try { reader.close(); diff --git a/testutils/src/main/java/com/mparticle/testutils/MPLatch.java b/testutils/src/main/java/com/mparticle/testutils/MPLatch.java index 699c9958f..7a89d11cd 100644 --- a/testutils/src/main/java/com/mparticle/testutils/MPLatch.java +++ b/testutils/src/main/java/com/mparticle/testutils/MPLatch.java @@ -6,8 +6,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import static junit.framework.TestCase.fail; - public class MPLatch extends CountDownLatch { int countDowned = 0; int count; diff --git a/testutils/src/main/java/com/mparticle/testutils/RandomUtils.java b/testutils/src/main/java/com/mparticle/testutils/RandomUtils.java index ca216f6e2..6714e2c61 100644 --- a/testutils/src/main/java/com/mparticle/testutils/RandomUtils.java +++ b/testutils/src/main/java/com/mparticle/testutils/RandomUtils.java @@ -26,7 +26,7 @@ public Map getRandomUserIdentities(Integer max) int identityTypeLength = MParticle.IdentityType.values().length; int numIdentities = randomInt(1, (max != null && max < identityTypeLength) ? max : identityTypeLength); Set identityIndices = randomIntSet(0, identityTypeLength, numIdentities); - for (Integer identityIndex: identityIndices) { + for (Integer identityIndex : identityIndices) { randomIdentities.put(MParticle.IdentityType.values()[identityIndex], getAlphaNumericString(randomInt(1, 55))); } randomIdentities.remove(MParticle.IdentityType.Alias); @@ -59,7 +59,7 @@ public Map getRandomAttributes(int count, boolean allowNull) { public Map getRandomUserAttributes(int count) { Map attributes = new HashMap<>(); - for (Map.Entry entry: getRandomAttributes(count).entrySet()) { + for (Map.Entry entry : getRandomAttributes(count).entrySet()) { attributes.put(entry.getKey(), entry.getValue()); } return attributes; @@ -76,7 +76,7 @@ public String getAlphaNumericString(int length) { private String getRandomString(int length, String characters) { StringBuilder builder = new StringBuilder(); - for (int i = 0; i < length; i++){ + for (int i = 0; i < length; i++) { builder.append(characters.charAt(randomInt(0, characters.length() - 1))); } return builder.toString(); diff --git a/testutils/src/main/java/com/mparticle/testutils/StreamAssert.java b/testutils/src/main/java/com/mparticle/testutils/StreamAssert.java index 71159e16d..359135b20 100644 --- a/testutils/src/main/java/com/mparticle/testutils/StreamAssert.java +++ b/testutils/src/main/java/com/mparticle/testutils/StreamAssert.java @@ -1,5 +1,7 @@ package com.mparticle.testutils; +import static junit.framework.Assert.fail; + import android.os.Handler; import android.os.Looper; @@ -10,8 +12,6 @@ import java.util.ArrayList; import java.util.List; -import static junit.framework.Assert.fail; - public class StreamAssert { private List> assertions; private List collection = new ArrayList(); diff --git a/testutils/src/main/java/com/mparticle/testutils/TestingUtils.java b/testutils/src/main/java/com/mparticle/testutils/TestingUtils.java index d8a5c0407..8b6bf6b1f 100644 --- a/testutils/src/main/java/com/mparticle/testutils/TestingUtils.java +++ b/testutils/src/main/java/com/mparticle/testutils/TestingUtils.java @@ -1,7 +1,7 @@ package com.mparticle.testutils; -import android.content.Context; -import android.database.Cursor; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import com.google.firebase.iid.FirebaseInstanceId; import com.mparticle.MPEvent; @@ -9,23 +9,16 @@ import com.mparticle.identity.AliasRequest; import com.mparticle.internal.JsonReportingMessage; import com.mparticle.internal.Logger; -import com.mparticle.internal.database.MPDatabase; -import com.mparticle.internal.database.services.MParticleDBManager; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; -import java.util.List; import java.util.Map; import java.util.Random; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - public class TestingUtils { private RandomUtils randomUtils = new RandomUtils(); Random random = new Random(); @@ -52,7 +45,7 @@ public static void setStrictMode(final MParticle.LogLevel logLevelLimit, final S public void log(MParticle.LogLevel logLevel, Throwable error, String messages) { super.log(logLevel, error, messages); if (logLevel.ordinal() <= logLevelLimit.ordinal()) { - for (String exclude: exclusions) { + for (String exclude : exclusions) { if (messages.equals(exclude)) { return; } @@ -78,7 +71,7 @@ public static boolean isFirebasePresent() { private MPEvent.Builder getRandomMPEventBuilder() { - return new MPEvent.Builder(randomUtils.getAlphaNumericString(randomUtils.randomInt(1,5)), MParticle.EventType.values()[randomUtils.randomInt(0, MParticle.EventType.values().length - 1)]); + return new MPEvent.Builder(randomUtils.getAlphaNumericString(randomUtils.randomInt(1, 5)), MParticle.EventType.values()[randomUtils.randomInt(0, MParticle.EventType.values().length - 1)]); } public MPEvent getRandomMPEventSimple() { @@ -230,14 +223,12 @@ public static void assertJsonArrayEqual(JSONArray jsonArray1, JSONArray jsonArra Object object2 = jsonArray2.opt(i); try { jsonObject1.put(object1 == null ? null : object1.toString(), object1); - } - catch (JSONException jse) { + } catch (JSONException jse) { fail(jse.getMessage()); } try { jsonObject2.put(object2 == null ? null : object2.toString(), object2); - } - catch (JSONException jse) { + } catch (JSONException jse) { fail(jse.getMessage()); } } diff --git a/testutils/src/main/kotlin/com.mparticle/Utils.kt b/testutils/src/main/kotlin/com.mparticle/Utils.kt index d4f7e5f46..f57145ad2 100644 --- a/testutils/src/main/kotlin/com.mparticle/Utils.kt +++ b/testutils/src/main/kotlin/com.mparticle/Utils.kt @@ -43,7 +43,12 @@ object Utils { } fun randomEventType(): MParticle.EventType { - return MParticle.EventType.values()[Random.Default.nextInt(0, MParticle.EventType.values().size - 1)] + return MParticle.EventType.values()[ + Random.Default.nextInt( + 0, + MParticle.EventType.values().size - 1 + ) + ] } fun randomProductAction(): String { diff --git a/tooling/common/src/main/java/com/mparticle/tooling/Config.kt b/tooling/common/src/main/java/com/mparticle/tooling/Config.kt index beaefd58a..78a6d1903 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/Config.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/Config.kt @@ -32,10 +32,14 @@ data class Config( val config = Config() json.keys().forEach { key -> if (key == "internal-config") { - config.internalConfig = InternalConfig.fromJson(json.optJSONObject("internal-config")) + config.internalConfig = + InternalConfig.fromJson(json.optJSONObject("internal-config")) } else { Config::class.java.declaredMethods - .firstOrNull { it.name.removePrefix("set").toLowerCase() == key?.toString()?.toLowerCase() } + .firstOrNull { + it.name.removePrefix("set").toLowerCase() == key?.toString() + ?.toLowerCase() + } ?.invoke(config, json.opt(key.toString())) } } diff --git a/tooling/common/src/main/java/com/mparticle/tooling/DataPlanningNodeApp.kt b/tooling/common/src/main/java/com/mparticle/tooling/DataPlanningNodeApp.kt index 449dc536b..8c97bd4c3 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/DataPlanningNodeApp.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/DataPlanningNodeApp.kt @@ -22,28 +22,63 @@ class DataPlanningNodeApp(val config: Config) { } } - fun validate(dataplan: String, message: String, version: String?): NodeAppResult> { + fun validate( + dataplan: String, + message: String, + version: String? + ): NodeAppResult> { try { val mpCommand = config.internalConfig.mpPath ?: "mp" val args = if (version == null) { - mutableListOf(mpCommand, "planning:events:validate", "--dataPlanVersion", dataplan, "--translateEvents", "--event", message) + mutableListOf( + mpCommand, + "planning:events:validate", + "--dataPlanVersion", + dataplan, + "--translateEvents", + "--event", + message + ) } else { - mutableListOf(mpCommand, "planning:events:validate", "--dataPlan", dataplan, "--translateEvents", "--event", message, "--versionNumber", version) + mutableListOf( + mpCommand, + "planning:events:validate", + "--dataPlan", + dataplan, + "--translateEvents", + "--event", + message, + "--versionNumber", + version + ) } - val results = args.toTypedArray().executeCLI(path, workingDirectory = config.credentialsFilePath ?: ".") + val results = args.toTypedArray() + .executeCLI(path, workingDirectory = config.credentialsFilePath ?: ".") val error = DataPlanError.values().firstOrNull { results.contains(it.message) } if (error != null) { return NodeAppResult(listOf(ValidationResult(error = error, arguments = args))) } return NodeAppResult(response = ValidationResult.from(results, arguments = args)) } catch (ioe: Exception) { - return NodeAppResult(ValidationResult.from("", listOf("${ioe.message}\n${ioe.stackTrace.joinToString("\n")}"))) + return NodeAppResult( + ValidationResult.from( + "", + listOf("${ioe.message}\n${ioe.stackTrace.joinToString("\n")}") + ) + ) } } fun fetchDataPlan(accountId: String, planId: String, version: String?): NodeAppResult { try { - val arguments = mutableListOf("mp", "data-plan:fetch", "--accountId", accountId, "--dataPlanId", planId) + val arguments = mutableListOf( + "mp", + "data-plan:fetch", + "--accountId", + accountId, + "--dataPlanId", + planId + ) if (version != null) { arguments.add("--version") arguments.add(version) diff --git a/tooling/common/src/main/java/com/mparticle/tooling/Utils.kt b/tooling/common/src/main/java/com/mparticle/tooling/Utils.kt index f2a598c42..d0f2ecbf9 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/Utils.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/Utils.kt @@ -16,7 +16,8 @@ object Utils { fun Array.executeCLI(path: String? = null, workingDirectory: String = "."): String { Logger.verbose( - "command line operation: ${joinToString(" ") { + "command line operation: ${ + joinToString(" ") { if (it.contains(" ")) { "\"$it\"" } else { diff --git a/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt b/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt index 9ad055623..b2675a811 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt @@ -4,8 +4,14 @@ import org.json.JSONArray import org.json.JSONException import org.json.JSONObject -data class ValidationResult(val eventType: String? = null, val data: ValidationResultData? = null, val error: DataPlanError? = null, val arguments: List) { +data class ValidationResult( + val eventType: String? = null, + val data: ValidationResultData? = null, + val error: DataPlanError? = null, + val arguments: List +) { var originalString: String? = null + companion object { fun from(json: String?, arguments: List): List? { @@ -16,6 +22,7 @@ data class ValidationResult(val eventType: String? = null, val data: ValidationR listOf(ValidationResult(arguments = arguments).apply { originalString = json }) } } + fun from(json: JSONArray, arguments: List): List { val validationResults = ArrayList() for (i in 0..json.length() - 1) { @@ -38,7 +45,12 @@ data class ValidationResult(val eventType: String? = null, val data: ValidationR "Data", JSONObject() .put("Match", data?.match) - .put("ValidationErrors", data?.validationErrors?.foldRight(JSONArray()) { item, arr -> arr.put(item) }) + .put( + "ValidationErrors", + data?.validationErrors?.foldRight(JSONArray()) { item, arr -> + arr.put(item) + } + ) ) .put("Event Type", eventType) return """ @@ -48,7 +60,10 @@ data class ValidationResult(val eventType: String? = null, val data: ValidationR arguments.toMutableList().apply { if (it >= 0) { val dataplan = removeAt(it + 1) - add(it + 1, "${dataplan.substring(0, Math.min(dataplan.length, 20))}...") + add( + it + 1, + "${dataplan.substring(0, Math.min(dataplan.length, 20))}..." + ) } } }.joinToString(" ") @@ -64,10 +79,18 @@ data class ValidationResult(val eventType: String? = null, val data: ValidationR } } -data class ValidationResultData(val match: ValidationResultMatch?, val validationErrors: List) { +data class ValidationResultData( + val match: ValidationResultMatch?, + val validationErrors: List +) { companion object { fun from(json: JSONObject?): ValidationResultData? { - return json?.let { ValidationResultData(ValidationResultMatch.from(it.optJSONObject("match")), ValidationResultErrors.from(it.optJSONArray("validation_errors"))) } + return json?.let { + ValidationResultData( + ValidationResultMatch.from(it.optJSONObject("match")), + ValidationResultErrors.from(it.optJSONArray("validation_errors")) + ) + } } } } @@ -84,7 +107,14 @@ data class ValidationResultMatch(val type: String, val criteria: Map { val validationResultErrors = ArrayList() @@ -97,7 +127,16 @@ data class ValidationResultErrors(val validationErrorType: ValidationErrorType, val expected = jsonObject.optString("expected") val actual = jsonObject.optString("actual") val schemaKeyword = jsonObject.optString("schema_keyword") - validationResultErrors.add(ValidationResultErrors(validationErrorType, errorPointer, key, expected, actual, schemaKeyword)) + validationResultErrors.add( + ValidationResultErrors( + validationErrorType, + errorPointer, + key, + expected, + actual, + schemaKeyword + ) + ) } return validationResultErrors } diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/Extensions.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/Extensions.kt index 03e1413ed..71f8c97fc 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/Extensions.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/Extensions.kt @@ -39,7 +39,10 @@ import org.jetbrains.uast.util.isConstructorCall import org.json.JSONArray import org.json.JSONObject -internal fun UCallExpression.resolveExpression(instance: Expression, returnValue: Boolean): Expression { +internal fun UCallExpression.resolveExpression( + instance: Expression, + returnValue: Boolean +): Expression { val expression = if (isConstructorCall()) { Constructor(instance, methodName, this) } else { @@ -212,7 +215,10 @@ internal fun PsiClass.getQualifiedName(reflectable: Boolean): String? { fun isParentTopLevel(child: PsiElement) { if (!child.isTopLevelKtOrJavaMember()) { val index = qualifiedName.indexOfLast { it == '.' } - qualifiedName = qualifiedName.substring(0, index) + "$" + qualifiedName.substring(index + 1, qualifiedName.length) + qualifiedName = qualifiedName.substring(0, index) + "$" + qualifiedName.substring( + index + 1, + qualifiedName.length + ) isParentTopLevel(child.parent) } } @@ -220,7 +226,10 @@ internal fun PsiClass.getQualifiedName(reflectable: Boolean): String? { return qualifiedName } -internal fun UExpression.resolveChainedCalls(returnValue: Boolean, instance: Expression): Expression { +internal fun UExpression.resolveChainedCalls( + returnValue: Boolean, + instance: Expression +): Expression { val initialInstance = instance var calls = (getOutermostQualified() ?: this).getQualifiedChain().toMutableList() calls = calls.filter { it is UCallExpression }.toMutableList() @@ -237,7 +246,9 @@ internal fun UExpression.resolveChainedCalls(returnValue: Boolean, instance: Exp internal fun Pair<*, *>.resolveToEnum(): Enum<*> { val className = when (first) { - is ClassId -> "${(first as ClassId).packageFqName}.${(first as ClassId).relativeClassName.asString().replace(".", "$")}" + is ClassId -> "${(first as ClassId).packageFqName}.${ + (first as ClassId).relativeClassName.asString().replace(".", "$") + }" is String -> first as String else -> null } diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/VariableCollector.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/VariableCollector.kt index c281e5c71..399dbb7b9 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/VariableCollector.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/VariableCollector.kt @@ -23,7 +23,12 @@ import org.jetbrains.uast.visitor.AbstractUastVisitor * class that will gather all {@link com.mparticle.ling.dtos.Call}s made to the provided PsiVariable instance. * After */ -internal class VariableCollector(val variable: PsiVariable, private val method: UMethod, val parent: Expression, val includeInitialization: Boolean = false) : AbstractUastVisitor() { +internal class VariableCollector( + val variable: PsiVariable, + private val method: UMethod, + val parent: Expression, + val includeInitialization: Boolean = false +) : AbstractUastVisitor() { private var expression: Expression? = null fun getUnresolvedObject(returnValue: Boolean? = null): Expression? { @@ -56,17 +61,28 @@ internal class VariableCollector(val variable: PsiVariable, private val method: is USimpleNameReferenceExpression -> { val reference = uastInitializer.resolve() if (reference is PsiVariable) { - expression = VariableCollector(reference, method, parent, true).getUnresolvedObject(true) + expression = VariableCollector( + reference, + method, + parent, + true + ).getUnresolvedObject(true) } } is UQualifiedReferenceExpression -> { // get the first call in a potential chain of calls - val reference = uastInitializer.getOutermostQualified().getQualifiedChain()[0].tryResolve() + val reference = uastInitializer.getOutermostQualified() + .getQualifiedChain()[0].tryResolve() when (reference) { // product = productBuilder.build() is PsiVariable -> { - expression = VariableCollector(reference, method, parent, true).getUnresolvedObject(true) + expression = VariableCollector( + reference, + method, + parent, + true + ).getUnresolvedObject(true) } // product = Product.Builder() (static method) is PsiClass -> { @@ -80,7 +96,10 @@ internal class VariableCollector(val variable: PsiVariable, private val method: // product = new Product() // map = mapOf() is UCallExpression -> { - expression = uastInitializer.resolveChainedCalls(true, RootParent(uastInitializer)) + expression = uastInitializer.resolveChainedCalls( + true, + RootParent(uastInitializer) + ) } } } diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/basedetectors/CallScanner.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/basedetectors/CallScanner.kt index d4ea432ab..674495483 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/basedetectors/CallScanner.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/basedetectors/CallScanner.kt @@ -25,7 +25,11 @@ import org.jetbrains.uast.util.isConstructorCall */ abstract class CallScanner : BaseDetector(), Detector.UastScanner { - abstract fun onInstanceCollected(context: JavaContext, unresolvedExpression: Expression, reportingNode: UExpression) + abstract fun onInstanceCollected( + context: JavaContext, + unresolvedExpression: Expression, + reportingNode: UExpression + ) abstract fun getApplicableClasses(): List> @@ -40,7 +44,9 @@ abstract class CallScanner : BaseDetector(), Detector.UastScanner { val method = node.getParentOfType(UMethod::class.java) if (variable != null && method != null) { - VariableCollector(variable, method, expression).getUnresolvedObject(false) + VariableCollector(variable, method, expression).getUnresolvedObject( + false + ) } if (expression != null) { node.receiverClassName()?.let { receiverName -> diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt index 8ba04fdf1..edae1185d 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/DataplanDetector.kt @@ -59,7 +59,8 @@ class DataplanDetector : CallScanner() { ) } - override fun getApplicableClasses() = listOf(MPEvent.Builder::class.java, CommerceEvent.Builder::class.java) + override fun getApplicableClasses() = + listOf(MPEvent.Builder::class.java, CommerceEvent.Builder::class.java) override fun beforeCheckRootProject(context: Context) { super.beforeCheckRootProject(context) @@ -71,7 +72,9 @@ class DataplanDetector : CallScanner() { if (config != null) { dataplanningNode = DataPlanningNodeApp(config!!) - dataplan = try { Utils.getLocalDataplan() } catch (e: Exception) { + dataplan = try { + Utils.getLocalDataplan() + } catch (e: Exception) { disabled = true return } @@ -88,8 +91,15 @@ class DataplanDetector : CallScanner() { } } - override fun onInstanceCollected(context: JavaContext, unresolvedObject: Expression, reportingNode: UExpression) { - val instance = try { unresolvedObject.resolve() } catch (e: Exception) { } + override fun onInstanceCollected( + context: JavaContext, + unresolvedObject: Expression, + reportingNode: UExpression + ) { + val instance = try { + unresolvedObject.resolve() + } catch (e: Exception) { + } // this will make MParticle not break incase Logger happens to be called val message = when (instance) { is MPEvent.Builder -> instance.build().message @@ -128,7 +138,8 @@ class DataplanDetector : CallScanner() { ) } else { val messageString = message.attributesToNumbers().toString() - val result: DataPlanningNodeApp.NodeAppResult>? = dataplanningNode?.validate(dp, messageString, config?.dataPlanVersion) + val result: DataPlanningNodeApp.NodeAppResult>? = + dataplanningNode?.validate(dp, messageString, config?.dataPlanVersion) if (config?.debugReportServerMessage === true) { val response = result?.response?.getOrNull(0) context.report( @@ -144,7 +155,10 @@ class DataplanDetector : CallScanner() { validationResult.data?.validationErrors?.forEach { error -> var errorMessage = when (error.errorPointer) { - "#/data/custom_attributes", "#/data/custom_attributes/${error.key}" -> getErrorMessageBySchemaKeyword(ViolationSchemaKeywordType.get(error.schemaKeyworkd), error.expected) + "#/data/custom_attributes", "#/data/custom_attributes/${error.key}" -> getErrorMessageBySchemaKeyword( + ViolationSchemaKeywordType.get(error.schemaKeyworkd), + error.expected + ) "#" -> when (validationResult.data?.match?.type) { "commerce_event" -> "Unplanned Commerce Event" "custom_event" -> "Unplanned Custom Event (MPEvent)" @@ -155,17 +169,19 @@ class DataplanDetector : CallScanner() { val matchingValues = ArrayList() unresolvedObject.forEachExpression { expression -> val value = expression.resolve() - val targetValue = if (error.actual.isNullOrEmpty()) error.key else error.actual + val targetValue = + if (error.actual.isNullOrEmpty()) error.key else error.actual if (value.toString() == targetValue) { expression.node.let { matchingValues.add(it) } } } val match = validationResult.data?.match - errorMessage = errorMessage ?: validationResult.data?.match?.criteria?.entries?.firstOrNull { - it.value == error.key - }?.let { entry -> - "For ${match?.type}, unexpected ${entry.key} value of \"${entry.value}\". exprected ${error.expected}" - } + errorMessage = errorMessage + ?: validationResult.data?.match?.criteria?.entries?.firstOrNull { + it.value == error.key + }?.let { entry -> + "For ${match?.type}, unexpected ${entry.key} value of \"${entry.value}\". exprected ${error.expected}" + } if (matchingValues.size == 1) { context.report( ISSUE, @@ -186,12 +202,18 @@ class DataplanDetector : CallScanner() { } } if (config?.resultsFile?.isEmpty() == false) { - File(config!!.resultsFile!!).appendText(result?.response?.joinToString { it.toString() } ?: "") + File(config!!.resultsFile!!).appendText( + result?.response?.joinToString { it.toString() } + ?: "" + ) } } } - fun getErrorMessageBySchemaKeyword(schemaKeyword: ViolationSchemaKeywordType, expectedValue: String? = null): String { + fun getErrorMessageBySchemaKeyword( + schemaKeyword: ViolationSchemaKeywordType, + expectedValue: String? = null + ): String { val expectedValueMessage = expectedValue?.let { ": $it" } ?: "" return when (schemaKeyword) { ViolationSchemaKeywordType.Const -> @@ -243,7 +265,8 @@ class DataplanDetector : CallScanner() { companion object { fun get(value: String?): ViolationSchemaKeywordType { - return values().firstOrNull { it.toString().toLowerCase() == value?.toLowerCase() } ?: Unknown + return values().firstOrNull { it.toString().toLowerCase() == value?.toLowerCase() } + ?: Unknown } } } diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/GradleBuildDetector.java b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/GradleBuildDetector.java index 6c2701828..2ab56049e 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/GradleBuildDetector.java +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/GradleBuildDetector.java @@ -1,6 +1,7 @@ package com.mparticle.lints.detectors; import com.android.annotations.NonNull; +import com.android.annotations.Nullable; import com.android.tools.lint.detector.api.Category; import com.android.tools.lint.detector.api.Context; import com.android.tools.lint.detector.api.DefaultPosition; @@ -12,7 +13,6 @@ import com.android.tools.lint.detector.api.Scope; import com.android.tools.lint.detector.api.Severity; import com.android.utils.Pair; -import com.android.annotations.Nullable; import com.mparticle.lints.basedetectors.BaseDetector; import org.codehaus.groovy.ast.ASTNode; @@ -36,7 +36,7 @@ public class GradleBuildDetector extends BaseDetector implements GradleScanner { "api" }; - private String[] includedArtifacts = new String[] { + private String[] includedArtifacts = new String[]{ "android-core", "-kit", }; @@ -60,7 +60,7 @@ public void beforeCheckRootProject(@NonNull Context context) { public void afterCheckRootProject(Context context) { // Check for inconsistent versions across MParticle dependencies (Core, Kits, etc) String currentVersion = null; - for (MPDependency mpDependency: mMPDependencies) { + for (MPDependency mpDependency : mMPDependencies) { if (currentVersion == null) { currentVersion = mpDependency.version; } else { @@ -81,7 +81,7 @@ public void checkDslPropertyAssignment(@NonNull GradleContext context, @NonNull String artifact = dependencySplit[1]; if (MPARTICLE_PACKAGE.equalsIgnoreCase(pkg) && artifact != null) { boolean isIncludedArtifact = false; - for (String includedArtifact: includedArtifacts) { + for (String includedArtifact : includedArtifacts) { if (artifact.contains(includedArtifact)) { isIncludedArtifact = true; } @@ -118,7 +118,7 @@ private void reportInconsistency(Context context) { message .append(MESSAGE_INCONSISTENCY_IN_VERSIONS_DETECTED) .append("\n\n"); - for(MPDependency mpDependency: mMPDependencies) { + for (MPDependency mpDependency : mMPDependencies) { if (commonContext == null) { commonContext = mpDependency.context; hasCommonContext = true; @@ -130,12 +130,12 @@ private void reportInconsistency(Context context) { } if (maxLineNumber == null) { maxLineNumber = mpDependency; - } else if (maxLineNumber.expression.getLastLineNumber() < mpDependency.expression.getLastLineNumber()){ + } else if (maxLineNumber.expression.getLastLineNumber() < mpDependency.expression.getLastLineNumber()) { maxLineNumber = mpDependency; } if (minLineNumber == null) { minLineNumber = mpDependency; - } else if (minLineNumber.expression.getLineNumber() > mpDependency.expression.getLineNumber()){ + } else if (minLineNumber.expression.getLineNumber() > mpDependency.expression.getLineNumber()) { minLineNumber = mpDependency; } diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt index 48119fde9..ba826cbbb 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/MpApiDetectorKt.kt @@ -33,8 +33,10 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { companion object { val MESSAGE_MULTIPLE_START_CALLS = "Duplicate call to MParticle.start" val MESSAGE_NO_START_CALL_IN_ON_CREATE = "This Method should call MParticle.start()" - val MESSAGE_START_CALLED_IN_WRONG_PLACE = "MParticle.start() should be called in Application.onCreate(), not here" - val MESSAGE_NO_START_CALL_AT_ALL = "In order to Initialize MParticle, you need to extend android.app.Application, and call MParticle.start() in it's onCreate() method" + val MESSAGE_START_CALLED_IN_WRONG_PLACE = + "MParticle.start() should be called in Application.onCreate(), not here" + val MESSAGE_NO_START_CALL_AT_ALL = + "In order to Initialize MParticle, you need to extend android.app.Application, and call MParticle.start() in it's onCreate() method" @JvmStatic val ISSUE = Issue.create( @@ -78,7 +80,11 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { if (properMethodCall == null) { if (applicationOnCreateCall != null) { - context.report(ISSUE, applicationOnCreateCall!!.location, MESSAGE_NO_START_CALL_IN_ON_CREATE) + context.report( + ISSUE, + applicationOnCreateCall!!.location, + MESSAGE_NO_START_CALL_IN_ON_CREATE + ) } else { context.report(ISSUE, Location.create(context.file), MESSAGE_NO_START_CALL_AT_ALL) } @@ -112,18 +118,35 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { forEach { methodCall -> if (isTargetMethod(TARGET_METHOD_QUALIFIED_NAME, methodCall)) { if (properMethodCall == null) { - properMethodCall = LocationWrapper(context.getLocation(methodCall)) + properMethodCall = + LocationWrapper(context.getLocation(methodCall)) } else { - extraProperMethodCalls.add(LocationWrapper(context.getLocation(methodCall))) + extraProperMethodCalls.add( + LocationWrapper( + context.getLocation( + methodCall + ) + ) + ) } } } } applicationOnCreateCall = LocationWrapper(context.getLocation(node)) } else { - findMethodCall(node, TARGET_METHOD_QUALIFIED_NAME, 1).forEach { methodCall -> + findMethodCall( + node, + TARGET_METHOD_QUALIFIED_NAME, + 1 + ).forEach { methodCall -> if (isTargetMethod(TARGET_METHOD_QUALIFIED_NAME, methodCall)) { - wrongPlaceMethodCalls.add(LocationWrapper(context.getLocation(methodCall))) + wrongPlaceMethodCalls.add( + LocationWrapper( + context.getLocation( + methodCall + ) + ) + ) } } } @@ -134,7 +157,11 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { } } - private fun findMethodCall(method: UMethod, targetMethodName: String, depth: Int): List { + private fun findMethodCall( + method: UMethod, + targetMethodName: String, + depth: Int + ): List { fun findMethodCall(element: UElement?, depth: Int): List { var callExpressions = mutableListOf() if (depth == 0) { @@ -175,7 +202,13 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { return@apply } val index = text.indexOf(name ?: "") - if (index > 0 && " ${text.substring(0, index)} ".contains(" fun ")) { + if (index > 0 && " ${ + text.substring( + 0, + index + ) + } ".contains(" fun ") + ) { return@apply } uastInitializer?.let { @@ -213,7 +246,8 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { * call refers to a local function, or a class level function, */ private fun getMethod(callExpression: UCallExpression): UExpression? { - return getLocalMethodImplmentation(callExpression) ?: getMethodImplementation(callExpression) + return getLocalMethodImplmentation(callExpression) + ?: getMethodImplementation(callExpression) } private fun getLocalMethodImplmentation(callExpression: UCallExpression): UExpression? { @@ -268,8 +302,10 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { val evaluator = context.evaluator return method.getParentOfType(true, UClass::class.java) ?.let { - var isApplicationSubclass = evaluator.extendsClass(it, "android.app.Application", false) - var isApplicationClass = method.containingClass?.qualifiedName.equals("android.app.Application") + var isApplicationSubclass = + evaluator.extendsClass(it, "android.app.Application", false) + var isApplicationClass = + method.containingClass?.qualifiedName.equals("android.app.Application") isApplicationSubclass && !isApplicationClass } ?: false } @@ -279,7 +315,8 @@ class MpApiDetectorKt : BaseDetector(), Detector.UastScanner { * before or not, is to compare their location. The Location object does not have an effective "equals()" * method, so this class provides us with a way to compare locations */ - internal class LocationWrapper constructor(val location: Location) : Comparable { + internal class LocationWrapper constructor(val location: Location) : + Comparable { override fun hashCode(): Int { return toString().hashCode() diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/ReferrerReceiverDetector.java b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/ReferrerReceiverDetector.java index 900505264..6d35bbfed 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/ReferrerReceiverDetector.java +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/detectors/ReferrerReceiverDetector.java @@ -1,5 +1,10 @@ package com.mparticle.lints.detectors; +import static com.android.SdkConstants.ANDROID_MANIFEST_XML; +import static com.android.SdkConstants.ANDROID_URI; +import static com.android.SdkConstants.ATTR_NAME; +import static com.android.SdkConstants.TAG_RECEIVER; + import com.android.tools.lint.detector.api.Category; import com.android.tools.lint.detector.api.Detector; import com.android.tools.lint.detector.api.Implementation; @@ -14,11 +19,6 @@ import java.util.Collection; import java.util.Collections; -import static com.android.SdkConstants.ANDROID_MANIFEST_XML; -import static com.android.SdkConstants.ANDROID_URI; -import static com.android.SdkConstants.ATTR_NAME; -import static com.android.SdkConstants.TAG_RECEIVER; - public class ReferrerReceiverDetector extends ResourceXmlDetector implements Detector.XmlScanner { public static final String ACTION_INSTALL_REFERRER = "com.android.vending.INSTALL_REFERRER"; @@ -28,7 +28,7 @@ public class ReferrerReceiverDetector extends ResourceXmlDetector implements Det "MParticleInstallRefReceiver", "com.mparticle.ReferrerReceiver should no longer be used", "MParticle ReferrerReceiver should no longer be registered in " + ANDROID_MANIFEST_XML + ". In order to receive InstallReferrer data, add the following dependency to your build.gradle\n" + - "\n" + + "\n" + "dependencies {\n" + "\timplementation 'com.android.installreferrer:installreferrer:1+'" + "\n}", diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Constructor.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Constructor.kt index f014ca499..5a3da1447 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Constructor.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Constructor.kt @@ -4,7 +4,11 @@ import com.mparticle.lints.receiverClassName import com.mparticle.lints.resolve import org.jetbrains.uast.UCallExpression -data class Constructor(override val parent: Expression, val methodName: String?, override val node: UCallExpression) : ParameterizedExpression { +data class Constructor( + override val parent: Expression, + val methodName: String?, + override val node: UCallExpression +) : ParameterizedExpression { override var arguments: List = listOf() override fun resolve(): Any? { diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/MethodCall.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/MethodCall.kt index eae094749..f6c71b767 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/MethodCall.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/MethodCall.kt @@ -3,13 +3,19 @@ package com.mparticle.lints.dtos import com.mparticle.lints.resolve import org.jetbrains.uast.UCallExpression -data class MethodCall(override val parent: Expression, val methodName: String?, override val node: UCallExpression, var returnValue: Boolean) : ParameterizedExpression { +data class MethodCall( + override val parent: Expression, + val methodName: String?, + override val node: UCallExpression, + var returnValue: Boolean +) : ParameterizedExpression { override var arguments: List = listOf() init { arguments.forEach { it.parent = this } } + override fun resolve(): Any? { val instance = parent.resolve() if (instance == null) { diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/StaticFactory.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/StaticFactory.kt index b54accb3d..41ccbc983 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/StaticFactory.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/StaticFactory.kt @@ -4,9 +4,9 @@ import com.intellij.psi.impl.compiled.ClsClassImpl import com.mparticle.lints.resolve import org.jetbrains.uast.UCallExpression import java.lang.reflect.Method -import java.util.HashSet -class StaticFactory(val methodName: String?, override val node: UCallExpression) : ParameterizedExpression { +class StaticFactory(val methodName: String?, override val node: UCallExpression) : + ParameterizedExpression { override val parent = RootParent(node) override var arguments: List = listOf() diff --git a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Value.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Value.kt index 79902fc44..223c280e0 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Value.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Value.kt @@ -3,7 +3,8 @@ package com.mparticle.lints.dtos import com.mparticle.lints.resolveToEnum import org.jetbrains.uast.UExpression -data class Value(override var parent: Expression, val value: Any?, override val node: UExpression) : Expression { +data class Value(override var parent: Expression, val value: Any?, override val node: UExpression) : + Expression { override fun toString(): String { return "$value" diff --git a/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/DataplanDetectorTest.kt b/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/DataplanDetectorTest.kt index b8d58677c..7784dd016 100644 --- a/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/DataplanDetectorTest.kt +++ b/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/DataplanDetectorTest.kt @@ -12,7 +12,8 @@ class DataplanDetectorTest : LintDetectorTest() { @Test fun testCollection() { - val sdkHome = System.getenv("ANDROID_HOME") ?: "${System.getProperty("user.home")}/Library/Android/sdk" + val sdkHome = System.getenv("ANDROID_HOME") + ?: "${System.getProperty("user.home")}/Library/Android/sdk" @Language("KT") val source = """ @@ -36,5 +37,6 @@ class DataplanDetectorTest : LintDetectorTest() { override fun requireCompileSdk() = false override fun getDetector() = DataplanDetector() - override fun getIssues() = listOf(DataplanDetector.ISSUE, DataplanDetector.NODE_MISSING, DataplanDetector.NO_DATA_PLAN) + override fun getIssues() = + listOf(DataplanDetector.ISSUE, DataplanDetector.NODE_MISSING, DataplanDetector.NO_DATA_PLAN) }