From d8a44616eb8443dd6f49ae5c2b40c00bcfbda0cd Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Tue, 29 Apr 2025 12:50:48 -0400 Subject: [PATCH 01/11] feat: Update Android Gradle plugin to 8.1.0 --- android-core/build.gradle | 4 +-- android-core/proguard.pro | 28 +++++++++++++++++++ android-kit-base/build.gradle | 6 ++-- build.gradle | 11 +++++++- gradle.properties | 5 +++- kit-plugin/build.gradle | 8 +++--- .../com/mparticle/kits/KitPlugin.groovy | 16 ++++------- testutils/build.gradle | 7 +++++ tooling/android-plugin/build.gradle | 6 ++-- tooling/common/build.gradle | 8 ++++-- tooling/custom-lint-rules/build.gradle | 15 +++++----- 11 files changed, 80 insertions(+), 34 deletions(-) diff --git a/android-core/build.gradle b/android-core/build.gradle index 3943a17f5..a36256bb4 100644 --- a/android-core/build.gradle +++ b/android-core/build.gradle @@ -13,8 +13,8 @@ android { exclude 'META-INF/LICENSE' } compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 } String url = '\"\"' diff --git a/android-core/proguard.pro b/android-core/proguard.pro index 6862bc3b1..83724dc16 100644 --- a/android-core/proguard.pro +++ b/android-core/proguard.pro @@ -265,3 +265,31 @@ -keep class com.mparticle.RoktEvent { *; } -keepclassmembers class com.mparticle.RoktEvent { *; } -keepclasseswithmembers class com.mparticle.RoktEvent$* { *; } + + +# Firebase and GMS CloudMessaging +-dontwarn com.google.android.gms.cloudmessaging.** +-dontwarn com.google.firebase.messaging.** +-keep class com.google.firebase.messaging.** { *; } + +# Java 9+ StringConcatFactory +-dontwarn java.lang.invoke.StringConcatFactory +-keep class java.lang.invoke.StringConcatFactory { *; } + +# Keep lambdas +-keepclassmembers class * { + private static synthetic *** lambda$*(...); +} + +# Keep any classes referenced but not found during R8 minification +-ignorewarnings +-keep class ** { *; } + +# Additional rules to prevent minification errors with Kotlin +-keepattributes *Annotation*, InnerClasses, Signature, EnclosingMethod +-keepclassmembers class kotlin.Metadata { + public ; +} +-keepclassmembers class * { + @kotlin.Metadata ; +} \ No newline at end of file diff --git a/android-kit-base/build.gradle b/android-kit-base/build.gradle index 3115550af..12d479abe 100644 --- a/android-kit-base/build.gradle +++ b/android-kit-base/build.gradle @@ -14,7 +14,7 @@ android { testBuildType 'debug' defaultConfig { - minSdkVersion 14 + minSdk 14 targetSdk 33 testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' } @@ -37,8 +37,8 @@ android { } compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 } } diff --git a/build.gradle b/build.gradle index 425b32142..f7d9ed63b 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,6 @@ buildscript { ext.kotlin_version = '1.9.0' - ext.gradle_version = '7.3.1' + ext.gradle_version = '8.1.0' repositories { mavenCentral() @@ -26,6 +26,15 @@ sonarqube { } subprojects { + afterEvaluate { project -> + if (project.hasProperty('android')) { + project.android { + if (namespace == null) { + namespace project.group + } + } + } + } apply plugin: 'org.sonarqube' sonarqube { androidVariant "release" diff --git a/gradle.properties b/gradle.properties index b2e5897e7..9f4b6bedb 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,4 +2,7 @@ android.useAndroidX=true org.gradle.daemon=true org.gradle.jvmargs=-Xmx2560m -#-XX:ThreadStackSize=4096 -XX:CompilerThreadStackSize=4096 \ No newline at end of file +#-XX:ThreadStackSize=4096 -XX:CompilerThreadStackSize=4096 +android.defaults.buildfeatures.buildconfig=true +org.gradle.caching=true +systemProp.org.gradle.kotlin.dsl.precompiled.accessors.strict=true diff --git a/kit-plugin/build.gradle b/kit-plugin/build.gradle index 5d78bc289..d99a08bd2 100644 --- a/kit-plugin/build.gradle +++ b/kit-plugin/build.gradle @@ -9,13 +9,13 @@ apply from: '../scripts/maven.gradle' dependencies { implementation gradleApi() implementation localGroovy() - compileOnly "com.android.tools.build:gradle:7.3.1" - testImplementation "com.android.tools.build:gradle:4.1.3" + compileOnly "com.android.tools.build:gradle:$gradle_version" + testImplementation "com.android.tools.build:gradle:$gradle_version" } compileGroovy { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 } dependencies { 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 f2bf43eb9..0e6320a02 100644 --- a/kit-plugin/src/main/groovy/com/mparticle/kits/KitPlugin.groovy +++ b/kit-plugin/src/main/groovy/com/mparticle/kits/KitPlugin.groovy @@ -139,17 +139,13 @@ class KitPlugin implements Plugin { url = 'https://ossrh-staging-api.central.sonatype.com/service/local/staging/deploy/maven2/' } - def signingKey = System.getenv("mavenSigningKeyId") - def signingPassword = System.getenv("mavenSigningKeyPassword") - - if (signingKey != null) { - target.extensions.add('signing.keyId', signingKey) - target.extensions.add('signing.password', signingPassword) - - SigningExtension signing = new SigningExtension(target) + target.extensions.configure(SigningExtension) { signing -> signing.required = { target.gradle.taskGraph.hasTask("publishReleasePublicationToMavenRepository") } - signing.useInMemoryPgpKeys(signingKey, signingPassword) - signing.sign publishing.publications.findByName("release") + def signingKey = target.findProperty('signingKey') ?: System.getenv("mavenSigningKeyId") + def signingPassword = target.findProperty('signingPassword') ?: System.getenv("mavenSigningKeyPassword") + if (signingKey && signingPassword) { + signing.useInMemoryPgpKeys(target.property('signingKey'), target.property('signingPassword')) + } } } diff --git a/testutils/build.gradle b/testutils/build.gradle index 707ee2dcd..c0ac695af 100644 --- a/testutils/build.gradle +++ b/testutils/build.gradle @@ -5,7 +5,14 @@ android { namespace 'com.mparticle.testutils' testNamespace 'com.mparticle.legacyTest' compileSdk 33 + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 // Set to your desired Java version + targetCompatibility = JavaVersion.VERSION_17 // Set to your desired Java version + } + kotlinOptions { + jvmTarget = "17" // Should match the Java version above + } defaultConfig { //This is set to 21 to avoid slow multidex. minSdk 21 diff --git a/tooling/android-plugin/build.gradle b/tooling/android-plugin/build.gradle index ee4b47d35..6eb7f296d 100644 --- a/tooling/android-plugin/build.gradle +++ b/tooling/android-plugin/build.gradle @@ -1,8 +1,8 @@ apply plugin: 'groovy' apply plugin: 'kotlin' -sourceCompatibility = JavaVersion.VERSION_1_8 -targetCompatibility = JavaVersion.VERSION_1_8 +sourceCompatibility = JavaVersion.VERSION_17 +targetCompatibility = JavaVersion.VERSION_17 ext { @@ -26,7 +26,7 @@ configurations { dependencies { fatJar project(':tooling:common') - compileOnly configurations.fatJar + compileOnly files(configurations.fatJar) implementation gradleApi() implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation files('libs/java-json.jar') diff --git a/tooling/common/build.gradle b/tooling/common/build.gradle index d1419a6bc..70ddb0bae 100644 --- a/tooling/common/build.gradle +++ b/tooling/common/build.gradle @@ -16,6 +16,10 @@ dependencies { } java { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +kotlin { + jvmToolchain(17) } \ No newline at end of file diff --git a/tooling/custom-lint-rules/build.gradle b/tooling/custom-lint-rules/build.gradle index 99af1017b..991a16e38 100755 --- a/tooling/custom-lint-rules/build.gradle +++ b/tooling/custom-lint-rules/build.gradle @@ -4,8 +4,8 @@ apply plugin: 'java-library' apply plugin: 'kotlin' apply plugin: 'com.android.lint' -sourceCompatibility = 1.8 -targetCompatibility = 1.8 +sourceCompatibility = 17 +targetCompatibility = 17 buildscript { ext { @@ -39,7 +39,7 @@ dependencies { lintBuild files(jar) lintJar files('libs/mparticle-min.jar') lintJar project(':tooling:common') - implementation configurations.lintJar + implementation files(configurations.lintJar) compileOnly "com.android.tools.lint:lint-api:$lintVersion" compileOnly "com.android.tools.lint:lint-checks:$lintVersion" compileOnly 'org.codehaus.groovy:groovy-all:3.0.13' @@ -51,7 +51,7 @@ dependencies { jar { dependsOn(":tooling:common:jar") - archiveName 'lint.jar' + archiveFileName = 'lint.jar' manifest { attributes 'Manifest-Version': 1.0 attributes 'Lint-Registry-v2': 'com.mparticle.lints.MParticleIssueRegistry' @@ -74,10 +74,9 @@ rootProject.project('android-core').android.buildTypes.all { task zipSources(type: Jar) { def fileName = "$project.rootDir/android-core/build/intermediates/javac/${targetBuildType}/classes" - from(fileTree(dir: fileName)) { - destinationDir new File("$project.projectDir/libs") - archiveName "mparticle.jar" - } + from(fileTree(dir: fileName)) + destinationDirectory.set(new File("$project.projectDir/libs")) + archiveFileName.set("mparticle.jar") outputs.upToDateWhen { false } } From c5689413ad1e7ca0a5254fccd264c1772f8ce945 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Wed, 30 Apr 2025 10:43:24 -0400 Subject: [PATCH 02/11] add othere file related to gradle 8 changes --- gradle/wrapper/gradle-wrapper.properties | 6 +++--- scripts/maven.gradle | 15 ++++++++++++--- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 60639c745..284897427 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Mon Oct 04 12:58:48 PDT 2021 distributionBase=GRADLE_USER_HOME -distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip distributionPath=wrapper/dists -zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-all.zip +networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/scripts/maven.gradle b/scripts/maven.gradle index 365510932..d1b191c7d 100644 --- a/scripts/maven.gradle +++ b/scripts/maven.gradle @@ -6,7 +6,16 @@ allprojects { ext."signing.secretKeyRingFile" = System.getenv("mavenSigningKeyRingFile") ext."signing.password" = System.getenv("mavenSigningKeyPassword") } - +// For AGP 8.x compatibility, configure Android library projects +if (project.plugins.findPlugin("com.android.library")) { + android { + publishing { + // Configure publishing for both variants + singleVariant("release") + singleVariant("debug") + } + } +} afterEvaluate { publishing { publications { @@ -115,5 +124,5 @@ afterEvaluate { } //Publishing task aliases for simpler local development -task publishLocal { dependsOn "publishDebugPublicationToMavenLocal" } -task publishReleaseLocal { dependsOn "publishReleasePublicationToMavenLocal" } +task publishLocal { dependsOn "publishDebugPublicationToMavenLocal"} +task publishReleaseLocal { dependsOn "publishReleasePublicationToMavenLocal"} From 8c26cf5d1524b57a993c5d20159e85aafdb34dbe Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Thu, 15 May 2025 14:47:09 -0400 Subject: [PATCH 03/11] Address review comments --- gradle.properties | 1 - gradle/wrapper/gradle-wrapper.properties | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index 9f4b6bedb..0ddb20a81 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,5 +4,4 @@ org.gradle.daemon=true org.gradle.jvmargs=-Xmx2560m #-XX:ThreadStackSize=4096 -XX:CompilerThreadStackSize=4096 android.defaults.buildfeatures.buildconfig=true -org.gradle.caching=true systemProp.org.gradle.kotlin.dsl.precompiled.accessors.strict=true diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 284897427..42defcc94 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists From 4a02cb78d46fb89d04baf9b3f55ff49ee995ebef Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Thu, 26 Jun 2025 15:31:22 -0400 Subject: [PATCH 04/11] fix merge conflict --- android-core/proguard.pro | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/android-core/proguard.pro b/android-core/proguard.pro index 83724dc16..5b4ce1c11 100644 --- a/android-core/proguard.pro +++ b/android-core/proguard.pro @@ -252,21 +252,6 @@ public static final ** CREATOR; } --keepclassmembers class com.mparticle.Rokt { - (...); - void *(...); - void *$default(...); - ; -} - --keep interface com.mparticle.MpRoktEventCallback { *; } --keep interface com.mparticle.UnloadReasons { *; } --keep class com.mparticle.UnloadReasons { *; } --keep class com.mparticle.RoktEvent { *; } --keepclassmembers class com.mparticle.RoktEvent { *; } --keepclasseswithmembers class com.mparticle.RoktEvent$* { *; } - - # Firebase and GMS CloudMessaging -dontwarn com.google.android.gms.cloudmessaging.** -dontwarn com.google.firebase.messaging.** @@ -292,4 +277,17 @@ } -keepclassmembers class * { @kotlin.Metadata ; -} \ No newline at end of file +} +-keepclassmembers class com.mparticle.Rokt { + (...); + void *(...); + void *$default(...); + ; +} + +-keep interface com.mparticle.MpRoktEventCallback { *; } +-keep interface com.mparticle.UnloadReasons { *; } +-keep class com.mparticle.UnloadReasons { *; } +-keep class com.mparticle.RoktEvent { *; } +-keepclassmembers class com.mparticle.RoktEvent { *; } +-keepclasseswithmembers class com.mparticle.RoktEvent$* { *; } From a44aa9a20fa20ff4abd5b39d7de94785660866d9 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Mon, 30 Jun 2025 17:02:59 -0400 Subject: [PATCH 05/11] Address review comments --- android-core/build.gradle | 4 ++-- android-kit-base/build.gradle | 4 ++-- gradle.properties | 1 + kit-plugin/build.gradle | 4 ++-- testutils/build.gradle | 6 +++--- tooling/android-plugin/build.gradle | 4 ++-- tooling/common/build.gradle | 6 +++--- 7 files changed, 15 insertions(+), 14 deletions(-) diff --git a/android-core/build.gradle b/android-core/build.gradle index a36256bb4..f3230652f 100644 --- a/android-core/build.gradle +++ b/android-core/build.gradle @@ -13,8 +13,8 @@ android { exclude 'META-INF/LICENSE' } compileOptions { - sourceCompatibility JavaVersion.VERSION_17 - targetCompatibility JavaVersion.VERSION_17 + sourceCompatibility JavaVersion.toVersion(JAVA_VERSION) + targetCompatibility JavaVersion.toVersion(JAVA_VERSION) } String url = '\"\"' diff --git a/android-kit-base/build.gradle b/android-kit-base/build.gradle index 12d479abe..2a1cdcc97 100644 --- a/android-kit-base/build.gradle +++ b/android-kit-base/build.gradle @@ -37,8 +37,8 @@ android { } compileOptions { - sourceCompatibility JavaVersion.VERSION_17 - targetCompatibility JavaVersion.VERSION_17 + sourceCompatibility JavaVersion.toVersion(JAVA_VERSION) + targetCompatibility JavaVersion.toVersion(JAVA_VERSION) } } diff --git a/gradle.properties b/gradle.properties index 0ddb20a81..2e22ec6d1 100644 --- a/gradle.properties +++ b/gradle.properties @@ -5,3 +5,4 @@ org.gradle.jvmargs=-Xmx2560m #-XX:ThreadStackSize=4096 -XX:CompilerThreadStackSize=4096 android.defaults.buildfeatures.buildconfig=true systemProp.org.gradle.kotlin.dsl.precompiled.accessors.strict=true +JAVA_VERSION=17 diff --git a/kit-plugin/build.gradle b/kit-plugin/build.gradle index d99a08bd2..1dd5660b1 100644 --- a/kit-plugin/build.gradle +++ b/kit-plugin/build.gradle @@ -14,8 +14,8 @@ dependencies { } compileGroovy { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 + sourceCompatibility = JavaVersion.toVersion(JAVA_VERSION) + targetCompatibility = JavaVersion.toVersion(JAVA_VERSION) } dependencies { diff --git a/testutils/build.gradle b/testutils/build.gradle index c0ac695af..2f34899c8 100644 --- a/testutils/build.gradle +++ b/testutils/build.gradle @@ -6,12 +6,12 @@ android { testNamespace 'com.mparticle.legacyTest' compileSdk 33 compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 // Set to your desired Java version - targetCompatibility = JavaVersion.VERSION_17 // Set to your desired Java version + sourceCompatibility = JavaVersion.toVersion(JAVA_VERSION) + targetCompatibility = JavaVersion.toVersion(JAVA_VERSION) } kotlinOptions { - jvmTarget = "17" // Should match the Java version above + jvmTarget = JAVA_VERSION } defaultConfig { //This is set to 21 to avoid slow multidex. diff --git a/tooling/android-plugin/build.gradle b/tooling/android-plugin/build.gradle index 6eb7f296d..1e5dce121 100644 --- a/tooling/android-plugin/build.gradle +++ b/tooling/android-plugin/build.gradle @@ -1,8 +1,8 @@ apply plugin: 'groovy' apply plugin: 'kotlin' -sourceCompatibility = JavaVersion.VERSION_17 -targetCompatibility = JavaVersion.VERSION_17 +sourceCompatibility = JavaVersion.toVersion(JAVA_VERSION) +targetCompatibility = JavaVersion.toVersion(JAVA_VERSION) ext { diff --git a/tooling/common/build.gradle b/tooling/common/build.gradle index 70ddb0bae..3969cecc4 100644 --- a/tooling/common/build.gradle +++ b/tooling/common/build.gradle @@ -16,10 +16,10 @@ dependencies { } java { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 + sourceCompatibility = JavaVersion.toVersion(JAVA_VERSION) + targetCompatibility = JavaVersion.toVersion(JAVA_VERSION) } kotlin { - jvmToolchain(17) + jvmToolchain(Integer.parseInt(JAVA_VERSION)) } \ No newline at end of file From a04ed71a1d21beb69924f81b26f264e910c45f57 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Wed, 2 Jul 2025 17:01:05 -0400 Subject: [PATCH 06/11] Address review comments --- android-core/proguard.pro | 5 ----- build.gradle | 2 +- gradle/wrapper/gradle-wrapper.properties | 2 +- .../src/main/groovy/com/mparticle/kits/KitPlugin.groovy | 6 +++--- 4 files changed, 5 insertions(+), 10 deletions(-) diff --git a/android-core/proguard.pro b/android-core/proguard.pro index 5b4ce1c11..dbb36cbe6 100644 --- a/android-core/proguard.pro +++ b/android-core/proguard.pro @@ -265,11 +265,6 @@ -keepclassmembers class * { private static synthetic *** lambda$*(...); } - -# Keep any classes referenced but not found during R8 minification --ignorewarnings --keep class ** { *; } - # Additional rules to prevent minification errors with Kotlin -keepattributes *Annotation*, InnerClasses, Signature, EnclosingMethod -keepclassmembers class kotlin.Metadata { diff --git a/build.gradle b/build.gradle index f7d9ed63b..5b1ebcbb2 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,6 @@ buildscript { ext.kotlin_version = '1.9.0' - ext.gradle_version = '8.1.0' + ext.gradle_version = '8.1.4' repositories { mavenCentral() diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 42defcc94..bdc9a83b1 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists 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 0e6320a02..c1a3db46d 100644 --- a/kit-plugin/src/main/groovy/com/mparticle/kits/KitPlugin.groovy +++ b/kit-plugin/src/main/groovy/com/mparticle/kits/KitPlugin.groovy @@ -140,9 +140,9 @@ class KitPlugin implements Plugin { } target.extensions.configure(SigningExtension) { signing -> - signing.required = { target.gradle.taskGraph.hasTask("publishReleasePublicationToMavenRepository") } - def signingKey = target.findProperty('signingKey') ?: System.getenv("mavenSigningKeyId") - def signingPassword = target.findProperty('signingPassword') ?: System.getenv("mavenSigningKeyPassword") + signing.required = { target.gradle.taskGraph.hasTask('publishReleasePublicationToMavenRepository') } + def signingKey = target.findProperty('signingKey') ?: System.getenv('mavenSigningKeyId') + def signingPassword = target.findProperty('signingPassword') ?: System.getenv('mavenSigningKeyPassword') if (signingKey && signingPassword) { signing.useInMemoryPgpKeys(target.property('signingKey'), target.property('signingPassword')) } From 72645f83d9acbb4a92f7c60c1815a3fd7b471c29 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Thu, 3 Jul 2025 17:55:27 -0400 Subject: [PATCH 07/11] Updated proguard rule for public method --- android-core/proguard.pro | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/android-core/proguard.pro b/android-core/proguard.pro index dbb36cbe6..d522ffa4a 100644 --- a/android-core/proguard.pro +++ b/android-core/proguard.pro @@ -273,11 +273,12 @@ -keepclassmembers class * { @kotlin.Metadata ; } --keepclassmembers class com.mparticle.Rokt { - (...); - void *(...); - void *$default(...); - ; + +-keep public class com.mparticle.Rokt { + public (...); + public void *(...); + public void *$default(...); + public ; } -keep interface com.mparticle.MpRoktEventCallback { *; } From ddeff0ea9866ac9d8a2228bda34f9f074bc44b9e Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Fri, 21 Nov 2025 16:06:55 -0500 Subject: [PATCH 08/11] upgrade ktlint plugin to version 13.0.0 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 5b1ebcbb2..5f4c97154 100644 --- a/build.gradle +++ b/build.gradle @@ -14,7 +14,7 @@ buildscript { plugins { id "org.sonarqube" version "3.5.0.2730" - id "org.jlleitschuh.gradle.ktlint" version "11.2.0" + id "org.jlleitschuh.gradle.ktlint" version "13.0.0" } sonarqube { From 3baa2de24666525f84ffdb562eaf5dac4eadfe4e Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Tue, 13 Jan 2026 13:20:03 -0500 Subject: [PATCH 09/11] fix lint issue with gradle 8 --- .../kotlin/com.mparticle/MParticleTest.kt | 15 +- .../com.mparticle/UploadEventKotlinTest.kt | 3 +- .../identity/IdentityApiOutgoingTest.kt | 15 +- .../MParticleIdentityClientImplTest.kt | 4 +- .../AppStateManagerInstrumentedTest.kt | 27 +- .../internal/BatchSessionInfoTest.kt | 3 +- .../internal/ConfigStalenessCheckTest.kt | 11 +- .../database/services/SessionServiceTest.kt | 11 +- .../PinningTestNetworkOptionsDisabled.kt | 17 +- .../PinningTestNetworkOptionsEnabled.kt | 17 +- .../KitsLoadedListenerConfiguration.kt | 4 +- .../mparticle/internal/SideloadedKitsUtils.kt | 5 +- .../internal/UserAudiencesRetriever.kt | 9 +- .../com/mparticle/MpRoktEventCallback.kt | 11 +- .../src/main/kotlin/com/mparticle/Rokt.kt | 22 +- .../main/kotlin/com/mparticle/RoktEvent.kt | 41 +- .../mparticle/TypedUserAttributeListener.kt | 6 +- .../main/kotlin/com/mparticle/WrapperSdk.kt | 10 +- .../kotlin/com/mparticle/audience/Audience.kt | 4 +- .../identity/UserAttributeListenerWrapper.kt | 10 +- .../com/mparticle/internal/AppStateManager.kt | 812 +++++++++--------- .../internal/ApplicationContextWrapper.kt | 46 +- .../com/mparticle/internal/Constants.kt | 8 +- .../com/mparticle/internal/CoreCallbacks.kt | 53 +- .../com/mparticle/internal/KitKatHelper.kt | 5 +- .../internal/MPLifecycleCallbackDelegate.kt | 14 +- .../mparticle/internal/MPLocationListener.kt | 10 +- .../com/mparticle/internal/UserStorage.kt | 57 +- .../internal/listeners/GraphListener.kt | 12 +- .../internal/listeners/InternalListener.kt | 108 +-- .../listeners/InternalListenerManager.kt | 96 +-- .../kotlin/com/mparticle/rokt/RoktConfig.kt | 11 +- .../rokt/RoktLayoutDimensionCallBack.kt | 7 +- .../kotlin/com/mparticle/rokt/RoktOptions.kt | 13 +- .../audience/BaseAudienceTaskTest.kt | 116 ++- .../mparticle/internal/AppStateManagerTest.kt | 43 +- .../internal/MParticleJSInterfaceTest.kt | 19 +- testutils/build.gradle | 5 +- 38 files changed, 675 insertions(+), 1005 deletions(-) diff --git a/android-core/src/androidTest/kotlin/com.mparticle/MParticleTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/MParticleTest.kt index c3ce58f58..dee94e65d 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/MParticleTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/MParticleTest.kt @@ -553,14 +553,13 @@ class MParticleTest : BaseCleanStartedEachTest() { } } - private fun getSharedPrefsContents(name: String): String = - try { - val prefs = mContext.getSharedPreferences(name, Context.MODE_PRIVATE) - """ + private fun getSharedPrefsContents(name: String): String = try { + val prefs = mContext.getSharedPreferences(name, Context.MODE_PRIVATE) + """ $name: ${JSONObject(prefs.all).toString(4)} - """.trimIndent() - } catch (e: JSONException) { - "error printing SharedPrefs :/" - } + """.trimIndent() + } catch (e: JSONException) { + "error printing SharedPrefs :/" + } } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/UploadEventKotlinTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/UploadEventKotlinTest.kt index aa738aa23..48c0d9739 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/UploadEventKotlinTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/UploadEventKotlinTest.kt @@ -81,7 +81,8 @@ class UploadEventKotlinTest : BaseCleanStartedEachTest() { .any { val eventMessageName = messagesArray.getJSONObject(it).optString("n") assertNotEquals("Should Not Upload", eventMessageName) - if (eventMessageName == "Should Upload 1" || eventMessageName == "Should Upload 2" || + if (eventMessageName == "Should Upload 1" || + eventMessageName == "Should Upload 2" || eventMessageName == "Should Upload 3" ) { numUploadedEvents++ diff --git a/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiOutgoingTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiOutgoingTest.kt index 585187c89..2ab2a8bdb 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiOutgoingTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/identity/IdentityApiOutgoingTest.kt @@ -16,8 +16,7 @@ class IdentityApiOutgoingTest : BaseCleanStartedEachTest() { Matcher(mServer.Endpoints().loginUrl).bodyMatch( object : IdentityMatcher() { - override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean = - mStartingMpid == identityRequest.previousMpid + override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean = mStartingMpid == identityRequest.previousMpid }, ), ) @@ -31,8 +30,7 @@ class IdentityApiOutgoingTest : BaseCleanStartedEachTest() { Matcher(mServer.Endpoints().loginUrl).bodyMatch( object : IdentityMatcher() { - override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean = - mStartingMpid == identityRequest.previousMpid + override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean = mStartingMpid == identityRequest.previousMpid }, ), ) @@ -46,8 +44,7 @@ class IdentityApiOutgoingTest : BaseCleanStartedEachTest() { Matcher(mServer.Endpoints().logoutUrl).bodyMatch( object : IdentityMatcher() { - override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean = - mStartingMpid == identityRequest.previousMpid + override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean = mStartingMpid == identityRequest.previousMpid }, ), ) @@ -61,8 +58,7 @@ class IdentityApiOutgoingTest : BaseCleanStartedEachTest() { Matcher(mServer.Endpoints().logoutUrl).bodyMatch( object : IdentityMatcher() { - override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean = - mStartingMpid == identityRequest.previousMpid + override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean = mStartingMpid == identityRequest.previousMpid }, ), ) @@ -88,8 +84,7 @@ class IdentityApiOutgoingTest : BaseCleanStartedEachTest() { Matcher(mServer.Endpoints().identifyUrl).bodyMatch( object : IdentityMatcher() { - override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean = - mStartingMpid == identityRequest.previousMpid + override fun isIdentityMatch(identityRequest: IdentityRequestBody): Boolean = mStartingMpid == identityRequest.previousMpid }, ), ) diff --git a/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleIdentityClientImplTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleIdentityClientImplTest.kt index e0fcfbb11..44f2b2c06 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleIdentityClientImplTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/identity/MParticleIdentityClientImplTest.kt @@ -249,8 +249,8 @@ class MParticleIdentityClientImplTest : BaseCleanStartedEachTest() { mparticle: Boolean, ) { if (connection.url - .toString() - .contains(MParticleIdentityClientImpl.MODIFY_PATH) + .toString() + .contains(MParticleIdentityClientImpl.MODIFY_PATH) ) { val jsonObject = payload?.let { JSONObject(it) } val changedIdentities = diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/AppStateManagerInstrumentedTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/AppStateManagerInstrumentedTest.kt index dc383532f..62978ec47 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/AppStateManagerInstrumentedTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/AppStateManagerInstrumentedTest.kt @@ -109,20 +109,19 @@ class AppStateManagerInstrumentedTest : BaseCleanStartedEachTest() { @Test @Throws(InterruptedException::class) - fun testOnApplicationForeground() = - runTest(StandardTestDispatcher()) { - val latch: CountDownLatch = MPLatch(2) - val kitManagerTester = KitManagerTester(mContext, latch) - com.mparticle.AccessUtils.setKitManager(kitManagerTester) - goToBackground() - Assert.assertNull(mAppStateManager?.currentActivity) - Thread.sleep(AppStateManager.ACTIVITY_DELAY + 100) - goToForeground() - Assert.assertNotNull(mAppStateManager?.currentActivity?.get()) - latch.await() - Assert.assertTrue(kitManagerTester.onApplicationBackgroundCalled) - Assert.assertTrue(kitManagerTester.onApplicationForegroundCalled) - } + fun testOnApplicationForeground() = runTest(StandardTestDispatcher()) { + val latch: CountDownLatch = MPLatch(2) + val kitManagerTester = KitManagerTester(mContext, latch) + com.mparticle.AccessUtils.setKitManager(kitManagerTester) + goToBackground() + Assert.assertNull(mAppStateManager?.currentActivity) + Thread.sleep(AppStateManager.ACTIVITY_DELAY + 100) + goToForeground() + Assert.assertNotNull(mAppStateManager?.currentActivity?.get()) + latch.await() + Assert.assertTrue(kitManagerTester.onApplicationBackgroundCalled) + Assert.assertTrue(kitManagerTester.onApplicationForegroundCalled) + } internal inner class KitManagerTester( context: Context?, 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 f3f4a18a4..fbe7c4c0c 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/BatchSessionInfoTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/BatchSessionInfoTest.kt @@ -13,8 +13,7 @@ import kotlin.test.assertNotEquals class BatchSessionInfoTest : BaseCleanStartedEachTest() { override fun useInMemoryDatabase() = true - override fun transformMParticleOptions(builder: MParticleOptions.Builder): MParticleOptions.Builder = - builder.logLevel(MParticle.LogLevel.INFO) + override fun transformMParticleOptions(builder: MParticleOptions.Builder): MParticleOptions.Builder = builder.logLevel(MParticle.LogLevel.INFO) /** * This test is in response to a bug where, when many messages (> 1 batch worth) diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigStalenessCheckTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigStalenessCheckTest.kt index 238c9d34a..eef48e108 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigStalenessCheckTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/ConfigStalenessCheckTest.kt @@ -222,12 +222,11 @@ class ConfigStalenessCheckTest : BaseCleanInstallEachTest() { assertEquals(config2.toString(), configManager.config) } - private fun randomJson(size: Int) = - (1..size) - .map { mRandomUtils.getAlphaNumericString(4) to mRandomUtils.getAlphaNumericString(6) } - .fold(JSONObject()) { init, attribute -> - init.apply { put(attribute.first, attribute.second) } - } + private fun randomJson(size: Int) = (1..size) + .map { mRandomUtils.getAlphaNumericString(4) to mRandomUtils.getAlphaNumericString(6) } + .fold(JSONObject()) { init, attribute -> + init.apply { put(attribute.first, attribute.second) } + } fun T?.assertNotNull(): T { assertNotNull(this) diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/SessionServiceTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/SessionServiceTest.kt index 4a3a5b849..80ab0de18 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/SessionServiceTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/services/SessionServiceTest.kt @@ -79,12 +79,11 @@ class SessionServiceTest : BaseMPServiceTest() { internal inner class MockMessageBatch( var id: Int, ) : MessageBatch() { - override fun equals(other: Any?): Boolean = - if (other is MockMessageBatch) { - id == other.id - } else { - super.equals(other) - } + override fun equals(other: Any?): Boolean = if (other is MockMessageBatch) { + id == other.id + } else { + super.equals(other) + } override fun hashCode(): Int = id } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsDisabled.kt b/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsDisabled.kt index ef221bb36..f1d2d48ea 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsDisabled.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsDisabled.kt @@ -6,13 +6,12 @@ import com.mparticle.MParticleOptions class PinningTestNetworkOptionsDisabled : PinningTest() { override fun shouldPin(): Boolean = true - override fun transformMParticleOptions(builder: MParticleOptions.Builder): MParticleOptions.Builder = - builder - .environment(MParticle.Environment.Production) - .networkOptions( - NetworkOptions - .builder() - .setPinningDisabledInDevelopment(true) - .build(), - ) + override fun transformMParticleOptions(builder: MParticleOptions.Builder): MParticleOptions.Builder = builder + .environment(MParticle.Environment.Production) + .networkOptions( + NetworkOptions + .builder() + .setPinningDisabledInDevelopment(true) + .build(), + ) } diff --git a/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsEnabled.kt b/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsEnabled.kt index 4ada9df2d..cc4e25402 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsEnabled.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/networking/PinningTestNetworkOptionsEnabled.kt @@ -6,13 +6,12 @@ import com.mparticle.MParticleOptions class PinningTestNetworkOptionsEnabled : PinningTest() { override fun shouldPin(): Boolean = false - override fun transformMParticleOptions(builder: MParticleOptions.Builder): MParticleOptions.Builder = - builder - .environment(MParticle.Environment.Development) - .networkOptions( - NetworkOptions - .builder() - .setPinningDisabledInDevelopment(true) - .build(), - ) + override fun transformMParticleOptions(builder: MParticleOptions.Builder): MParticleOptions.Builder = builder + .environment(MParticle.Environment.Development) + .networkOptions( + NetworkOptions + .builder() + .setPinningDisabledInDevelopment(true) + .build(), + ) } 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 4dd766900..d1792b096 100644 --- a/android-core/src/main/java/com/mparticle/internal/KitsLoadedListenerConfiguration.kt +++ b/android-core/src/main/java/com/mparticle/internal/KitsLoadedListenerConfiguration.kt @@ -2,9 +2,7 @@ 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) diff --git a/android-core/src/main/java/com/mparticle/internal/SideloadedKitsUtils.kt b/android-core/src/main/java/com/mparticle/internal/SideloadedKitsUtils.kt index e769fd02b..0cd2769ab 100644 --- a/android-core/src/main/java/com/mparticle/internal/SideloadedKitsUtils.kt +++ b/android-core/src/main/java/com/mparticle/internal/SideloadedKitsUtils.kt @@ -3,10 +3,7 @@ package com.mparticle.internal import org.json.JSONArray object SideloadedKitsUtils { - fun combineConfig( - kitConfig: JSONArray?, - kits: List, - ): JSONArray { + fun combineConfig(kitConfig: JSONArray?, kits: List): JSONArray { var results = JSONArray() var addedIds = mutableSetOf() kitConfig?.let { kitConfig -> diff --git a/android-core/src/main/java/com/mparticle/internal/UserAudiencesRetriever.kt b/android-core/src/main/java/com/mparticle/internal/UserAudiencesRetriever.kt index 111239185..f3b1d5c52 100644 --- a/android-core/src/main/java/com/mparticle/internal/UserAudiencesRetriever.kt +++ b/android-core/src/main/java/com/mparticle/internal/UserAudiencesRetriever.kt @@ -8,15 +8,10 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch -internal class UserAudiencesRetriever( - apiClient: MParticleApiClient, -) { +internal class UserAudiencesRetriever(apiClient: MParticleApiClient) { private val mApiClient: MParticleApiClient = apiClient - fun fetchAudiences( - mpId: Long, - featureFlagEnabled: Boolean, - ): AudienceTask { + fun fetchAudiences(mpId: Long, featureFlagEnabled: Boolean): AudienceTask { val task = BaseAudienceTask() if (featureFlagEnabled) { CoroutineScope(Dispatchers.IO).launch { diff --git a/android-core/src/main/kotlin/com/mparticle/MpRoktEventCallback.kt b/android-core/src/main/kotlin/com/mparticle/MpRoktEventCallback.kt index dbf07f66f..92318642c 100644 --- a/android-core/src/main/kotlin/com/mparticle/MpRoktEventCallback.kt +++ b/android-core/src/main/kotlin/com/mparticle/MpRoktEventCallback.kt @@ -79,11 +79,10 @@ enum class UnloadReasons { * @param value the name of the enum constant to look up * @return the corresponding UnloadReasons constant or UNKNOWN if no match is found */ - fun from(value: String): UnloadReasons = - try { - valueOf(value) - } catch (e: IllegalArgumentException) { - UNKNOWN - } + fun from(value: String): UnloadReasons = try { + valueOf(value) + } catch (e: IllegalArgumentException) { + UNKNOWN + } } } diff --git a/android-core/src/main/kotlin/com/mparticle/Rokt.kt b/android-core/src/main/kotlin/com/mparticle/Rokt.kt index 8c2146084..58a70543e 100644 --- a/android-core/src/main/kotlin/com/mparticle/Rokt.kt +++ b/android-core/src/main/kotlin/com/mparticle/Rokt.kt @@ -11,10 +11,7 @@ import kotlinx.coroutines.flow.flowOf import java.lang.ref.WeakReference @ApiClass -class Rokt internal constructor( - private val mConfigManager: ConfigManager, - private val mKitManager: KitManager, -) { +class Rokt internal constructor(private val mConfigManager: ConfigManager, private val mKitManager: KitManager) { @JvmOverloads fun selectPlacements( identifier: String, @@ -29,18 +26,13 @@ class Rokt internal constructor( } } - fun events(identifier: String): Flow = - if (mConfigManager.isEnabled) { - mKitManager.events(identifier) - } else { - flowOf() - } + fun events(identifier: String): Flow = if (mConfigManager.isEnabled) { + mKitManager.events(identifier) + } else { + flowOf() + } - fun purchaseFinalized( - placementId: String, - catalogItemId: String, - status: Boolean, - ) { + fun purchaseFinalized(placementId: String, catalogItemId: String, status: Boolean) { if (mConfigManager.isEnabled) { mKitManager.purchaseFinalized(placementId, catalogItemId, status) } diff --git a/android-core/src/main/kotlin/com/mparticle/RoktEvent.kt b/android-core/src/main/kotlin/com/mparticle/RoktEvent.kt index 9e265b01a..fa9d6aa85 100644 --- a/android-core/src/main/kotlin/com/mparticle/RoktEvent.kt +++ b/android-core/src/main/kotlin/com/mparticle/RoktEvent.kt @@ -17,84 +17,63 @@ sealed interface RoktEvent { * OfferEngagement event will be triggered if User engaged with the offer * @param placementId - identifier for the placement emitting the event */ - data class OfferEngagement( - val placementId: String, - ) : RoktEvent + data class OfferEngagement(val placementId: String) : RoktEvent /** * PositiveEngagement event will be triggered if User positively engaged with the offer * @param placementId - identifier for the placement emitting the event */ - data class PositiveEngagement( - val placementId: String, - ) : RoktEvent + data class PositiveEngagement(val placementId: String) : RoktEvent /** * FirstPositiveEngagement event will be triggered when the user positively engaged with the offer first time * @param placementId - identifier for the placement emitting the event */ - data class FirstPositiveEngagement( - val placementId: String, - ) : RoktEvent + data class FirstPositiveEngagement(val placementId: String) : RoktEvent /** * PlacementInteractive event will be triggered when placement has been rendered and is interactable * @param placementId - identifier for the placement emitting the event */ - data class PlacementInteractive( - val placementId: String, - ) : RoktEvent + data class PlacementInteractive(val placementId: String) : RoktEvent /** * PlacementReady event will be triggered when placement is ready to display but has not rendered content yet * @param placementId - identifier for the placement emitting the event */ - data class PlacementReady( - val placementId: String, - ) : RoktEvent + data class PlacementReady(val placementId: String) : RoktEvent /** * PlacementClosed event will be triggered when placement closes by user * @param placementId - identifier for the placement emitting the event */ - data class PlacementClosed( - val placementId: String, - ) : RoktEvent + data class PlacementClosed(val placementId: String) : RoktEvent /** * PlacementCompleted event will be triggered when the offer progression moves to the end and no more * offer to display * @param placementId - identifier for the placement emitting the event */ - data class PlacementCompleted( - val placementId: String, - ) : RoktEvent + data class PlacementCompleted(val placementId: String) : RoktEvent /** * PlacementFailure event will be triggered when placement could not be displayed due to some failure * @param placementId - optional identifier for the placement emitting the event */ - data class PlacementFailure( - val placementId: String? = null, - ) : RoktEvent + data class PlacementFailure(val placementId: String? = null) : RoktEvent /** * InitComplete event will be triggered when SDK has finished initialization * @param success - true if init was successful */ - data class InitComplete( - val success: Boolean, - ) : RoktEvent + data class InitComplete(val success: Boolean) : RoktEvent /** * OpenUrl event will be triggered when user clicks on a link and the link target is set to Passthrough * @param placementId - identifier for the placement emitting the event * @param url - url to open */ - data class OpenUrl( - val placementId: String, - val url: String, - ) : RoktEvent + data class OpenUrl(val placementId: String, val url: String) : RoktEvent /** * CartItemInstantPurchase event will be triggered when the catalog item purchase is initiated diff --git a/android-core/src/main/kotlin/com/mparticle/TypedUserAttributeListener.kt b/android-core/src/main/kotlin/com/mparticle/TypedUserAttributeListener.kt index e1750fb32..3ea111dfe 100644 --- a/android-core/src/main/kotlin/com/mparticle/TypedUserAttributeListener.kt +++ b/android-core/src/main/kotlin/com/mparticle/TypedUserAttributeListener.kt @@ -1,9 +1,5 @@ package com.mparticle interface TypedUserAttributeListener : UserAttributeListenerType { - fun onUserAttributesReceived( - userAttributes: Map, - userAttributeLists: Map?>, - mpid: Long, - ) + fun onUserAttributesReceived(userAttributes: Map, userAttributeLists: Map?>, mpid: Long) } diff --git a/android-core/src/main/kotlin/com/mparticle/WrapperSdk.kt b/android-core/src/main/kotlin/com/mparticle/WrapperSdk.kt index 15a3b7cb3..7cab96443 100644 --- a/android-core/src/main/kotlin/com/mparticle/WrapperSdk.kt +++ b/android-core/src/main/kotlin/com/mparticle/WrapperSdk.kt @@ -1,9 +1,6 @@ package com.mparticle -enum class WrapperSdk( - wrapperSdkId: Int, - wrapperSdkName: String, -) { +enum class WrapperSdk(wrapperSdkId: Int, wrapperSdkName: String) { WrapperNone(0, "None"), WrapperSdkUnity(1, "Unity"), WrapperSdkReactNative(2, "React Native"), @@ -18,7 +15,4 @@ enum class WrapperSdk( * @param version represents the configured version for the wrapper sdk. Will return null if * [WrapperSdk.WrapperNone] is set as the sdk wrapper */ -data class WrapperSdkVersion( - val sdk: WrapperSdk, - val version: String?, -) +data class WrapperSdkVersion(val sdk: WrapperSdk, val version: String?) diff --git a/android-core/src/main/kotlin/com/mparticle/audience/Audience.kt b/android-core/src/main/kotlin/com/mparticle/audience/Audience.kt index 4865dc140..41e21c951 100644 --- a/android-core/src/main/kotlin/com/mparticle/audience/Audience.kt +++ b/android-core/src/main/kotlin/com/mparticle/audience/Audience.kt @@ -1,5 +1,3 @@ package com.mparticle.audience -data class Audience( - val audienceID: String, -) +data class Audience(val audienceID: String) 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 9d88daf00..47836bdd4 100644 --- a/android-core/src/main/kotlin/com/mparticle/identity/UserAttributeListenerWrapper.kt +++ b/android-core/src/main/kotlin/com/mparticle/identity/UserAttributeListenerWrapper.kt @@ -4,14 +4,8 @@ import com.mparticle.TypedUserAttributeListener import com.mparticle.UserAttributeListener import com.mparticle.UserAttributeListenerType -class UserAttributeListenerWrapper( - val listener: UserAttributeListenerType, -) { - fun onUserAttributesReceived( - singles: Map?, - lists: Map?>?, - mpid: Long?, - ) { +class UserAttributeListenerWrapper(val listener: UserAttributeListenerType) { + fun onUserAttributesReceived(singles: Map?, lists: Map?>?, mpid: Long?) { when (listener) { is UserAttributeListener -> (singles ?: mutableMapOf()) diff --git a/android-core/src/main/kotlin/com/mparticle/internal/AppStateManager.kt b/android-core/src/main/kotlin/com/mparticle/internal/AppStateManager.kt index f05ca83ec..0387841f4 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/AppStateManager.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/AppStateManager.kt @@ -29,484 +29,468 @@ import java.util.concurrent.atomic.AtomicLong * This class is responsible for maintaining the session state by listening to the Activity lifecycle. */ open class AppStateManager - @JvmOverloads - constructor( - context: Context, - unitTesting: Boolean = false, - ) { - private var mConfigManager: ConfigManager? = null - var mContext: Context - private val mPreferences: SharedPreferences - open var session: InternalSession = InternalSession() - - open var currentActivity: WeakReference? = null - set - - var currentActivityName: String? = null - private set - var mLastStoppedTime: AtomicLong - - /** - * it can take some time between when an activity stops and when a new one (or the same one on a configuration change/rotation) - * starts again, so use this handler and ACTIVITY_DELAY to determine when we're *really" in the background - */ - @JvmField - var delayedBackgroundCheckHandler: Handler = Handler(Looper.getMainLooper()) - - /** - * Some providers need to know for the given session, how many 'interruptions' there were - how many - * times did the user leave and return prior to the session timing out. - */ - var mInterruptionCount: AtomicInteger = AtomicInteger(0) - - /** - * Important to determine foreground-time length for a given session. - * Uses the system-uptime clock to avoid devices which wonky clocks, or clocks - * that change while the app is running. - */ - private var mLastForegroundTime: Long = 0 - - var mUnitTesting: Boolean = false - private var mMessageManager: MessageManager? = null - open var launchUri: Uri? = null - set - var launchAction: String? = null - private set - - init { - mUnitTesting = unitTesting - mContext = context.applicationContext - mLastStoppedTime = AtomicLong(time) - mPreferences = context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE) - ConfigManager.addMpIdChangeListener { newMpid, previousMpid -> - if (session != null) { - session.addMpid(newMpid) - } +@JvmOverloads +constructor(context: Context, unitTesting: Boolean = false) { + private var mConfigManager: ConfigManager? = null + var mContext: Context + private val mPreferences: SharedPreferences + open var session: InternalSession = InternalSession() + + open var currentActivity: WeakReference? = null + set + + var currentActivityName: String? = null + private set + var mLastStoppedTime: AtomicLong + + /** + * it can take some time between when an activity stops and when a new one (or the same one on a configuration change/rotation) + * starts again, so use this handler and ACTIVITY_DELAY to determine when we're *really" in the background + */ + @JvmField + var delayedBackgroundCheckHandler: Handler = Handler(Looper.getMainLooper()) + + /** + * Some providers need to know for the given session, how many 'interruptions' there were - how many + * times did the user leave and return prior to the session timing out. + */ + var mInterruptionCount: AtomicInteger = AtomicInteger(0) + + /** + * Important to determine foreground-time length for a given session. + * Uses the system-uptime clock to avoid devices which wonky clocks, or clocks + * that change while the app is running. + */ + private var mLastForegroundTime: Long = 0 + + var mUnitTesting: Boolean = false + private var mMessageManager: MessageManager? = null + open var launchUri: Uri? = null + set + var launchAction: String? = null + private set + + init { + mUnitTesting = unitTesting + mContext = context.applicationContext + mLastStoppedTime = AtomicLong(time) + mPreferences = context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE) + ConfigManager.addMpIdChangeListener { newMpid, previousMpid -> + if (session != null) { + session.addMpid(newMpid) } } + } - fun init(apiVersion: Int) { - if (apiVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { - setupLifecycleCallbacks() - } + fun init(apiVersion: Int) { + if (apiVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { + setupLifecycleCallbacks() } + } - fun setConfigManager(manager: ConfigManager?) { - mConfigManager = manager - } + fun setConfigManager(manager: ConfigManager?) { + mConfigManager = manager + } - fun setMessageManager(manager: MessageManager?) { - mMessageManager = manager - } + fun setMessageManager(manager: MessageManager?) { + mMessageManager = manager + } - private val time: Long - get() = - if (mUnitTesting) { - System.currentTimeMillis() - } else { - SystemClock.elapsedRealtime() - } + private val time: Long + get() = + if (mUnitTesting) { + System.currentTimeMillis() + } else { + SystemClock.elapsedRealtime() + } - fun onActivityResumed(activity: Activity?) { - try { - currentActivityName = getActivityName(activity) + fun onActivityResumed(activity: Activity?) { + try { + currentActivityName = getActivityName(activity) - val interruptions = mInterruptionCount.get() - if (!mInitialized || !session.isActive) { - mInterruptionCount = AtomicInteger(0) + val interruptions = mInterruptionCount.get() + if (!mInitialized || !session.isActive) { + mInterruptionCount = AtomicInteger(0) + } + var previousSessionPackage: String? = null + var previousSessionUri: String? = null + var previousSessionParameters: String? = null + if (activity != null) { + val callingApplication = activity.callingActivity + if (callingApplication != null) { + previousSessionPackage = callingApplication.packageName } - var previousSessionPackage: String? = null - var previousSessionUri: String? = null - var previousSessionParameters: String? = null - if (activity != null) { - val callingApplication = activity.callingActivity - if (callingApplication != null) { - previousSessionPackage = callingApplication.packageName + if (activity.intent != null) { + previousSessionUri = activity.intent.dataString + if (launchUri == null) { + launchUri = activity.intent.data } - if (activity.intent != null) { - previousSessionUri = activity.intent.dataString - if (launchUri == null) { - launchUri = activity.intent.data - } - if (launchAction == null) { - launchAction = activity.intent.action - } - if (activity.intent.extras?.getBundle(Constants.External.APPLINK_KEY) != null) { - val parameters = JSONObject() - try { - parameters.put( - Constants.External.APPLINK_KEY, - MPUtility.wrapExtras( - activity.intent.extras?.getBundle(Constants.External.APPLINK_KEY), - ), - ) - } catch (e: Exception) { - Logger.error("Exception on onActivityResumed ") - } - previousSessionParameters = parameters.toString() + if (launchAction == null) { + launchAction = activity.intent.action + } + if (activity.intent.extras?.getBundle(Constants.External.APPLINK_KEY) != null) { + val parameters = JSONObject() + try { + parameters.put( + Constants.External.APPLINK_KEY, + MPUtility.wrapExtras( + activity.intent.extras?.getBundle(Constants.External.APPLINK_KEY), + ), + ) + } catch (e: Exception) { + Logger.error("Exception on onActivityResumed ") } + previousSessionParameters = parameters.toString() } } + } - session.updateBackgroundTime(mLastStoppedTime, time) + session.updateBackgroundTime(mLastStoppedTime, time) - var isBackToForeground = false - if (!mInitialized) { - initialize( - currentActivityName, - previousSessionUri, - previousSessionParameters, - previousSessionPackage, - ) - } else if (isBackgrounded() && mLastStoppedTime.get() > 0) { - isBackToForeground = true - mMessageManager?.postToMessageThread(CheckAdIdRunnable(mConfigManager)) - logStateTransition( - Constants.StateTransitionType.STATE_TRANS_FORE, - currentActivityName, - mLastStoppedTime.get() - mLastForegroundTime, - time - mLastStoppedTime.get(), - previousSessionUri, - previousSessionParameters, - previousSessionPackage, - interruptions, - ) - } - CoroutineScope(Dispatchers.IO).launch { - mConfigManager?.setPreviousAdId() - } - mLastForegroundTime = time + var isBackToForeground = false + if (!mInitialized) { + initialize( + currentActivityName, + previousSessionUri, + previousSessionParameters, + previousSessionPackage, + ) + } else if (isBackgrounded() && mLastStoppedTime.get() > 0) { + isBackToForeground = true + mMessageManager?.postToMessageThread(CheckAdIdRunnable(mConfigManager)) + logStateTransition( + Constants.StateTransitionType.STATE_TRANS_FORE, + currentActivityName, + mLastStoppedTime.get() - mLastForegroundTime, + time - mLastStoppedTime.get(), + previousSessionUri, + previousSessionParameters, + previousSessionPackage, + interruptions, + ) + } + CoroutineScope(Dispatchers.IO).launch { + mConfigManager?.setPreviousAdId() + } + mLastForegroundTime = time - if (currentActivity != null) { - currentActivity?.clear() - currentActivity = null - } - currentActivity = WeakReference(activity) + if (currentActivity != null) { + currentActivity?.clear() + currentActivity = null + } + currentActivity = WeakReference(activity) - val instance = MParticle.getInstance() - if (instance != null) { - if (instance.isAutoTrackingEnabled) { - currentActivityName?.let { - instance.logScreen(it) - } - } - if (isBackToForeground) { - instance.Internal().kitManager.onApplicationForeground() - Logger.debug("App foregrounded.") + val instance = MParticle.getInstance() + if (instance != null) { + if (instance.isAutoTrackingEnabled) { + currentActivityName?.let { + instance.logScreen(it) } - instance.Internal().kitManager.onActivityResumed(activity) } - } catch (e: Exception) { - Logger.verbose("Failed while trying to track activity resume: " + e.message) + if (isBackToForeground) { + instance.Internal().kitManager.onApplicationForeground() + Logger.debug("App foregrounded.") + } + instance.Internal().kitManager.onActivityResumed(activity) } + } catch (e: Exception) { + Logger.verbose("Failed while trying to track activity resume: " + e.message) } + } - fun onActivityPaused(activity: Activity) { - try { - mPreferences.edit().putBoolean(Constants.PrefKeys.CRASHED_IN_FOREGROUND, false).apply() - mLastStoppedTime = AtomicLong(time) - if (currentActivity != null && activity === currentActivity?.get()) { - currentActivity?.clear() - currentActivity = null - } + fun onActivityPaused(activity: Activity) { + try { + mPreferences.edit().putBoolean(Constants.PrefKeys.CRASHED_IN_FOREGROUND, false).apply() + mLastStoppedTime = AtomicLong(time) + if (currentActivity != null && activity === currentActivity?.get()) { + currentActivity?.clear() + currentActivity = null + } - delayedBackgroundCheckHandler.postDelayed( - { - try { - if (isBackgrounded()) { - checkSessionTimeout() - logBackgrounded() - } - } catch (e: Exception) { - Logger.error(e) + delayedBackgroundCheckHandler.postDelayed( + { + try { + if (isBackgrounded()) { + checkSessionTimeout() + logBackgrounded() } - }, - ACTIVITY_DELAY, - ) - - val instance = MParticle.getInstance() - if (instance != null) { - if (instance.isAutoTrackingEnabled) { - instance.logScreen( - MPEvent - .Builder(getActivityName(activity)) - .internalNavigationDirection(false) - .build(), - ) + } catch (e: Exception) { + e.printStackTrace() } - instance.Internal().kitManager.onActivityPaused(activity) + }, + ACTIVITY_DELAY, + ) + + val instance = MParticle.getInstance() + if (instance != null) { + if (instance.isAutoTrackingEnabled) { + instance.logScreen( + MPEvent + .Builder(getActivityName(activity)) + .internalNavigationDirection(false) + .build(), + ) } - } catch (e: Exception) { - Logger.verbose("Failed while trying to track activity pause: " + e.message) + instance.Internal().kitManager.onActivityPaused(activity) } + } catch (e: Exception) { + Logger.verbose("Failed while trying to track activity pause: " + e.message) } + } - fun ensureActiveSession() { - if (!mInitialized) { - initialize(null, null, null, null) - } - session.mLastEventTime = System.currentTimeMillis() - if (!session.isActive) { - newSession() - } else { - mMessageManager?.updateSessionEnd(this.session) - } + fun ensureActiveSession() { + if (!mInitialized) { + initialize(null, null, null, null) } - - fun logStateTransition( - transitionType: String?, - currentActivity: String?, - previousForegroundTime: Long, - suspendedTime: Long, - dataString: String?, - launchParameters: String?, - launchPackage: String?, - interruptions: Int, - ) { - if (mConfigManager?.isEnabled == true) { - ensureActiveSession() - mMessageManager?.logStateTransition( - transitionType, - currentActivity, - dataString, - launchParameters, - launchPackage, - previousForegroundTime, - suspendedTime, - interruptions, - ) - } + session.mLastEventTime = System.currentTimeMillis() + if (!session.isActive) { + newSession() + } else { + mMessageManager?.updateSessionEnd(this.session) } + } - fun logStateTransition( - transitionType: String?, - currentActivity: String?, - ) { - logStateTransition(transitionType, currentActivity, 0, 0, null, null, null, 0) + fun logStateTransition( + transitionType: String?, + currentActivity: String?, + previousForegroundTime: Long, + suspendedTime: Long, + dataString: String?, + launchParameters: String?, + launchPackage: String?, + interruptions: Int, + ) { + if (mConfigManager?.isEnabled == true) { + ensureActiveSession() + mMessageManager?.logStateTransition( + transitionType, + currentActivity, + dataString, + launchParameters, + launchPackage, + previousForegroundTime, + suspendedTime, + interruptions, + ) } + } - /** - * Creates a new session and generates the start-session message. - */ - private fun newSession() { - startSession() - mMessageManager?.startSession(session) - Logger.debug("Started new session") - mMessageManager?.startUploadLoop() - enableLocationTracking() - checkSessionTimeout() - } + fun logStateTransition(transitionType: String?, currentActivity: String?) { + logStateTransition(transitionType, currentActivity, 0, 0, null, null, null, 0) + } - private fun enableLocationTracking() { - if (mPreferences.contains(Constants.PrefKeys.LOCATION_PROVIDER)) { - val provider = mPreferences.getString(Constants.PrefKeys.LOCATION_PROVIDER, null) - val minTime = mPreferences.getLong(Constants.PrefKeys.LOCATION_MINTIME, 0) - val minDistance = mPreferences.getLong(Constants.PrefKeys.LOCATION_MINDISTANCE, 0) - if (provider != null && minTime > 0 && minDistance > 0) { - val instance = MParticle.getInstance() - instance?.enableLocationTracking(provider, minTime, minDistance) - } + /** + * Creates a new session and generates the start-session message. + */ + private fun newSession() { + startSession() + mMessageManager?.startSession(session) + Logger.debug("Started new session") + mMessageManager?.startUploadLoop() + enableLocationTracking() + checkSessionTimeout() + } + + private fun enableLocationTracking() { + if (mPreferences.contains(Constants.PrefKeys.LOCATION_PROVIDER)) { + val provider = mPreferences.getString(Constants.PrefKeys.LOCATION_PROVIDER, null) + val minTime = mPreferences.getLong(Constants.PrefKeys.LOCATION_MINTIME, 0) + val minDistance = mPreferences.getLong(Constants.PrefKeys.LOCATION_MINDISTANCE, 0) + if (provider != null && minTime > 0 && minDistance > 0) { + val instance = MParticle.getInstance() + instance?.enableLocationTracking(provider, minTime, minDistance) } } + } - fun shouldEndSession(): Boolean { - val instance = MParticle.getInstance() - return ( - 0L != session?.mSessionStartTime && - isBackgrounded() && - mConfigManager?.sessionTimeout?.let { session.isTimedOut(it) } == true && - (instance == null || !instance.Media().audioPlaying) + fun shouldEndSession(): Boolean { + val instance = MParticle.getInstance() + return ( + 0L != session?.mSessionStartTime && + isBackgrounded() && + mConfigManager?.sessionTimeout?.let { session.isTimedOut(it) } == true && + (instance == null || !instance.Media().audioPlaying) ) - } + } - private fun checkSessionTimeout() { - mConfigManager?.sessionTimeout?.toLong()?.let { - delayedBackgroundCheckHandler.postDelayed({ - if (shouldEndSession()) { - Logger.debug("Session timed out") - endSession() - } - }, it) - } + private fun checkSessionTimeout() { + mConfigManager?.sessionTimeout?.toLong()?.let { + delayedBackgroundCheckHandler.postDelayed({ + if (shouldEndSession()) { + Logger.debug("Session timed out") + endSession() + } + }, it) } + } - private fun initialize( - currentActivityName: String?, - previousSessionUri: String?, - previousSessionParameters: String?, - previousSessionPackage: String?, - ) { - mInitialized = true - logStateTransition( - Constants.StateTransitionType.STATE_TRANS_INIT, - currentActivityName, - 0, - 0, - previousSessionUri, - previousSessionParameters, - previousSessionPackage, - 0, - ) - } + private fun initialize( + currentActivityName: String?, + previousSessionUri: String?, + previousSessionParameters: String?, + previousSessionPackage: String?, + ) { + mInitialized = true + logStateTransition( + Constants.StateTransitionType.STATE_TRANS_INIT, + currentActivityName, + 0, + 0, + previousSessionUri, + previousSessionParameters, + previousSessionPackage, + 0, + ) + } - fun onActivityCreated( - activity: Activity?, - savedInstanceState: Bundle?, - ) { - val instance = MParticle.getInstance() - instance?.Internal()?.kitManager?.onActivityCreated(activity, savedInstanceState) - } + fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) { + val instance = MParticle.getInstance() + instance?.Internal()?.kitManager?.onActivityCreated(activity, savedInstanceState) + } - fun onActivityStarted(activity: Activity?) { - val instance = MParticle.getInstance() - instance?.Internal()?.kitManager?.onActivityStarted(activity) - } + fun onActivityStarted(activity: Activity?) { + val instance = MParticle.getInstance() + instance?.Internal()?.kitManager?.onActivityStarted(activity) + } - fun onActivityStopped(activity: Activity?) { - val instance = MParticle.getInstance() - instance?.Internal()?.kitManager?.onActivityStopped(activity) - } + fun onActivityStopped(activity: Activity?) { + val instance = MParticle.getInstance() + instance?.Internal()?.kitManager?.onActivityStopped(activity) + } - private fun logBackgrounded() { - val instance = MParticle.getInstance() - if (instance != null) { - logStateTransition(Constants.StateTransitionType.STATE_TRANS_BG, currentActivityName) - instance.Internal().kitManager.onApplicationBackground() - currentActivityName = null - Logger.debug("App backgrounded.") - mInterruptionCount.incrementAndGet() - } + private fun logBackgrounded() { + val instance = MParticle.getInstance() + if (instance != null) { + logStateTransition(Constants.StateTransitionType.STATE_TRANS_BG, currentActivityName) + instance.Internal().kitManager.onApplicationBackground() + currentActivityName = null + Logger.debug("App backgrounded.") + mInterruptionCount.incrementAndGet() } + } - @TargetApi(14) - private fun setupLifecycleCallbacks() { - (mContext as Application).registerActivityLifecycleCallbacks( - MPLifecycleCallbackDelegate( - this, - ), - ) - } + @TargetApi(14) + private fun setupLifecycleCallbacks() { + (mContext as Application).registerActivityLifecycleCallbacks( + MPLifecycleCallbackDelegate( + this, + ), + ) + } - open fun isBackgrounded(): Boolean = !mInitialized || (currentActivity == null && (time - mLastStoppedTime.get() >= ACTIVITY_DELAY)) + open fun isBackgrounded(): Boolean = !mInitialized || (currentActivity == null && (time - mLastStoppedTime.get() >= ACTIVITY_DELAY)) - open fun fetchSession(): InternalSession = session + open fun fetchSession(): InternalSession = session - fun endSession() { - Logger.debug("Ended session") - mMessageManager?.endSession(session) - disableLocationTracking() - session = InternalSession() - val instance = MParticle.getInstance() - instance?.Internal()?.kitManager?.onSessionEnd() - InternalListenerManager.listener.onSessionUpdated(session) - } + fun endSession() { + Logger.debug("Ended session") + mMessageManager?.endSession(session) + disableLocationTracking() + session = InternalSession() + val instance = MParticle.getInstance() + instance?.Internal()?.kitManager?.onSessionEnd() + InternalListenerManager.listener.onSessionUpdated(session) + } - private fun disableLocationTracking() { - val editor = mPreferences.edit() - editor - .remove(Constants.PrefKeys.LOCATION_PROVIDER) - .remove(Constants.PrefKeys.LOCATION_MINTIME) - .remove(Constants.PrefKeys.LOCATION_MINDISTANCE) - .apply() - val instance = MParticle.getInstance() - instance?.disableLocationTracking() - } + private fun disableLocationTracking() { + val editor = mPreferences.edit() + editor + .remove(Constants.PrefKeys.LOCATION_PROVIDER) + .remove(Constants.PrefKeys.LOCATION_MINTIME) + .remove(Constants.PrefKeys.LOCATION_MINDISTANCE) + .apply() + val instance = MParticle.getInstance() + instance?.disableLocationTracking() + } - fun startSession() { - session = InternalSession().start(mContext) - mLastStoppedTime = AtomicLong(time) - enableLocationTracking() - val instance = MParticle.getInstance() - instance?.Internal()?.kitManager?.onSessionStart() - } + fun startSession() { + session = InternalSession().start(mContext) + mLastStoppedTime = AtomicLong(time) + enableLocationTracking() + val instance = MParticle.getInstance() + instance?.Internal()?.kitManager?.onSessionStart() + } - fun onActivitySaveInstanceState( - activity: Activity?, - outState: Bundle?, - ) { - val instance = MParticle.getInstance() - instance?.Internal()?.kitManager?.onActivitySaveInstanceState(activity, outState) - } + fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) { + val instance = MParticle.getInstance() + instance?.Internal()?.kitManager?.onActivitySaveInstanceState(activity, outState) + } - fun onActivityDestroyed(activity: Activity?) { - val instance = MParticle.getInstance() - instance?.Internal()?.kitManager?.onActivityDestroyed(activity) - } + fun onActivityDestroyed(activity: Activity?) { + val instance = MParticle.getInstance() + instance?.Internal()?.kitManager?.onActivityDestroyed(activity) + } - internal class CheckAdIdRunnable( - var configManager: ConfigManager?, - ) : Runnable { - override fun run() { - val adIdInfo = - MPUtility.getAdIdInfo( - MParticle - .getInstance() - ?.Internal() - ?.appStateManager - ?.mContext, - ) - val currentAdId = - (if (adIdInfo == null) null else (if (adIdInfo.isLimitAdTrackingEnabled) null else adIdInfo.id)) - val previousAdId = configManager?.previousAdId - if (currentAdId != null && currentAdId != previousAdId) { - val instance = MParticle.getInstance() - if (instance != null) { - val user = instance.Identity().currentUser - if (user != null) { - instance.Identity().modify( - Builder(user) - .googleAdId(currentAdId, previousAdId) - .build(), + internal class CheckAdIdRunnable(var configManager: ConfigManager?) : Runnable { + override fun run() { + val adIdInfo = + MPUtility.getAdIdInfo( + MParticle + .getInstance() + ?.Internal() + ?.appStateManager + ?.mContext, + ) + val currentAdId = + (if (adIdInfo == null) null else (if (adIdInfo.isLimitAdTrackingEnabled) null else adIdInfo.id)) + val previousAdId = configManager?.previousAdId + if (currentAdId != null && currentAdId != previousAdId) { + val instance = MParticle.getInstance() + if (instance != null) { + val user = instance.Identity().currentUser + if (user != null) { + instance.Identity().modify( + Builder(user) + .googleAdId(currentAdId, previousAdId) + .build(), + ) + } else { + instance + .Identity() + .addIdentityStateListener( + object : SingleUserIdentificationCallback() { + override fun onUserFound(user: MParticleUser) { + instance.Identity().modify( + Builder(user) + .googleAdId(currentAdId, previousAdId) + .build(), + ) + } + }, ) - } else { - instance - .Identity() - .addIdentityStateListener( - object : SingleUserIdentificationCallback() { - override fun onUserFound(user: MParticleUser) { - instance.Identity().modify( - Builder(user) - .googleAdId(currentAdId, previousAdId) - .build(), - ) - } - }, - ) - } } } } } + } - internal class Builder : IdentityApiRequest.Builder { - constructor(user: MParticleUser?) : super(user) + internal class Builder : IdentityApiRequest.Builder { + constructor(user: MParticleUser?) : super(user) - constructor() : super() + constructor() : super() - public override fun googleAdId( - newGoogleAdId: String?, - oldGoogleAdId: String?, - ): IdentityApiRequest.Builder = super.googleAdId(newGoogleAdId, oldGoogleAdId) - } + public override fun googleAdId(newGoogleAdId: String?, oldGoogleAdId: String?): IdentityApiRequest.Builder = + super.googleAdId(newGoogleAdId, oldGoogleAdId) + } - companion object { - /** - * This boolean is important in determining if the app is running due to the user opening the app, - * or if we're running due to the reception of a Intent such as an FCM message. - */ - @JvmField - var mInitialized: Boolean = false - - const val ACTIVITY_DELAY: Long = 1000 - - /** - * Constants used by the messaging/push framework to describe the app state when various - * interactions occur (receive/show/tap). - */ - const val APP_STATE_FOREGROUND: String = "foreground" - const val APP_STATE_BACKGROUND: String = "background" - const val APP_STATE_NOTRUNNING: String = "not_running" - - private fun getActivityName(activity: Activity?): String = activity?.javaClass?.canonicalName ?: "" - } + companion object { + /** + * This boolean is important in determining if the app is running due to the user opening the app, + * or if we're running due to the reception of a Intent such as an FCM message. + */ + @JvmField + var mInitialized: Boolean = false + + const val ACTIVITY_DELAY: Long = 1000 + + /** + * Constants used by the messaging/push framework to describe the app state when various + * interactions occur (receive/show/tap). + */ + const val APP_STATE_FOREGROUND: String = "foreground" + const val APP_STATE_BACKGROUND: String = "background" + const val APP_STATE_NOTRUNNING: String = "not_running" + + private fun getActivityName(activity: Activity?): String = activity?.javaClass?.canonicalName ?: "" } +} diff --git a/android-core/src/main/kotlin/com/mparticle/internal/ApplicationContextWrapper.kt b/android-core/src/main/kotlin/com/mparticle/internal/ApplicationContextWrapper.kt index a2075719d..84613bbd5 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/ApplicationContextWrapper.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/ApplicationContextWrapper.kt @@ -16,9 +16,7 @@ import java.lang.ref.WeakReference import java.util.Collections import java.util.LinkedList -open class ApplicationContextWrapper( - private val mBaseApplication: Application, -) : Application() { +open class ApplicationContextWrapper(private val mBaseApplication: Application) : Application() { var isReplayActivityLifecycle: Boolean = true private var mRecord = true private var mActivityLifecycleCallbackRecorder: ActivityLifecycleCallbackRecorder? @@ -95,10 +93,7 @@ open class ApplicationContextWrapper( } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) - fun registerActivityLifecycleCallbacks( - callback: ActivityLifecycleCallbacks, - unitTesting: Boolean, - ) { + fun registerActivityLifecycleCallbacks(callback: ActivityLifecycleCallbacks, unitTesting: Boolean) { mBaseApplication.registerActivityLifecycleCallbacks(callback) val runnable = ReplayLifecycleCallbacksRunnable(callback) if (unitTesting) { @@ -152,27 +147,19 @@ open class ApplicationContextWrapper( val activityLifecycleCallbackRecorderInstance: ActivityLifecycleCallbackRecorder get() = ActivityLifecycleCallbackRecorder() - fun getLifeCycleEventInstance( - methodType: MethodType, - activityRef: WeakReference?, - ): LifeCycleEvent = LifeCycleEvent(methodType, activityRef) + fun getLifeCycleEventInstance(methodType: MethodType, activityRef: WeakReference?): LifeCycleEvent = + LifeCycleEvent(methodType, activityRef) - fun getLifeCycleEventInstance( - methodType: MethodType, - activityRef: WeakReference?, - bundle: Bundle?, - ): LifeCycleEvent = LifeCycleEvent(methodType, activityRef, bundle) + fun getLifeCycleEventInstance(methodType: MethodType, activityRef: WeakReference?, bundle: Bundle?): LifeCycleEvent = + LifeCycleEvent(methodType, activityRef, bundle) @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) inner class ActivityLifecycleCallbackRecorder : ActivityLifecycleCallbacks { var lifeCycleEvents: MutableList = Collections.synchronizedList(LinkedList()) - val MAX_LIST_SIZE: Int = 10 + val maxListSize: Int = 10 - override fun onActivityCreated( - activity: Activity, - savedInstanceState: Bundle?, - ) { + override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { recordedLifecycleList.add( LifeCycleEvent( MethodType.ON_CREATED, @@ -213,10 +200,7 @@ open class ApplicationContextWrapper( ) } - override fun onActivitySaveInstanceState( - activity: Activity, - outState: Bundle, - ) { + override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) { recordedLifecycleList.add( LifeCycleEvent( MethodType.ON_SAVE_INSTANCE_STATE, @@ -237,7 +221,7 @@ open class ApplicationContextWrapper( private val recordedLifecycleList: MutableList get() { - if (lifeCycleEvents.size > MAX_LIST_SIZE) { + if (lifeCycleEvents.size > maxListSize) { lifeCycleEvents.removeAt(0) return recordedLifecycleList } @@ -254,11 +238,7 @@ open class ApplicationContextWrapper( } } - inner class LifeCycleEvent( - val methodType: MethodType, - val activityRef: WeakReference?, - val bundle: Bundle?, - ) { + inner class LifeCycleEvent(val methodType: MethodType, val activityRef: WeakReference?, val bundle: Bundle?) { constructor( methodType: MethodType, activityRef: WeakReference?, @@ -279,9 +259,7 @@ open class ApplicationContextWrapper( } } - internal inner class ReplayLifecycleCallbacksRunnable( - var callback: ActivityLifecycleCallbacks, - ) : Runnable { + internal inner class ReplayLifecycleCallbacksRunnable(var callback: ActivityLifecycleCallbacks) : Runnable { @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) override fun run() { if (callback != null && mActivityLifecycleCallbackRecorder != null && isReplayActivityLifecycle) { diff --git a/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt b/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt index 81d6fc48e..14aade988 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/Constants.kt @@ -7,17 +7,17 @@ import com.mparticle.BuildConfig * */ object Constants { - private var MAX_MESSAGE_PER_BATCH = 100 + private var maxMessagePerBatchInternal = 100 @JvmStatic @set:VisibleForTesting var maxMessagePerBatch: Int - get() = MAX_MESSAGE_PER_BATCH + get() = maxMessagePerBatchInternal set(max) { if (max > 1) { - MAX_MESSAGE_PER_BATCH = max + maxMessagePerBatchInternal = max } else { - MAX_MESSAGE_PER_BATCH = 100 + maxMessagePerBatchInternal = 100 } } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/CoreCallbacks.kt b/android-core/src/main/kotlin/com/mparticle/internal/CoreCallbacks.kt index ba822656d..27dd7af3d 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/CoreCallbacks.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/CoreCallbacks.kt @@ -14,10 +14,7 @@ interface CoreCallbacks { fun isEnabled(): Boolean - fun setIntegrationAttributes( - kitId: Int, - integrationAttributes: Map, - ) + fun setIntegrationAttributes(kitId: Int, integrationAttributes: Map) fun getIntegrationAttributes(kitId: Int): Map? @@ -43,30 +40,15 @@ interface CoreCallbacks { interface KitListener { fun kitFound(kitId: Int) - fun kitConfigReceived( - kitId: Int, - configuration: String?, - ) + fun kitConfigReceived(kitId: Int, configuration: String?) - fun kitExcluded( - kitId: Int, - reason: String?, - ) + fun kitExcluded(kitId: Int, reason: String?) fun kitStarted(kitId: Int) - fun onKitApiCalled( - kitId: Int, - used: Boolean?, - vararg objects: Any?, - ) + fun onKitApiCalled(kitId: Int, used: Boolean?, vararg objects: Any?) - fun onKitApiCalled( - methodName: String?, - kitId: Int, - used: Boolean?, - vararg objects: Any?, - ) + fun onKitApiCalled(methodName: String?, kitId: Int, used: Boolean?, vararg objects: Any?) companion object { @JvmField @@ -74,30 +56,15 @@ interface CoreCallbacks { object : KitListener { override fun kitFound(kitId: Int) {} - override fun kitConfigReceived( - kitId: Int, - configuration: String?, - ) {} + override fun kitConfigReceived(kitId: Int, configuration: String?) {} - override fun kitExcluded( - kitId: Int, - reason: String?, - ) {} + override fun kitExcluded(kitId: Int, reason: String?) {} override fun kitStarted(kitId: Int) {} - override fun onKitApiCalled( - kitId: Int, - used: Boolean?, - vararg objects: Any?, - ) {} - - override fun onKitApiCalled( - methodName: String?, - kitId: Int, - used: Boolean?, - vararg objects: Any?, - ) {} + override fun onKitApiCalled(kitId: Int, used: Boolean?, vararg objects: Any?) {} + + override fun onKitApiCalled(methodName: String?, kitId: Int, used: Boolean?, vararg objects: Any?) {} } } } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/KitKatHelper.kt b/android-core/src/main/kotlin/com/mparticle/internal/KitKatHelper.kt index 2d86dd132..07fdbf11e 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/KitKatHelper.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/KitKatHelper.kt @@ -11,10 +11,7 @@ import org.json.JSONArray @TargetApi(19) object KitKatHelper { @JvmStatic - fun remove( - array: JSONArray, - index: Int, - ) { + fun remove(array: JSONArray, index: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { array.remove(index) } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/MPLifecycleCallbackDelegate.kt b/android-core/src/main/kotlin/com/mparticle/internal/MPLifecycleCallbackDelegate.kt index 27e81638d..cc5eac4e8 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/MPLifecycleCallbackDelegate.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/MPLifecycleCallbackDelegate.kt @@ -12,13 +12,8 @@ import android.os.Bundle * Separated into its own class to avoid annoying logcat messages on pre-ICS devices. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) -internal class MPLifecycleCallbackDelegate( - private val mStateManager: AppStateManager, -) : ActivityLifecycleCallbacks { - override fun onActivityCreated( - activity: Activity, - savedInstanceState: Bundle?, - ) { +internal class MPLifecycleCallbackDelegate(private val mStateManager: AppStateManager) : ActivityLifecycleCallbacks { + override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { mStateManager.onActivityCreated(activity, savedInstanceState) } @@ -38,10 +33,7 @@ internal class MPLifecycleCallbackDelegate( mStateManager.onActivityStopped(activity) } - override fun onActivitySaveInstanceState( - activity: Activity, - outState: Bundle, - ) { + override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) { mStateManager.onActivitySaveInstanceState(activity, outState) } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/MPLocationListener.kt b/android-core/src/main/kotlin/com/mparticle/internal/MPLocationListener.kt index ae0259ac9..3e46250c9 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/MPLocationListener.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/MPLocationListener.kt @@ -5,18 +5,12 @@ import android.location.LocationListener import android.os.Bundle import com.mparticle.MParticle -class MPLocationListener( - private val mParticle: MParticle, -) : LocationListener { +class MPLocationListener(private val mParticle: MParticle) : LocationListener { override fun onLocationChanged(location: Location) { mParticle.setLocation(location) } - override fun onStatusChanged( - provider: String, - status: Int, - extras: Bundle, - ) { + override fun onStatusChanged(provider: String, status: Int, extras: Bundle) { } override fun onProviderEnabled(provider: String) { diff --git a/android-core/src/main/kotlin/com/mparticle/internal/UserStorage.kt b/android-core/src/main/kotlin/com/mparticle/internal/UserStorage.kt index 91bde6d3f..8e4adaa46 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/UserStorage.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/UserStorage.kt @@ -11,18 +11,12 @@ import org.json.JSONObject import java.util.TreeSet import java.util.UUID -class UserStorage private constructor( - private val mContext: Context, - val mpid: Long, -) { +class UserStorage private constructor(private val mContext: Context, val mpid: Long) { private val mPreferences: SharedPreferences var messageManagerSharedPreferences: SharedPreferences - fun deleteUserConfig( - context: Context, - mpId: Long, - ): Boolean { + fun deleteUserConfig(context: Context, mpId: Long): Boolean { if (Build.VERSION.SDK_INT >= 24) { context.deleteSharedPreferences(getFileName(mpId)) } else { @@ -316,9 +310,7 @@ class UserStorage private constructor( * process will associate all current values covered by UserStorage to the current MPID, which should * be passed into the parameter "currentMpId". */ - private class SharedPreferencesMigrator( - context: Context, - ) { + private class SharedPreferencesMigrator(context: Context) { private val messageManagerSharedPreferences: SharedPreferences = context.getSharedPreferences(Constants.PREFS_FILE, Context.MODE_PRIVATE) private val configManagerSharedPreferences: SharedPreferences = @@ -500,16 +492,12 @@ class UserStorage private constructor( * @param context * @return */ - fun needsToMigrate(context: Context): Boolean = - getMParticleSharedPrefs(context).getBoolean( - NEEDS_TO_MIGRATE_TO_MPID_DEPENDENT, - false, - ) + fun needsToMigrate(context: Context): Boolean = getMParticleSharedPrefs(context).getBoolean( + NEEDS_TO_MIGRATE_TO_MPID_DEPENDENT, + false, + ) - fun setNeedsToMigrate( - context: Context, - needsToMigrate: Boolean, - ) { + fun setNeedsToMigrate(context: Context, needsToMigrate: Boolean) { getMParticleSharedPrefs(context) .edit() .putBoolean( @@ -554,23 +542,14 @@ class UserStorage private constructor( } @JvmStatic - fun create( - context: Context, - mpid: Long, - ): UserStorage = UserStorage(context, mpid) + fun create(context: Context, mpid: Long): UserStorage = UserStorage(context, mpid) @JvmStatic - fun setNeedsToMigrate( - context: Context, - needsToMigrate: Boolean, - ) { + fun setNeedsToMigrate(context: Context, needsToMigrate: Boolean) { SharedPreferencesMigrator.setNeedsToMigrate(context, needsToMigrate) } - private fun removeMpId( - context: Context, - mpid: Long, - ): Boolean { + private fun removeMpId(context: Context, mpid: Long): Boolean { val mpids = getMpIdSet(context) val removed = mpids.remove(mpid) setMpIds(context, mpids) @@ -600,10 +579,7 @@ class UserStorage private constructor( return mpIds } - private fun setMpIds( - context: Context, - mpIds: Set, - ) { + private fun setMpIds(context: Context, mpIds: Set) { val jsonArray = JSONArray() for (mpId in mpIds) { jsonArray.put(mpId) @@ -616,10 +592,9 @@ class UserStorage private constructor( private fun getFileName(mpId: Long): String = ConfigManager.PREFERENCES_FILE + ":" + mpId - private fun getMParticleSharedPrefs(context: Context): SharedPreferences = - context.getSharedPreferences( - ConfigManager.PREFERENCES_FILE, - Context.MODE_PRIVATE, - ) + private fun getMParticleSharedPrefs(context: Context): SharedPreferences = context.getSharedPreferences( + ConfigManager.PREFERENCES_FILE, + Context.MODE_PRIVATE, + ) } } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/listeners/GraphListener.kt b/android-core/src/main/kotlin/com/mparticle/internal/listeners/GraphListener.kt index c7797ba42..d7c2dc8c4 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/listeners/GraphListener.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/listeners/GraphListener.kt @@ -3,15 +3,7 @@ package com.mparticle.internal.listeners import android.os.Message interface GraphListener { - fun onCompositeObjects( - child: Any?, - parent: Any?, - ) + fun onCompositeObjects(child: Any?, parent: Any?) - fun onThreadMessage( - handlerName: String, - msg: Message?, - onNewThread: Boolean, - stackTrace: Array?, - ) + fun onThreadMessage(handlerName: String, msg: Message?, onNewThread: Boolean, stackTrace: Array?) } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListener.kt b/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListener.kt index 2fc42aa52..2d858bb10 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListener.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListener.kt @@ -28,11 +28,7 @@ interface InternalListener { * @param used whether the Kit's method returned ReportingMessages, or null if return type is void * @param objects the arguments supplied to the Kit */ - fun onKitApiCalled( - kitId: Int, - used: Boolean, - vararg objects: Any, - ) + fun onKitApiCalled(kitId: Int, used: Boolean, vararg objects: Any) /** * to be called when a Kit's API method is invoked, and the name of the Kit's method is different @@ -43,12 +39,7 @@ interface InternalListener { * @param used whether the Kit's method returned ReportingMessages, or null if return type is void * @param objects the arguments supplied to the Kit */ - fun onKitApiCalled( - methodName: String, - kitId: Int, - used: Boolean, - vararg objects: Any, - ) + fun onKitApiCalled(methodName: String, kitId: Int, used: Boolean, vararg objects: Any) /** * establishes a child-parent relationship between two objects. It is not necessary to call this @@ -57,10 +48,7 @@ interface InternalListener { * @param child the child object * @param parent the parent object */ - fun onCompositeObjects( - child: Any?, - parent: Any?, - ) + fun onCompositeObjects(child: Any?, parent: Any?) /** * denotes that an object is going to be passed to a new Thread, and is a candidate to be a "composite" @@ -70,11 +58,7 @@ interface InternalListener { * @param handlerName the Name of the Handler class, for example "com.mparticle.internal.MessageHandler" * @param msg the Message object */ - fun onThreadMessage( - handlerName: String, - msg: Message, - onNewThread: Boolean, - ) + fun onThreadMessage(handlerName: String, msg: Message, onNewThread: Boolean) /** * indicates that an entry has been stored in the Database @@ -84,11 +68,7 @@ interface InternalListener { * @param contentValues the ContentValues object to be inserted */ @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB) - fun onEntityStored( - rowId: Long, - tableName: String, - contentValues: ContentValues?, - ) + fun onEntityStored(rowId: Long, tableName: String, contentValues: ContentValues?) /** * indicates that a Network Request has been started @@ -98,12 +78,7 @@ interface InternalListener { * @param body the request body * @param objects any underlying objects that the request body is derived from, for example, an IdentityApiRequest instance */ - fun onNetworkRequestStarted( - type: SdkListener.Endpoint, - url: String, - body: JSONObject?, - vararg objects: Any, - ) + fun onNetworkRequestStarted(type: SdkListener.Endpoint, url: String, body: JSONObject?, vararg objects: Any) /** * indicates that a NetworkRequest has been finished @@ -112,12 +87,7 @@ interface InternalListener { * @param response the response body * @param responseCode the response code */ - fun onNetworkRequestFinished( - type: SdkListener.Endpoint, - url: String, - response: JSONObject?, - responseCode: Int, - ) + fun onNetworkRequestFinished(type: SdkListener.Endpoint, url: String, response: JSONObject?, responseCode: Int) /** * this should be called when the current Session changes, for example, it starts, stops or the @@ -140,10 +110,7 @@ interface InternalListener { * @param kitId * @param configuration */ - fun onKitConfigReceived( - kitId: Int, - configuration: String?, - ) + fun onKitConfigReceived(kitId: Int, configuration: String?) /** * indicates that a Kit was present, and a configuration was received for it, but it was not started, @@ -153,10 +120,7 @@ interface InternalListener { * @param kitId * @param reason */ - fun onKitExcluded( - kitId: Int, - reason: String?, - ) + fun onKitExcluded(kitId: Int, reason: String?) /** * indicates that a Kit successfully executed it's onKitCreate() method @@ -174,42 +138,19 @@ interface InternalListener { override fun onApiCalled(vararg objects: Any) { // stub } - override fun onKitApiCalled( - kitId: Int, - used: Boolean, - vararg objects: Any, - ) { // stub + override fun onKitApiCalled(kitId: Int, used: Boolean, vararg objects: Any) { // stub } - override fun onKitApiCalled( - methodName: String, - kitId: Int, - used: Boolean, - vararg objects: Any, - ) { // stub + override fun onKitApiCalled(methodName: String, kitId: Int, used: Boolean, vararg objects: Any) { // stub } - override fun onEntityStored( - rowId: Long, - tableName: String, - contentValues: ContentValues?, - ) { // stub + override fun onEntityStored(rowId: Long, tableName: String, contentValues: ContentValues?) { // stub } - override fun onNetworkRequestStarted( - type: SdkListener.Endpoint, - url: String, - body: JSONObject?, - vararg objects: Any, - ) { // stub + override fun onNetworkRequestStarted(type: SdkListener.Endpoint, url: String, body: JSONObject?, vararg objects: Any) { // stub } - override fun onNetworkRequestFinished( - type: SdkListener.Endpoint, - url: String, - response: JSONObject?, - responseCode: Int, - ) { // stub + override fun onNetworkRequestFinished(type: SdkListener.Endpoint, url: String, response: JSONObject?, responseCode: Int) { // stub } override fun onSessionUpdated(internalSession: InternalSession) { // stub @@ -218,16 +159,10 @@ interface InternalListener { override fun onKitDetected(kitId: Int) { // stub } - override fun onKitConfigReceived( - kitId: Int, - configuration: String?, - ) { // stub + override fun onKitConfigReceived(kitId: Int, configuration: String?) { // stub } - override fun onKitExcluded( - kitId: Int, - reason: String?, - ) { // stub + override fun onKitExcluded(kitId: Int, reason: String?) { // stub } override fun onKitStarted(kitId: Int) { // stub @@ -236,17 +171,10 @@ interface InternalListener { override fun onAliasRequestFinished(aliasResponse: AliasResponse?) { // stub } - override fun onCompositeObjects( - child: Any?, - parent: Any?, - ) { // stub + override fun onCompositeObjects(child: Any?, parent: Any?) { // stub } - override fun onThreadMessage( - handlerName: String, - msg: Message, - onNewThread: Boolean, - ) { // stub + override fun onThreadMessage(handlerName: String, msg: Message, onNewThread: Boolean) { // stub } } } diff --git a/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListenerManager.kt b/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListenerManager.kt index fbb42ba69..b6d1c3b9d 100644 --- a/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListenerManager.kt +++ b/android-core/src/main/kotlin/com/mparticle/internal/listeners/InternalListenerManager.kt @@ -14,9 +14,7 @@ import org.json.JSONObject import java.lang.ref.WeakReference import java.util.Locale -class InternalListenerManager private constructor( - private val context: Context, -) : InternalListener { +class InternalListenerManager private constructor(private val context: Context) : InternalListener { val sdkListeners: MutableList> = ArrayList() val graphListeners: MutableList> = ArrayList() private val thrown = false @@ -49,11 +47,7 @@ class InternalListenerManager private constructor( override fun onApiCalled(vararg objects: Any) { } - override fun onKitApiCalled( - kitId: Int, - used: Boolean, - vararg objects: Any, - ) { + override fun onKitApiCalled(kitId: Int, used: Boolean, vararg objects: Any) { val stackTrace = Thread.currentThread().stackTrace var methodName: String? = null for (i in stackTrace.indices) { @@ -65,22 +59,11 @@ class InternalListenerManager private constructor( methodName?.let { onKitApiCalled(stackTrace, it, kitId, used, *objects) } } - override fun onKitApiCalled( - methodName: String, - kitId: Int, - used: Boolean, - vararg objects: Any, - ) { + override fun onKitApiCalled(methodName: String, kitId: Int, used: Boolean, vararg objects: Any) { onKitApiCalled(Thread.currentThread().stackTrace, methodName, kitId, used, *objects) } - private fun onKitApiCalled( - stackTrace: Array, - methodName: String, - kitId: Int, - used: Boolean, - vararg objects: Any, - ) { + private fun onKitApiCalled(stackTrace: Array, methodName: String, kitId: Int, used: Boolean, vararg objects: Any) { var invokingApiMethodName: String? = null var kitManagerMethodName: String? = null var foundInternal = false @@ -121,10 +104,7 @@ class InternalListenerManager private constructor( ) } - override fun onCompositeObjects( - child: Any?, - parent: Any?, - ) { + override fun onCompositeObjects(child: Any?, parent: Any?) { broadcast( object : SdkGraphListenerRunnable { override fun run(listener: GraphListener) { @@ -134,11 +114,7 @@ class InternalListenerManager private constructor( ) } - override fun onThreadMessage( - handlerName: String, - msg: Message, - onNewThread: Boolean, - ) { + override fun onThreadMessage(handlerName: String, msg: Message, onNewThread: Boolean) { var stackTrace: Array? = null if (!onNewThread) { stackTrace = Thread.currentThread().stackTrace @@ -153,11 +129,7 @@ class InternalListenerManager private constructor( ) } - override fun onEntityStored( - primaryKey: Long, - tableName: String, - contentValues: ContentValues?, - ) { + override fun onEntityStored(primaryKey: Long, tableName: String, contentValues: ContentValues?) { onCompositeObjects(contentValues, tableName + primaryKey) val jsonObject = JSONObject() var table: SdkListener.DatabaseTable? = null @@ -190,12 +162,7 @@ class InternalListenerManager private constructor( ) } - override fun onNetworkRequestStarted( - type: SdkListener.Endpoint, - url: String, - body: JSONObject?, - vararg objects: Any, - ) { + override fun onNetworkRequestStarted(type: SdkListener.Endpoint, url: String, body: JSONObject?, vararg objects: Any) { for (obj in objects) { onCompositeObjects(obj, body) } @@ -212,12 +179,7 @@ class InternalListenerManager private constructor( ) } - override fun onNetworkRequestFinished( - type: SdkListener.Endpoint, - url: String, - response: JSONObject?, - responseCode: Int, - ) { + override fun onNetworkRequestFinished(type: SdkListener.Endpoint, url: String, response: JSONObject?, responseCode: Int) { broadcast( object : SdkListenerRunnable { override fun run(listener: SdkListener) { @@ -247,10 +209,7 @@ class InternalListenerManager private constructor( ) } - override fun onKitConfigReceived( - kitId: Int, - configuration: String?, - ) { + override fun onKitConfigReceived(kitId: Int, configuration: String?) { var jsonObject = JSONObject() try { jsonObject = JSONObject(configuration) @@ -266,10 +225,7 @@ class InternalListenerManager private constructor( ) } - override fun onKitExcluded( - kitId: Int, - reason: String?, - ) { + override fun onKitExcluded(kitId: Int, reason: String?) { broadcast( object : SdkListenerRunnable { override fun run(listener: SdkListener) { @@ -334,10 +290,7 @@ class InternalListenerManager private constructor( return getApiFormattedName(classNameString, element.methodName) } - private fun getClassName( - className: String, - methodName: String, - ): String { + private fun getClassName(className: String, methodName: String): String { val packageNames = className.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val simpleClassName = packageNames[packageNames.size - 1] @@ -368,12 +321,13 @@ class InternalListenerManager private constructor( private fun isObfuscated(className: String): Boolean = Character.isLowerCase(className.toCharArray()[0]) && className.length <= 3 - private fun isExternalApiInvocation(element: StackTraceElement): Boolean = - !element.className.startsWith("com.mparticle") || ( + private fun isExternalApiInvocation(element: StackTraceElement): Boolean = !element.className.startsWith("com.mparticle") || + ( element.className.startsWith( context.applicationContext.packageName, - ) && context.applicationContext.packageName.length > 1 - ) + ) && + context.applicationContext.packageName.length > 1 + ) private fun hasListeners(): Boolean = (instance?.sdkListeners?.size ?: 0) > 0 || (instance?.graphListeners?.size ?: 0) > 0 @@ -401,15 +355,11 @@ class InternalListenerManager private constructor( if (isEnabled) it else InternalListener.EMPTY } ?: InternalListener.EMPTY - fun getApiFormattedName( - className: String?, - methodName: String?, - ): String = - StringBuilder() - .append(className) - .append(".") - .append(methodName) - .append("()") - .toString() + fun getApiFormattedName(className: String?, methodName: String?): String = StringBuilder() + .append(className) + .append(".") + .append(methodName) + .append("()") + .toString() } } diff --git a/android-core/src/main/kotlin/com/mparticle/rokt/RoktConfig.kt b/android-core/src/main/kotlin/com/mparticle/rokt/RoktConfig.kt index 4507df1ea..28488a0e1 100644 --- a/android-core/src/main/kotlin/com/mparticle/rokt/RoktConfig.kt +++ b/android-core/src/main/kotlin/com/mparticle/rokt/RoktConfig.kt @@ -1,10 +1,6 @@ package com.mparticle.rokt -class RoktConfig private constructor( - val colorMode: ColorMode?, - val cacheConfig: CacheConfig?, - val edgeToEdgeDisplay: Boolean, -) { +class RoktConfig private constructor(val colorMode: ColorMode?, val cacheConfig: CacheConfig?, val edgeToEdgeDisplay: Boolean) { data class Builder( private var colorMode: ColorMode? = null, private var cacheConfig: CacheConfig? = null, @@ -22,10 +18,7 @@ class RoktConfig private constructor( enum class ColorMode { LIGHT, DARK, SYSTEM } } -class CacheConfig( - val cacheDurationInSeconds: Long = DEFAULT_CACHE_DURATION_SECS, - val cacheAttributes: Map? = null, -) { +class CacheConfig(val cacheDurationInSeconds: Long = DEFAULT_CACHE_DURATION_SECS, val cacheAttributes: Map? = null) { companion object { const val DEFAULT_CACHE_DURATION_SECS: Long = 90 * 60 } diff --git a/android-core/src/main/kotlin/com/mparticle/rokt/RoktLayoutDimensionCallBack.kt b/android-core/src/main/kotlin/com/mparticle/rokt/RoktLayoutDimensionCallBack.kt index e4d560c47..e22535c90 100644 --- a/android-core/src/main/kotlin/com/mparticle/rokt/RoktLayoutDimensionCallBack.kt +++ b/android-core/src/main/kotlin/com/mparticle/rokt/RoktLayoutDimensionCallBack.kt @@ -3,10 +3,5 @@ package com.mparticle.rokt interface RoktLayoutDimensionCallBack { fun onHeightChanged(height: Int) - fun onMarginChanged( - start: Int, - top: Int, - end: Int, - bottom: Int, - ) + fun onMarginChanged(start: Int, top: Int, end: Int, bottom: Int) } diff --git a/android-core/src/main/kotlin/com/mparticle/rokt/RoktOptions.kt b/android-core/src/main/kotlin/com/mparticle/rokt/RoktOptions.kt index f062ca794..7b4c8ebb8 100644 --- a/android-core/src/main/kotlin/com/mparticle/rokt/RoktOptions.kt +++ b/android-core/src/main/kotlin/com/mparticle/rokt/RoktOptions.kt @@ -1,11 +1,8 @@ package com.mparticle.rokt class RoktOptions - @JvmOverloads - constructor( - fontFilePathMap: Map = emptyMap(), - fontPostScriptNames: Set = emptySet(), - ) { - val fontFilePathMap: Map = fontFilePathMap.toMap() - val fontPostScriptNames: Set = fontPostScriptNames.toSet() - } +@JvmOverloads +constructor(fontFilePathMap: Map = emptyMap(), fontPostScriptNames: Set = emptySet()) { + val fontFilePathMap: Map = fontFilePathMap.toMap() + val fontPostScriptNames: Set = fontPostScriptNames.toSet() +} diff --git a/android-core/src/test/kotlin/com/mparticle/audience/BaseAudienceTaskTest.kt b/android-core/src/test/kotlin/com/mparticle/audience/BaseAudienceTaskTest.kt index 9aa6505fd..68a783c14 100644 --- a/android-core/src/test/kotlin/com/mparticle/audience/BaseAudienceTaskTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/audience/BaseAudienceTaskTest.kt @@ -29,70 +29,66 @@ class BaseAudienceTaskTest { } @Test - fun setFailedTest() = - runBlocking { - val listenerMock = mock(AudienceTaskFailureListener::class.java) - classInstance.addFailureListener(listenerMock) - classInstance.setFailed(AudienceResponse(401, "Unauthorized user")) - val failureListenersField: Field = - BaseAudienceTask::class.java.getDeclaredField("failureListeners") - failureListenersField.isAccessible = true - Assert.assertEquals(classInstance.isComplete(), true) - Assert.assertEquals(classInstance.isSuccessful(), false) - val failureListener = failureListenersField.get(classInstance) as MutableSet<*> - Assert.assertEquals(1, failureListener.size) - } + fun setFailedTest() = runBlocking { + val listenerMock = mock(AudienceTaskFailureListener::class.java) + classInstance.addFailureListener(listenerMock) + classInstance.setFailed(AudienceResponse(401, "Unauthorized user")) + val failureListenersField: Field = + BaseAudienceTask::class.java.getDeclaredField("failureListeners") + failureListenersField.isAccessible = true + Assert.assertEquals(classInstance.isComplete(), true) + Assert.assertEquals(classInstance.isSuccessful(), false) + val failureListener = failureListenersField.get(classInstance) as MutableSet<*> + Assert.assertEquals(1, failureListener.size) + } @Test - fun setFailedTest_when_Listener_not_register() = - runBlocking { - classInstance.setFailed(AudienceResponse(401, "Unauthorized user")) - val failureListenersField: Field = - BaseAudienceTask::class.java.getDeclaredField("failureListeners") - failureListenersField.isAccessible = true - Assert.assertEquals(classInstance.isComplete(), true) - Assert.assertEquals(classInstance.isSuccessful(), false) - val failureListener = failureListenersField.get(classInstance) as MutableSet<*> - Assert.assertEquals(0, failureListener.size) - } + fun setFailedTest_when_Listener_not_register() = runBlocking { + classInstance.setFailed(AudienceResponse(401, "Unauthorized user")) + val failureListenersField: Field = + BaseAudienceTask::class.java.getDeclaredField("failureListeners") + failureListenersField.isAccessible = true + Assert.assertEquals(classInstance.isComplete(), true) + Assert.assertEquals(classInstance.isSuccessful(), false) + val failureListener = failureListenersField.get(classInstance) as MutableSet<*> + Assert.assertEquals(0, failureListener.size) + } @Test - fun setSuccessfulTest() = - runBlocking { - val listenerMock = mock(AudienceTaskSuccessListener::class.java) - classInstance.addSuccessListener(listenerMock) - val sampleJson = - "{'dt':'ar','id':'54335128-0b2c-4089-a36d-8b456890dfe8','ct':1713390288601}" - classInstance.setSuccessful(AudienceResponse(200, sampleJson)) - val isCompletedField: Field = BaseAudienceTask::class.java.getDeclaredField("isCompleted") - isCompletedField.isAccessible = true - val isSuccessfulField: Field = BaseAudienceTask::class.java.getDeclaredField("isSuccessful") - isSuccessfulField.isAccessible = true - val successListenersField: Field = - BaseAudienceTask::class.java.getDeclaredField("successListeners") - successListenersField.isAccessible = true - Assert.assertEquals(classInstance.isComplete(), true) - Assert.assertEquals(classInstance.isSuccessful(), true) - val successListener = successListenersField.get(classInstance) as MutableSet<*> - Assert.assertEquals(1, successListener.size) - } + fun setSuccessfulTest() = runBlocking { + val listenerMock = mock(AudienceTaskSuccessListener::class.java) + classInstance.addSuccessListener(listenerMock) + val sampleJson = + "{'dt':'ar','id':'54335128-0b2c-4089-a36d-8b456890dfe8','ct':1713390288601}" + classInstance.setSuccessful(AudienceResponse(200, sampleJson)) + val isCompletedField: Field = BaseAudienceTask::class.java.getDeclaredField("isCompleted") + isCompletedField.isAccessible = true + val isSuccessfulField: Field = BaseAudienceTask::class.java.getDeclaredField("isSuccessful") + isSuccessfulField.isAccessible = true + val successListenersField: Field = + BaseAudienceTask::class.java.getDeclaredField("successListeners") + successListenersField.isAccessible = true + Assert.assertEquals(classInstance.isComplete(), true) + Assert.assertEquals(classInstance.isSuccessful(), true) + val successListener = successListenersField.get(classInstance) as MutableSet<*> + Assert.assertEquals(1, successListener.size) + } @Test - fun setSuccessfulTest_when_Listener_not_register() = - runBlocking { - val sampleJson = - "{'dt':'ar','id':'54335128-0b2c-4089-a36d-8b456890dfe8','ct':1713390288601}" - classInstance.setSuccessful(AudienceResponse(200, sampleJson)) - val isCompletedField: Field = BaseAudienceTask::class.java.getDeclaredField("isCompleted") - isCompletedField.isAccessible = true - val isSuccessfulField: Field = BaseAudienceTask::class.java.getDeclaredField("isSuccessful") - isSuccessfulField.isAccessible = true - val successListenersField: Field = - BaseAudienceTask::class.java.getDeclaredField("successListeners") - successListenersField.isAccessible = true - Assert.assertEquals(classInstance.isComplete(), true) - Assert.assertEquals(classInstance.isSuccessful(), true) - val successListener = successListenersField.get(classInstance) as MutableSet<*> - Assert.assertEquals(0, successListener.size) - } + fun setSuccessfulTest_when_Listener_not_register() = runBlocking { + val sampleJson = + "{'dt':'ar','id':'54335128-0b2c-4089-a36d-8b456890dfe8','ct':1713390288601}" + classInstance.setSuccessful(AudienceResponse(200, sampleJson)) + val isCompletedField: Field = BaseAudienceTask::class.java.getDeclaredField("isCompleted") + isCompletedField.isAccessible = true + val isSuccessfulField: Field = BaseAudienceTask::class.java.getDeclaredField("isSuccessful") + isSuccessfulField.isAccessible = true + val successListenersField: Field = + BaseAudienceTask::class.java.getDeclaredField("successListeners") + successListenersField.isAccessible = true + Assert.assertEquals(classInstance.isComplete(), true) + Assert.assertEquals(classInstance.isSuccessful(), true) + val successListener = successListenersField.get(classInstance) as MutableSet<*> + Assert.assertEquals(0, successListener.size) + } } diff --git a/android-core/src/test/kotlin/com/mparticle/internal/AppStateManagerTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/AppStateManagerTest.kt index 8edc5a2af..ff83c0cab 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/AppStateManagerTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/AppStateManagerTest.kt @@ -139,28 +139,27 @@ class AppStateManagerTest { */ @Test @Throws(Exception::class) - fun testSecondActivityStart() = - runTest(StandardTestDispatcher()) { - manager.onActivityPaused(activity) - Thread.sleep(1000) - Assert.assertEquals(true, manager.isBackgrounded()) - manager.onActivityResumed(activity) - val activity2 = - Mockito.mock( - Activity::class.java, - ) - val activity3 = - Mockito.mock( - Activity::class.java, - ) - manager.onActivityPaused(activity2) - manager.onActivityPaused(activity3) - Thread.sleep(1000) - Assert.assertEquals(false, manager.isBackgrounded()) - manager.onActivityPaused(activity) - Thread.sleep(1000) - Assert.assertEquals(true, manager.isBackgrounded()) - } + fun testSecondActivityStart() = runTest(StandardTestDispatcher()) { + manager.onActivityPaused(activity) + Thread.sleep(1000) + Assert.assertEquals(true, manager.isBackgrounded()) + manager.onActivityResumed(activity) + val activity2 = + Mockito.mock( + Activity::class.java, + ) + val activity3 = + Mockito.mock( + Activity::class.java, + ) + manager.onActivityPaused(activity2) + manager.onActivityPaused(activity3) + Thread.sleep(1000) + Assert.assertEquals(false, manager.isBackgrounded()) + manager.onActivityPaused(activity) + Thread.sleep(1000) + Assert.assertEquals(true, manager.isBackgrounded()) + } @Test @Throws(Exception::class) diff --git a/android-core/src/test/kotlin/com/mparticle/internal/MParticleJSInterfaceTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/MParticleJSInterfaceTest.kt index 716061712..328689329 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/MParticleJSInterfaceTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/MParticleJSInterfaceTest.kt @@ -354,14 +354,13 @@ class MParticleJSInterfaceTest : MParticleJSInterface() { fun isEqual( product1: Product, product2: Product?, - ): Boolean = - try { - val object1 = JSONObject(product1.toString()) - val object2 = JSONObject(product2.toString()) - object1.remove("act") - object2.remove("act") - object1.toString() == object2.toString() - } catch (ignore: JSONException) { - false - } + ): Boolean = try { + val object1 = JSONObject(product1.toString()) + val object2 = JSONObject(product2.toString()) + object1.remove("act") + object2.remove("act") + object1.toString() == object2.toString() + } catch (ignore: JSONException) { + false + } } diff --git a/testutils/build.gradle b/testutils/build.gradle index 2f34899c8..d63d180ca 100644 --- a/testutils/build.gradle +++ b/testutils/build.gradle @@ -51,6 +51,9 @@ android { sourceSets { main.java.srcDirs += 'src/main/kotlin' } + lint { + disable 'OutdatedLibrary' + } } dependencies { @@ -84,4 +87,4 @@ dependencies { boolean legacyTest() { return project.hasProperty('legacy') ? project.property('legacy') : false -} \ No newline at end of file +} From e93518fad64588c27c4f0fae3f003b280d873155 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Tue, 13 Jan 2026 14:08:34 -0500 Subject: [PATCH 10/11] fix line and gradle test issue --- .../internal/database/UpgradeVersionTest.kt | 10 +- .../database/tables/BreadcrumbTableTest.kt | 2 +- .../database/tables/MessageTableTest.kt | 6 +- .../database/tables/ReportingTableTest.kt | 2 +- .../database/tables/SessionTableTest.kt | 2 +- .../database/tables/UserAttributeTableTest.kt | 2 +- .../audience/AudienceResponseTest.kt | 12 +- .../internal/ApplicationContextWrapperTest.kt | 4 +- .../mparticle/internal/ConfigManagerTest.kt | 90 +++++------ .../mparticle/kits/ConfiguredKitOptions.kt | 3 +- .../kits/DataplanBlockingUserTests.kt | 52 ++++--- .../kits/testkits/CommerceListenerTestKit.kt | 5 +- .../kits/testkits/ListenerTestKit.kt | 10 +- .../com/mparticle/kits/MPSideloadedKit.kt | 20 +-- .../com/mparticle/kits/DataplanFilter.kt | 59 ++++---- .../kotlin/com/mparticle/kits/KitOptions.kt | 9 +- .../mparticle/kits/DataplanFilterImplTest.kt | 141 +++++++++--------- .../mparticle/kits/KitConfigurationTest.kt | 31 ++-- .../com/mparticle/kits/KitManagerImplTest.kt | 16 +- .../kits/mappings/CustomMappingTest.kt | 4 +- .../google/firebase/iid/FirebaseInstanceId.kt | 5 +- .../src/main/kotlin/com.mparticle/Utils.kt | 50 +++---- .../main/java/com/mparticle/tooling/Config.kt | 21 +-- .../mparticle/tooling/DataPlanningNodeApp.kt | 37 ++--- .../tooling/MockDataPlanningNodeApp.kt | 3 + .../main/java/com/mparticle/tooling/Utils.kt | 50 +++---- .../com/mparticle/tooling/ValidationResult.kt | 75 +++------- .../java/com/mparticle/lints/Extensions.kt | 28 ++-- .../com/mparticle/lints/VariableCollector.kt | 7 +- .../lints/basedetectors/CallScanner.kt | 47 +++--- .../lints/detectors/DataplanDetector.kt | 24 +-- .../lints/detectors/MpApiDetectorKt.kt | 132 +++++++--------- .../com/mparticle/lints/dtos/Constructor.kt | 6 +- .../com/mparticle/lints/dtos/Expression.kt | 4 +- .../com/mparticle/lints/dtos/MethodCall.kt | 7 +- .../com/mparticle/lints/dtos/StaticFactory.kt | 5 +- .../java/com/mparticle/lints/dtos/Value.kt | 19 +-- .../java/com/mparticle/lints/Constants.kt | 8 +- 38 files changed, 422 insertions(+), 586 deletions(-) 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 63a9716dd..33f0158fb 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 @@ -158,11 +158,11 @@ class UpgradeVersionTest : BaseTableTest() { val sqLiteOpenHelperWrapper: SQLiteOpenHelperWrapper = object : SQLiteOpenHelperWrapper { override fun onCreate(db: SQLiteDatabase) { - db.execSQL(SessionTableTest.old_CREATE_SESSION_DDL) - db.execSQL(MessageTableTest.old_no_mpid_CREATE_MESSAGES_DDL) - db.execSQL(BreadcrumbTableTest.old_CREATE_BREADCRUMBS_DDL) - db.execSQL(ReportingTableTest.old_CREATE_REPORTING_DDL) - db.execSQL(UserAttributeTableTest.old_CREATE_USER_ATTRIBUTES_DDL) + db.execSQL(SessionTableTest.OLD_CREATE_SESSION_DDL) + db.execSQL(MessageTableTest.OLD_NO_MPID_CREATE_MESSAGES_DDL) + db.execSQL(BreadcrumbTableTest.OLD_CREATE_BREADCRUMBS_DDL) + db.execSQL(ReportingTableTest.OLD_CREATE_REPORTING_DDL) + db.execSQL(UserAttributeTableTest.OLD_CREATE_USER_ATTRIBUTES_DDL) } override fun onUpgrade( diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BreadcrumbTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BreadcrumbTableTest.kt index deb678347..b1f910a67 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BreadcrumbTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/BreadcrumbTableTest.kt @@ -31,7 +31,7 @@ class BreadcrumbTableTest : BaseTableTest() { } companion object { - const val old_CREATE_BREADCRUMBS_DDL = + const val OLD_CREATE_BREADCRUMBS_DDL = "CREATE TABLE IF NOT EXISTS " + BreadcrumbTable.BreadcrumbTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + BreadcrumbTable.BreadcrumbTableColumns.SESSION_ID + " STRING NOT NULL, " + diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/MessageTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/MessageTableTest.kt index 018bb9aae..9ead6411d 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/MessageTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/MessageTableTest.kt @@ -38,7 +38,7 @@ class MessageTableTest : BaseTableTest() { runTest( object : SQLiteOpenHelperWrapper { override fun onCreate(database: SQLiteDatabase) { - database.execSQL(old_no_dp_CREATE_MESSAGES_DDL) + database.execSQL(OLD_NO_DP_CREATE_MESSAGES_DDL) } override fun onUpgrade( @@ -60,7 +60,7 @@ class MessageTableTest : BaseTableTest() { } companion object { - const val old_no_mpid_CREATE_MESSAGES_DDL = + const val OLD_NO_MPID_CREATE_MESSAGES_DDL = "CREATE TABLE IF NOT EXISTS " + MessageTable.MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + MessageTable.MessageTableColumns.SESSION_ID + " STRING NOT NULL, " + @@ -71,7 +71,7 @@ class MessageTableTest : BaseTableTest() { MessageTable.MessageTableColumns.MESSAGE_TYPE + " TEXT, " + MessageTable.MessageTableColumns.CF_UUID + " TEXT" + ");" - private const val old_no_dp_CREATE_MESSAGES_DDL = + private const val OLD_NO_DP_CREATE_MESSAGES_DDL = "CREATE TABLE IF NOT EXISTS " + MessageTable.MessageTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + MessageTable.MessageTableColumns.SESSION_ID + " STRING NOT NULL, " + diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/ReportingTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/ReportingTableTest.kt index 0915a2d2f..abf15c9dd 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/ReportingTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/ReportingTableTest.kt @@ -31,7 +31,7 @@ class ReportingTableTest : BaseTableTest() { } companion object { - const val old_CREATE_REPORTING_DDL = + const val OLD_CREATE_REPORTING_DDL = "CREATE TABLE IF NOT EXISTS " + ReportingTable.ReportingTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ReportingTable.ReportingTableColumns.MODULE_ID + " INTEGER NOT NULL, " + diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/SessionTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/SessionTableTest.kt index b1ec29a71..7219f1ee6 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/SessionTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/SessionTableTest.kt @@ -31,7 +31,7 @@ class SessionTableTest : BaseTableTest() { } companion object { - const val old_CREATE_SESSION_DDL = + const val OLD_CREATE_SESSION_DDL = "CREATE TABLE IF NOT EXISTS " + SessionTable.SessionTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + SessionTable.SessionTableColumns.SESSION_ID + " STRING NOT NULL, " + diff --git a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UserAttributeTableTest.kt b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UserAttributeTableTest.kt index 0aacff006..f4befd7e3 100644 --- a/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UserAttributeTableTest.kt +++ b/android-core/src/androidTest/kotlin/com.mparticle/internal/database/tables/UserAttributeTableTest.kt @@ -31,7 +31,7 @@ class UserAttributeTableTest : BaseTableTest() { } companion object { - const val old_CREATE_USER_ATTRIBUTES_DDL = + const val OLD_CREATE_USER_ATTRIBUTES_DDL = "CREATE TABLE IF NOT EXISTS " + UserAttributesTable.UserAttributesTableColumns.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + UserAttributesTable.UserAttributesTableColumns.ATTRIBUTE_KEY + " COLLATE NOCASE NOT NULL, " + diff --git a/android-core/src/test/kotlin/com/mparticle/audience/AudienceResponseTest.kt b/android-core/src/test/kotlin/com/mparticle/audience/AudienceResponseTest.kt index 3033a7f7b..a92a958ae 100644 --- a/android-core/src/test/kotlin/com/mparticle/audience/AudienceResponseTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/audience/AudienceResponseTest.kt @@ -94,21 +94,21 @@ class AudienceResponseTest { @Test fun getErrorTest() { - val error_Msg = "Unauthorized" - classInstance = AudienceResponse(401, error_Msg) + val errorMsg = "Unauthorized" + classInstance = AudienceResponse(401, errorMsg) val field: Field = AudienceResponse::class.java.getDeclaredField("code") field.isAccessible = true - Assert.assertEquals(error_Msg, classInstance.getError()) + Assert.assertEquals(errorMsg, classInstance.getError()) Assert.assertEquals(401, field.getInt(classInstance)) } @Test fun getErrorTest_When_Error_Is_Empty() { - val error_Msg = "" - classInstance = AudienceResponse(-1, error_Msg) + val errorMsg = "" + classInstance = AudienceResponse(-1, errorMsg) val field: Field = AudienceResponse::class.java.getDeclaredField("code") field.isAccessible = true - Assert.assertEquals(error_Msg, classInstance.getError()) + Assert.assertEquals(errorMsg, classInstance.getError()) Assert.assertEquals(-1, field.getInt(classInstance)) } } diff --git a/android-core/src/test/kotlin/com/mparticle/internal/ApplicationContextWrapperTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/ApplicationContextWrapperTest.kt index cbbbcb5c2..6d4756dbf 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/ApplicationContextWrapperTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/ApplicationContextWrapperTest.kt @@ -222,7 +222,7 @@ class ApplicationContextWrapperTest { @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) internal inner class ActivityLifecycleCallbackRecordTester : ActivityLifecycleCallbacks { var lifeCycleEvents = LinkedList() - var MAX_LIST_SIZE = 10 + var maxListSize = 10 override fun onActivityCreated( activity: Activity, @@ -297,7 +297,7 @@ class ApplicationContextWrapperTest { val recordedLifecycleList: LinkedList get() { - if (lifeCycleEvents.size > MAX_LIST_SIZE) { + if (lifeCycleEvents.size > maxListSize) { lifeCycleEvents.removeFirst() return recordedLifecycleList } diff --git a/android-core/src/test/kotlin/com/mparticle/internal/ConfigManagerTest.kt b/android-core/src/test/kotlin/com/mparticle/internal/ConfigManagerTest.kt index 47681f60a..92e252bc2 100644 --- a/android-core/src/test/kotlin/com/mparticle/internal/ConfigManagerTest.kt +++ b/android-core/src/test/kotlin/com/mparticle/internal/ConfigManagerTest.kt @@ -44,7 +44,7 @@ class ConfigManagerTest { ) mockMp = MockMParticle() MParticle.setInstance(mockMp) - manager.updateConfig(JSONObject(sampleConfig)) + manager.updateConfig(JSONObject(SAMPLE_CONFIG)) } @Test @@ -130,7 +130,7 @@ class ConfigManagerTest { @Test @Throws(Exception::class) fun testUpdateConfigWithReload() { - manager.updateConfig(JSONObject(sampleConfig)) + manager.updateConfig(JSONObject(SAMPLE_CONFIG)) manager.reloadCoreConfig(JSONObject()) val `object` = ConfigManager.sPreferences @@ -217,7 +217,7 @@ class ConfigManagerTest { Assert.assertFalse(manager.logUnhandledExceptions) manager.logUnhandledExceptions = true Assert.assertTrue(manager.logUnhandledExceptions) - val `object` = JSONObject(sampleConfig) + val `object` = JSONObject(SAMPLE_CONFIG) `object`.put(ConfigManager.KEY_UNHANDLED_EXCEPTIONS, "forcecatch") manager.updateConfig(`object`) manager.logUnhandledExceptions = false @@ -241,7 +241,7 @@ class ConfigManagerTest { @Test @Throws(Exception::class) fun testUploadInterval() { - val `object` = JSONObject(sampleConfig) + val `object` = JSONObject(SAMPLE_CONFIG) manager.setUploadInterval(987) Assert.assertEquals((1000 * 987).toLong(), manager.uploadInterval) `object`.put(ConfigManager.KEY_UPLOAD_INTERVAL, 110) @@ -260,7 +260,7 @@ class ConfigManagerTest { fun testSessionTimeout() { manager.sessionTimeout = 123 Assert.assertEquals((123 * 1000).toLong(), manager.sessionTimeout.toLong()) - val `object` = JSONObject(sampleConfig) + val `object` = JSONObject(SAMPLE_CONFIG) `object`.put(ConfigManager.KEY_SESSION_TIMEOUT, 123) manager.updateConfig(`object`) Assert.assertEquals((123 * 1000).toLong(), manager.sessionTimeout.toLong()) @@ -280,7 +280,7 @@ class ConfigManagerTest { Assert.assertTrue(manager.isEnabled) manager.setOptOut(true) Assert.assertFalse(manager.isEnabled) - val `object` = JSONObject(sampleConfig) + val `object` = JSONObject(SAMPLE_CONFIG) `object`.put(ConfigManager.KEY_OPT_OUT, true) manager.updateConfig(`object`) Assert.assertTrue(manager.isEnabled) @@ -341,7 +341,7 @@ class ConfigManagerTest { @Throws(Exception::class) fun testGetCurrentRampValue() { Assert.assertEquals(-1, manager.currentRampValue.toLong()) - val `object` = JSONObject(sampleConfig) + val `object` = JSONObject(SAMPLE_CONFIG) `object`.put(ConfigManager.KEY_RAMP, 43) manager.updateConfig(`object`) Assert.assertEquals(43, manager.currentRampValue.toLong()) @@ -398,47 +398,47 @@ class ConfigManagerTest { @Test @Throws(Exception::class) fun testSetNullIntegrationAttributes() { - Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) + Assert.assertFalse(ConfigManager.sPreferences.contains(attributes)) manager.setIntegrationAttributes(1, null) - Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) + Assert.assertFalse(ConfigManager.sPreferences.contains(attributes)) ConfigManager.sPreferences .edit() - .putString(ATTRIBUTES, "{\"1\":{\"test-key\":\"test-value\"}}") + .putString(attributes, "{\"1\":{\"test-key\":\"test-value\"}}") .apply() - Assert.assertTrue(ConfigManager.sPreferences.contains(ATTRIBUTES)) + Assert.assertTrue(ConfigManager.sPreferences.contains(attributes)) manager.setIntegrationAttributes(1, null) - Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) + Assert.assertFalse(ConfigManager.sPreferences.contains(attributes)) } @Test @Throws(Exception::class) fun testSetEmptyIntegrationAttributes() { - Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) - val attributes: Map = HashMap() - manager.setIntegrationAttributes(1, attributes) - Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) + Assert.assertFalse(ConfigManager.sPreferences.contains(attributes)) + val testAttributes: Map = HashMap() + manager.setIntegrationAttributes(1, testAttributes) + Assert.assertFalse(ConfigManager.sPreferences.contains(attributes)) ConfigManager.sPreferences .edit() - .putString(ATTRIBUTES, "{\"1\":{\"test-key\":\"test-value\"}}") + .putString(attributes, "{\"1\":{\"test-key\":\"test-value\"}}") .apply() - Assert.assertTrue(ConfigManager.sPreferences.contains(ATTRIBUTES)) - manager.setIntegrationAttributes(1, attributes) - Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) + Assert.assertTrue(ConfigManager.sPreferences.contains(attributes)) + manager.setIntegrationAttributes(1, testAttributes) + Assert.assertFalse(ConfigManager.sPreferences.contains(attributes)) } @Test @Throws(Exception::class) fun testSetNonEmptyIntegrationAttributes() { - Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) - val attributes: MutableMap = HashMap() - attributes["test-key"] = "value 2" - manager.setIntegrationAttributes(1, attributes) - attributes["test-key"] = "value 3" - manager.setIntegrationAttributes(12, attributes) + Assert.assertFalse(ConfigManager.sPreferences.contains(attributes)) + val testAttributes: MutableMap = HashMap() + testAttributes["test-key"] = "value 2" + manager.setIntegrationAttributes(1, testAttributes) + testAttributes["test-key"] = "value 3" + manager.setIntegrationAttributes(12, testAttributes) Assert.assertEquals( "{\"1\":{\"test-key\":\"value 2\"},\"12\":{\"test-key\":\"value 3\"}}", ConfigManager.sPreferences.getString( - ATTRIBUTES, + attributes, null, ), ) @@ -447,23 +447,23 @@ class ConfigManagerTest { @Test @Throws(Exception::class) fun testGetKitIntegrationAttributes() { - Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) + Assert.assertFalse(ConfigManager.sPreferences.contains(attributes)) Assert.assertEquals(0, manager.getIntegrationAttributes(1).size.toLong()) ConfigManager.sPreferences .edit() .putString( - ATTRIBUTES, + attributes, "{\"1\":{\"test-key\":\"value 2\"},\"12\":{\"test-key\":\"value 3\"}}", ).apply() - var attributes = manager.getIntegrationAttributes(1) - Assert.assertEquals(1, attributes.size.toLong()) - Assert.assertEquals("value 2", attributes["test-key"]) - attributes = manager.getIntegrationAttributes(12) - Assert.assertEquals(1, attributes.size.toLong()) - Assert.assertEquals("value 3", attributes["test-key"]) + var testAttributes = manager.getIntegrationAttributes(1) + Assert.assertEquals(1, testAttributes.size.toLong()) + Assert.assertEquals("value 2", testAttributes["test-key"]) + testAttributes = manager.getIntegrationAttributes(12) + Assert.assertEquals(1, testAttributes.size.toLong()) + Assert.assertEquals("value 3", testAttributes["test-key"]) ConfigManager.sPreferences .edit() - .remove(ATTRIBUTES) + .remove(attributes) .apply() Assert.assertEquals(0, manager.getIntegrationAttributes(1).size.toLong()) Assert.assertEquals(0, manager.getIntegrationAttributes(12).size.toLong()) @@ -472,21 +472,21 @@ class ConfigManagerTest { @Test @Throws(Exception::class) fun testGetAllIntegrationAttributes() { - Assert.assertFalse(ConfigManager.sPreferences.contains(ATTRIBUTES)) + Assert.assertFalse(ConfigManager.sPreferences.contains(attributes)) Assert.assertNull(manager.integrationAttributes) ConfigManager.sPreferences .edit() .putString( - ATTRIBUTES, + attributes, "{\"1\":{\"test-key\":\"value 2\"},\"12\":{\"test-key\":\"value 3\"}}", ).apply() - val attributes = manager.integrationAttributes - Assert.assertEquals(2, attributes.length().toLong()) - Assert.assertEquals("value 2", attributes.getJSONObject("1")["test-key"]) - Assert.assertEquals("value 3", attributes.getJSONObject("12")["test-key"]) + val testAttributes = manager.integrationAttributes + Assert.assertEquals(2, testAttributes.length().toLong()) + Assert.assertEquals("value 2", testAttributes.getJSONObject("1")["test-key"]) + Assert.assertEquals("value 3", testAttributes.getJSONObject("12")["test-key"]) ConfigManager.sPreferences .edit() - .remove(ATTRIBUTES) + .remove(attributes) .apply() Assert.assertNull(manager.integrationAttributes) } @@ -730,8 +730,8 @@ class ConfigManagerTest { } companion object { - private const val sampleConfig = + private const val SAMPLE_CONFIG = "{ \"dt\":\"ac\", \"id\":\"5b7b8073-852b-47c2-9b89-c4bc66e3bd55\", \"ct\":1428030730685, \"dbg\":false, \"cue\":\"appdefined\", \"pmk\":[ \"mp_message\", \"com.urbanairship.push.ALERT\", \"alert\", \"a\", \"message\" ], \"cnp\":\"appdefined\", \"soc\":0, \"oo\":false, \"tri\" : { \"mm\" : [{ \"dt\" : \"x\", \"eh\" : true } ], \"evts\" : [1217787541, 2, 3] }, \"eks\":[ { \"id\":64, \"as\":{ \"clientId\":\"8FMBElARYl9ZtgwYIN5sZA==\", \"surveyId\":\"android_app\", \"sendAppVersion\":\"True\", \"rootUrl\":\"http://survey.foreseeresults.com/survey/display\" }, \"hs\":{ \"et\":{ \"57\":0, \"49\":0, \"55\":0, \"52\":0, \"53\":0, \"50\":0, \"56\":0, \"51\":0, \"54\":0, \"48\":0 }, \"ec\":{ \"609391310\":0, \"-1282670145\":0, \"2138942058\":0, \"-1262630649\":0, \"-877324321\":0, \"1700497048\":0, \"1611158813\":0, \"1900204162\":0, \"-998867355\":0, \"-1758179958\":0, \"-994832826\":0, \"1598473606\":0, \"-2106320589\":0 }, \"ea\":{ \"343635109\":0, \"1162787110\":0, \"-427055400\":0, \"-1285822129\":0, \"1699530232\":0 }, \"svec\":{ \"-725356351\":0, \"-1992427723\":0, \"751512662\":0, \"-118381281\":0, \"-171137512\":0, \"-2036479142\":0, \"-1338304551\":0, \"1003167705\":0, \"1046650497\":0, \"1919407518\":0, \"-1326325184\":0, \"480870493\":0, \"-1087232483\":0, \"-725540438\":0, \"-461793000\":0, \"1935019626\":0, \"76381608\":0, \"273797382\":0, \"-948909976\":0, \"-348193740\":0, \"-685370074\":0, \"-849874419\":0, \"2074021738\":0, \"-767572488\":0, \"-1091433459\":0, \"1671688881\":0, \"1304651793\":0, \"1299738196\":0, \"326063875\":0, \"296835202\":0, \"268236000\":0, \"1708308839\":0, \"101093345\":0, \"-652558691\":0, \"-1613021771\":0, \"1106318256\":0, \"-473874363\":0, \"-1267780435\":0, \"486732621\":0, \"1855792002\":0, \"-881258627\":0, \"698731249\":0, \"1510155838\":0, \"1119638805\":0, \"479337352\":0, \"1312099430\":0, \"1712783405\":0, \"-459721027\":0, \"-214402990\":0, \"617910950\":0, \"428901717\":0, \"-201124647\":0, \"940674176\":0, \"1632668193\":0, \"338835860\":0, \"879890181\":0, \"1667730064\":0 } } } ], \"lsv\":\"2.1.4\", \"pio\":30 }" - var ATTRIBUTES = "mp::integrationattributes" + var attributes = "mp::integrationattributes" } } 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 2deb4ce22..ed0862473 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 @@ -21,5 +21,4 @@ class ConfiguredKitOptions : KitOptions() { } } -fun ConfiguredKitOptions(configuredKitOptions: ConfiguredKitOptions.() -> Unit): ConfiguredKitOptions = - ConfiguredKitOptions().apply(configuredKitOptions) +fun ConfiguredKitOptions(configuredKitOptions: ConfiguredKitOptions.() -> Unit): ConfiguredKitOptions = ConfiguredKitOptions().apply(configuredKitOptions) 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 69f488624..f54545bc2 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 @@ -338,32 +338,30 @@ class DataplanBlockingUserTests : BaseKitOptionsTest() { // assertEquals(allowedIdentities + blockedIdentities, MParticle.getInstance()?.Identity()?.currentUser?.userIdentities) // } - private fun getRandomDataplanEventKey(): DataplanFilterImpl.DataPoint = - when (Random.Default.nextInt(0, 5)) { - 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(), - ) - 4 -> DataplanFilterImpl.DataPoint(DataplanFilterImpl.PRODUCT_IMPRESSION_KEY) - else -> throw IllegalArgumentException("messed this implementation up :/") - } + private fun getRandomDataplanEventKey(): DataplanFilterImpl.DataPoint = when (Random.Default.nextInt(0, 5)) { + 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(), + ) + 4 -> DataplanFilterImpl.DataPoint(DataplanFilterImpl.PRODUCT_IMPRESSION_KEY) + else -> throw IllegalArgumentException("messed this implementation up :/") + } - private fun getRandomDataplanPoints(): MutableMap> = - (0..Random.Default.nextInt(0, 10)) - .associate { - getRandomDataplanEventKey().toString() to randomAttributes().keys.toHashSet() - }.toMutableMap() + private fun getRandomDataplanPoints(): MutableMap> = (0..Random.Default.nextInt(0, 10)) + .associate { + getRandomDataplanEventKey().toString() to randomAttributes().keys.toHashSet() + }.toMutableMap() } 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 c59f095a4..a9bd33edc 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 @@ -19,7 +19,6 @@ class CommerceListenerTestKit : valueTotal: BigDecimal?, eventName: String?, contextInfo: Map?, - ): List = - logLtvIncrease?.invoke(valueIncreased, valueTotal, eventName, contextInfo) - ?: listOf() + ): List = logLtvIncrease?.invoke(valueIncreased, valueTotal, eventName, contextInfo) + ?: listOf() } 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 bb3b41b0a..1f617cacd 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 @@ -17,14 +17,12 @@ abstract class ListenerTestKit : BaseTestKit() { override fun getName() = getName?.invoke() ?: "Test Kit thing" - override fun setOptOut(optedOut: Boolean) = - setOptOut?.invoke(optedOut) - ?: listOf() + override fun setOptOut(optedOut: Boolean) = setOptOut?.invoke(optedOut) + ?: listOf() override fun onKitCreate( settings: Map?, context: Context, - ): List = - onKitCreate?.invoke(settings, context) - ?: listOf() + ): List = onKitCreate?.invoke(settings, context) + ?: listOf() } diff --git a/android-kit-base/src/main/java/com/mparticle/kits/MPSideloadedKit.kt b/android-kit-base/src/main/java/com/mparticle/kits/MPSideloadedKit.kt index 8747ce4df..3ab1cdbf5 100644 --- a/android-kit-base/src/main/java/com/mparticle/kits/MPSideloadedKit.kt +++ b/android-kit-base/src/main/java/com/mparticle/kits/MPSideloadedKit.kt @@ -4,9 +4,8 @@ import android.content.Context import com.mparticle.internal.SideloadedKit import org.json.JSONObject -abstract class MPSideloadedKit( - val kitId: Int, -) : KitIntegration(), +abstract class MPSideloadedKit(val kitId: Int) : + KitIntegration(), SideloadedKit { companion object { const val MIN_SIDELOADED_KIT = 1000000 @@ -24,16 +23,13 @@ abstract class MPSideloadedKit( override fun kitId(): Int = kitId - override fun getName(): String = - this::class.java.name - .split(".") - .last() - .orEmpty() + override fun getName(): String = this::class.java.name + .split(".") + .last() + .orEmpty() - override fun onKitCreate( - settings: MutableMap?, - context: Context?, - ): MutableList = mutableListOf() + override fun onKitCreate(settings: MutableMap?, context: Context?): MutableList = + mutableListOf() override fun setOptOut(optedOut: Boolean): MutableList = mutableListOf() 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 8de7308cf..a9c6498e0 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 @@ -48,9 +48,9 @@ Data Plan parsed for Kit Filtering: blockUserAttributes=$blockUserAttributes blockUserIdentities=$blockUserIdentities ${ - dataPoints.entries.joinToString("\n") { (key, value) -> - "$key\n\t${value?.joinToString("\n\t") { it }}" - } + dataPoints.entries.joinToString("\n") { (key, value) -> + "$key\n\t${value?.joinToString("\n\t") { it }}" + } } """, ) @@ -296,10 +296,7 @@ Data Plan parsed for Kit Filtering: } // returns a set of "allowed" keys, or `null` if all keys are allowed - private fun getAllowedKeys( - datapoint: DataPoint, - jsonObject: JSONObject, - ): HashSet? { + private fun getAllowedKeys(datapoint: DataPoint, jsonObject: JSONObject): HashSet? { val definition = jsonObject .optJSONObject("validator") @@ -427,19 +424,18 @@ Data Plan parsed for Kit Filtering: fun MParticle.IdentityType.getEventsApiName(): String = MParticleIdentityClientImpl.getStringValue(this) - fun MParticle.EventType.getEventsApiName(): String = - when (this) { - MParticle.EventType.Location -> "location" - MParticle.EventType.Media -> "media" - MParticle.EventType.Navigation -> "navigation" - MParticle.EventType.Other -> "other" - MParticle.EventType.Search -> "search" - MParticle.EventType.Social -> "social" - MParticle.EventType.Transaction -> "transaction" - MParticle.EventType.UserContent -> "user_content" - MParticle.EventType.UserPreference -> "user_preference" - else -> "unknown" - } + fun MParticle.EventType.getEventsApiName(): String = when (this) { + MParticle.EventType.Location -> "location" + MParticle.EventType.Media -> "media" + MParticle.EventType.Navigation -> "navigation" + MParticle.EventType.Other -> "other" + MParticle.EventType.Search -> "search" + MParticle.EventType.Social -> "social" + MParticle.EventType.Transaction -> "transaction" + MParticle.EventType.UserContent -> "user_content" + MParticle.EventType.UserPreference -> "user_preference" + else -> "unknown" + } fun Iterator.toHashSet(): HashSet { val set = HashSet() @@ -448,11 +444,7 @@ Data Plan parsed for Kit Filtering: } } - class DataPoint( - val type: String, - val name: String? = null, - val eventType: String? = null, - ) { + class DataPoint(val type: String, val name: String? = null, val eventType: String? = null) { constructor(datapoint: DataPoint) : this( datapoint.type, datapoint.name, @@ -462,15 +454,14 @@ Data Plan parsed for Kit Filtering: var productAttributeType: String? = null private set - fun getProductDataPoints() = - when (type) { - PRODUCT_ACTION_KEY, PRODUCT_IMPRESSION_KEY -> - listOf( - DataPoint(this).apply { productAttributeType = PRODUCT_ACTION_PRODUCTS }, - DataPoint(this).apply { productAttributeType = PRODUCT_IMPRESSION_PRODUCTS }, - ) - else -> null - } + fun getProductDataPoints() = when (type) { + PRODUCT_ACTION_KEY, PRODUCT_IMPRESSION_KEY -> + listOf( + DataPoint(this).apply { productAttributeType = PRODUCT_ACTION_PRODUCTS }, + DataPoint(this).apply { productAttributeType = PRODUCT_IMPRESSION_PRODUCTS }, + ) + else -> null + } override fun toString() = "$type${if (name != null) ".$name" else ""}${if (eventType != null) ".$eventType" else ""}${productAttributeType?.let { diff --git a/android-kit-base/src/main/kotlin/com/mparticle/kits/KitOptions.kt b/android-kit-base/src/main/kotlin/com/mparticle/kits/KitOptions.kt index ec7f9b158..a76942dc2 100644 --- a/android-kit-base/src/main/kotlin/com/mparticle/kits/KitOptions.kt +++ b/android-kit-base/src/main/kotlin/com/mparticle/kits/KitOptions.kt @@ -2,19 +2,14 @@ package com.mparticle.kits import com.mparticle.Configuration -open class KitOptions( - initializer: KitOptions.() -> Unit = {}, -) : Configuration { +open class KitOptions(initializer: KitOptions.() -> Unit = {}) : Configuration { val kits: MutableMap> = mutableMapOf() init { this.initializer() } - open fun addKit( - kitId: Int, - type: Class, - ): KitOptions { + open fun addKit(kitId: Int, type: Class): KitOptions { kits[kitId] = type return this } 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 45e84b874..7969e8e9f 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 @@ -344,91 +344,84 @@ class DataplanFilterImplTest { SCREEN_EVENT_KEY, ) - fun getRandomEvent(datapoint: DataplanPoint): BaseEvent = - 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!!, + fun getRandomEvent(datapoint: DataplanPoint): BaseEvent = 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() + PROMOTION_ACTION_KEY -> CommerceEvent.Builder(datapoint.name!!, Promotion()).build() + PRODUCT_IMPRESSION_KEY -> + CommerceEvent + .Builder( + Impression( + "impressionname", 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() - else -> throw IllegalArgumentException(datapoint.type + ": messed this implementation up :/") - } + ), + ).build() + else -> throw IllegalArgumentException(datapoint.type + ": messed this implementation up :/") + } - fun getRandomDataplanEventKey(): DataplanPoint = - when (Random.Default.nextInt(0, 5)) { - 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()) - 4 -> DataplanPoint(PRODUCT_IMPRESSION_KEY) - else -> throw IllegalArgumentException("messed this implementation up :/") - } + fun getRandomDataplanEventKey(): DataplanPoint = when (Random.Default.nextInt(0, 5)) { + 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()) + 4 -> DataplanPoint(PRODUCT_IMPRESSION_KEY) + else -> throw IllegalArgumentException("messed this implementation up :/") + } - fun getRandomDataplanPoints(): MutableMap?> = - (0..Random.Default.nextInt(0, 10)) - .associate { - getRandomDataplanEventKey().toString() to randomAttributes().keys.toHashSet() - }.toMutableMap() + fun getRandomDataplanPoints(): MutableMap?> = (0..Random.Default.nextInt(0, 10)) + .associate { + getRandomDataplanEventKey().toString() to randomAttributes().keys.toHashSet() + }.toMutableMap() val chars: List = ('a'..'z') + ('A'..'Z') - fun randomAttributes(): Map = - (0..Random.Default.nextInt(0, 5)) - .map { - randomString(4) to randomString(8) - }.toMap() - - fun randomString(length: Int): String = - (0 until length) - .map { - chars[Random.Default.nextInt(0, chars.size - 1)] - }.joinToString("") - - fun randomEventType(): MParticle.EventType = - MParticle.EventType.values()[ - Random.Default.nextInt( - 0, - MParticle.EventType.values().size - 1, - ), - ] + fun randomAttributes(): Map = (0..Random.Default.nextInt(0, 5)) + .map { + randomString(4) to randomString(8) + }.toMap() + + fun randomString(length: Int): String = (0 until length) + .map { + chars[Random.Default.nextInt(0, chars.size - 1)] + }.joinToString("") + + fun randomEventType(): MParticle.EventType = MParticle.EventType.values()[ + Random.Default.nextInt( + 0, + MParticle.EventType.values().size - 1, + ), + ] fun randomProductAction(): String = randomConstString(Product::class.java) fun randomPromotionAction(): String = randomConstString(Promotion::class.java) - fun randomConstString(clazz: Class<*>): String = - clazz.fields - .filter { Modifier.isPublic(it.modifiers) && Modifier.isStatic(it.modifiers) } - .filter { it.name.all { it.isUpperCase() } } - .filter { it.type == String::class.java } - .let { - it[Random.Default.nextInt(0, it.size - 1)].get(null) as String - } + fun randomConstString(clazz: Class<*>): String = clazz.fields + .filter { Modifier.isPublic(it.modifiers) && Modifier.isStatic(it.modifiers) } + .filter { it.name.all { it.isUpperCase() } } + .filter { it.type == String::class.java } + .let { + it[Random.Default.nextInt(0, it.size - 1)].get(null) as String + } private fun String.toJSON() = JSONObject(this) 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 d00fb2694..3ef993a67 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 @@ -36,10 +36,11 @@ class KitConfigurationTest { val configuration = MockKitConfiguration.createKitConfiguration(ekConfig) if (ekConfig.has("avf")) { val attributeValueFilter = ekConfig.getJSONObject("avf") - if (attributeValueFilter.has("i") && attributeValueFilter.has("a") && + if (attributeValueFilter.has("i") && + attributeValueFilter.has("a") && attributeValueFilter.has( - "v", - ) + "v", + ) ) { val shouldIncludeMatches = attributeValueFilter["i"] val hashedAttribute = attributeValueFilter["a"] @@ -174,7 +175,7 @@ class KitConfigurationTest { fun testFilterCommerceAttributes() { // CUSTOM ATTRIBUTES val configuration = - MockKitConfiguration.createKitConfiguration(JSONObject(COMMERCE_FILTERS)) + MockKitConfiguration.createKitConfiguration(JSONObject(commerceFilters)) val attributes: MutableMap = HashMap() attributes["my custom attribute"] = "whatever" var event = @@ -236,7 +237,7 @@ class KitConfigurationTest { var configuration = MockKitConfiguration.createKitConfiguration( JSONObject( - COMMERCE_FILTERS, + commerceFilters, ), ) val impression = Impression("Cool list name", Product.Builder("name2", "sku", 2.0).build()) @@ -260,7 +261,7 @@ class KitConfigurationTest { Assert.assertEquals(0, imp.products.size.toLong()) } } - val config = JSONObject(COMMERCE_FILTERS) + val config = JSONObject(commerceFilters) // enable product, disable impressions config.getJSONObject("hs").getJSONObject("ent").put("2", 0) config.getJSONObject("hs").getJSONObject("ent").put("1", 1) @@ -300,7 +301,7 @@ class KitConfigurationTest { var configuration = MockKitConfiguration.createKitConfiguration( JSONObject( - COMMERCE_FILTERS, + commerceFilters, ), ) Assert.assertEquals("the creative", event.promotions?.get(0)?.creative) @@ -327,7 +328,7 @@ class KitConfigurationTest { ?.get("my custom product attribute"), ) Assert.assertEquals("cool brand", event.products?.get(0)?.brand) - configuration = MockKitConfiguration.createKitConfiguration(JSONObject(COMMERCE_FILTERS_2)) + configuration = MockKitConfiguration.createKitConfiguration(JSONObject(commerceFilters2)) filteredEvent = configuration.filterCommerceEvent(event) Assert.assertNull( filteredEvent.products @@ -343,7 +344,7 @@ class KitConfigurationTest { fun testFilterCommerceEventType() { // CUSTOM ATTRIBUTES val configuration = - MockKitConfiguration.createKitConfiguration(JSONObject(COMMERCE_FILTERS)) + MockKitConfiguration.createKitConfiguration(JSONObject(commerceFilters)) val event = CommerceEvent .Builder(Product.ADD_TO_CART, Product.Builder("name", "sku", 2.0).build()) @@ -375,13 +376,13 @@ class KitConfigurationTest { val includeTrueConfiguration = MockKitConfiguration.createKitConfiguration( JSONObject( - ATTRIBUTE_VALUE_FILTERING_INCLUDE_TRUE, + attributeValueFilteringIncludeTrue, ), ) val includeFalseConfiguration = MockKitConfiguration.createKitConfiguration( JSONObject( - ATTRIBUTE_VALUE_FILTERING_INCLUDE_FALSE, + attributeValueFilteringIncludeFalse, ), ) var result: Boolean = @@ -900,15 +901,15 @@ class KitConfigurationTest { MParticle.setInstance(mockMp) } - var COMMERCE_FILTERS = + var commerceFilters = "{\"id\":28, \"as\":{\"apiKey\":\"2687a8d1-1022-4820-9327-48582e930098\", \"sendPushOpenedWhenAppInForeground\":\"False\", \"push_enabled\":\"True\", \"register_inapp\":\"True\", \"appGroupId\":\"\"}, \"hs\":{\"et\":{\"1568\":0 }, \"cea\":{\"-1015386651\":0, \"-2090340318\":0, \"-1091394645\":0 }, \"ent\":{\"1\":0 }, \"afa\":{\"2\":{\"1820422063\":0 } } }, \"pr\":[] }" - var COMMERCE_FILTERS_2 = + var commerceFilters2 = "{\"id\":28, \"as\":{\"apiKey\":\"1fd18e0e-22cd-4b86-a106-551ccc59175f\", \"sendPushOpenedWhenAppInForeground\":\"False\", \"push_enabled\":\"True\", \"register_inapp\":\"True\", \"appGroupId\":\"a8f63b1f-1bc2-4373-8947-8dacdd113ad4\", \"addEventAttributeList\":\"[{\\\"map\\\":\\\"Value\\\",\\\"value\\\":null,\\\"maptype\\\":\\\"AttributeSelector\\\"}]\", \"removeEventAttributeList\":\"[]\", \"singleItemEventAttributeList\":\"[]\"}, \"hs\":{\"et\":{\"1568\":0, \"1576\":0 }, \"cea\":{\"-1015386651\":0, \"-1091394645\":0, \"-2090340318\":0 }, \"afa\":{\"1\":{\"93997959\":0, \"-870793808\":0 }, \"2\":{\"1820422063\":0 } } }, \"pr\":[] }" // attribute hash 3288498 matches "key1", value hash 3611952 matches "val1" - var ATTRIBUTE_VALUE_FILTERING_INCLUDE_TRUE = + var attributeValueFilteringIncludeTrue = "{\"id\":28, \"avf\":{\"i\":true, \"a\":3288498, \"v\":3611952}, \"as\":{\"apiKey\":\"2687a8d1-1022-4820-9327-48582e930098\", \"sendPushOpenedWhenAppInForeground\":\"False\", \"push_enabled\":\"True\", \"register_inapp\":\"True\", \"appGroupId\":\"\"}, \"hs\":{\"et\":{\"1568\":0 }, \"cea\":{\"-1015386651\":0, \"-2090340318\":0, \"-1091394645\":0 }, \"ent\":{\"1\":0 }, \"afa\":{\"2\":{\"1820422063\":0 } } }, \"pr\":[] }" - var ATTRIBUTE_VALUE_FILTERING_INCLUDE_FALSE = + var attributeValueFilteringIncludeFalse = "{\"id\":28, \"avf\":{\"i\":false, \"a\":3288498, \"v\":3611952}, \"as\":{\"apiKey\":\"2687a8d1-1022-4820-9327-48582e930098\", \"sendPushOpenedWhenAppInForeground\":\"False\", \"push_enabled\":\"True\", \"register_inapp\":\"True\", \"appGroupId\":\"\"}, \"hs\":{\"et\":{\"1568\":0 }, \"cea\":{\"-1015386651\":0, \"-2090340318\":0, \"-1091394645\":0 }, \"ent\":{\"1\":0 }, \"afa\":{\"2\":{\"1820422063\":0 } } }, \"pr\":[] }" } } 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 1f0a59939..699ac3b1a 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 @@ -915,7 +915,7 @@ class KitManagerImplTest { field.isAccessible = true field.set(mockedKitConfig, settingsMap) - val mockedProvider = mockProvider(mockedKitConfig) + val mockedProvider = MockProvider(mockedKitConfig) val options = MParticleOptions @@ -988,7 +988,7 @@ class KitManagerImplTest { field.isAccessible = true field.set(mockedKitConfig, settingsMap) - val mockedProvider = mockProvider(mockedKitConfig) + val mockedProvider = MockProvider(mockedKitConfig) val options = MParticleOptions @@ -1062,7 +1062,7 @@ class KitManagerImplTest { field.isAccessible = true field.set(mockedKitConfig, settingsMap) - val mockedProvider = mockProvider(mockedKitConfig) + val mockedProvider = MockProvider(mockedKitConfig) val options = MParticleOptions @@ -1133,7 +1133,7 @@ class KitManagerImplTest { field.isAccessible = true field.set(mockedKitConfig, settingsMap) - val mockedProvider = mockProvider(mockedKitConfig) + val mockedProvider = MockProvider(mockedKitConfig) val options = MParticleOptions @@ -1802,7 +1802,7 @@ class KitManagerImplTest { field.isAccessible = true field.set(mockedKitConfig, settingsMap) - val mockedProvider = mockProvider(mockedKitConfig) + val mockedProvider = MockProvider(mockedKitConfig) val options = MParticleOptions @@ -1870,7 +1870,7 @@ class KitManagerImplTest { field.isAccessible = true field.set(mockedKitConfig, settingsMap) - val mockedProvider = mockProvider(mockedKitConfig) + val mockedProvider = MockProvider(mockedKitConfig) val options = MParticleOptions @@ -1940,7 +1940,7 @@ class KitManagerImplTest { field.isAccessible = true field.set(mockedKitConfig, settingsMap) - val mockedProvider = mockProvider(mockedKitConfig) + val mockedProvider = MockProvider(mockedKitConfig) val options = MParticleOptions @@ -2232,7 +2232,7 @@ class KitManagerImplTest { assertEquals(expectedFlow, result) } - internal inner class mockProvider( + internal inner class MockProvider( val config: KitConfiguration, ) : KitIntegration(), KitIntegration.RoktListener { diff --git a/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt b/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt index 5210cf429..598c07ae7 100644 --- a/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt +++ b/android-kit-base/src/test/kotlin/com/mparticle/kits/mappings/CustomMappingTest.kt @@ -107,8 +107,8 @@ class CustomMappingTest { val attProj = CustomMapping.AttributeMap(attribute) Assert.assertEquals(attribute.optBoolean("is_required"), attProj.mIsRequired) if (attribute - .getString("match_type") - .startsWith(CustomMapping.MATCH_TYPE_STATIC) + .getString("match_type") + .startsWith(CustomMapping.MATCH_TYPE_STATIC) ) { Assert.assertFalse(customMapping.mRequiredAttributeMapList.contains(attProj)) Assert.assertTrue(customMapping.mStaticAttributeMapList.contains(attProj)) diff --git a/testutils/src/main/java/com/google/firebase/iid/FirebaseInstanceId.kt b/testutils/src/main/java/com/google/firebase/iid/FirebaseInstanceId.kt index 0a42cbb33..ef30fa8f6 100644 --- a/testutils/src/main/java/com/google/firebase/iid/FirebaseInstanceId.kt +++ b/testutils/src/main/java/com/google/firebase/iid/FirebaseInstanceId.kt @@ -17,8 +17,5 @@ class FirebaseInstanceId { fun getToken() = FirebaseInstanceIdToken.token - fun getToken( - authority: String, - scope: String, - ) = FirebaseInstanceIdToken.token + fun getToken(authority: String, scope: String) = FirebaseInstanceIdToken.token } diff --git a/testutils/src/main/kotlin/com.mparticle/Utils.kt b/testutils/src/main/kotlin/com.mparticle/Utils.kt index c93bd6b1f..14a292def 100644 --- a/testutils/src/main/kotlin/com.mparticle/Utils.kt +++ b/testutils/src/main/kotlin/com.mparticle/Utils.kt @@ -8,23 +8,21 @@ import kotlin.random.Random object Utils { fun randomPromotionAction(): String = randomConstString(Promotion::class.java) - fun randomConstString(clazz: Class<*>): String = - clazz.fields - .filter { Modifier.isPublic(it.modifiers) && Modifier.isStatic(it.modifiers) } - .filter { it.name.all { it.isUpperCase() } } - .filter { it.type == String::class.java } - .let { - it[Random.Default.nextInt(0, it.size - 1)].get(null) as String - } + fun randomConstString(clazz: Class<*>): String = clazz.fields + .filter { Modifier.isPublic(it.modifiers) && Modifier.isStatic(it.modifiers) } + .filter { it.name.all { it.isUpperCase() } } + .filter { it.type == String::class.java } + .let { + it[Random.Default.nextInt(0, it.size - 1)].get(null) as String + } val chars: List = ('a'..'z') + ('A'..'Z') - fun randomAttributes(): MutableMap = - (0..Random.Default.nextInt(0, 5)) - .map { - randomString(4) to randomString(8) - }.toMap() - .toMutableMap() + fun randomAttributes(): MutableMap = (0..Random.Default.nextInt(0, 5)) + .map { + randomString(4) to randomString(8) + }.toMap() + .toMutableMap() fun randomIdentities(): MutableMap { val identities = MParticle.IdentityType.values() @@ -35,19 +33,17 @@ object Utils { .toMutableMap() } - fun randomString(length: Int): String = - (0..length - 1) - .map { - chars[Random.Default.nextInt(0, chars.size - 1)] - }.joinToString("") - - fun randomEventType(): MParticle.EventType = - MParticle.EventType.values()[ - Random.Default.nextInt( - 0, - MParticle.EventType.values().size - 1, - ), - ] + fun randomString(length: Int): String = (0..length - 1) + .map { + chars[Random.Default.nextInt(0, chars.size - 1)] + }.joinToString("") + + fun randomEventType(): MParticle.EventType = MParticle.EventType.values()[ + Random.Default.nextInt( + 0, + MParticle.EventType.values().size - 1, + ), + ] fun randomProductAction(): String = randomConstString(Product::class.java) } 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 2d35b079a..2749d8027 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/Config.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/Config.kt @@ -47,21 +47,16 @@ data class Config( } } - data class InternalConfig( - var nodePath: String? = null, - var mpPath: String? = null, - ) { - fun toJson(): JSONObject = - JSONObject() - .putOpt("node-path", nodePath) - .putOpt("mp-path", mpPath) + data class InternalConfig(var nodePath: String? = null, var mpPath: String? = null) { + fun toJson(): JSONObject = JSONObject() + .putOpt("node-path", nodePath) + .putOpt("mp-path", mpPath) companion object { - fun fromJson(json: JSONObject): InternalConfig = - InternalConfig( - nodePath = json.optString("node-path", null), - mpPath = json.optString("mp-path", null), - ) + fun fromJson(json: JSONObject): InternalConfig = InternalConfig( + nodePath = json.optString("node-path", null), + mpPath = json.optString("mp-path", null), + ) } } } 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 a8bfc6621..ea7caa32a 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/DataPlanningNodeApp.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/DataPlanningNodeApp.kt @@ -4,15 +4,11 @@ import com.mparticle.tooling.Utils.executeCLI import java.io.File import java.io.IOException -enum class DataPlanError( - val message: String, -) { +enum class DataPlanError(val message: String) { VersionInvalid("Error: Data Plan Version is Invalid"), } -class DataPlanningNodeApp( - val config: Config, -) { +class DataPlanningNodeApp(val config: Config) { var path = System.getenv("PATH") init { @@ -26,11 +22,7 @@ class DataPlanningNodeApp( } } - 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 = @@ -76,11 +68,7 @@ class DataPlanningNodeApp( } } - fun fetchDataPlan( - accountId: String, - planId: String, - version: String?, - ): NodeAppResult { + fun fetchDataPlan(accountId: String, planId: String, version: String?): NodeAppResult { try { val arguments = mutableListOf( @@ -163,16 +151,13 @@ class DataPlanningNodeApp( } } - fun fromJS(jsFileBlob: String): DataPlanningNodeApp? = - Utils.getFileLocation(tempNodeFileName)?.let { nodeFile -> - val nodeFile = File(nodeFile) - nodeFile.createNewFile() - nodeFile.writeText(jsFileBlob) - DataPlanningNodeApp(Config()) - } + fun fromJS(jsFileBlob: String): DataPlanningNodeApp? = Utils.getFileLocation(tempNodeFileName)?.let { nodeFile -> + val nodeFile = File(nodeFile) + nodeFile.createNewFile() + nodeFile.writeText(jsFileBlob) + DataPlanningNodeApp(Config()) + } } - class NodeAppResult( - val response: T? = null, - ) + class NodeAppResult(val response: T? = null) } diff --git a/tooling/common/src/main/java/com/mparticle/tooling/MockDataPlanningNodeApp.kt b/tooling/common/src/main/java/com/mparticle/tooling/MockDataPlanningNodeApp.kt index bebb07a48..17328fd36 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/MockDataPlanningNodeApp.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/MockDataPlanningNodeApp.kt @@ -1 +1,4 @@ package com.mparticle.tooling + +// Placeholder file +object MockDataPlanningNodeApp 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 7debc0edd..e23037a93 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/Utils.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/Utils.kt @@ -7,28 +7,24 @@ import java.io.File import java.io.InputStreamReader object Utils { - fun getCurrentFileLocation(fileName: String): String = - javaClass - .getResource(fileName) - .path - .replace( - "file:", - "", - ).split("lint.jar")[0] + fun getCurrentFileLocation(fileName: String): String = javaClass + .getResource(fileName) + .path + .replace( + "file:", + "", + ).split("lint.jar")[0] - fun Array.executeCLI( - path: String? = null, - workingDirectory: String = ".", - ): String { + fun Array.executeCLI(path: String? = null, workingDirectory: String = "."): String { Logger.verbose( "command line operation: ${ - joinToString(" ") { - if (it.contains(" ")) { - "\"$it\"" - } else { - it + joinToString(" ") { + if (it.contains(" ")) { + "\"$it\"" + } else { + it + } } - } }", ) var error = "" @@ -54,7 +50,7 @@ object Utils { } fun getConfigFile(): Config? { - val file = File(getFileLocation(configFileName)) + val file = File(getFileLocation(CONFIG_FILE_NAME)) if (file.exists()) { val contents = file.readText() try { @@ -67,7 +63,7 @@ object Utils { } fun getConfigFileLastModified(): Long { - val file = File(getFileLocation(configFileName)) + val file = File(getFileLocation(CONFIG_FILE_NAME)) if (file.exists()) { return file.lastModified() } else { @@ -76,19 +72,19 @@ object Utils { } fun setConfigFile(config: Config) { - File(getFileLocation(configFileName)) + File(getFileLocation(CONFIG_FILE_NAME)) .writeText(config.toJson().toString()) } fun removeConfigFile() { - val file = File(getFileLocation(configFileName)) + val file = File(getFileLocation(CONFIG_FILE_NAME)) if (file.exists()) { file.delete() } } fun getLocalDataplan(): String? { - val file = File(getFileLocation(dataplanFileName)) + val file = File(getFileLocation(DATAPLAN_FILE_NAME)) if (file.exists()) { return file.readText() } else { @@ -97,14 +93,14 @@ object Utils { } fun removeLocalDataplan() { - val file = File(getFileLocation(dataplanFileName)) + val file = File(getFileLocation(DATAPLAN_FILE_NAME)) if (file.exists()) { file.delete() } } fun setLocalDataplan(dataplan: String) { - File(getFileLocation(dataplanFileName)) + File(getFileLocation(DATAPLAN_FILE_NAME)) .writeText(dataplan) } @@ -118,5 +114,5 @@ object Utils { } } -const val configFileName = "mparticle-config" -const val dataplanFileName = "mparticle-dataplan" +const val CONFIG_FILE_NAME = "mparticle-config" +const val DATAPLAN_FILE_NAME = "mparticle-dataplan" 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 8c1a2ee81..77a288d35 100644 --- a/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt +++ b/tooling/common/src/main/java/com/mparticle/tooling/ValidationResult.kt @@ -4,30 +4,18 @@ 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? = - try { - val jsonArray = JSONObject(json).getJSONArray("results") - from(jsonArray, arguments) - } catch (jse: JSONException) { - listOf(ValidationResult(arguments = arguments).apply { originalString = json }) - } + fun from(json: String?, arguments: List): List? = try { + val jsonArray = JSONObject(json).getJSONArray("results") + from(jsonArray, arguments) + } catch (jse: JSONException) { + listOf(ValidationResult(arguments = arguments).apply { originalString = json }) + } - fun from( - json: JSONArray, - arguments: List, - ): List { + fun from(json: JSONArray, arguments: List): List { val validationResults = ArrayList() for (i in 0 until json.length()) { val validationResultJson = json.getJSONObject(i) @@ -76,43 +64,28 @@ data class ValidationResult( } } -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? = - json?.let { - ValidationResultData( - ValidationResultMatch.from(it.optJSONObject("match")), - ValidationResultErrors.from(it.optJSONArray("validation_errors")), - ) - } + fun from(json: JSONObject?): ValidationResultData? = json?.let { + ValidationResultData( + ValidationResultMatch.from(it.optJSONObject("match")), + ValidationResultErrors.from(it.optJSONArray("validation_errors")), + ) + } } } -data class ValidationResultMatch( - val type: String, - val criteria: Map, -) { +data class ValidationResultMatch(val type: String, val criteria: Map) { companion object { - fun from(json: JSONObject?): ValidationResultMatch? = - json?.let { - val type = it.optString("type") - val criteria = it.optJSONObject("criteria")?.toHashMap() ?: hashMapOf() - ValidationResultMatch(type, criteria) - } + fun from(json: JSONObject?): ValidationResultMatch? = json?.let { + val type = it.optString("type") + val criteria = it.optJSONObject("criteria")?.toHashMap() ?: hashMapOf() + ValidationResultMatch(type, criteria) + } } } -data class ValidationResultErrors( - val validationErrorType: ValidationErrorType, - val errorPointer: String?, - val key: String?, - val expected: String?, - val actual: String?, - val schemaKeyword: String?, -) { +data class ValidationResultErrors(val validationErrorType: ValidationErrorType, val errorPointer: String?, val key: String?, val expected: String?, val actual: String?, val schemaKeyword: String?) { companion object { fun from(json: JSONArray): List { val validationResultErrors = ArrayList() @@ -141,9 +114,7 @@ data class ValidationResultErrors( } } -enum class ValidationErrorType( - val text: String, -) { +enum class ValidationErrorType(val text: String) { Unplanned("unplanned"), MissingRequied("missing_required"), InvalidValue("invalid_value"), 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 2218bfdd5..896f49756 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,10 +39,7 @@ 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) @@ -110,10 +107,7 @@ internal fun UExpression.getUltimateReceiverVariable(): PsiVariable? { } } -internal fun UExpression.getVariableElement( - allowChainedCalls: Boolean, - allowFields: Boolean, -): PsiVariable? { +internal fun UExpression.getVariableElement(allowChainedCalls: Boolean, allowFields: Boolean): PsiVariable? { var parent = skipParenthesizedExprUp(getQualifiedParentOrThis().uastParent) // Handle some types of chained calls; e.g. you might have @@ -201,12 +195,11 @@ internal fun UCallExpression.receiverClassName(stripGenerics: Boolean = true): S return className } -internal fun PsiType.getClassName(): String? = - when (this) { - is PsiClassReferenceType -> this.reference.qualifiedName - is PsiImmediateClassType -> this.resolve()?.qualifiedName - else -> null - } +internal fun PsiType.getClassName(): String? = when (this) { + is PsiClassReferenceType -> this.reference.qualifiedName + is PsiImmediateClassType -> this.resolve()?.qualifiedName + else -> null +} internal fun PsiClass.getQualifiedName(reflectable: Boolean): String? { if (!reflectable) { @@ -229,10 +222,7 @@ 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() @@ -252,7 +242,7 @@ internal fun Pair<*, *>.resolveToEnum(): Enum<*> { val className = when (first) { is ClassId -> "${(first as ClassId).packageFqName}.${ - (first as ClassId).relativeClassName.asString().replace(".", "$") + (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 3c54cb082..7d9fb7d91 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,12 +23,7 @@ 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? { 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 bd6367274..e4c1ecaba 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 @@ -27,42 +27,37 @@ 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> - override fun createUastHandler(context: JavaContext): UElementHandler? = - object : UElementHandler() { - override fun visitCallExpression(node: UCallExpression) { - try { - if (!disabled && ofInterest(node)) { - var expression = node.resolveChainedCalls(true, RootParent(node)) + override fun createUastHandler(context: JavaContext): UElementHandler? = object : UElementHandler() { + override fun visitCallExpression(node: UCallExpression) { + try { + if (!disabled && ofInterest(node)) { + var expression = node.resolveChainedCalls(true, RootParent(node)) - val variable = node.getVariableElement(true, true) - val method = node.getParentOfType(UMethod::class.java) + val variable = node.getVariableElement(true, true) + val method = node.getParentOfType(UMethod::class.java) - if (variable != null && method != null) { - VariableCollector(variable, method, expression).getUnresolvedObject( - false, - ) - } - if (expression != null) { - node.receiverClassName()?.let { receiverName -> - onInstanceCollected(context, expression, node) - } - } + if (variable != null && method != null) { + VariableCollector(variable, method, expression).getUnresolvedObject( + false, + ) } - } catch (e: Exception) { - if (config?.verbose == true) { - Logger.error(e.toString()) + if (expression != null) { + node.receiverClassName()?.let { receiverName -> + onInstanceCollected(context, expression, node) + } } } + } catch (e: Exception) { + if (config?.verbose == true) { + Logger.error(e.toString()) + } } } + } override fun getApplicableUastTypes(): List>? = listOf(UCallExpression::class.java) 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 38a4450e7..3b8bee4c3 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 @@ -56,7 +56,7 @@ class DataplanDetector : CallScanner() { |Retrieving the MParticle Data Plan is necessary to evaluate any violations. |There may be a problem with locating your "dataPlanVersionFile". |Please double check the values is correct in your "mparticle" block in build.gradle or your mp.config.json file - """.trimMargin(), + """, Category.USABILITY, 4, Severity.INFORMATIONAL, @@ -72,11 +72,7 @@ class DataplanDetector : CallScanner() { // stub logger in MParticle to avoid any dependencies on Android Log when building Events Logger.setLogHandler( object : Logger.DefaultLogHandler() { - override fun log( - priority: MParticle.LogLevel?, - error: Throwable?, - messages: String?, - ) {} + override fun log(priority: MParticle.LogLevel?, error: Throwable?, messages: String?) {} }, ) @@ -102,11 +98,7 @@ class DataplanDetector : CallScanner() { } } - override fun onInstanceCollected( - context: JavaContext, - unresolvedObject: Expression, - reportingNode: UExpression, - ) { + override fun onInstanceCollected(context: JavaContext, unresolvedObject: Expression, reportingNode: UExpression) { val instance = try { unresolvedObject.resolve() @@ -230,10 +222,7 @@ class DataplanDetector : CallScanner() { } } - 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 -> @@ -285,9 +274,8 @@ class DataplanDetector : CallScanner() { ; companion object { - fun get(value: String?): ViolationSchemaKeywordType = - values().firstOrNull { it.toString().toLowerCase() == value?.toLowerCase() } - ?: Unknown + fun get(value: String?): ViolationSchemaKeywordType = values().firstOrNull { it.toString().toLowerCase() == value?.toLowerCase() } + ?: Unknown } } 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 48d072f7e..d483f39e5 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 @@ -110,64 +110,56 @@ class MpApiDetectorKt : * including the same call made through different code paths, these are "Duplicate calls". Any method we find outside of a code path originating * in Application.onCreate() is a "Wrong place call" */ - override fun createUastHandler(context: JavaContext): UElementHandler = - object : UElementHandler() { - override fun visitMethod(node: UMethod) { - try { - this@MpApiDetectorKt.context = context - if (isApplicationSubClassOnCreate(context, node)) { - findMethodCall(node, TARGET_METHOD_QUALIFIED_NAME, MAX_AST_DEPTH) - .apply { - forEach { methodCall -> - if (isTargetMethod(TARGET_METHOD_QUALIFIED_NAME, methodCall)) { - if (properMethodCall == null) { - properMethodCall = - LocationWrapper(context.getLocation(methodCall)) - } else { - extraProperMethodCalls.add( - LocationWrapper( - context.getLocation( - methodCall, - ), + override fun createUastHandler(context: JavaContext): UElementHandler = object : UElementHandler() { + override fun visitMethod(node: UMethod) { + try { + this@MpApiDetectorKt.context = context + if (isApplicationSubClassOnCreate(context, node)) { + findMethodCall(node, TARGET_METHOD_QUALIFIED_NAME, MAX_AST_DEPTH) + .apply { + forEach { methodCall -> + if (isTargetMethod(TARGET_METHOD_QUALIFIED_NAME, methodCall)) { + if (properMethodCall == null) { + properMethodCall = + LocationWrapper(context.getLocation(methodCall)) + } else { + extraProperMethodCalls.add( + LocationWrapper( + context.getLocation( + methodCall, ), - ) - } + ), + ) } } } - applicationOnCreateCall = LocationWrapper(context.getLocation(node)) - } else { - findMethodCall( - node, - TARGET_METHOD_QUALIFIED_NAME, - 1, - ).forEach { methodCall -> - if (isTargetMethod(TARGET_METHOD_QUALIFIED_NAME, methodCall)) { - wrongPlaceMethodCalls.add( - LocationWrapper( - context.getLocation( - methodCall, - ), + } + applicationOnCreateCall = LocationWrapper(context.getLocation(node)) + } else { + findMethodCall( + node, + TARGET_METHOD_QUALIFIED_NAME, + 1, + ).forEach { methodCall -> + if (isTargetMethod(TARGET_METHOD_QUALIFIED_NAME, methodCall)) { + wrongPlaceMethodCalls.add( + LocationWrapper( + context.getLocation( + methodCall, ), - ) - } + ), + ) } } - } catch (e: Exception) { - Logger.error(e.toString()) } + } catch (e: Exception) { + Logger.error(e.toString()) } } + } - private fun findMethodCall( - method: UMethod, - targetMethodName: String, - depth: Int, - ): List { - fun findMethodCall( - element: UElement?, - 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) { return callExpressions @@ -210,7 +202,7 @@ class MpApiDetectorKt : val index = text.indexOf(name ?: "") if (index > 0 && " ${ - text.substring( + text.substring( 0, index, ) @@ -252,9 +244,8 @@ class MpApiDetectorKt : * Especially with local functions, introduced in kotlin, we have to check both whether is method * call refers to a local function, or a class level function, */ - private fun getMethod(callExpression: UCallExpression): UExpression? = - getLocalMethodImplmentation(callExpression) - ?: getMethodImplementation(callExpression) + private fun getMethod(callExpression: UCallExpression): UExpression? = getLocalMethodImplmentation(callExpression) + ?: getMethodImplementation(callExpression) private fun getLocalMethodImplmentation(callExpression: UCallExpression): UExpression? { (callExpression.uastParent as? UBlockExpression) @@ -284,13 +275,9 @@ class MpApiDetectorKt : /** * */ - private fun getMethodImplementation(callExpression: UCallExpression): UExpression? = - (callExpression.tryResolveUDeclaration() as? UMethod)?.uastBody + private fun getMethodImplementation(callExpression: UCallExpression): UExpression? = (callExpression.tryResolveUDeclaration() as? UMethod)?.uastBody - private fun isTargetMethod( - targetMethodName: String, - element: UCallExpression, - ): Boolean { + private fun isTargetMethod(targetMethodName: String, element: UCallExpression): Boolean { // before we resolve the method, do a quick check to see if the name matches if (targetMethodName.endsWith(element.methodName ?: "")) { // if the name matches, do the more expensive operation of resolving the method implementation, @@ -302,15 +289,9 @@ class MpApiDetectorKt : return false } - private fun isApplicationSubClassOnCreate( - context: JavaContext, - method: UMethod, - ): Boolean = isApplicationSubClass(context, method) && method.name.equals("onCreate") + private fun isApplicationSubClassOnCreate(context: JavaContext, method: UMethod): Boolean = isApplicationSubClass(context, method) && method.name.equals("onCreate") - private fun isApplicationSubClass( - context: JavaContext, - method: UMethod, - ): Boolean { + private fun isApplicationSubClass(context: JavaContext, method: UMethod): Boolean { val evaluator = context.evaluator return method .getParentOfType(true, UClass::class.java) @@ -328,9 +309,7 @@ class MpApiDetectorKt : * 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 = toString().hashCode() override fun equals(other: Any?): Boolean { @@ -349,18 +328,13 @@ class MpApiDetectorKt : return false } - fun compareLocation( - l1: Position?, - l2: Position?, - ): Boolean = - l1?.column == l2?.column && - l1?.line == l2?.line && - l1?.offset == l2?.offset + fun compareLocation(l1: Position?, l2: Position?): Boolean = l1?.column == l2?.column && + l1?.line == l2?.line && + l1?.offset == l2?.offset - override fun toString(): String = - location.file.getAbsolutePath() + "\n" + - (location.start?.offset.toString() + " " + location.start?.line + " " + location.start?.column) + "\n" + - (location.end?.offset.toString() + " " + location.end?.line + " " + location.end?.column) + override fun toString(): String = location.file.getAbsolutePath() + "\n" + + (location.start?.offset.toString() + " " + location.start?.line + " " + location.start?.column) + "\n" + + (location.end?.offset.toString() + " " + location.end?.line + " " + location.end?.column) override fun compareTo(other: LocationWrapper): Int = toString().compareTo(other.toString()) } 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 274be5a63..1c7f5a241 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,11 +4,7 @@ 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/Expression.kt b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Expression.kt index 397c4b450..b68d19f9f 100644 --- a/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Expression.kt +++ b/tooling/custom-lint-rules/src/main/java/com/mparticle/lints/dtos/Expression.kt @@ -15,9 +15,7 @@ interface ParameterizedExpression : Expression { var arguments: List } -class RootParent( - override val node: UExpression, -) : Expression { +class RootParent(override val node: UExpression) : Expression { override val parent: Expression = this override fun resolve() = null 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 0d62baac1..760743ee6 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,12 +3,7 @@ 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 { 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 d9a89e0ce..eda586ac0 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 @@ -5,10 +5,7 @@ import com.mparticle.lints.resolve import org.jetbrains.uast.UCallExpression import java.lang.reflect.Method -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 63c2553f1..b7d968786 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,21 +3,16 @@ 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 = "$value" - override fun resolve(): Any? = - when (value) { - is Expression -> { - value.resolve() - } - is Pair<*, *> -> value.resolveToEnum() - else -> value + override fun resolve(): Any? = when (value) { + is Expression -> { + value.resolve() } + is Pair<*, *> -> value.resolveToEnum() + else -> value + } override fun forEachExpression(predicate: (Expression) -> Unit) { predicate(this) diff --git a/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/Constants.kt b/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/Constants.kt index 2958b3385..bdd888f5d 100644 --- a/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/Constants.kt +++ b/tooling/custom-lint-rules/src/test/java/com/mparticle/lints/Constants.kt @@ -14,20 +14,20 @@ object Constants { ): String = String.format(ERROR_WARNING_FORMAT, errors, warnings) @Language("JAVA") - const val mparticleStub = + const val MPARTICLE_STUB = """package com.mparticle; public class MParticle { public static void start() {} }""" @Language("JAVA") - const val applicationStub = """ + const val APPLICATION_STUB = """ package android.app; public class Application { public void onCreate() {} public void onResume() {} }""" - val mParticleStubClass = java(mparticleStub) - val mApplicationStubClass = java(applicationStub) + val mParticleStubClass = java(MPARTICLE_STUB) + val mApplicationStubClass = java(APPLICATION_STUB) } From 15b734059dd25b48769b400888ab3442cabc8fa1 Mon Sep 17 00:00:00 2001 From: Mansi Pandya Date: Tue, 13 Jan 2026 16:04:26 -0500 Subject: [PATCH 11/11] Addressed the review comment related to signing the release. --- build.gradle | 5 ++++- .../main/groovy/com/mparticle/kits/KitPlugin.groovy | 11 +++++++++-- scripts/maven.gradle | 4 ++-- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/build.gradle b/build.gradle index 5f4c97154..f9030b0b8 100644 --- a/build.gradle +++ b/build.gradle @@ -30,7 +30,10 @@ subprojects { if (project.hasProperty('android')) { project.android { if (namespace == null) { - namespace project.group + throw new GradleException( + "Module '${project.name}' is missing an explicit namespace declaration. " + + "Please add 'namespace' to the android {} block in ${project.buildFile.name}" + ) } } } 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 c1a3db46d..ac016fb20 100644 --- a/kit-plugin/src/main/groovy/com/mparticle/kits/KitPlugin.groovy +++ b/kit-plugin/src/main/groovy/com/mparticle/kits/KitPlugin.groovy @@ -140,11 +140,18 @@ class KitPlugin implements Plugin { } target.extensions.configure(SigningExtension) { signing -> - signing.required = { target.gradle.taskGraph.hasTask('publishReleasePublicationToMavenRepository') } + signing.required { + target.gradle.taskGraph.hasTask("publishReleasePublicationToMavenRepository") + } + def signingKey = target.findProperty('signingKey') ?: System.getenv('mavenSigningKeyId') def signingPassword = target.findProperty('signingPassword') ?: System.getenv('mavenSigningKeyPassword') + if (signingKey && signingPassword) { - signing.useInMemoryPgpKeys(target.property('signingKey'), target.property('signingPassword')) + signing.useInMemoryPgpKeys(signingKey, signingPassword) + signing.sign(target.extensions.getByType(PublishingExtension) + .publications + .findByName("release")) } } } diff --git a/scripts/maven.gradle b/scripts/maven.gradle index d1b191c7d..66063bcbb 100644 --- a/scripts/maven.gradle +++ b/scripts/maven.gradle @@ -124,5 +124,5 @@ afterEvaluate { } //Publishing task aliases for simpler local development -task publishLocal { dependsOn "publishDebugPublicationToMavenLocal"} -task publishReleaseLocal { dependsOn "publishReleasePublicationToMavenLocal"} +task publishLocal { dependsOn "publishDebugPublicationToMavenLocal" } +task publishReleaseLocal { dependsOn "publishReleasePublicationToMavenLocal" }