diff --git a/SensorsAnalyticsSDK/pom.xml b/SensorsAnalyticsSDK/pom.xml index d5f4fed..ebb64a9 100644 --- a/SensorsAnalyticsSDK/pom.xml +++ b/SensorsAnalyticsSDK/pom.xml @@ -1,6 +1,5 @@ - 4.0.0 @@ -10,39 +9,26 @@ 7 - jar - com.sensorsdata.analytics.javasdk - SensorsAnalyticsSDK SensorsAnalyticsSDK - 3.6.7 - The official Java SDK of Sensors Analytics - http://sensorsdata.cn + 3.6.8 - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - - - - - scm:git@github.com:sensorsdata/sa-sdk-java.git - scm:git@github.com:sensorsdata/sa-sdk-java.git - git@github.com:sensorsdata/sa-sdk-java.git - + jar + SensorsAnalyticsSDK + The official Java SDK of Sensors Analytics utf-8 utf-8 - 1.7 4.5.13 2.12.7.1 1.18.20 - 4.11 + 5.9.0 1.7.25 1.6.6 9.4.12.v20180830 + 2.29.0 + false @@ -73,22 +59,22 @@ ${slf4j-simple.version} test - - junit - junit - ${junit.version} - test - org.eclipse.jetty.websocket websocket-server ${jetty.version} test + + org.junit.jupiter + junit-jupiter-engine + 5.9.0 + test + org.junit.jupiter junit-jupiter - RELEASE + 5.9.0 test @@ -98,10 +84,10 @@ org.apache.maven.plugins maven-compiler-plugin - 3.3 + 3.10.1 - ${jdk.version} - ${jdk.version} + 8 + 8 UTF-8 @@ -113,10 +99,10 @@ - compile jar + compile @@ -135,27 +121,94 @@ org.apache.maven.plugins maven-surefire-plugin - 2.18.1 + 2.22.2 -Xms1024m -Xmx1024m + + com.diffplug.spotless + spotless-maven-plugin + ${spotless.version} + + ${skip.spotless} + + + 1.7 + + + + + + Remove wildcard imports + import\s+(static)*\s*[^\*\s]+\*;(\r\n|\r|\n) + $1 + + + Block powermock + import\s+org\.powermock\.[^\*\s]*(|\*);(\r\n|\r|\n) + $1 + + + Block jUnit4 imports + import\s+org\.junit\.[^jupiter][^\*\s]*(|\*);(\r\n|\r|\n) + $1 + + + + + UTF-8 + 4 + true + false + true + true + false + false + custom_1 + false + false + + + Leading blank line + project + project + + + + true + + + + + spotless-check + + check + + validate + + + + http://sensorsdata.cn + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + + + + + scm:git@github.com:sensorsdata/sa-sdk-java.git + scm:git@github.com:sensorsdata/sa-sdk-java.git + git@github.com:sensorsdata/sa-sdk-java.git + release - - - ossrh - https://s01.oss.sonatype.org/content/repositories/snapshots/ - - - ossrh - https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/ - - @@ -165,10 +218,10 @@ 2.4 - package jar-no-fork + package @@ -179,10 +232,10 @@ 2.10.3 - package jar + package @@ -194,19 +247,26 @@ sign-artifacts - verify sign + verify + + + ossrh + https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/ + + + ossrh + https://s01.oss.sonatype.org/content/repositories/snapshots/ + + - - - diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/HelloSensorsAnalytics.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/HelloSensorsAnalytics.java index 235a68f..f830176 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/HelloSensorsAnalytics.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/HelloSensorsAnalytics.java @@ -6,7 +6,6 @@ import com.sensorsdata.analytics.javasdk.bean.SuperPropertiesRecord; import com.sensorsdata.analytics.javasdk.bean.UserRecord; import com.sensorsdata.analytics.javasdk.consumer.ConcurrentLoggingConsumer; - import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; @@ -20,17 +19,18 @@ */ public class HelloSensorsAnalytics { - public static void main(final String[] args) throws Exception { // LoggingConsumer - final ISensorsAnalytics sa = new SensorsAnalytics(new ConcurrentLoggingConsumer("file.log")); - - //设置公共属性,以后上传的每一个事件都附带该属性 - SuperPropertiesRecord propertiesRecord = SuperPropertiesRecord.builder() - .addProperty("$os", "Windows") - .addProperty("$os_version", "8.1") - .addProperty("$ip", "123.123.123.123") - .build(); + final ISensorsAnalytics sa = + new SensorsAnalytics(new ConcurrentLoggingConsumer("file.log")); + + // 设置公共属性,以后上传的每一个事件都附带该属性 + SuperPropertiesRecord propertiesRecord = + SuperPropertiesRecord.builder() + .addProperty("$os", "Windows") + .addProperty("$os_version", "8.1") + .addProperty("$ip", "123.123.123.123") + .build(); sa.registerSuperProperties(propertiesRecord); // 1. 用户匿名访问网站,cookieId 默认神策生成分配 @@ -38,115 +38,148 @@ public static void main(final String[] args) throws Exception { // 1.1 访问首页 // 前面有$开头的property字段,是SA提供给用户的预置字段 // 对于预置字段,已经确定好了字段类型和字段的显示名 - EventRecord firstRecord = EventRecord.builder().setDistinctId(cookieId).isLoginId(Boolean.FALSE) - .setEventName("track") - .addProperty("$time", Calendar.getInstance().getTime()) - .addProperty("Channel", "baidu") - .addProperty("$project", "abc") - .addProperty("$token", "123") - .build(); + EventRecord firstRecord = + EventRecord.builder() + .setDistinctId(cookieId) + .isLoginId(Boolean.FALSE) + .setEventName("track") + .addProperty("$time", Calendar.getInstance().getTime()) + .addProperty("Channel", "baidu") + .addProperty("$project", "abc") + .addProperty("$token", "123") + .build(); sa.track(firstRecord); // 1.2 搜索商品 - EventRecord searchRecord = EventRecord.builder().setDistinctId(cookieId).isLoginId(Boolean.FALSE) - .setEventName("SearchProduct") - .addProperty("KeyWord", "XX手机") - .build(); + EventRecord searchRecord = + EventRecord.builder() + .setDistinctId(cookieId) + .isLoginId(Boolean.FALSE) + .setEventName("SearchProduct") + .addProperty("KeyWord", "XX手机") + .build(); sa.track(searchRecord); // 1.3 浏览商品 - EventRecord lookRecord = EventRecord.builder().setDistinctId(cookieId).isLoginId(Boolean.FALSE) - .setEventName("ViewProduct") - .addProperty("ProductName", "XX手机") - .addProperty("ProductType", "智能手机") - .addProperty("ShopName", "XX官方旗舰店") - .build(); + EventRecord lookRecord = + EventRecord.builder() + .setDistinctId(cookieId) + .isLoginId(Boolean.FALSE) + .setEventName("ViewProduct") + .addProperty("ProductName", "XX手机") + .addProperty("ProductType", "智能手机") + .addProperty("ShopName", "XX官方旗舰店") + .build(); sa.track(lookRecord); // 2. 用户注册登录之后,系统分配的注册ID String registerId = "123456"; - //使用trackSignUp关联用户匿名ID和登录ID + // 使用trackSignUp关联用户匿名ID和登录ID sa.trackSignUp(registerId, cookieId); // 2.2 用户注册时,填充了一些个人信息,可以用Profile接口记录下来 List interests = new ArrayList(); interests.add("movie"); interests.add("swim"); - UserRecord userRecord = UserRecord.builder().setDistinctId(registerId).isLoginId(Boolean.TRUE) - .addProperty("$city", "武汉") - .addProperty("$province", "湖北") - .addProperty("$name", "昵称123") - .addProperty("$signup_time", Calendar.getInstance().getTime()) - .addProperty("Gender", "male") - .addProperty("age", 20) - .addProperty("interest", interests) - .build(); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId(registerId) + .isLoginId(Boolean.TRUE) + .addProperty("$city", "武汉") + .addProperty("$province", "湖北") + .addProperty("$name", "昵称123") + .addProperty("$signup_time", Calendar.getInstance().getTime()) + .addProperty("Gender", "male") + .addProperty("age", 20) + .addProperty("interest", interests) + .build(); sa.profileSet(userRecord); - //2.3 设置首次访问时间 - UserRecord firstVisitRecord = UserRecord.builder().setDistinctId(registerId).isLoginId(Boolean.TRUE) - .addProperty("$first_visit_time", Calendar.getInstance().getTime()) - .build(); + // 2.3 设置首次访问时间 + UserRecord firstVisitRecord = + UserRecord.builder() + .setDistinctId(registerId) + .isLoginId(Boolean.TRUE) + .addProperty("$first_visit_time", Calendar.getInstance().getTime()) + .build(); sa.profileSetOnce(firstVisitRecord); - //2.4 追加属性 + // 2.4 追加属性 List newInterest = new ArrayList(); newInterest.add("ball"); - UserRecord appendRecord = UserRecord.builder().setDistinctId(registerId).isLoginId(Boolean.TRUE) - .addProperty("interest", newInterest) - .build(); + UserRecord appendRecord = + UserRecord.builder() + .setDistinctId(registerId) + .isLoginId(Boolean.TRUE) + .addProperty("interest", newInterest) + .build(); sa.profileAppend(appendRecord); - //2.5 给属性加值 - UserRecord incrementRecord = UserRecord.builder().setDistinctId(registerId).isLoginId(Boolean.TRUE) - .addProperty("age", 2) - .build(); + // 2.5 给属性加值 + UserRecord incrementRecord = + UserRecord.builder() + .setDistinctId(registerId) + .isLoginId(Boolean.TRUE) + .addProperty("age", 2) + .build(); sa.profileIncrement(incrementRecord); - //2.6 移除用户属性 - UserRecord unsetRecord = UserRecord.builder().setDistinctId(registerId).isLoginId(Boolean.TRUE) - .addProperty("age", true) - .build(); + // 2.6 移除用户属性 + UserRecord unsetRecord = + UserRecord.builder() + .setDistinctId(registerId) + .isLoginId(Boolean.TRUE) + .addProperty("age", true) + .build(); sa.profileUnset(unsetRecord); // 3. 用户注册后,进行后续行为 // 3.1 提交订单和提交订单详情 // 订单的信息 - EventRecord orderRecord = EventRecord.builder().setDistinctId(registerId).isLoginId(Boolean.TRUE) - .setEventName("SubmitOrder") - .addProperty("OrderId", "SN_123_AB_TEST") - .build(); + EventRecord orderRecord = + EventRecord.builder() + .setDistinctId(registerId) + .isLoginId(Boolean.TRUE) + .setEventName("SubmitOrder") + .addProperty("OrderId", "SN_123_AB_TEST") + .build(); sa.track(orderRecord); // 3.2 支付订单和支付订单详情 // 整个订单的支付情况 - EventRecord payRecord = EventRecord.builder().setDistinctId(registerId).isLoginId(Boolean.TRUE) - .setEventName("PayOrder") - .addProperty("PaymentMethod", "AliPay") - .addProperty("AllowanceAmount", 30.0) - .addProperty("PaymentAmount", 1204.0) - .build(); + EventRecord payRecord = + EventRecord.builder() + .setDistinctId(registerId) + .isLoginId(Boolean.TRUE) + .setEventName("PayOrder") + .addProperty("PaymentMethod", "AliPay") + .addProperty("AllowanceAmount", 30.0) + .addProperty("PaymentAmount", 1204.0) + .build(); sa.track(payRecord); - //物品纬度表上报 + // 物品纬度表上报 String itemId = "product001", itemType = "mobile"; - ItemRecord addRecord = ItemRecord.builder().setItemId(itemId).setItemType(itemType) - .addProperty("color", "white") - .build(); + ItemRecord addRecord = + ItemRecord.builder() + .setItemId(itemId) + .setItemType(itemType) + .addProperty("color", "white") + .build(); sa.itemSet(addRecord); - //删除物品纬度信息 - ItemRecord deleteRecord = ItemRecord.builder().setItemId(itemId).setItemType(itemType) - .build(); + // 删除物品纬度信息 + ItemRecord deleteRecord = + ItemRecord.builder().setItemId(itemId).setItemType(itemType).build(); sa.itemDelete(deleteRecord); - //Id-mapping - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("email", "fz@163.com") - .build(); + // Id-mapping + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("email", "fz@163.com") + .build(); Map properties = new HashMap(); properties.put("Channel", "baidu"); sa.trackById(identity, "test", properties); - SensorsAnalyticsIdentity identity1 = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("login_id", "fz123") - .build(); + SensorsAnalyticsIdentity identity1 = + SensorsAnalyticsIdentity.builder().addIdentityProperty("login_id", "fz123").build(); sa.bind(identity, identity1); sa.profileSetById(identity, "age", 15); List sports = new ArrayList(); @@ -157,6 +190,6 @@ public static void main(final String[] args) throws Exception { sa.profileSetById(identity, hh); sa.profileIncrementById(identity, "age", 1); sa.profileAppendById(identity, "sport", "ball"); - sa.profileUnsetById(identity,"sport"); + sa.profileUnsetById(identity, "sport"); } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/ISensorsAnalytics.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/ISensorsAnalytics.java index e7629dd..4d450ab 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/ISensorsAnalytics.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/ISensorsAnalytics.java @@ -14,10 +14,8 @@ import com.sensorsdata.analytics.javasdk.bean.schema.UserEventSchema; import com.sensorsdata.analytics.javasdk.bean.schema.UserSchema; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import lombok.NonNull; - import java.util.Map; +import lombok.NonNull; /** * 外部可调用的接口方法 @@ -44,22 +42,20 @@ public interface ISensorsAnalytics { /** * 设置每个事件都带有的一些公共属性 - *

- * 当track的Properties,superProperties和SDK自动生成的automaticProperties有相同的key时,遵循如下的优先级: + * + *

当track的Properties,superProperties和SDK自动生成的automaticProperties有相同的key时,遵循如下的优先级: * track.properties 高于 superProperties 高于 automaticProperties - *

- * 另外,当这个接口被多次调用时,是用新传入的数据去merge先前的数据 - *

- * 例如,在调用接口前,dict是 {"a":1, "b": "bbb"},传入的dict是 {"b": 123, "c": "asd"},则merge后 - * 的结果是 {"a":1, "b": 123, "c": "asd"} + * + *

另外,当这个接口被多次调用时,是用新传入的数据去merge先前的数据 + * + *

例如,在调用接口前,dict是 {"a":1, "b": "bbb"},传入的dict是 {"b": 123, "c": "asd"},则merge后 的结果是 {"a":1, + * "b": 123, "c": "asd"} * * @param superPropertiesMap 一个或多个公共属性 */ void registerSuperProperties(@NonNull Map superPropertiesMap); - /** - * 清除公共属性 - */ + /** 清除公共属性 */ void clearSuperProperties(); /** @@ -72,8 +68,7 @@ public interface ISensorsAnalytics { /** * 记录事件 * - * @param eventRecord 事件消息对象 - * 通过 {@link EventRecord.Builder} 来构造; + * @param eventRecord 事件消息对象 通过 {@link EventRecord.Builder} 来构造; * @throws InvalidArgumentException eventName 或 properties 不符合命名规范和类型规范时抛出该异常 */ void track(@NonNull EventRecord eventRecord) throws InvalidArgumentException; @@ -82,65 +77,67 @@ public interface ISensorsAnalytics { * 记录一个没有任何属性的事件 * * @param distinctId 用户 ID - * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID - * @param eventName 事件名称 + * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID + * @param eventName 事件名称 * @throws InvalidArgumentException eventName 或 properties 不符合命名规范和类型规范时抛出该异常 */ void track(@NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String eventName) - throws InvalidArgumentException; + throws InvalidArgumentException; /** - * 记录一个拥有一个或多个属性的事件。属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和 - * {@link java.util.List}; - * 若属性包含 $time 字段,则它会覆盖事件的默认时间属性,该字段只接受{@link java.util.Date}类型; - * 若属性包含 $project 字段,则它会指定事件导入的项目; + * 记录一个拥有一个或多个属性的事件。属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和 {@link + * java.util.List}; 若属性包含 $time 字段,则它会覆盖事件的默认时间属性,该字段只接受{@link java.util.Date}类型; 若属性包含 $project + * 字段,则它会指定事件导入的项目; * * @param distinctId 用户 ID - * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID - * @param eventName 事件名称 + * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID + * @param eventName 事件名称 * @param properties 事件的属性 * @throws InvalidArgumentException eventName 或 properties 不符合命名规范和类型规范时抛出该异常 */ - void track(@NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String eventName, - Map properties) - throws InvalidArgumentException; + void track( + @NonNull String distinctId, + @NonNull boolean isLoginId, + @NonNull String eventName, + Map properties) + throws InvalidArgumentException; /** * 记录用户注册事件 - *

- * 这个接口是一个较为复杂的功能,请在使用前先阅读相关说明: - * http://www.sensorsdata.cn/manual/track_signup.html + * + *

这个接口是一个较为复杂的功能,请在使用前先阅读相关说明: http://www.sensorsdata.cn/manual/track_signup.html * 并在必要时联系我们的技术支持人员。 * - * @param loginId 登录 ID + * @param loginId 登录 ID * @param anonymousId 匿名 ID * @throws InvalidArgumentException eventName 或 properties 不符合命名规范和类型规范时抛出该异常 */ - void trackSignUp(@NonNull String loginId, @NonNull String anonymousId) throws InvalidArgumentException; + void trackSignUp(@NonNull String loginId, @NonNull String anonymousId) + throws InvalidArgumentException; /** * 记录用户注册事件 - *

- * 这个接口是一个较为复杂的功能,请在使用前先阅读相关说明: - * http://www.sensorsdata.cn/manual/track_signup.html + * + *

这个接口是一个较为复杂的功能,请在使用前先阅读相关说明: http://www.sensorsdata.cn/manual/track_signup.html * 并在必要时联系我们的技术支持人员。 - *

- * 属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link java.util.List}; - * 若属性包含 $time 字段,它会覆盖事件的默认时间属性,该字段只接受{@link java.util.Date}类型; - * 若属性包含 $project 字段,则它会指定事件导入的项目; * - * @param loginId 登录 ID + *

属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link java.util.List}; + * 若属性包含 $time 字段,它会覆盖事件的默认时间属性,该字段只接受{@link java.util.Date}类型; 若属性包含 $project 字段,则它会指定事件导入的项目; + * + * @param loginId 登录 ID * @param anonymousId 匿名 ID - * @param properties 事件的属性 + * @param properties 事件的属性 * @throws InvalidArgumentException eventName 或 properties 不符合命名规范和类型规范时抛出该异常 */ - void trackSignUp(@NonNull String loginId, @NonNull String anonymousId, Map properties) - throws InvalidArgumentException; + void trackSignUp( + @NonNull String loginId, @NonNull String anonymousId, Map properties) + throws InvalidArgumentException; /** - * 设置用户的属性。属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link java.util.List}; - *

- * 如果要设置的properties的key,之前在这个用户的profile中已经存在,则覆盖,否则,新创建 + * 设置用户的属性。属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link + * java.util.List}; + * + *

如果要设置的properties的key,之前在这个用户的profile中已经存在,则覆盖,否则,新创建 * * @param userRecord 用户属性实体 * @throws InvalidArgumentException 用户属性类型或者用户ID不合法则抛出该异常 @@ -148,36 +145,41 @@ void trackSignUp(@NonNull String loginId, @NonNull String anonymousId, Map - * 如果要设置的properties的key,之前在这个用户的profile中已经存在,则覆盖,否则,新创建 + * 设置用户的属性。属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link + * java.util.List}; + * + *

如果要设置的properties的key,之前在这个用户的profile中已经存在,则覆盖,否则,新创建 * * @param distinctId 用户 ID - * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID + * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID * @param properties 用户的属性 * @throws InvalidArgumentException eventName 或 properties 不符合命名规范和类型规范时抛出该异常 */ - void profileSet(@NonNull String distinctId, @NonNull boolean isLoginId, Map properties) - throws InvalidArgumentException; + void profileSet( + @NonNull String distinctId, @NonNull boolean isLoginId, Map properties) + throws InvalidArgumentException; /** * 设置用户的属性。这个接口只能设置单个key对应的内容,同样,如果已经存在,则覆盖,否则,新创建 * * @param distinctId 用户 ID - * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID - * @param property 属性名称 - * @param value 属性的值 + * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID + * @param property 属性名称 + * @param value 属性的值 * @throws InvalidArgumentException eventName 或 properties 不符合命名规范和类型规范时抛出该异常 */ - void profileSet(@NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String property, - @NonNull Object value) throws InvalidArgumentException; + void profileSet( + @NonNull String distinctId, + @NonNull boolean isLoginId, + @NonNull String property, + @NonNull Object value) + throws InvalidArgumentException; /** - * 首次设置用户的属性。 - * 属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link java.util.List}; - *

- * 与profileSet接口不同的是: - * 如果要设置的properties的key,在这个用户的profile中已经存在,则不处理,否则,新创建 + * 首次设置用户的属性。 属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link + * java.util.List}; + * + *

与profileSet接口不同的是: 如果要设置的properties的key,在这个用户的profile中已经存在,则不处理,否则,新创建 * * @param userRecord 用户属性实体 * @throws InvalidArgumentException 用户属性类型或者用户ID不合法则抛出该异常 @@ -185,32 +187,35 @@ void profileSet(@NonNull String distinctId, @NonNull boolean isLoginId, @NonNull void profileSetOnce(@NonNull UserRecord userRecord) throws InvalidArgumentException; /** - * 首次设置用户的属性。 - * 属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link java.util.List}; - *

- * 与profileSet接口不同的是: - * 如果要设置的properties的key,在这个用户的profile中已经存在,则不处理,否则,新创建 + * 首次设置用户的属性。 属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link + * java.util.List}; + * + *

与profileSet接口不同的是: 如果要设置的properties的key,在这个用户的profile中已经存在,则不处理,否则,新创建 * * @param distinctId 用户 ID - * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID + * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID * @param properties 用户的属性 * @throws InvalidArgumentException eventName 或 properties 不符合命名规范和类型规范时抛出该异常 */ - void profileSetOnce(@NonNull String distinctId, @NonNull boolean isLoginId, Map properties) - throws InvalidArgumentException; + void profileSetOnce( + @NonNull String distinctId, @NonNull boolean isLoginId, Map properties) + throws InvalidArgumentException; /** - * 首次设置用户的属性。这个接口只能设置单个key对应的内容。 - * 与profileSet接口不同的是,如果key的内容之前已经存在,则不处理,否则,重新创建 + * 首次设置用户的属性。这个接口只能设置单个key对应的内容。 与profileSet接口不同的是,如果key的内容之前已经存在,则不处理,否则,重新创建 * * @param distinctId 用户 ID - * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID - * @param property 属性名称 - * @param value 属性的值 + * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID + * @param property 属性名称 + * @param value 属性的值 * @throws InvalidArgumentException eventName 或 properties 不符合命名规范和类型规范时抛出该异常 */ - void profileSetOnce(@NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String property, - @NonNull Object value) throws InvalidArgumentException; + void profileSetOnce( + @NonNull String distinctId, + @NonNull boolean isLoginId, + @NonNull String property, + @NonNull Object value) + throws InvalidArgumentException; /** * 为用户的数值类型的属性累加一个数值,若该属性不存在,则创建它并设置默认值为0 @@ -221,32 +226,35 @@ void profileSetOnce(@NonNull String distinctId, @NonNull boolean isLoginId, @Non void profileIncrement(@NonNull UserRecord userRecord) throws InvalidArgumentException; /** - * 为用户的一个或多个数值类型的属性累加一个数值,若该属性不存在,则创建它并设置默认值为0。属性取值只接受 - * {@link Number}类型 + * 为用户的一个或多个数值类型的属性累加一个数值,若该属性不存在,则创建它并设置默认值为0。属性取值只接受 {@link Number}类型 * * @param distinctId 用户 ID - * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID + * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID * @param properties 用户的属性 * @throws InvalidArgumentException eventName 或 properties 不符合命名规范和类型规范时抛出该异常 */ - void profileIncrement(@NonNull String distinctId, @NonNull boolean isLoginId, Map properties) - throws InvalidArgumentException; + void profileIncrement( + @NonNull String distinctId, @NonNull boolean isLoginId, Map properties) + throws InvalidArgumentException; /** * 为用户的数值类型的属性累加一个数值,若该属性不存在,则创建它并设置默认值为0 * * @param distinctId 用户 ID - * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID - * @param property 属性名称 - * @param value 属性的值 + * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID + * @param property 属性名称 + * @param value 属性的值 * @throws InvalidArgumentException eventName 或 properties 不符合命名规范和类型规范时抛出该异常 */ - void profileIncrement(@NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String property, - @NonNull long value) throws InvalidArgumentException; + void profileIncrement( + @NonNull String distinctId, + @NonNull boolean isLoginId, + @NonNull String property, + @NonNull long value) + throws InvalidArgumentException; /** - * 为用户的一个或多个数组类型的属性追加字符串,属性取值类型必须为 {@link java.util.List},且列表中元素的类型 - * 必须为 {@link String} + * 为用户的一个或多个数组类型的属性追加字符串,属性取值类型必须为 {@link java.util.List},且列表中元素的类型 必须为 {@link String} * * @param userRecord 用户属性实体 * @throws InvalidArgumentException 用户属性类型或者用户ID不合法则抛出该异常 @@ -254,28 +262,32 @@ void profileIncrement(@NonNull String distinctId, @NonNull boolean isLoginId, @N void profileAppend(@NonNull UserRecord userRecord) throws InvalidArgumentException; /** - * 为用户的一个或多个数组类型的属性追加字符串,属性取值类型必须为 {@link java.util.List},且列表中元素的类型 - * 必须为 {@link String} + * 为用户的一个或多个数组类型的属性追加字符串,属性取值类型必须为 {@link java.util.List},且列表中元素的类型 必须为 {@link String} * * @param distinctId 用户 ID - * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID + * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID * @param properties 用户的属性 * @throws InvalidArgumentException eventName 或 properties 不符合命名规范和类型规范时抛出该异常 */ - void profileAppend(@NonNull String distinctId, @NonNull boolean isLoginId, Map properties) - throws InvalidArgumentException; + void profileAppend( + @NonNull String distinctId, @NonNull boolean isLoginId, Map properties) + throws InvalidArgumentException; /** * 为用户的数组类型的属性追加一个字符串 * * @param distinctId 用户 ID - * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID - * @param property 属性名称 - * @param value 属性的值 + * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID + * @param property 属性名称 + * @param value 属性的值 * @throws InvalidArgumentException eventName 或 properties 不符合命名规范和类型规范时抛出该异常 */ - void profileAppend(@NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String property, - @NonNull String value) throws InvalidArgumentException; + void profileAppend( + @NonNull String distinctId, + @NonNull boolean isLoginId, + @NonNull String property, + @NonNull String value) + throws InvalidArgumentException; /** * 删除用户已存在的一条或者多条属性 @@ -289,23 +301,25 @@ void profileAppend(@NonNull String distinctId, @NonNull boolean isLoginId, @NonN * 删除用户某一个属性 * * @param distinctId 用户 ID - * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID - * @param property 属性名称 + * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID + * @param property 属性名称 * @throws InvalidArgumentException 用户属性类型或者用户ID不合法则抛出该异常 */ - void profileUnset(@NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String property) - throws InvalidArgumentException; + void profileUnset( + @NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String property) + throws InvalidArgumentException; /** * 删除用户属性 * * @param distinctId 用户 ID - * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID + * @param isLoginId 用户 ID 是否是登录 ID,false 表示该 ID 是一个匿名 ID * @param properties 用户属性名称列表,要删除的属性值请设置为 Boolean 类型的 true,如果要删除指定项目的用户属性,需正确传 $project 字段 * @throws InvalidArgumentException 用户属性类型或者用户ID不合法则抛出该异常 */ - void profileUnset(@NonNull String distinctId, @NonNull boolean isLoginId, Map properties) - throws InvalidArgumentException; + void profileUnset( + @NonNull String distinctId, @NonNull boolean isLoginId, Map properties) + throws InvalidArgumentException; /** * 删除用户所有属性 @@ -319,10 +333,11 @@ void profileUnset(@NonNull String distinctId, @NonNull boolean isLoginId, Map properties) - throws InvalidArgumentException; + void itemSet( + @NonNull String itemType, + @NonNull String itemId, + @NonNull Map properties) + throws InvalidArgumentException; /** * 删除维度表记录 @@ -354,13 +372,14 @@ void itemSet(@NonNull String itemType, @NonNull String itemId, @NonNull Map properties) - throws InvalidArgumentException; + void itemDelete( + @NonNull String itemType, @NonNull String itemId, Map properties) + throws InvalidArgumentException; /** * 用户标识绑定 @@ -368,7 +387,8 @@ void itemDelete(@NonNull String itemType, @NonNull String itemId, Map properties, @NonNull SensorsAnalyticsIdentity... analyticsIdentity) - throws InvalidArgumentException; + void bind( + Map properties, @NonNull SensorsAnalyticsIdentity... analyticsIdentity) + throws InvalidArgumentException; /** * 用户标识解绑 * - * @param key 用户标识 key - * @param value 用户标识值 + * @param key 用户标识 key + * @param value 用户标识值 * @param properties 自定义属性 * @throws InvalidArgumentException 不合法参数异常 */ void unbind(@NonNull String key, @NonNull String value, Map properties) - throws InvalidArgumentException; + throws InvalidArgumentException; /** * 使用用户标识 3.0 系统埋点事件 * * @param analyticsIdentity 用户标识 ID - * @param eventName 事件名 - * @param properties 事件属性 + * @param eventName 事件名 + * @param properties 事件属性 * @throws InvalidArgumentException 不合法参数异常 */ - void trackById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonNull String eventName, - Map properties) throws InvalidArgumentException; + void trackById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, + @NonNull String eventName, + Map properties) + throws InvalidArgumentException; /** - * 设置用户的属性。属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link java.util.List}; - *

- * 如果要设置的 properties 的 key,之前在这个用户的 profile 中已经存在,则覆盖,否则,新创建 + * 设置用户的属性。属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link + * java.util.List}; + * + *

如果要设置的 properties 的 key,之前在这个用户的 profile 中已经存在,则覆盖,否则,新创建 * * @param analyticsIdentity 用户标识 ID - * @param properties 用户属性 + * @param properties 用户属性 * @throws InvalidArgumentException 不合法参数异常 */ - void profileSetById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) - throws InvalidArgumentException; + void profileSetById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) + throws InvalidArgumentException; /** - * 设置用户的属性。属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link java.util.List}; - *

- * 如果要设置的properties的key,之前在这个用户的profile中已经存在,则覆盖,否则,新创建 + * 设置用户的属性。属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link + * java.util.List}; + * + *

如果要设置的properties的key,之前在这个用户的profile中已经存在,则覆盖,否则,新创建 * * @param analyticsIdentity 用户标识 ID - * @param property 属性名 - * @param value 用于属性 + * @param property 属性名 + * @param value 用于属性 * @throws InvalidArgumentException 不合法参数异常 */ - void profileSetById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonNull String property, - @NonNull Object value) throws InvalidArgumentException; + void profileSetById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, + @NonNull String property, + @NonNull Object value) + throws InvalidArgumentException; /** - * 首次设置用户的属性。 - * 属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link java.util.List}; - *

- * 与 profileSetById 接口不同的是: - * 如果要设置的 properties 的 key,在这个用户的 profile 中已经存在,则不处理,否则,新创建 + * 首次设置用户的属性。 属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link + * java.util.List}; + * + *

与 profileSetById 接口不同的是: 如果要设置的 properties 的 key,在这个用户的 profile 中已经存在,则不处理,否则,新创建 * * @param analyticsIdentity 用户标识 ID - * @param properties 用户属性 + * @param properties 用户属性 * @throws InvalidArgumentException 不合法参数异常 */ - void profileSetOnceById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) - throws InvalidArgumentException; + void profileSetOnceById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) + throws InvalidArgumentException; /** - * 首次设置用户的属性。 - * 属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link java.util.List}; - *

- * 与 profileSetById 接口不同的是: - * 如果要设置的 properties 的 key,在这个用户的 profile 中已经存在,则不处理,否则,新创建 + * 首次设置用户的属性。 属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link + * java.util.List}; + * + *

与 profileSetById 接口不同的是: 如果要设置的 properties 的 key,在这个用户的 profile 中已经存在,则不处理,否则,新创建 * * @param analyticsIdentity 用户标识 ID - * @param property 属性名 - * @param value 属性值 + * @param property 属性名 + * @param value 属性值 * @throws InvalidArgumentException 不合法参数异常 */ - void profileSetOnceById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonNull String property, - @NonNull Object value) throws InvalidArgumentException; + void profileSetOnceById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, + @NonNull String property, + @NonNull Object value) + throws InvalidArgumentException; /** * 为用户的一个或多个数值类型的属性累加一个数值,若该属性不存在,则创建它并设置默认值为 0。属性取值只接受{@link Number}类型 * * @param analyticsIdentity 用户标识 ID - * @param properties 用户属性 + * @param properties 用户属性 * @throws InvalidArgumentException 不合法参数异常 */ - void profileIncrementById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) - throws InvalidArgumentException; + void profileIncrementById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) + throws InvalidArgumentException; /** * 为用户的一个或多个数值类型的属性累加一个数值,若该属性不存在,则创建它并设置默认值为 0。属性取值只接受{@link Number}类型 * * @param analyticsIdentity 用户标识 ID - * @param property 属性名 - * @param value 属性值 + * @param property 属性名 + * @param value 属性值 * @throws InvalidArgumentException 不合法参数异常 */ - void profileIncrementById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, String property, long value) - throws InvalidArgumentException; + void profileIncrementById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, String property, long value) + throws InvalidArgumentException; /** * 为用户的一个或多个数组类型的属性追加字符串,属性取值类型必须为 {@link java.util.List},且列表中元素的类型必须为 {@link String} * * @param analyticsIdentity 用户标识 ID - * @param properties 用户属性 + * @param properties 用户属性 * @throws InvalidArgumentException 不合法参数异常 */ - void profileAppendById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) - throws InvalidArgumentException; + void profileAppendById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) + throws InvalidArgumentException; /** * 为用户的一个或多个数组类型的属性追加字符串,属性取值类型必须为 {@link java.util.List},且列表中元素的类型必须为 {@link String} * * @param analyticsIdentity 用户标识 ID - * @param property 属性名 - * @param value 属性值 + * @param property 属性名 + * @param value 属性值 * @throws InvalidArgumentException 不合法参数异常 */ - void profileAppendById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonNull String property, - @NonNull String value) throws InvalidArgumentException; + void profileAppendById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, + @NonNull String property, + @NonNull String value) + throws InvalidArgumentException; /** * 删除用户某一个属性 * * @param analyticsIdentity 用户标识 ID - * @param properties 用户属性 + * @param properties 用户属性 * @throws InvalidArgumentException 不合法参数异常 */ - void profileUnsetById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) - throws InvalidArgumentException; + void profileUnsetById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) + throws InvalidArgumentException; /** * 删除用户某一个属性 * * @param analyticsIdentity 用户标识 ID - * @param property 用户属性 + * @param property 用户属性 * @throws InvalidArgumentException 不合法参数异常 */ - void profileUnsetById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonNull String property) - throws InvalidArgumentException; + void profileUnsetById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonNull String property) + throws InvalidArgumentException; /** * 删除用户所有属性 @@ -545,16 +586,18 @@ void profileUnsetById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonN * @see #profileDeleteById(String, String) */ @Deprecated - void profileDeleteById(@NonNull SensorsAnalyticsIdentity analyticsIdentity) throws InvalidArgumentException; + void profileDeleteById(@NonNull SensorsAnalyticsIdentity analyticsIdentity) + throws InvalidArgumentException; /** * 删除指定用户的所有属性 * - * @param key 用户标识 key + * @param key 用户标识 key * @param value 用户标识值 * @throws InvalidArgumentException 不合法参数异常 */ - void profileDeleteById(@NonNull String key, @NonNull String value) throws InvalidArgumentException; + void profileDeleteById(@NonNull String key, @NonNull String value) + throws InvalidArgumentException; /** * 使用 IDM3.0 触发埋点事件 @@ -565,9 +608,10 @@ void profileUnsetById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonN void trackById(@NonNull IDMEventRecord idmEventRecord) throws InvalidArgumentException; /** - * 设置用户的属性。属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link java.util.List}; - *

- * 如果要设置的 properties 的 key,之前在这个用户的 profile 中已经存在,则覆盖,否则,新创建 + * 设置用户的属性。属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link + * java.util.List}; + * + *

如果要设置的 properties 的 key,之前在这个用户的 profile 中已经存在,则覆盖,否则,新创建 * * @param idmUserRecord 用户属性集合对象 {@link com.sensorsdata.analytics.javasdk.bean.IDMUserRecord} * @throws InvalidArgumentException 不合法参数异常 @@ -575,8 +619,8 @@ void profileUnsetById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonN void profileSetById(@NonNull IDMUserRecord idmUserRecord) throws InvalidArgumentException; /** - * 首次设置用户的属性。 - * 属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link java.util.List}; + * 首次设置用户的属性。 属性取值可接受类型为{@link Number}, {@link String}, {@link java.util.Date}和{@link + * java.util.List}; * * @param idmUserRecord 用户属性集合对象 {@link com.sensorsdata.analytics.javasdk.bean.IDMUserRecord} * @throws InvalidArgumentException 不合法参数异常 @@ -607,7 +651,6 @@ void profileUnsetById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonN */ void profileUnsetById(@NonNull IDMUserRecord idmUserRecord) throws InvalidArgumentException; - void track(@NonNull UserEventSchema userEventSchema) throws InvalidArgumentException; void track(@NonNull ItemEventSchema itemEventSchema) throws InvalidArgumentException; @@ -650,13 +693,9 @@ void profileUnsetById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonN */ void detailDelete(@NonNull DetailSchema detailSchema) throws InvalidArgumentException; - /** - * 立即发送缓存中的所有日志 - */ + /** 立即发送缓存中的所有日志 */ void flush(); - /** - * 停止SensorsDataAPI所有线程,API停止前会清空所有本地数据 - */ + /** 停止SensorsDataAPI所有线程,API停止前会清空所有本地数据 */ void shutdown(); } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsAnalytics.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsAnalytics.java index 1cbc929..be98fc4 100755 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsAnalytics.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsAnalytics.java @@ -39,19 +39,15 @@ import com.sensorsdata.analytics.javasdk.consumer.Consumer; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - -import lombok.NonNull; -import lombok.extern.slf4j.Slf4j; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import lombok.NonNull; +import lombok.extern.slf4j.Slf4j; -/** - * Sensors Analytics SDK - */ +/** Sensors Analytics SDK */ @Slf4j public class SensorsAnalytics implements ISensorsAnalytics { @@ -65,8 +61,8 @@ public class SensorsAnalytics implements ISensorsAnalytics { void setSuperProperties(Map superProperties) { for (Map.Entry entry : superProperties.entrySet()) { - if (SensorsAnalyticsUtil.KEY_PATTERN.matcher(entry.getKey()).matches() && - !"$track_id".equals(entry.getKey())) { + if (SensorsAnalyticsUtil.KEY_PATTERN.matcher(entry.getKey()).matches() + && !"$track_id".equals(entry.getKey())) { this.superProperties.put(entry.getKey(), entry.getValue()); } } @@ -111,7 +107,9 @@ public void clearSuperProperties() { @Override public void track(@NonNull EventRecord eventRecord) throws InvalidArgumentException { - eventRecord.getPropertyMap().putAll(putAllSuperPro(eventRecord.getPropertyMap(), superProperties)); + eventRecord + .getPropertyMap() + .putAll(putAllSuperPro(eventRecord.getPropertyMap(), superProperties)); worker.doAddData(new SensorsData(eventRecord, TRACK_ACTION_TYPE)); } @@ -148,7 +146,8 @@ public void profileUnset(@NonNull UserRecord userRecord) throws InvalidArgumentE continue; } } - throw new InvalidArgumentException("The property value of " + property.getKey() + " should be true."); + throw new InvalidArgumentException( + "The property value of " + property.getKey() + " should be true."); } } dealProfile(userRecord, PROFILE_UNSET_ACTION_TYPE); @@ -161,91 +160,129 @@ public void profileDelete(@NonNull UserRecord userRecord) throws InvalidArgument @Override public void itemSet(@NonNull ItemRecord itemRecord) throws InvalidArgumentException { - addItem(itemRecord.getItemType(), itemRecord.getItemId(), ITEM_SET_ACTION_TYPE, - itemRecord.getPropertyMap()); + addItem( + itemRecord.getItemType(), + itemRecord.getItemId(), + ITEM_SET_ACTION_TYPE, + itemRecord.getPropertyMap()); } @Override public void itemDelete(@NonNull ItemRecord itemRecord) throws InvalidArgumentException { - addItem(itemRecord.getItemType(), itemRecord.getItemId(), ITEM_DELETE_ACTION_TYPE, - itemRecord.getPropertyMap()); + addItem( + itemRecord.getItemType(), + itemRecord.getItemId(), + ITEM_DELETE_ACTION_TYPE, + itemRecord.getPropertyMap()); } @Override - public void track(@NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String eventName) - throws InvalidArgumentException { + public void track( + @NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String eventName) + throws InvalidArgumentException { addEvent(distinctId, isLoginId, null, TRACK_ACTION_TYPE, eventName, null); } @Override - public void track(@NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String eventName, - Map properties) - throws InvalidArgumentException { + public void track( + @NonNull String distinctId, + @NonNull boolean isLoginId, + @NonNull String eventName, + Map properties) + throws InvalidArgumentException { addEvent(distinctId, isLoginId, null, TRACK_ACTION_TYPE, eventName, properties); } @Override - public void trackSignUp(@NonNull String loginId, @NonNull String anonymousId) throws InvalidArgumentException { + public void trackSignUp(@NonNull String loginId, @NonNull String anonymousId) + throws InvalidArgumentException { addEvent(loginId, false, anonymousId, TRACK_SIGN_UP_ACTION_TYPE, SIGN_UP_SYSTEM_ATTR, null); } @Override - public void trackSignUp(@NonNull String loginId, @NonNull String anonymousId, Map properties) - throws InvalidArgumentException { - addEvent(loginId, false, anonymousId, TRACK_SIGN_UP_ACTION_TYPE, SIGN_UP_SYSTEM_ATTR, properties); + public void trackSignUp( + @NonNull String loginId, @NonNull String anonymousId, Map properties) + throws InvalidArgumentException { + addEvent( + loginId, + false, + anonymousId, + TRACK_SIGN_UP_ACTION_TYPE, + SIGN_UP_SYSTEM_ATTR, + properties); } @Override - public void profileSet(@NonNull String distinctId, @NonNull boolean isLoginId, Map properties) - throws InvalidArgumentException { + public void profileSet( + @NonNull String distinctId, @NonNull boolean isLoginId, Map properties) + throws InvalidArgumentException { dealProfile(distinctId, isLoginId, properties, PROFILE_SET_ACTION_TYPE); } @Override - public void profileSet(@NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String property, - @NonNull Object value) throws InvalidArgumentException { + public void profileSet( + @NonNull String distinctId, + @NonNull boolean isLoginId, + @NonNull String property, + @NonNull Object value) + throws InvalidArgumentException { Map properties = new HashMap<>(); properties.put(property, value); dealProfile(distinctId, isLoginId, properties, PROFILE_SET_ACTION_TYPE); } @Override - public void profileSetOnce(@NonNull String distinctId, @NonNull boolean isLoginId, Map properties) - throws InvalidArgumentException { + public void profileSetOnce( + @NonNull String distinctId, @NonNull boolean isLoginId, Map properties) + throws InvalidArgumentException { dealProfile(distinctId, isLoginId, properties, PROFILE_SET_ONCE_ACTION_TYPE); } @Override - public void profileSetOnce(@NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String property, - @NonNull Object value) throws InvalidArgumentException { + public void profileSetOnce( + @NonNull String distinctId, + @NonNull boolean isLoginId, + @NonNull String property, + @NonNull Object value) + throws InvalidArgumentException { Map properties = new HashMap<>(); properties.put(property, value); dealProfile(distinctId, isLoginId, properties, PROFILE_SET_ONCE_ACTION_TYPE); } @Override - public void profileIncrement(@NonNull String distinctId, @NonNull boolean isLoginId, Map properties) - throws InvalidArgumentException { + public void profileIncrement( + @NonNull String distinctId, @NonNull boolean isLoginId, Map properties) + throws InvalidArgumentException { dealProfile(distinctId, isLoginId, properties, PROFILE_INCREMENT_ACTION_TYPE); } @Override - public void profileIncrement(@NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String property, - @NonNull long value) throws InvalidArgumentException { + public void profileIncrement( + @NonNull String distinctId, + @NonNull boolean isLoginId, + @NonNull String property, + @NonNull long value) + throws InvalidArgumentException { Map properties = new HashMap<>(); properties.put(property, value); dealProfile(distinctId, isLoginId, properties, PROFILE_INCREMENT_ACTION_TYPE); } @Override - public void profileAppend(@NonNull String distinctId, @NonNull boolean isLoginId, Map properties) - throws InvalidArgumentException { + public void profileAppend( + @NonNull String distinctId, @NonNull boolean isLoginId, Map properties) + throws InvalidArgumentException { dealProfile(distinctId, isLoginId, properties, PROFILE_APPEND_ACTION_TYPE); } @Override - public void profileAppend(@NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String property, - @NonNull String value) throws InvalidArgumentException { + public void profileAppend( + @NonNull String distinctId, + @NonNull boolean isLoginId, + @NonNull String property, + @NonNull String value) + throws InvalidArgumentException { List values = new ArrayList<>(); values.add(value); Map properties = new HashMap<>(); @@ -254,16 +291,18 @@ public void profileAppend(@NonNull String distinctId, @NonNull boolean isLoginId } @Override - public void profileUnset(@NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String property) - throws InvalidArgumentException { + public void profileUnset( + @NonNull String distinctId, @NonNull boolean isLoginId, @NonNull String property) + throws InvalidArgumentException { Map properties = new HashMap<>(); properties.put(property, true); dealProfile(distinctId, isLoginId, properties, PROFILE_UNSET_ACTION_TYPE); } @Override - public void profileUnset(@NonNull String distinctId, @NonNull boolean isLoginId, Map properties) - throws InvalidArgumentException { + public void profileUnset( + @NonNull String distinctId, @NonNull boolean isLoginId, Map properties) + throws InvalidArgumentException { if (properties == null) { return; } @@ -275,134 +314,164 @@ public void profileUnset(@NonNull String distinctId, @NonNull boolean isLoginId, continue; } } - throw new InvalidArgumentException("The property value of " + property.getKey() + " should be true."); + throw new InvalidArgumentException( + "The property value of " + property.getKey() + " should be true."); } } dealProfile(distinctId, isLoginId, properties, PROFILE_UNSET_ACTION_TYPE); } @Override - public void profileDelete(@NonNull String distinctId, @NonNull boolean isLoginId) throws InvalidArgumentException { + public void profileDelete(@NonNull String distinctId, @NonNull boolean isLoginId) + throws InvalidArgumentException { dealProfile(distinctId, isLoginId, null, PROFILE_DELETE_ACTION_TYPE); } @Override - public void itemSet(@NonNull String itemType, @NonNull String itemId, Map properties) - throws InvalidArgumentException { + public void itemSet( + @NonNull String itemType, @NonNull String itemId, Map properties) + throws InvalidArgumentException { addItem(itemType, itemId, ITEM_SET_ACTION_TYPE, properties); } @Override - public void itemDelete(@NonNull String itemType, @NonNull String itemId, Map properties) - throws InvalidArgumentException { + public void itemDelete( + @NonNull String itemType, @NonNull String itemId, Map properties) + throws InvalidArgumentException { addItem(itemType, itemId, ITEM_DELETE_ACTION_TYPE, properties); } @Override - public void bind(@NonNull SensorsAnalyticsIdentity... identities) throws InvalidArgumentException { - bind(null,identities); + public void bind(@NonNull SensorsAnalyticsIdentity... identities) + throws InvalidArgumentException { + bind(null, identities); } @Override - public void unbind(@NonNull SensorsAnalyticsIdentity analyticsIdentity) throws InvalidArgumentException { + public void unbind(@NonNull SensorsAnalyticsIdentity analyticsIdentity) + throws InvalidArgumentException { if (analyticsIdentity.getIdentityMap().size() != 1) { - throw new InvalidArgumentException("unbind user operation cannot input multiple or none identifiers."); + throw new InvalidArgumentException( + "unbind user operation cannot input multiple or none identifiers."); } - addEventIdentity(analyticsIdentity.getIdentityMap(), null, UNBIND_ID_ACTION_TYPE, UNBIND_ID); + addEventIdentity( + analyticsIdentity.getIdentityMap(), null, UNBIND_ID_ACTION_TYPE, UNBIND_ID); } @Override public void unbind(@NonNull String key, @NonNull String value) throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder().addIdentityProperty(key, value).build(); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder().addIdentityProperty(key, value).build(); addEventIdentity(identity.getIdentityMap(), null, UNBIND_ID_ACTION_TYPE, UNBIND_ID); } @Override - public void bind(Map properties, @NonNull SensorsAnalyticsIdentity... analyticsIdentity) - throws InvalidArgumentException { + public void bind( + Map properties, @NonNull SensorsAnalyticsIdentity... analyticsIdentity) + throws InvalidArgumentException { Map identityMap = new HashMap<>(); for (SensorsAnalyticsIdentity identity : analyticsIdentity) { identityMap.putAll(identity.getIdentityMap()); } if (identityMap.size() < 2) { - throw new InvalidArgumentException("The identities is invalid,you should have at least two identities."); + throw new InvalidArgumentException( + "The identities is invalid,you should have at least two identities."); } addEventIdentity(identityMap, properties, BIND_ID_ACTION_TYPE, BIND_ID); } @Override public void unbind(@NonNull String key, @NonNull String value, Map properties) - throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder().addIdentityProperty(key, value).build(); + throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder().addIdentityProperty(key, value).build(); addEventIdentity(identity.getIdentityMap(), properties, UNBIND_ID_ACTION_TYPE, UNBIND_ID); } @Override - public void trackById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonNull String eventName, - Map properties) throws InvalidArgumentException { + public void trackById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, + @NonNull String eventName, + Map properties) + throws InvalidArgumentException { if (properties == null) { properties = new HashMap<>(); } properties.putAll(superProperties); - IDMEventRecord eventRecord = IDMEventRecord.starter() - .identityMap(analyticsIdentity.getIdentityMap()) - .setEventName(eventName) - .addProperties(properties) - .build(); + IDMEventRecord eventRecord = + IDMEventRecord.starter() + .identityMap(analyticsIdentity.getIdentityMap()) + .setEventName(eventName) + .addProperties(properties) + .build(); worker.doAddData(new SensorsData(eventRecord)); } @Override - public void profileSetById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) - throws InvalidArgumentException { - addProfileIdentity(analyticsIdentity, PROFILE_SET_ACTION_TYPE, properties); + public void profileSetById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) + throws InvalidArgumentException { + addProfileIdentity(analyticsIdentity, PROFILE_SET_ACTION_TYPE, properties); } @Override - public void profileSetById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonNull String property, - @NonNull Object value) throws InvalidArgumentException { + public void profileSetById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, + @NonNull String property, + @NonNull Object value) + throws InvalidArgumentException { Map properties = new HashMap<>(); properties.put(property, value); addProfileIdentity(analyticsIdentity, PROFILE_SET_ACTION_TYPE, properties); } @Override - public void profileSetOnceById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) - throws InvalidArgumentException { + public void profileSetOnceById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) + throws InvalidArgumentException { addProfileIdentity(analyticsIdentity, PROFILE_SET_ONCE_ACTION_TYPE, properties); } @Override - public void profileSetOnceById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonNull String property, - @NonNull Object value) throws InvalidArgumentException { + public void profileSetOnceById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, + @NonNull String property, + @NonNull Object value) + throws InvalidArgumentException { Map properties = new HashMap<>(); properties.put(property, value); - addProfileIdentity(analyticsIdentity, PROFILE_SET_ONCE_ACTION_TYPE, properties); + addProfileIdentity(analyticsIdentity, PROFILE_SET_ONCE_ACTION_TYPE, properties); } @Override - public void profileIncrementById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, - Map properties) throws InvalidArgumentException { + public void profileIncrementById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) + throws InvalidArgumentException { addProfileIdentity(analyticsIdentity, PROFILE_INCREMENT_ACTION_TYPE, properties); } @Override - public void profileIncrementById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, String property, long value) - throws InvalidArgumentException { + public void profileIncrementById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, String property, long value) + throws InvalidArgumentException { Map properties = new HashMap<>(); properties.put(property, value); - addProfileIdentity(analyticsIdentity, PROFILE_INCREMENT_ACTION_TYPE, properties); + addProfileIdentity(analyticsIdentity, PROFILE_INCREMENT_ACTION_TYPE, properties); } @Override - public void profileAppendById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) - throws InvalidArgumentException { + public void profileAppendById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) + throws InvalidArgumentException { addProfileIdentity(analyticsIdentity, PROFILE_APPEND_ACTION_TYPE, properties); } @Override - public void profileAppendById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonNull String property, - @NonNull String value) throws InvalidArgumentException { + public void profileAppendById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, + @NonNull String property, + @NonNull String value) + throws InvalidArgumentException { List values = new ArrayList<>(); values.add(value); Map properties = new HashMap<>(); @@ -411,8 +480,9 @@ public void profileAppendById(@NonNull SensorsAnalyticsIdentity analyticsIdentit } @Override - public void profileUnsetById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) - throws InvalidArgumentException { + public void profileUnsetById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, Map properties) + throws InvalidArgumentException { if (properties == null) { return; } @@ -424,68 +494,85 @@ public void profileUnsetById(@NonNull SensorsAnalyticsIdentity analyticsIdentity continue; } } - throw new InvalidArgumentException("The property value of [" + property.getKey() + "] should be true."); + throw new InvalidArgumentException( + "The property value of [" + property.getKey() + "] should be true."); } } addProfileIdentity(analyticsIdentity, PROFILE_UNSET_ACTION_TYPE, properties); } @Override - public void profileUnsetById(@NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonNull String property) - throws InvalidArgumentException { + public void profileUnsetById( + @NonNull SensorsAnalyticsIdentity analyticsIdentity, @NonNull String property) + throws InvalidArgumentException { Map properties = new HashMap<>(); properties.put(property, true); addProfileIdentity(analyticsIdentity, PROFILE_UNSET_ACTION_TYPE, properties); } @Override - public void profileDeleteById(@NonNull SensorsAnalyticsIdentity analyticsIdentity) throws InvalidArgumentException { + public void profileDeleteById(@NonNull SensorsAnalyticsIdentity analyticsIdentity) + throws InvalidArgumentException { if (analyticsIdentity.getIdentityMap().size() != 1) { - throw new InvalidArgumentException("delete user operation cannot input multiple or none identifiers."); + throw new InvalidArgumentException( + "delete user operation cannot input multiple or none identifiers."); } addProfileIdentity(analyticsIdentity, PROFILE_DELETE_ACTION_TYPE, null); } @Override - public void profileDeleteById(@NonNull String key, @NonNull String value) throws InvalidArgumentException { + public void profileDeleteById(@NonNull String key, @NonNull String value) + throws InvalidArgumentException { SensorsAnalyticsIdentity analyticsIdentity = - SensorsAnalyticsIdentity.builder().addIdentityProperty(key, value).build(); + SensorsAnalyticsIdentity.builder().addIdentityProperty(key, value).build(); addProfileIdentity(analyticsIdentity, PROFILE_DELETE_ACTION_TYPE, null); } @Override public void trackById(@NonNull IDMEventRecord idmEventRecord) throws InvalidArgumentException { - idmEventRecord.getPropertyMap().putAll(putAllSuperPro(idmEventRecord.getPropertyMap(), superProperties)); + idmEventRecord + .getPropertyMap() + .putAll(putAllSuperPro(idmEventRecord.getPropertyMap(), superProperties)); worker.doAddData(new SensorsData(idmEventRecord)); } @Override - public void profileSetById(@NonNull IDMUserRecord idmUserRecord) throws InvalidArgumentException { - SensorsAnalyticsUtil.assertProperties(PROFILE_SET_ACTION_TYPE, idmUserRecord.getPropertyMap()); + public void profileSetById(@NonNull IDMUserRecord idmUserRecord) + throws InvalidArgumentException { + SensorsAnalyticsUtil.assertProperties( + PROFILE_SET_ACTION_TYPE, idmUserRecord.getPropertyMap()); worker.doAddData(new SensorsData(idmUserRecord, PROFILE_SET_ACTION_TYPE)); } @Override - public void profileSetOnceById(@NonNull IDMUserRecord idmUserRecord) throws InvalidArgumentException { - SensorsAnalyticsUtil.assertProperties(PROFILE_SET_ONCE_ACTION_TYPE, idmUserRecord.getPropertyMap()); + public void profileSetOnceById(@NonNull IDMUserRecord idmUserRecord) + throws InvalidArgumentException { + SensorsAnalyticsUtil.assertProperties( + PROFILE_SET_ONCE_ACTION_TYPE, idmUserRecord.getPropertyMap()); worker.doAddData(new SensorsData(idmUserRecord, PROFILE_SET_ONCE_ACTION_TYPE)); } @Override - public void profileIncrementById(@NonNull IDMUserRecord idmUserRecord) throws InvalidArgumentException { - SensorsAnalyticsUtil.assertProperties(PROFILE_INCREMENT_ACTION_TYPE, idmUserRecord.getPropertyMap()); + public void profileIncrementById(@NonNull IDMUserRecord idmUserRecord) + throws InvalidArgumentException { + SensorsAnalyticsUtil.assertProperties( + PROFILE_INCREMENT_ACTION_TYPE, idmUserRecord.getPropertyMap()); worker.doAddData(new SensorsData(idmUserRecord, PROFILE_INCREMENT_ACTION_TYPE)); } @Override - public void profileAppendById(@NonNull IDMUserRecord idmUserRecord) throws InvalidArgumentException { - SensorsAnalyticsUtil.assertProperties(PROFILE_APPEND_ACTION_TYPE, idmUserRecord.getPropertyMap()); + public void profileAppendById(@NonNull IDMUserRecord idmUserRecord) + throws InvalidArgumentException { + SensorsAnalyticsUtil.assertProperties( + PROFILE_APPEND_ACTION_TYPE, idmUserRecord.getPropertyMap()); worker.doAddData(new SensorsData(idmUserRecord, PROFILE_APPEND_ACTION_TYPE)); } @Override - public void profileUnsetById(@NonNull IDMUserRecord idmUserRecord) throws InvalidArgumentException { - SensorsAnalyticsUtil.assertProperties(PROFILE_UNSET_ACTION_TYPE, idmUserRecord.getPropertyMap()); + public void profileUnsetById(@NonNull IDMUserRecord idmUserRecord) + throws InvalidArgumentException { + SensorsAnalyticsUtil.assertProperties( + PROFILE_UNSET_ACTION_TYPE, idmUserRecord.getPropertyMap()); if (idmUserRecord.getPropertyMap() == null) { return; } @@ -497,83 +584,99 @@ public void profileUnsetById(@NonNull IDMUserRecord idmUserRecord) throws Invali continue; } } - throw new InvalidArgumentException("The property value of " + property.getKey() + " should be true."); + throw new InvalidArgumentException( + "The property value of " + property.getKey() + " should be true."); } } worker.doAddData(new SensorsData(idmUserRecord, PROFILE_UNSET_ACTION_TYPE)); } - @Override public void track(@NonNull UserEventSchema userEventSchema) throws InvalidArgumentException { - userEventSchema.getPropertyMap().putAll(putAllSuperPro(userEventSchema.getPropertyMap(), superProperties)); + userEventSchema + .getPropertyMap() + .putAll(putAllSuperPro(userEventSchema.getPropertyMap(), superProperties)); worker.doSchemaData(new SensorsSchemaData(userEventSchema, TRACK_ACTION_TYPE)); } @Override public void track(@NonNull ItemEventSchema itemEventSchema) throws InvalidArgumentException { - itemEventSchema.getProperties().putAll(putAllSuperPro(itemEventSchema.getProperties(), superProperties)); + itemEventSchema + .getProperties() + .putAll(putAllSuperPro(itemEventSchema.getProperties(), superProperties)); worker.doSchemaData(new SensorsSchemaData(itemEventSchema, TRACK_ACTION_TYPE)); } @Override public void bind(@NonNull IdentitySchema identitySchema) throws InvalidArgumentException { if (identitySchema.getIdMap().size() < 2) { - throw new InvalidArgumentException("The identities is invalid,you should have at least two identities."); + throw new InvalidArgumentException( + "The identities is invalid,you should have at least two identities."); } - UserEventSchema userEventSchema = UserEventSchema.init() - .setEventName(BIND_ID) - .identityMap(identitySchema.getIdMap()) - .addProperties(putAllSuperPro(identitySchema.getProperties(), superProperties)) - .start(); + UserEventSchema userEventSchema = + UserEventSchema.init() + .setEventName(BIND_ID) + .identityMap(identitySchema.getIdMap()) + .addProperties( + putAllSuperPro(identitySchema.getProperties(), superProperties)) + .start(); worker.doSchemaData(new SensorsSchemaData(userEventSchema, BIND_ID_ACTION_TYPE)); } @Override public void unbind(@NonNull IdentitySchema identitySchema) throws InvalidArgumentException { if (identitySchema.getIdMap().size() != 1) { - throw new InvalidArgumentException("unbind user operation cannot input multiple or none identifiers."); + throw new InvalidArgumentException( + "unbind user operation cannot input multiple or none identifiers."); } - UserEventSchema userEventSchema = UserEventSchema.init() - .setEventName(UNBIND_ID) - .identityMap(identitySchema.getIdMap()) - .addProperties(putAllSuperPro(identitySchema.getProperties(), superProperties)) - .start(); + UserEventSchema userEventSchema = + UserEventSchema.init() + .setEventName(UNBIND_ID) + .identityMap(identitySchema.getIdMap()) + .addProperties( + putAllSuperPro(identitySchema.getProperties(), superProperties)) + .start(); worker.doSchemaData(new SensorsSchemaData(userEventSchema, UNBIND_ID_ACTION_TYPE)); } @Override public void profileSet(@NonNull UserSchema userSchema) throws InvalidArgumentException { - SensorsAnalyticsUtil.assertSchemaProperties(userSchema.getPropertyMap(), PROFILE_SET_ACTION_TYPE); + SensorsAnalyticsUtil.assertSchemaProperties( + userSchema.getPropertyMap(), PROFILE_SET_ACTION_TYPE); worker.doSchemaData(new SensorsSchemaData(userSchema, PROFILE_SET_ACTION_TYPE)); } @Override public void profileSetOnce(@NonNull UserSchema userSchema) throws InvalidArgumentException { - SensorsAnalyticsUtil.assertSchemaProperties(userSchema.getPropertyMap(), PROFILE_SET_ONCE_ACTION_TYPE); + SensorsAnalyticsUtil.assertSchemaProperties( + userSchema.getPropertyMap(), PROFILE_SET_ONCE_ACTION_TYPE); worker.doSchemaData(new SensorsSchemaData(userSchema, PROFILE_SET_ONCE_ACTION_TYPE)); } @Override public void profileIncrement(@NonNull UserSchema userSchema) throws InvalidArgumentException { - SensorsAnalyticsUtil.assertSchemaProperties(userSchema.getPropertyMap(), PROFILE_INCREMENT_ACTION_TYPE); + SensorsAnalyticsUtil.assertSchemaProperties( + userSchema.getPropertyMap(), PROFILE_INCREMENT_ACTION_TYPE); worker.doSchemaData(new SensorsSchemaData(userSchema, PROFILE_INCREMENT_ACTION_TYPE)); } @Override public void profileAppend(@NonNull UserSchema userSchema) throws InvalidArgumentException { - SensorsAnalyticsUtil.assertSchemaProperties(userSchema.getPropertyMap(), PROFILE_APPEND_ACTION_TYPE); + SensorsAnalyticsUtil.assertSchemaProperties( + userSchema.getPropertyMap(), PROFILE_APPEND_ACTION_TYPE); worker.doSchemaData(new SensorsSchemaData(userSchema, PROFILE_APPEND_ACTION_TYPE)); } @Override public void profileUnset(@NonNull UserSchema userSchema) throws InvalidArgumentException { - SensorsAnalyticsUtil.assertSchemaProperties(userSchema.getPropertyMap(), PROFILE_UNSET_ACTION_TYPE); + SensorsAnalyticsUtil.assertSchemaProperties( + userSchema.getPropertyMap(), PROFILE_UNSET_ACTION_TYPE); worker.doSchemaData(new SensorsSchemaData(userSchema, PROFILE_UNSET_ACTION_TYPE)); } @Override - public void profileDelete(@NonNull String key, @NonNull String value) throws InvalidArgumentException { + public void profileDelete(@NonNull String key, @NonNull String value) + throws InvalidArgumentException { UserSchema userSchema = UserSchema.init().addIdentityProperty(key, value).start(); worker.doSchemaData(new SensorsSchemaData(userSchema, PROFILE_DELETE_ACTION_TYPE)); } @@ -614,90 +717,110 @@ public void shutdown() { worker.shutdown(); } - private void dealProfile(String distinctId, Boolean isLoginId, Map properties, String actionType) - throws InvalidArgumentException { + private void dealProfile( + String distinctId, Boolean isLoginId, Map properties, String actionType) + throws InvalidArgumentException { SensorsAnalyticsUtil.assertProperties(actionType, properties); - UserRecord userRecord = UserRecord.builder() - .setDistinctId(distinctId) - .isLoginId(isLoginId) - .addProperties(properties) - .build(); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId(distinctId) + .isLoginId(isLoginId) + .addProperties(properties) + .build(); worker.doAddData(new SensorsData(userRecord, actionType)); } - private void dealProfile(UserRecord userRecord, String actionType) throws InvalidArgumentException { + private void dealProfile(UserRecord userRecord, String actionType) + throws InvalidArgumentException { SensorsAnalyticsUtil.assertProperties(actionType, userRecord.getPropertyMap()); worker.doAddData(new SensorsData(userRecord, actionType)); } - private void addItem(String itemType, String itemId, String actionType, Map properties) - throws InvalidArgumentException { + private void addItem( + String itemType, String itemId, String actionType, Map properties) + throws InvalidArgumentException { SensorsAnalyticsUtil.assertProperties(actionType, properties); - ItemRecord itemRecord = ItemRecord.builder() - .setItemId(itemId) - .setItemType(itemType) - .addProperties(properties) - .build(); + ItemRecord itemRecord = + ItemRecord.builder() + .setItemId(itemId) + .setItemType(itemType) + .addProperties(properties) + .build(); worker.doAddData(new SensorsData(itemRecord, actionType)); } - private void addEvent(String distinctId, boolean isLoginId, String originDistinctId, String actionType, - String eventName, Map properties) throws InvalidArgumentException { + private void addEvent( + String distinctId, + boolean isLoginId, + String originDistinctId, + String actionType, + String eventName, + Map properties) + throws InvalidArgumentException { SensorsAnalyticsUtil.assertProperties(actionType, properties); if (actionType.equals(TRACK_SIGN_UP_ACTION_TYPE)) { SensorsAnalyticsUtil.assertValue(ORIGINAL_DISTINCT_ID, originDistinctId); } - EventRecord eventRecord = EventRecord.builder() - .setEventName(eventName) - .setDistinctId(distinctId) - .isLoginId(isLoginId) - .addProperties(putAllSuperPro(properties, superProperties)) - .build(); + EventRecord eventRecord = + EventRecord.builder() + .setEventName(eventName) + .setDistinctId(distinctId) + .isLoginId(isLoginId) + .addProperties(putAllSuperPro(properties, superProperties)) + .build(); SensorsData sensorsData = new SensorsData(eventRecord, actionType); sensorsData.setOriginalId(originDistinctId); worker.doAddData(sensorsData); } - private void addProfileIdentity(SensorsAnalyticsIdentity analyticsIdentity, String actionType, - Map properties) throws InvalidArgumentException { + private void addProfileIdentity( + SensorsAnalyticsIdentity analyticsIdentity, + String actionType, + Map properties) + throws InvalidArgumentException { if (analyticsIdentity.getIdentityMap().isEmpty()) { throw new InvalidArgumentException("The identity is empty."); } assertIdentityMap(actionType, analyticsIdentity.getIdentityMap()); SensorsAnalyticsUtil.assertProperties(actionType, properties); - IDMUserRecord idmUserRecord = IDMUserRecord.starter() - .identityMap(analyticsIdentity.getIdentityMap()) - .addProperties(properties) - .build(); + IDMUserRecord idmUserRecord = + IDMUserRecord.starter() + .identityMap(analyticsIdentity.getIdentityMap()) + .addProperties(properties) + .build(); worker.doAddData(new SensorsData(idmUserRecord, actionType)); } - private void addEventIdentity(Map identityMap, Map properties, String actionType, - String eventName) - throws InvalidArgumentException { + private void addEventIdentity( + Map identityMap, + Map properties, + String actionType, + String eventName) + throws InvalidArgumentException { if (identityMap.isEmpty()) { throw new InvalidArgumentException("The identity is empty."); } assertIdentityMap(actionType, identityMap); SensorsAnalyticsUtil.assertProperties(actionType, properties); - IDMEventRecord idmEventRecord = IDMEventRecord.starter() - .setEventName(eventName) - .identityMap(identityMap) - .addProperties(putAllSuperPro(properties, superProperties)) - .build(); + IDMEventRecord idmEventRecord = + IDMEventRecord.starter() + .setEventName(eventName) + .identityMap(identityMap) + .addProperties(putAllSuperPro(properties, superProperties)) + .build(); worker.doAddData(new SensorsData(idmEventRecord, actionType)); } - - - private void assertIdentityMap(String actionType, Map identityMap) throws InvalidArgumentException { + private void assertIdentityMap(String actionType, Map identityMap) + throws InvalidArgumentException { for (Map.Entry entry : identityMap.entrySet()) { SensorsAnalyticsUtil.assertKey(actionType, entry.getKey()); SensorsAnalyticsUtil.assertValue(actionType, entry.getValue()); } } - private Map putAllSuperPro(Map pro, Map superPro) { + private Map putAllSuperPro( + Map pro, Map superPro) { if (pro == null) { pro = new HashMap<>(); } @@ -708,5 +831,4 @@ private Map putAllSuperPro(Map pro, Map data = SensorsData.generateData(sensorsData); - data.put("lib", generateLibInfo()); - if (timeFree && (TRACK_ACTION_TYPE.equals(sensorsData.getType()) - || TRACK_SIGN_UP_ACTION_TYPE.equals(sensorsData.getType())) - || BIND_ID_ACTION_TYPE.equals(sensorsData.getType()) - || UNBIND_ID_ACTION_TYPE.equals(sensorsData.getType())) { - data.put("time_free", true); + public SensorsAnalyticsWorker(Consumer consumer) { + this.consumer = consumer; + Runtime.getRuntime() + .addShutdownHook( + new Thread( + new Runnable() { + @Override + public void run() { + log.info("Triggered flush when the program is closed."); + flush(); + } + })); } - this.consumer.send(data); - } - void flush() { - this.consumer.flush(); - } + void doAddData(@NonNull SensorsData sensorsData) { + Map data = SensorsData.generateData(sensorsData); + data.put("lib", generateLibInfo()); + if (timeFree + && (TRACK_ACTION_TYPE.equals(sensorsData.getType()) + || TRACK_SIGN_UP_ACTION_TYPE.equals(sensorsData.getType())) + || BIND_ID_ACTION_TYPE.equals(sensorsData.getType()) + || UNBIND_ID_ACTION_TYPE.equals(sensorsData.getType())) { + data.put("time_free", true); + } + this.consumer.send(data); + } - void shutdown() { - this.consumer.close(); - } + void flush() { + this.consumer.flush(); + } + void shutdown() { + this.consumer.close(); + } - public void doSchemaData(@NonNull SensorsSchemaData schemaData) { - Map sensorsData = schemaData.generateData(); - sensorsData.put("lib", generateLibInfo()); - if (timeFree && (TRACK_ACTION_TYPE.equals(schemaData.getType()) - || TRACK_SIGN_UP_ACTION_TYPE.equals(schemaData.getType()) - || BIND_ID_ACTION_TYPE.equals(schemaData.getType()) - || UNBIND_ID_ACTION_TYPE.equals(schemaData.getType()))) { - sensorsData.put("time_free", true); + public void doSchemaData(@NonNull SensorsSchemaData schemaData) { + Map sensorsData = schemaData.generateData(); + sensorsData.put("lib", generateLibInfo()); + if (timeFree + && (TRACK_ACTION_TYPE.equals(schemaData.getType()) + || TRACK_SIGN_UP_ACTION_TYPE.equals(schemaData.getType()) + || BIND_ID_ACTION_TYPE.equals(schemaData.getType()) + || UNBIND_ID_ACTION_TYPE.equals(schemaData.getType()))) { + sensorsData.put("time_free", true); + } + this.consumer.send(sensorsData); } - this.consumer.send(sensorsData); - } - public void setEnableTimeFree(boolean enableTimeFree) { - this.timeFree = enableTimeFree; - } + public void setEnableTimeFree(boolean enableTimeFree) { + this.timeFree = enableTimeFree; + } - public void setEnableCollectMethodStack(boolean enableCollectMethodStack) { - this.enableCollectMethodStack = enableCollectMethodStack; - } + public void setEnableCollectMethodStack(boolean enableCollectMethodStack) { + this.enableCollectMethodStack = enableCollectMethodStack; + } - public Map generateLibInfo() { - Map libProperties = new HashMap<>(); - libProperties.put(LIB_SYSTEM_ATTR, LIB); - libProperties.put(LIB_VERSION_SYSTEM_ATTR, SDK_VERSION); - libProperties.put(LIB_METHOD_SYSTEM_ATTR, "code"); - if (enableCollectMethodStack) { - StackTraceElement[] trace = (new Exception()).getStackTrace(); - if (trace.length > 3) { - StackTraceElement traceElement = trace[3]; - libProperties.put(LIB_DETAIL_SYSTEM_ATTR, - String.format("%s##%s##%s##%s", traceElement.getClassName(), traceElement.getMethodName(), - traceElement.getFileName(), traceElement.getLineNumber())); - } - } else { - libProperties.put(LIB_DETAIL_SYSTEM_ATTR, DEFAULT_LIB_DETAIL); + public Map generateLibInfo() { + Map libProperties = new HashMap<>(); + libProperties.put(LIB_SYSTEM_ATTR, LIB); + libProperties.put(LIB_VERSION_SYSTEM_ATTR, SDK_VERSION); + libProperties.put(LIB_METHOD_SYSTEM_ATTR, "code"); + if (enableCollectMethodStack) { + StackTraceElement[] trace = (new Exception()).getStackTrace(); + if (trace.length > 3) { + StackTraceElement traceElement = trace[3]; + libProperties.put( + LIB_DETAIL_SYSTEM_ATTR, + String.format( + "%s##%s##%s##%s", + traceElement.getClassName(), + traceElement.getMethodName(), + traceElement.getFileName(), + traceElement.getLineNumber())); + } + } else { + libProperties.put(LIB_DETAIL_SYSTEM_ATTR, DEFAULT_LIB_DETAIL); + } + return libProperties; } - return libProperties; - } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsConst.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsConst.java index ecec8bc..9f9b473 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsConst.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsConst.java @@ -9,36 +9,24 @@ */ public class SensorsConst { - private SensorsConst() { - } + private SensorsConst() {} - /** - * 当前JDK版本号,注意要和pom文件里面的version保持一致 - */ + /** 当前JDK版本号,注意要和pom文件里面的version保持一致 */ public static final String SDK_VERSION = "3.6.7"; - /** - * 当前语言类型 - */ + /** 当前语言类型 */ public static final String LIB = "Java"; - /** - * 当前数据协议版本 - */ + /** 当前数据协议版本 */ public static final String PROTOCOL_VERSION = "2.0"; - /** - * user events 所属 schema - */ + /** user events 所属 schema */ public static final String USER_EVENT_SCHEMA = "events"; - /** - * user 所属 schema - */ + /** user 所属 schema */ public static final String USER_SCHEMA = "users"; public static final String USER_ID_PREFIX = "SENSORS_ID:"; - /** - * 事件上报类型 - */ + /** 事件上报类型 */ public static final String TRACK_ACTION_TYPE = "track"; + public static final String TRACK_SIGN_UP_ACTION_TYPE = "track_signup"; public static final String PROFILE_SET_ACTION_TYPE = "profile_set"; public static final String PROFILE_SET_ONCE_ACTION_TYPE = "profile_set_once"; @@ -51,28 +39,22 @@ private SensorsConst() { public static final String DETAIL_SET_ACTION_TYPE = "detail_set"; public static final String DETAIL_DELETE_ACTION_TYPE = "detail_delete"; - /** - * ID-Mapping - */ + /** ID-Mapping */ public static final String BIND_ID_ACTION_TYPE = "track_id_bind"; + public static final String UNBIND_ID_ACTION_TYPE = "track_id_unbind"; public static final String ITEM_TYPE = "Item Type"; public static final String ITEM_ID = "Item Id"; - /** - * 绑定事件名称 - */ + /** 绑定事件名称 */ public static final String BIND_ID = "$BindID"; - /** - * 解绑事件名称 - */ + /** 解绑事件名称 */ public static final String UNBIND_ID = "$UnbindID"; public static final String PROPERTIES = "properties"; - /** - * 系统预置属性 - */ + /** 系统预置属性 */ public static final String TRACK_ID = "$track_id"; + public static final String PROJECT_SYSTEM_ATTR = "$project"; public static final String TIME_SYSTEM_ATTR = "$time"; public static final String TOKEN_SYSTEM_ATTR = "$token"; @@ -85,5 +67,5 @@ private SensorsConst() { public static final String SIGN_UP_SYSTEM_ATTR = "$SignUp"; public static final String TIME_FREE_ATTR = "$time_free"; - public static final String DEFAULT_LIB_DETAIL="JavaSDK##generateLibInfo"; + public static final String DEFAULT_LIB_DETAIL = "JavaSDK##generateLibInfo"; } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsData.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsData.java index 1ed406c..3c521a3 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsData.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsData.java @@ -10,13 +10,11 @@ import com.sensorsdata.analytics.javasdk.bean.IDMUserRecord; import com.sensorsdata.analytics.javasdk.bean.ItemRecord; import com.sensorsdata.analytics.javasdk.bean.UserRecord; - -import lombok.Getter; -import lombok.Setter; - import java.util.Date; import java.util.HashMap; import java.util.Map; +import lombok.Getter; +import lombok.Setter; /** * 神策数据格式(IDM2.0 和 IDM3.0 格式的数据) @@ -28,185 +26,230 @@ @Getter @Setter class SensorsData { - /** - * 数据唯一标识 - */ - private Integer trackId; - /** - * 数据用户唯一标识 - */ - private String distinctId; - /** - * 数据用户匿名标识 - */ - private String originalId; - /** - * IDM3.0 用户维度标识 - */ - private Map identities; - /** - * 事件类型 - */ - private String type; - /** - * 事件名称 - */ - private String event; - /** - * 数据采集来源 - */ - private Map lib; - /** - * 记录生成时间 - */ - private Date time; - /** - * 数据属性集合 - */ - private Map properties; - /** - * 数据接收项目 - */ - private String project; - /** - * 数据 token - */ - private String token; - /** - * 纬度类型 - */ - private String itemType; - /** - * 纬度 ID - */ - private String itemId; - - private boolean timeFree = false; - - protected SensorsData() { - } - - protected SensorsData(EventRecord eventRecord, String actionType) { - this(eventRecord.getDistinctId(), eventRecord.getOriginalId(), null, actionType, eventRecord.getEventName(), - eventRecord.getPropertyMap(), null, null, eventRecord.getTrackId()); - } - - protected SensorsData(ItemRecord itemRecord, String actionType) { - this(null, null, null, actionType, null, itemRecord.getPropertyMap(), - itemRecord.getItemType(), itemRecord.getItemId(), itemRecord.getTrackId()); - } - - protected SensorsData(UserRecord userRecord, String actionType) { - this(userRecord.getDistinctId(), actionType, null, userRecord.getPropertyMap(), userRecord.getTrackId()); - } - - protected SensorsData(T userRecord, String actionType) { - this(userRecord.getDistinctId(), actionType, userRecord.getIdentityMap(), userRecord.getPropertyMap(), - userRecord.getTrackId()); - } - - protected SensorsData(T eventRecord) { - this(eventRecord.getDistinctId(), eventRecord.getIdentityMap(), eventRecord.getEventName(), - eventRecord.getPropertyMap(), eventRecord.getTrackId()); - } - - protected SensorsData(T eventRecord, String actionType) { - this(eventRecord.getDistinctId(), null, eventRecord.getIdentityMap(), actionType, - eventRecord.getEventName(), eventRecord.getPropertyMap(), null, null, eventRecord.getTrackId()); - } - - protected SensorsData(String distinctId, String type, Map identities, - Map properties, Integer trackId) { - this(distinctId, null, identities, type, null, properties, null, null, trackId); - } - - /** - * 构建 track 数据实体 - * - * @param distinctId 用户ID - * @param event 事件名 - * @param properties 事件属性集合 - */ - protected SensorsData(String distinctId, Map identities, String event, - Map properties, Integer trackId) { - this(distinctId, null, identities, TRACK_ACTION_TYPE, event, properties, null, null, trackId); - } - - /** - * 专用于 item 相关 schema 构建 - */ - protected SensorsData(Integer trackId, String distinctId, Map identities, String itemId, String type, - String event, Map properties) { - this(distinctId, null, identities, type, event, properties, null, itemId, trackId); - } - - protected SensorsData(String distinctId, String originalId, Map identities, String type, String event, - Map properties, String itemType, String itemId, Integer trackId) { - this.trackId = trackId; - this.distinctId = distinctId; - this.originalId = originalId; - this.identities = identities; - this.type = type; - this.event = event; - this.time = properties.containsKey(SensorsConst.TIME_SYSTEM_ATTR) ? - (Date) properties.remove(SensorsConst.TIME_SYSTEM_ATTR) : new Date(); - this.properties = properties; - this.itemType = itemType; - this.itemId = itemId; - this.project = properties.get(SensorsConst.PROJECT_SYSTEM_ATTR) == null ? - null : String.valueOf(properties.remove(SensorsConst.PROJECT_SYSTEM_ATTR)); - this.token = properties.get(SensorsConst.TOKEN_SYSTEM_ATTR) == null ? - null : String.valueOf(properties.remove(SensorsConst.TOKEN_SYSTEM_ATTR)); - this.timeFree = properties.containsKey(SensorsConst.TIME_FREE_ATTR) - && Boolean.parseBoolean(properties.remove(SensorsConst.TIME_FREE_ATTR).toString()); - } - - - protected static Map generateData(SensorsData sensorsData) { - Map eventMap = new HashMap<>(); - if (sensorsData.getTrackId() != null) { - eventMap.put("_track_id", sensorsData.getTrackId()); - } - if (sensorsData.getDistinctId() != null) { - eventMap.put("distinct_id", sensorsData.getDistinctId()); + /** 数据唯一标识 */ + private Integer trackId; + /** 数据用户唯一标识 */ + private String distinctId; + /** 数据用户匿名标识 */ + private String originalId; + /** IDM3.0 用户维度标识 */ + private Map identities; + /** 事件类型 */ + private String type; + /** 事件名称 */ + private String event; + /** 数据采集来源 */ + private Map lib; + /** 记录生成时间 */ + private Date time; + /** 数据属性集合 */ + private Map properties; + /** 数据接收项目 */ + private String project; + /** 数据 token */ + private String token; + /** 纬度类型 */ + private String itemType; + /** 纬度 ID */ + private String itemId; + + private boolean timeFree = false; + + protected SensorsData() {} + + protected SensorsData(EventRecord eventRecord, String actionType) { + this( + eventRecord.getDistinctId(), + eventRecord.getOriginalId(), + null, + actionType, + eventRecord.getEventName(), + eventRecord.getPropertyMap(), + null, + null, + eventRecord.getTrackId()); } - if (sensorsData.getOriginalId() != null) { - eventMap.put("original_id", sensorsData.getOriginalId()); - } - if (sensorsData.getIdentities() != null) { - eventMap.put("identities", sensorsData.getIdentities()); + + protected SensorsData(ItemRecord itemRecord, String actionType) { + this( + null, + null, + null, + actionType, + null, + itemRecord.getPropertyMap(), + itemRecord.getItemType(), + itemRecord.getItemId(), + itemRecord.getTrackId()); } - if (sensorsData.getType() != null) { - eventMap.put("type", sensorsData.getType()); + + protected SensorsData(UserRecord userRecord, String actionType) { + this( + userRecord.getDistinctId(), + actionType, + null, + userRecord.getPropertyMap(), + userRecord.getTrackId()); } - if (sensorsData.getEvent() != null) { - eventMap.put("event", sensorsData.getEvent()); + + protected SensorsData(T userRecord, String actionType) { + this( + userRecord.getDistinctId(), + actionType, + userRecord.getIdentityMap(), + userRecord.getPropertyMap(), + userRecord.getTrackId()); } - // fix 【SDK-4709】time 类型保持为时间戳类型 - eventMap.put("time", sensorsData.getTime().getTime()); - if (sensorsData.getProject() != null) { - eventMap.put("project", sensorsData.getProject()); + + protected SensorsData(T eventRecord) { + this( + eventRecord.getDistinctId(), + eventRecord.getIdentityMap(), + eventRecord.getEventName(), + eventRecord.getPropertyMap(), + eventRecord.getTrackId()); } - if (sensorsData.getToken() != null) { - eventMap.put("token", sensorsData.getToken()); + + protected SensorsData(T eventRecord, String actionType) { + this( + eventRecord.getDistinctId(), + null, + eventRecord.getIdentityMap(), + actionType, + eventRecord.getEventName(), + eventRecord.getPropertyMap(), + null, + null, + eventRecord.getTrackId()); } - if (sensorsData.getItemId() != null) { - eventMap.put("item_id", sensorsData.getItemId()); + + protected SensorsData( + String distinctId, + String type, + Map identities, + Map properties, + Integer trackId) { + this(distinctId, null, identities, type, null, properties, null, null, trackId); } - if (sensorsData.getItemType() != null) { - eventMap.put("item_type", sensorsData.getItemType()); + + /** + * 构建 track 数据实体 + * + * @param distinctId 用户ID + * @param event 事件名 + * @param properties 事件属性集合 + */ + protected SensorsData( + String distinctId, + Map identities, + String event, + Map properties, + Integer trackId) { + this( + distinctId, + null, + identities, + TRACK_ACTION_TYPE, + event, + properties, + null, + null, + trackId); } - if (sensorsData.getProperties() != null) { - eventMap.put("properties", sensorsData.getProperties()); + + /** 专用于 item 相关 schema 构建 */ + protected SensorsData( + Integer trackId, + String distinctId, + Map identities, + String itemId, + String type, + String event, + Map properties) { + this(distinctId, null, identities, type, event, properties, null, itemId, trackId); } - if (sensorsData.isTimeFree() - && (TRACK_ACTION_TYPE.equals(sensorsData.getType()) - || TRACK_SIGN_UP_ACTION_TYPE.equals(sensorsData.getType()) - || BIND_ID_ACTION_TYPE.equals(sensorsData.getType()) - || UNBIND_ID_ACTION_TYPE.equals(sensorsData.getType()))) { - eventMap.put("time_free", true); + + protected SensorsData( + String distinctId, + String originalId, + Map identities, + String type, + String event, + Map properties, + String itemType, + String itemId, + Integer trackId) { + this.trackId = trackId; + this.distinctId = distinctId; + this.originalId = originalId; + this.identities = identities; + this.type = type; + this.event = event; + this.time = + properties.containsKey(SensorsConst.TIME_SYSTEM_ATTR) + ? (Date) properties.remove(SensorsConst.TIME_SYSTEM_ATTR) + : new Date(); + this.properties = properties; + this.itemType = itemType; + this.itemId = itemId; + this.project = + properties.get(SensorsConst.PROJECT_SYSTEM_ATTR) == null + ? null + : String.valueOf(properties.remove(SensorsConst.PROJECT_SYSTEM_ATTR)); + this.token = + properties.get(SensorsConst.TOKEN_SYSTEM_ATTR) == null + ? null + : String.valueOf(properties.remove(SensorsConst.TOKEN_SYSTEM_ATTR)); + this.timeFree = + properties.containsKey(SensorsConst.TIME_FREE_ATTR) + && Boolean.parseBoolean( + properties.remove(SensorsConst.TIME_FREE_ATTR).toString()); } - return eventMap; - } + protected static Map generateData(SensorsData sensorsData) { + Map eventMap = new HashMap<>(); + if (sensorsData.getTrackId() != null) { + eventMap.put("_track_id", sensorsData.getTrackId()); + } + if (sensorsData.getDistinctId() != null) { + eventMap.put("distinct_id", sensorsData.getDistinctId()); + } + if (sensorsData.getOriginalId() != null) { + eventMap.put("original_id", sensorsData.getOriginalId()); + } + if (sensorsData.getIdentities() != null) { + eventMap.put("identities", sensorsData.getIdentities()); + } + if (sensorsData.getType() != null) { + eventMap.put("type", sensorsData.getType()); + } + if (sensorsData.getEvent() != null) { + eventMap.put("event", sensorsData.getEvent()); + } + // fix 【SDK-4709】time 类型保持为时间戳类型 + eventMap.put("time", sensorsData.getTime().getTime()); + if (sensorsData.getProject() != null) { + eventMap.put("project", sensorsData.getProject()); + } + if (sensorsData.getToken() != null) { + eventMap.put("token", sensorsData.getToken()); + } + if (sensorsData.getItemId() != null) { + eventMap.put("item_id", sensorsData.getItemId()); + } + if (sensorsData.getItemType() != null) { + eventMap.put("item_type", sensorsData.getItemType()); + } + if (sensorsData.getProperties() != null) { + eventMap.put("properties", sensorsData.getProperties()); + } + if (sensorsData.isTimeFree() + && (TRACK_ACTION_TYPE.equals(sensorsData.getType()) + || TRACK_SIGN_UP_ACTION_TYPE.equals(sensorsData.getType()) + || BIND_ID_ACTION_TYPE.equals(sensorsData.getType()) + || UNBIND_ID_ACTION_TYPE.equals(sensorsData.getType()))) { + eventMap.put("time_free", true); + } + return eventMap; + } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsSchemaData.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsSchemaData.java index 11a9407..75b2e0c 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsSchemaData.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/SensorsSchemaData.java @@ -12,11 +12,9 @@ import com.sensorsdata.analytics.javasdk.bean.schema.UserSchema; import com.sensorsdata.analytics.javasdk.common.Pair; import com.sensorsdata.analytics.javasdk.common.SchemaTypeEnum; - -import lombok.extern.slf4j.Slf4j; - import java.util.HashMap; import java.util.Map; +import lombok.extern.slf4j.Slf4j; /** * 神策多实体数据 @@ -28,151 +26,178 @@ @Slf4j class SensorsSchemaData extends SensorsData { - private String version = SensorsConst.PROTOCOL_VERSION; - - private String schema; - - private Long userId; - - private String detailId; - - private Pair itemEventPair; - - private SchemaTypeEnum schemaTypeEnum; - - /** - * 构建 userEventSchema 数据,actionType:track/bind/unbind - */ - protected SensorsSchemaData(UserEventSchema userEventSchema, String actionType) { - super(userEventSchema.getDistinctId(), null, userEventSchema.getIdentityMap(), actionType, - userEventSchema.getEventName(), userEventSchema.getPropertyMap(), null, null, userEventSchema.getTrackId()); - this.schema = SensorsConst.USER_EVENT_SCHEMA; - this.userId = userEventSchema.getUserId(); - this.schemaTypeEnum = SchemaTypeEnum.USER_EVENT; - } - - protected SensorsSchemaData(ItemSchema itemSchema, String actionType) { - super(itemSchema.getTrackId(), null, null, itemSchema.getItemId(), actionType, null, itemSchema.getProperties()); - this.schema = itemSchema.getSchema(); - this.schemaTypeEnum = SchemaTypeEnum.ITEM; - } - - protected SensorsSchemaData(ItemEventSchema itemEventSchema, String actionType) { - super(itemEventSchema.getTrackId(), null, null, null, actionType, - itemEventSchema.getEventName(), - itemEventSchema.getProperties()); - this.schema = itemEventSchema.getSchema(); - this.itemEventPair = itemEventSchema.getItemPair(); - this.schemaTypeEnum = SchemaTypeEnum.ITEM_EVENT; - } - - protected SensorsSchemaData(UserSchema userSchema, String actionType) { - super(userSchema.getDistinctId(), actionType, userSchema.getIdentityMap(), userSchema.getPropertyMap(), - userSchema.getTrackId()); - this.schema = SensorsConst.USER_SCHEMA; - this.userId = userSchema.getUserId(); - this.schemaTypeEnum = SchemaTypeEnum.USER; - } - - protected SensorsSchemaData(DetailSchema detailSchema, String actionType) { - super(detailSchema.getTrackId(), detailSchema.getDistinctId(), detailSchema.getIdentities(), - null, actionType, null, - detailSchema.getProperties()); - this.schema = detailSchema.getSchema(); - this.itemEventPair = detailSchema.getItemPair(); - this.detailId = detailSchema.getDetailId(); - this.schemaTypeEnum = SchemaTypeEnum.DETAIL; - } - - public Map generateData() { - Map data = new HashMap<>(); - data.put("_track_id", getTrackId()); - data.put("version", version); - data.put("type", getType()); - data.put("schema", schema); - data.put("lib", getLib()); - data.put("time", getTime().getTime()); - if (getProject() != null && !"".equals(getProject())) { - data.put("project", getProject()); + private String version = SensorsConst.PROTOCOL_VERSION; + + private String schema; + + private Long userId; + + private String detailId; + + private Pair itemEventPair; + + private SchemaTypeEnum schemaTypeEnum; + + /** 构建 userEventSchema 数据,actionType:track/bind/unbind */ + protected SensorsSchemaData(UserEventSchema userEventSchema, String actionType) { + super( + userEventSchema.getDistinctId(), + null, + userEventSchema.getIdentityMap(), + actionType, + userEventSchema.getEventName(), + userEventSchema.getPropertyMap(), + null, + null, + userEventSchema.getTrackId()); + this.schema = SensorsConst.USER_EVENT_SCHEMA; + this.userId = userEventSchema.getUserId(); + this.schemaTypeEnum = SchemaTypeEnum.USER_EVENT; + } + + protected SensorsSchemaData(ItemSchema itemSchema, String actionType) { + super( + itemSchema.getTrackId(), + null, + null, + itemSchema.getItemId(), + actionType, + null, + itemSchema.getProperties()); + this.schema = itemSchema.getSchema(); + this.schemaTypeEnum = SchemaTypeEnum.ITEM; + } + + protected SensorsSchemaData(ItemEventSchema itemEventSchema, String actionType) { + super( + itemEventSchema.getTrackId(), + null, + null, + null, + actionType, + itemEventSchema.getEventName(), + itemEventSchema.getProperties()); + this.schema = itemEventSchema.getSchema(); + this.itemEventPair = itemEventSchema.getItemPair(); + this.schemaTypeEnum = SchemaTypeEnum.ITEM_EVENT; + } + + protected SensorsSchemaData(UserSchema userSchema, String actionType) { + super( + userSchema.getDistinctId(), + actionType, + userSchema.getIdentityMap(), + userSchema.getPropertyMap(), + userSchema.getTrackId()); + this.schema = SensorsConst.USER_SCHEMA; + this.userId = userSchema.getUserId(); + this.schemaTypeEnum = SchemaTypeEnum.USER; } - if (getToken() != null && !"".equals(getToken())) { - data.put("token", getToken()); + + protected SensorsSchemaData(DetailSchema detailSchema, String actionType) { + super( + detailSchema.getTrackId(), + detailSchema.getDistinctId(), + detailSchema.getIdentities(), + null, + actionType, + null, + detailSchema.getProperties()); + this.schema = detailSchema.getSchema(); + this.itemEventPair = detailSchema.getItemPair(); + this.detailId = detailSchema.getDetailId(); + this.schemaTypeEnum = SchemaTypeEnum.DETAIL; } - switch (schemaTypeEnum) { - case ITEM: - data.put("id", getItemId()); - break; - case ITEM_EVENT: - getProperties().put(itemEventPair.getKey(), itemEventPair.getValue()); - addTimeFree(data); - data.put("event", getEvent()); - break; - case USER: - checkUserIdAndAddUser(data, "id"); - break; - case USER_EVENT: - addTimeFree(data); - data.put("event", getEvent()); - checkUserIdAndAddUser(getProperties(), "user_id"); - break; - case USER_ITEM: - data.put("id", getItemId()); - checkUserIdAndAddUser(getProperties(), "user_id"); - break; - case DETAIL: - data.put("id", detailId); - if (itemEventPair != null) { - getProperties().put(itemEventPair.getKey(), itemEventPair.getValue()); + + public Map generateData() { + Map data = new HashMap<>(); + data.put("_track_id", getTrackId()); + data.put("version", version); + data.put("type", getType()); + data.put("schema", schema); + data.put("lib", getLib()); + data.put("time", getTime().getTime()); + if (getProject() != null && !"".equals(getProject())) { + data.put("project", getProject()); } - if (!getIdentities().isEmpty()) { - checkUserIdAndAddUser(getProperties(), "user_id"); + if (getToken() != null && !"".equals(getToken())) { + data.put("token", getToken()); } - default: - break; + switch (schemaTypeEnum) { + case ITEM: + data.put("id", getItemId()); + break; + case ITEM_EVENT: + getProperties().put(itemEventPair.getKey(), itemEventPair.getValue()); + addTimeFree(data); + data.put("event", getEvent()); + break; + case USER: + checkUserIdAndAddUser(data, "id"); + break; + case USER_EVENT: + addTimeFree(data); + data.put("event", getEvent()); + checkUserIdAndAddUser(getProperties(), "user_id"); + break; + case USER_ITEM: + data.put("id", getItemId()); + checkUserIdAndAddUser(getProperties(), "user_id"); + break; + case DETAIL: + data.put("id", detailId); + if (itemEventPair != null) { + getProperties().put(itemEventPair.getKey(), itemEventPair.getValue()); + } + if (!getIdentities().isEmpty()) { + checkUserIdAndAddUser(getProperties(), "user_id"); + } + default: + break; + } + data.put("properties", getProperties()); + return data; + } + + public boolean isEventSchemaData() { + return SchemaTypeEnum.ITEM_EVENT.equals(schemaTypeEnum) + || SchemaTypeEnum.USER_EVENT.equals(schemaTypeEnum); + } + + public String getVersion() { + return version; + } + + public String getSchema() { + return schema; + } + + public Long getUserId() { + return userId; } - data.put("properties", getProperties()); - return data; - } - - public boolean isEventSchemaData() { - return SchemaTypeEnum.ITEM_EVENT.equals(schemaTypeEnum) - || SchemaTypeEnum.USER_EVENT.equals(schemaTypeEnum); - } - - - public String getVersion() { - return version; - } - - public String getSchema() { - return schema; - } - - public Long getUserId() { - return userId; - } - - public SchemaTypeEnum getSchemaTypeEnum() { - return schemaTypeEnum; - } - - private void addTimeFree(Map data) { - if (isTimeFree() && (TRACK_ACTION_TYPE.equals(getType()) - || TRACK_SIGN_UP_ACTION_TYPE.equals(getType()) - || BIND_ID_ACTION_TYPE.equals(getType()) - || UNBIND_ID_ACTION_TYPE.equals(getType()))) { - data.put("time_free", true); + + public SchemaTypeEnum getSchemaTypeEnum() { + return schemaTypeEnum; } - } - private void checkUserIdAndAddUser(Map data, String key) { - if (null != getUserId()) { - data.put(key, getUserId()); - } else if (null != getIdentities() && !getIdentities().isEmpty()) { - data.put("identities", getIdentities()); + private void addTimeFree(Map data) { + if (isTimeFree() + && (TRACK_ACTION_TYPE.equals(getType()) + || TRACK_SIGN_UP_ACTION_TYPE.equals(getType()) + || BIND_ID_ACTION_TYPE.equals(getType()) + || UNBIND_ID_ACTION_TYPE.equals(getType()))) { + data.put("time_free", true); + } } - if (null != getDistinctId()) { - data.put("distinct_id", getDistinctId()); + + private void checkUserIdAndAddUser(Map data, String key) { + if (null != getUserId()) { + data.put(key, getUserId()); + } else if (null != getIdentities() && !getIdentities().isEmpty()) { + data.put("identities", getIdentities()); + } + if (null != getDistinctId()) { + data.put("distinct_id", getDistinctId()); + } } - } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/EventRecord.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/EventRecord.java index f3361bb..4ba33e3 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/EventRecord.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/EventRecord.java @@ -3,16 +3,13 @@ import com.sensorsdata.analytics.javasdk.SensorsConst; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; -/** - * 事件表信息实体对象 - */ +/** 事件表信息实体对象 */ public class EventRecord implements Serializable { private static final long serialVersionUID = -2327319579147636283L; @@ -28,8 +25,13 @@ public class EventRecord implements Serializable { private final String originalId; - private EventRecord(String eventName, String distinctId, Boolean isLoginId, Map propertyMap, - Integer trackId, String originalId) { + private EventRecord( + String eventName, + String distinctId, + Boolean isLoginId, + Map propertyMap, + Integer trackId, + String originalId) { this.eventName = eventName; this.distinctId = distinctId; this.isLoginId = isLoginId; @@ -43,12 +45,19 @@ private EventRecord(String eventName, String distinctId, Boolean isLoginId, Map< @Override public String toString() { - return "EventRecord{" + - "propertyMap=" + propertyMap + - ", eventName='" + eventName + '\'' + - ", distinctId='" + distinctId + '\'' + - ", isLoginId='" + isLoginId + '\'' + - '}'; + return "EventRecord{" + + "propertyMap=" + + propertyMap + + ", eventName='" + + eventName + + '\'' + + ", distinctId='" + + distinctId + + '\'' + + ", isLoginId='" + + isLoginId + + '\'' + + '}'; } public static Builder builder() { @@ -75,7 +84,9 @@ public String getOriginalId() { return originalId; } - public Integer getTrackId() {return trackId; } + public Integer getTrackId() { + return trackId; + } public static class Builder { private final Map propertyMap = new HashMap<>(); @@ -85,8 +96,8 @@ public static class Builder { private Integer trackId; private String originalId; - private Builder() { - } + private Builder() {} + public EventRecord build() throws InvalidArgumentException { if (eventName == null) { @@ -98,12 +109,16 @@ public EventRecord build() throws InvalidArgumentException { if (isLoginId == null) { throw new InvalidArgumentException("The isLoginId is empty."); } - SensorsAnalyticsUtil.assertKey("event_name",eventName); + SensorsAnalyticsUtil.assertKey("event_name", eventName); SensorsAnalyticsUtil.assertProperties("property", propertyMap); SensorsAnalyticsUtil.assertValue("distinct_id", distinctId); - String message = String.format("[distinct_id=%s,event_name=%s,is_login_id=%s]",distinctId,eventName,isLoginId); + String message = + String.format( + "[distinct_id=%s,event_name=%s,is_login_id=%s]", + distinctId, eventName, isLoginId); trackId = SensorsAnalyticsUtil.getTrackId(propertyMap, message); - return new EventRecord(eventName, distinctId, isLoginId, propertyMap,trackId, originalId); + return new EventRecord( + eventName, distinctId, isLoginId, propertyMap, trackId, originalId); } public EventRecord.Builder setOriginalId(String originalId) { @@ -164,4 +179,4 @@ private void addPropertyObject(String key, Object property) { } } } -} \ No newline at end of file +} diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/FailedData.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/FailedData.java index 242aaa5..2285366 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/FailedData.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/FailedData.java @@ -1,15 +1,12 @@ package com.sensorsdata.analytics.javasdk.bean; - - +import java.util.List; +import java.util.Map; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import java.util.List; -import java.util.Map; - /** * 发送异常数据包装类 * @@ -22,12 +19,8 @@ @AllArgsConstructor @ToString public class FailedData { - /** - * 失败原因 - */ - private String failedMessage; - /** - * 失败数据 - */ - private List> failedData; + /** 失败原因 */ + private String failedMessage; + /** 失败数据 */ + private List> failedData; } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/IDMEventRecord.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/IDMEventRecord.java index 8376c0e..a310a5f 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/IDMEventRecord.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/IDMEventRecord.java @@ -6,24 +6,20 @@ import com.sensorsdata.analytics.javasdk.common.Pair; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - -import lombok.AccessLevel; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.NonNull; - import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.NonNull; /** - * IDM3.0 事件参数对象,用于构建 IDM3.0 track 请求 - * 使用示例: - *

- * IDMEventRecord.starter().identityMap(identityMap).setEventName(eventName).addProperties(properties).build(); - *

+ * IDM3.0 事件参数对象,用于构建 IDM3.0 track 请求 使用示例: + * + *

IDMEventRecord.starter().identityMap(identityMap).setEventName(eventName).addProperties(properties).build(); * * @author fangzhuo * @version 1.0.0 @@ -31,124 +27,119 @@ */ @Getter public class IDMEventRecord { - /** - * 事件名称 - */ - private String eventName; - /** - * distinctId 标识,在 IDM3.0 里面,该参数可传可不传 - */ - private String distinctId; - /** - * 事件携带的属性集合 - */ - private Map propertyMap; - - private Integer trackId; - - private Map identityMap; - - - protected IDMEventRecord(Map identityMap, String eventName, String distinctId, - Map propertyMap, Integer trackId) { - this.identityMap = identityMap; - this.eventName = eventName; - this.distinctId = distinctId; - this.propertyMap = propertyMap; - this.trackId = trackId; - } - - public static IDMBuilder starter() { - return new IDMBuilder(); - } - - @NoArgsConstructor(access = AccessLevel.PRIVATE) - public static class IDMBuilder { - private final Map idMap = new LinkedHashMap<>(); - private final Map propertyMap = new HashMap<>(); + /** 事件名称 */ private String eventName; + /** distinctId 标识,在 IDM3.0 里面,该参数可传可不传 */ private String distinctId; - private Integer trackId; - - public IDMEventRecord build() throws InvalidArgumentException { - SensorsAnalyticsUtil.assertKey("event_name", eventName); - if (propertyMap.size() != 0) { - SensorsAnalyticsUtil.assertProperties(TRACK_ACTION_TYPE, propertyMap); - } - if (idMap.size() < 1) { - throw new InvalidArgumentException("The identity is empty."); - } - Pair resPair = - SensorsAnalyticsUtil.checkIdentitiesAndGenerateDistinctId(distinctId, idMap); - if (resPair.getValue()) { - propertyMap.put(SensorsConst.LOGIN_SYSTEM_ATTR, true); - } - String message = String.format("[distinct_id=%s,event_name=%s]",distinctId,eventName); - trackId = SensorsAnalyticsUtil.getTrackId(propertyMap, message); - return new IDMEventRecord(idMap, eventName, resPair.getKey(), propertyMap,trackId); - } - - public IDMEventRecord.IDMBuilder identityMap(Map identityMap) { - if (identityMap != null) { - this.idMap.putAll(identityMap); - } - return this; - } + /** 事件携带的属性集合 */ + private Map propertyMap; - public IDMEventRecord.IDMBuilder addIdentityProperty(String key, String value) { - this.idMap.put(key, value); - return this; - } - - public IDMEventRecord.IDMBuilder setEventName(@NonNull String eventName) { - this.eventName = eventName; - return this; - } - - public IDMEventRecord.IDMBuilder setDistinctId(@NonNull String distinctId) { - this.distinctId = distinctId; - // IDM3.0 设置 distinctId,设置 $is_login_id = false,其实也可不设置 - return this; - } - - public IDMEventRecord.IDMBuilder addProperties(Map properties) { - if (properties != null) { - propertyMap.putAll(properties); - } - return this; - } - - public IDMEventRecord.IDMBuilder addProperty(String key, String property) { - addPropertyObject(key, property); - return this; - } - - public IDMEventRecord.IDMBuilder addProperty(String key, boolean property) { - addPropertyObject(key, property); - return this; - } - - public IDMEventRecord.IDMBuilder addProperty(String key, Number property) { - addPropertyObject(key, property); - return this; - } + private Integer trackId; - public IDMEventRecord.IDMBuilder addProperty(String key, Date property) { - addPropertyObject(key, property); - return this; + private Map identityMap; + + protected IDMEventRecord( + Map identityMap, + String eventName, + String distinctId, + Map propertyMap, + Integer trackId) { + this.identityMap = identityMap; + this.eventName = eventName; + this.distinctId = distinctId; + this.propertyMap = propertyMap; + this.trackId = trackId; } - public IDMEventRecord.IDMBuilder addProperty(String key, List property) { - addPropertyObject(key, property); - return this; + public static IDMBuilder starter() { + return new IDMBuilder(); } - private void addPropertyObject(String key, Object property) { - if (key != null) { - propertyMap.put(key, property); - } + @NoArgsConstructor(access = AccessLevel.PRIVATE) + public static class IDMBuilder { + private final Map idMap = new LinkedHashMap<>(); + private final Map propertyMap = new HashMap<>(); + private String eventName; + private String distinctId; + private Integer trackId; + + public IDMEventRecord build() throws InvalidArgumentException { + SensorsAnalyticsUtil.assertKey("event_name", eventName); + if (propertyMap.size() != 0) { + SensorsAnalyticsUtil.assertProperties(TRACK_ACTION_TYPE, propertyMap); + } + if (idMap.size() < 1) { + throw new InvalidArgumentException("The identity is empty."); + } + Pair resPair = + SensorsAnalyticsUtil.checkIdentitiesAndGenerateDistinctId(distinctId, idMap); + if (resPair.getValue()) { + propertyMap.put(SensorsConst.LOGIN_SYSTEM_ATTR, true); + } + String message = String.format("[distinct_id=%s,event_name=%s]", distinctId, eventName); + trackId = SensorsAnalyticsUtil.getTrackId(propertyMap, message); + return new IDMEventRecord(idMap, eventName, resPair.getKey(), propertyMap, trackId); + } + + public IDMEventRecord.IDMBuilder identityMap(Map identityMap) { + if (identityMap != null) { + this.idMap.putAll(identityMap); + } + return this; + } + + public IDMEventRecord.IDMBuilder addIdentityProperty(String key, String value) { + this.idMap.put(key, value); + return this; + } + + public IDMEventRecord.IDMBuilder setEventName(@NonNull String eventName) { + this.eventName = eventName; + return this; + } + + public IDMEventRecord.IDMBuilder setDistinctId(@NonNull String distinctId) { + this.distinctId = distinctId; + // IDM3.0 设置 distinctId,设置 $is_login_id = false,其实也可不设置 + return this; + } + + public IDMEventRecord.IDMBuilder addProperties(Map properties) { + if (properties != null) { + propertyMap.putAll(properties); + } + return this; + } + + public IDMEventRecord.IDMBuilder addProperty(String key, String property) { + addPropertyObject(key, property); + return this; + } + + public IDMEventRecord.IDMBuilder addProperty(String key, boolean property) { + addPropertyObject(key, property); + return this; + } + + public IDMEventRecord.IDMBuilder addProperty(String key, Number property) { + addPropertyObject(key, property); + return this; + } + + public IDMEventRecord.IDMBuilder addProperty(String key, Date property) { + addPropertyObject(key, property); + return this; + } + + public IDMEventRecord.IDMBuilder addProperty(String key, List property) { + addPropertyObject(key, property); + return this; + } + + private void addPropertyObject(String key, Object property) { + if (key != null) { + propertyMap.put(key, property); + } + } } - - - } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/IDMUserRecord.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/IDMUserRecord.java index 331f7c4..a81ae62 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/IDMUserRecord.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/IDMUserRecord.java @@ -1,28 +1,23 @@ package com.sensorsdata.analytics.javasdk.bean; - import com.sensorsdata.analytics.javasdk.SensorsConst; import com.sensorsdata.analytics.javasdk.common.Pair; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - -import lombok.AccessLevel; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.NonNull; - import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import lombok.AccessLevel; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.NonNull; /** - * IDM3.0 用户参数信息对象,用于构建 IDM3.0 profile 相关接口请求 - * 使用示例: - *

- * IDMUserRecord.starter().identityMap(identityMap).addProperties(properties).build(); - *

+ * IDM3.0 用户参数信息对象,用于构建 IDM3.0 profile 相关接口请求 使用示例: + * + *

IDMUserRecord.starter().identityMap(identityMap).addProperties(properties).build(); * * @author fangzhuo * @version 1.0.0 @@ -31,101 +26,102 @@ @Getter public class IDMUserRecord { - private Map propertyMap; - - private String distinctId; - - private Integer trackId; - - private Map identityMap; - - - protected IDMUserRecord(Map identityMap, Map propertyMap, String distinctId, - Integer trackId) { - this.identityMap = identityMap; - this.propertyMap = propertyMap; - this.distinctId = distinctId; - this.trackId = trackId; - } - - public static IDMBuilder starter() { - return new IDMBuilder(); - } + private Map propertyMap; - @NoArgsConstructor(access = AccessLevel.PRIVATE) - public static class IDMBuilder { - private final Map idMap = new LinkedHashMap<>(); private String distinctId; - private final Map propertyMap = new HashMap<>(); - private Integer trackId; - - public IDMUserRecord build() throws InvalidArgumentException { - Pair resPair = - SensorsAnalyticsUtil.checkIdentitiesAndGenerateDistinctId(distinctId, idMap); - if (resPair.getValue()) { - propertyMap.put(SensorsConst.LOGIN_SYSTEM_ATTR, true); - } - // 填充 distinct_id 和 目标表 - String message = String.format("[distinct_id=%s,target_table=user]",distinctId); - trackId = SensorsAnalyticsUtil.getTrackId(propertyMap, message); - return new IDMUserRecord(idMap, propertyMap, resPair.getKey(), trackId); - } - - public IDMUserRecord.IDMBuilder identityMap(Map identityMap) { - if (identityMap != null) { - this.idMap.putAll(identityMap); - } - return this; - } - - public IDMUserRecord.IDMBuilder addIdentityProperty(String key, String value) { - this.idMap.put(key, value); - return this; - } - - public IDMUserRecord.IDMBuilder setDistinctId(@NonNull String distinctId) { - this.distinctId = distinctId; - // IDM3.0 设置 distinctId,设置 $is_login_id = false,其实也可不设置 - return this; - } - public IDMUserRecord.IDMBuilder addProperties(Map properties) { - if (properties != null) { - propertyMap.putAll(properties); - } - return this; - } - - public IDMUserRecord.IDMBuilder addProperty(String key, String property) { - addPropertyObject(key, property); - return this; - } - - public IDMUserRecord.IDMBuilder addProperty(String key, boolean property) { - addPropertyObject(key, property); - return this; - } - - public IDMUserRecord.IDMBuilder addProperty(String key, Number property) { - addPropertyObject(key, property); - return this; - } + private Integer trackId; - public IDMUserRecord.IDMBuilder addProperty(String key, Date property) { - addPropertyObject(key, property); - return this; + private Map identityMap; + + protected IDMUserRecord( + Map identityMap, + Map propertyMap, + String distinctId, + Integer trackId) { + this.identityMap = identityMap; + this.propertyMap = propertyMap; + this.distinctId = distinctId; + this.trackId = trackId; } - public IDMUserRecord.IDMBuilder addProperty(String key, List property) { - addPropertyObject(key, property); - return this; + public static IDMBuilder starter() { + return new IDMBuilder(); } - private void addPropertyObject(String key, Object property) { - if (key != null) { - propertyMap.put(key, property); - } + @NoArgsConstructor(access = AccessLevel.PRIVATE) + public static class IDMBuilder { + private final Map idMap = new LinkedHashMap<>(); + private String distinctId; + private final Map propertyMap = new HashMap<>(); + private Integer trackId; + + public IDMUserRecord build() throws InvalidArgumentException { + Pair resPair = + SensorsAnalyticsUtil.checkIdentitiesAndGenerateDistinctId(distinctId, idMap); + if (resPair.getValue()) { + propertyMap.put(SensorsConst.LOGIN_SYSTEM_ATTR, true); + } + // 填充 distinct_id 和 目标表 + String message = String.format("[distinct_id=%s,target_table=user]", distinctId); + trackId = SensorsAnalyticsUtil.getTrackId(propertyMap, message); + return new IDMUserRecord(idMap, propertyMap, resPair.getKey(), trackId); + } + + public IDMUserRecord.IDMBuilder identityMap(Map identityMap) { + if (identityMap != null) { + this.idMap.putAll(identityMap); + } + return this; + } + + public IDMUserRecord.IDMBuilder addIdentityProperty(String key, String value) { + this.idMap.put(key, value); + return this; + } + + public IDMUserRecord.IDMBuilder setDistinctId(@NonNull String distinctId) { + this.distinctId = distinctId; + // IDM3.0 设置 distinctId,设置 $is_login_id = false,其实也可不设置 + return this; + } + + public IDMUserRecord.IDMBuilder addProperties(Map properties) { + if (properties != null) { + propertyMap.putAll(properties); + } + return this; + } + + public IDMUserRecord.IDMBuilder addProperty(String key, String property) { + addPropertyObject(key, property); + return this; + } + + public IDMUserRecord.IDMBuilder addProperty(String key, boolean property) { + addPropertyObject(key, property); + return this; + } + + public IDMUserRecord.IDMBuilder addProperty(String key, Number property) { + addPropertyObject(key, property); + return this; + } + + public IDMUserRecord.IDMBuilder addProperty(String key, Date property) { + addPropertyObject(key, property); + return this; + } + + public IDMUserRecord.IDMBuilder addProperty(String key, List property) { + addPropertyObject(key, property); + return this; + } + + private void addPropertyObject(String key, Object property) { + if (key != null) { + propertyMap.put(key, property); + } + } } - - } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/ItemRecord.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/ItemRecord.java index 8ca2130..edb0924 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/ItemRecord.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/ItemRecord.java @@ -5,7 +5,6 @@ import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - import java.io.Serializable; import java.util.Date; import java.util.HashMap; @@ -31,7 +30,8 @@ public class ItemRecord implements Serializable { private final Integer trackId; - private ItemRecord(Map propertyMap, String itemId, String itemType, Integer trackId) { + private ItemRecord( + Map propertyMap, String itemId, String itemType, Integer trackId) { this.propertyMap = propertyMap; this.itemId = itemId; this.itemType = itemType; @@ -50,7 +50,9 @@ public String getItemType() { return itemType; } - public Integer getTrackId() { return trackId; } + public Integer getTrackId() { + return trackId; + } public static Builder builder() { return new Builder(); @@ -66,8 +68,7 @@ public static class Builder { private Integer trackId; - private Builder() { - } + private Builder() {} public ItemRecord build() throws InvalidArgumentException { if (null == itemId) { diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/SensorsAnalyticsIdentity.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/SensorsAnalyticsIdentity.java index 9bb7b0b..3f6f157 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/SensorsAnalyticsIdentity.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/SensorsAnalyticsIdentity.java @@ -1,14 +1,13 @@ package com.sensorsdata.analytics.javasdk.bean; +import java.util.LinkedHashMap; +import java.util.Map; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.LinkedHashMap; -import java.util.Map; - @Getter @Setter(AccessLevel.PROTECTED) @AllArgsConstructor(access = AccessLevel.PROTECTED) @@ -20,9 +19,7 @@ public class SensorsAnalyticsIdentity { public static final String MOBILE = "$identity_mobile"; // 邮箱 public static final String EMAIL = "$identity_email"; - /** - * 用户纬度标识集合 - */ + /** 用户纬度标识集合 */ protected Map identityMap; public static Builder builder() { diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/SuperPropertiesRecord.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/SuperPropertiesRecord.java index 6783411..61fbb71 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/SuperPropertiesRecord.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/SuperPropertiesRecord.java @@ -1,7 +1,6 @@ package com.sensorsdata.analytics.javasdk.bean; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - import java.io.Serializable; import java.util.Date; import java.util.HashMap; @@ -36,8 +35,7 @@ public static Builder builder() { public static class Builder { private Map propertyMap = new HashMap(); - private Builder() { - } + private Builder() {} public SuperPropertiesRecord build() throws InvalidArgumentException { if (propertyMap.size() == 0) { @@ -46,7 +44,6 @@ public SuperPropertiesRecord build() throws InvalidArgumentException { return new SuperPropertiesRecord(propertyMap); } - public SuperPropertiesRecord.Builder addProperties(Map properties) { if (properties != null) { propertyMap.putAll(properties); diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/UserRecord.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/UserRecord.java index 07afde6..eecb709 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/UserRecord.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/UserRecord.java @@ -1,10 +1,8 @@ package com.sensorsdata.analytics.javasdk.bean; - import com.sensorsdata.analytics.javasdk.SensorsConst; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - import java.io.Serializable; import java.util.Date; import java.util.HashMap; @@ -30,7 +28,11 @@ public class UserRecord implements Serializable { private final Integer trackId; - private UserRecord(Map propertyMap, String distinctId, Boolean isLoginId, Integer trackId) { + private UserRecord( + Map propertyMap, + String distinctId, + Boolean isLoginId, + Integer trackId) { this.propertyMap = propertyMap; if (isLoginId) { propertyMap.put(SensorsConst.LOGIN_SYSTEM_ATTR, true); @@ -56,7 +58,9 @@ public Map getPropertyMap() { return propertyMap; } - public Integer getTrackId() {return trackId; } + public Integer getTrackId() { + return trackId; + } public static class Builder { private final Map propertyMap = new HashMap<>(); @@ -64,8 +68,7 @@ public static class Builder { private Boolean isLoginId; private Integer trackId; - private Builder() { - } + private Builder() {} public UserRecord build() throws InvalidArgumentException { if (distinctId == null) { @@ -75,7 +78,7 @@ public UserRecord build() throws InvalidArgumentException { throw new InvalidArgumentException("The isLoginId is empty."); } SensorsAnalyticsUtil.assertValue("distinct_id", distinctId); - String message = String.format("[distinct_id=%s,target_table=user]",distinctId); + String message = String.format("[distinct_id=%s,target_table=user]", distinctId); trackId = SensorsAnalyticsUtil.getTrackId(propertyMap, message); return new UserRecord(propertyMap, distinctId, isLoginId, trackId); } @@ -127,7 +130,5 @@ private void addPropertyObject(String key, Object property) { propertyMap.put(key, property); } } - } - } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/DetailSchema.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/DetailSchema.java index 7404ae8..7dddd9d 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/DetailSchema.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/DetailSchema.java @@ -3,15 +3,13 @@ import com.sensorsdata.analytics.javasdk.common.Pair; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - -import lombok.Getter; -import lombok.NonNull; - import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import lombok.Getter; +import lombok.NonNull; /** * 明细数据入参 @@ -22,144 +20,158 @@ */ @Getter public class DetailSchema { - /** - * detail 对应的 schema - *

必传参数,若不传入,则抛出 InvalidArgumentException 异常;

- */ - private String schema; - /** - * detail 对应的 id - *

必传参数,若不传入,则抛出 InvalidArgumentException 异常;

- */ - private String detailId; - /** - * detail 的自定义属性集合 - *

非必传参数

- */ - private Map properties; - /** - * 若传入该参数,该 detail 则被视为该用户实体的明细 - *

非必传参数,跟 itemId 节点互斥,若同时传入,则会抛出 InvalidArgumentException 异常;

- */ - private Map identities; - /** - * 只有传入 identities 节点信息,再设置该节点才会生效,否则设置该值无效; - *

非必传参数,不传此值,会取 identities 节点集合里第一个节点的用户信息作为 distinct_id

- */ - private String distinctId; - /** - * 设置该参数,则该 detail 被视为 item 实体的明细 - *

非必传参数,跟 identities 节点互斥。若同时传入,则会抛出 InvalidArgumentException 异常;

- */ - private Pair itemPair; - - private Integer trackId; - - - protected DetailSchema(String schema, String detailId, Map properties, - Map identities, String distinctId, Pair itemPair, Integer trackId) { - this.schema = schema; - this.detailId = detailId; - this.properties = properties; - this.identities = identities; - this.distinctId = distinctId; - this.itemPair = itemPair; - this.trackId = trackId; - } - - public static Builder init() { - return new Builder(); - } - - public static class Builder { + /** + * detail 对应的 schema + * + *

必传参数,若不传入,则抛出 InvalidArgumentException 异常; + */ private String schema; + /** + * detail 对应的 id + * + *

必传参数,若不传入,则抛出 InvalidArgumentException 异常; + */ private String detailId; - private Map properties = new HashMap<>(); - private Map identities = new LinkedHashMap<>(); + /** + * detail 的自定义属性集合 + * + *

非必传参数 + */ + private Map properties; + /** + * 若传入该参数,该 detail 则被视为该用户实体的明细 + * + *

非必传参数,跟 itemId 节点互斥,若同时传入,则会抛出 InvalidArgumentException 异常; + */ + private Map identities; + /** + * 只有传入 identities 节点信息,再设置该节点才会生效,否则设置该值无效; + * + *

非必传参数,不传此值,会取 identities 节点集合里第一个节点的用户信息作为 distinct_id + */ private String distinctId; + /** + * 设置该参数,则该 detail 被视为 item 实体的明细 + * + *

非必传参数,跟 identities 节点互斥。若同时传入,则会抛出 InvalidArgumentException 异常; + */ private Pair itemPair; - private Integer trackId; - - - public DetailSchema start() throws InvalidArgumentException { - SensorsAnalyticsUtil.assertSchema(schema); - SensorsAnalyticsUtil.assertValue("detail_id", detailId); - if (!identities.isEmpty() && null != itemPair) { - throw new InvalidArgumentException("detail schema cannot both set identities and itemPair."); - } - this.trackId = SensorsAnalyticsUtil.getTrackId(properties, - String.format("detail generate trackId error.[distinct_id=%s,detail_id=%s,schema=%s]", - distinctId, detailId, schema)); - if (!identities.isEmpty()) { - this.distinctId = SensorsAnalyticsUtil.checkUserInfo(null, identities, distinctId); - } - SensorsAnalyticsUtil.assertSchemaProperties(properties, null); - return new DetailSchema(schema, detailId, properties, identities, distinctId, itemPair, trackId); - } - - public Builder setSchema(@NonNull String schema) { - this.schema = schema; - return this; - } - - public Builder setDetailId(@NonNull String detailId) { - this.detailId = detailId; - return this; - } - - public Builder setItemPair(@NonNull String key, @NonNull String value) { - this.itemPair = Pair.of(key, value); - return this; - } - public Builder addProperties(@NonNull Map properties) { - this.properties.putAll(properties); - return this; - } - - public Builder addProperty(@NonNull String key, @NonNull String property) { - addPropertyObject(key, property); - return this; - } - - public Builder addProperty(@NonNull String key, boolean property) { - addPropertyObject(key, property); - return this; - } - - public Builder addProperty(@NonNull String key, @NonNull Number property) { - addPropertyObject(key, property); - return this; - } - - public Builder addProperty(@NonNull String key, @NonNull Date property) { - addPropertyObject(key, property); - return this; - } - - public Builder addProperty(@NonNull String key, @NonNull List property) { - addPropertyObject(key, property); - return this; - } - - public Builder identityMap(@NonNull Map identities) { - this.identities.putAll(identities); - return this; - } + private Integer trackId; - public Builder addIdentityProperty(@NonNull String key, @NonNull String value) { - this.identities.put(key, value); - return this; + protected DetailSchema( + String schema, + String detailId, + Map properties, + Map identities, + String distinctId, + Pair itemPair, + Integer trackId) { + this.schema = schema; + this.detailId = detailId; + this.properties = properties; + this.identities = identities; + this.distinctId = distinctId; + this.itemPair = itemPair; + this.trackId = trackId; } - public Builder setDistinctId(@NonNull String distinctId) { - this.distinctId = distinctId; - return this; + public static Builder init() { + return new Builder(); } - private void addPropertyObject(@NonNull String key, @NonNull Object property) { - this.properties.put(key, property); + public static class Builder { + private String schema; + private String detailId; + private Map properties = new HashMap<>(); + private Map identities = new LinkedHashMap<>(); + private String distinctId; + private Pair itemPair; + private Integer trackId; + + public DetailSchema start() throws InvalidArgumentException { + SensorsAnalyticsUtil.assertSchema(schema); + SensorsAnalyticsUtil.assertValue("detail_id", detailId); + if (!identities.isEmpty() && null != itemPair) { + throw new InvalidArgumentException( + "detail schema cannot both set identities and itemPair."); + } + this.trackId = + SensorsAnalyticsUtil.getTrackId( + properties, + String.format( + "detail generate trackId error.[distinct_id=%s,detail_id=%s,schema=%s]", + distinctId, detailId, schema)); + if (!identities.isEmpty()) { + this.distinctId = SensorsAnalyticsUtil.checkUserInfo(null, identities, distinctId); + } + SensorsAnalyticsUtil.assertSchemaProperties(properties, null); + return new DetailSchema( + schema, detailId, properties, identities, distinctId, itemPair, trackId); + } + + public Builder setSchema(@NonNull String schema) { + this.schema = schema; + return this; + } + + public Builder setDetailId(@NonNull String detailId) { + this.detailId = detailId; + return this; + } + + public Builder setItemPair(@NonNull String key, @NonNull String value) { + this.itemPair = Pair.of(key, value); + return this; + } + + public Builder addProperties(@NonNull Map properties) { + this.properties.putAll(properties); + return this; + } + + public Builder addProperty(@NonNull String key, @NonNull String property) { + addPropertyObject(key, property); + return this; + } + + public Builder addProperty(@NonNull String key, boolean property) { + addPropertyObject(key, property); + return this; + } + + public Builder addProperty(@NonNull String key, @NonNull Number property) { + addPropertyObject(key, property); + return this; + } + + public Builder addProperty(@NonNull String key, @NonNull Date property) { + addPropertyObject(key, property); + return this; + } + + public Builder addProperty(@NonNull String key, @NonNull List property) { + addPropertyObject(key, property); + return this; + } + + public Builder identityMap(@NonNull Map identities) { + this.identities.putAll(identities); + return this; + } + + public Builder addIdentityProperty(@NonNull String key, @NonNull String value) { + this.identities.put(key, value); + return this; + } + + public Builder setDistinctId(@NonNull String distinctId) { + this.distinctId = distinctId; + return this; + } + + private void addPropertyObject(@NonNull String key, @NonNull Object property) { + this.properties.put(key, property); + } } - } - } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/IdentitySchema.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/IdentitySchema.java index 6ca0829..28326c7 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/IdentitySchema.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/IdentitySchema.java @@ -1,13 +1,12 @@ package com.sensorsdata.analytics.javasdk.bean.schema; -import lombok.Getter; -import lombok.NonNull; - import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import lombok.Getter; +import lombok.NonNull; /** * identitySchema @@ -19,75 +18,73 @@ @Getter public class IdentitySchema { - private Map idMap; - - private Map properties; - - protected IdentitySchema(Map idMap, Map properties) { - this.idMap = idMap; - this.properties = properties; - } - - public static IdentitySchema.Builder init() { - return new IdentitySchema.Builder(); - } - - - public static class Builder { - - private Map idMap = new LinkedHashMap<>(); - - private Map properties = new HashMap<>(); - - public Builder identityMap(Map identityMap) { - if (identityMap != null) { - this.idMap.putAll(identityMap); - } - return this; - } - - public Builder addIdentityProperty(String key, String value) { - this.idMap.put(key, value); - return this; - } - + private Map idMap; - public Builder addProperties(@NonNull Map properties) { - this.properties.putAll(properties); - return this; - } - - public Builder addProperty(@NonNull String key, @NonNull String property) { - addPropertyObject(key, property); - return this; - } - - public Builder addProperty(@NonNull String key, boolean property) { - addPropertyObject(key, property); - return this; - } - - public Builder addProperty(@NonNull String key, @NonNull Number property) { - addPropertyObject(key, property); - return this; - } - - public Builder addProperty(@NonNull String key, @NonNull Date property) { - addPropertyObject(key, property); - return this; - } + private Map properties; - public Builder addProperty(@NonNull String key, @NonNull List property) { - addPropertyObject(key, property); - return this; + protected IdentitySchema(Map idMap, Map properties) { + this.idMap = idMap; + this.properties = properties; } - private void addPropertyObject(@NonNull String key, @NonNull Object property) { - this.properties.put(key, property); + public static IdentitySchema.Builder init() { + return new IdentitySchema.Builder(); } - public IdentitySchema build() { - return new IdentitySchema(idMap, properties); + public static class Builder { + + private Map idMap = new LinkedHashMap<>(); + + private Map properties = new HashMap<>(); + + public Builder identityMap(Map identityMap) { + if (identityMap != null) { + this.idMap.putAll(identityMap); + } + return this; + } + + public Builder addIdentityProperty(String key, String value) { + this.idMap.put(key, value); + return this; + } + + public Builder addProperties(@NonNull Map properties) { + this.properties.putAll(properties); + return this; + } + + public Builder addProperty(@NonNull String key, @NonNull String property) { + addPropertyObject(key, property); + return this; + } + + public Builder addProperty(@NonNull String key, boolean property) { + addPropertyObject(key, property); + return this; + } + + public Builder addProperty(@NonNull String key, @NonNull Number property) { + addPropertyObject(key, property); + return this; + } + + public Builder addProperty(@NonNull String key, @NonNull Date property) { + addPropertyObject(key, property); + return this; + } + + public Builder addProperty(@NonNull String key, @NonNull List property) { + addPropertyObject(key, property); + return this; + } + + private void addPropertyObject(@NonNull String key, @NonNull Object property) { + this.properties.put(key, property); + } + + public IdentitySchema build() { + return new IdentitySchema(idMap, properties); + } } - } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/ItemEventSchema.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/ItemEventSchema.java index f90a77e..9871b05 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/ItemEventSchema.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/ItemEventSchema.java @@ -3,14 +3,12 @@ import com.sensorsdata.analytics.javasdk.common.Pair; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - -import lombok.Getter; -import lombok.NonNull; - import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import lombok.Getter; +import lombok.NonNull; /** * item event schema @@ -22,111 +20,116 @@ @Getter public class ItemEventSchema { - private String schema; - - private String eventName; - - private Map properties; - - private Integer trackId; - - private Pair itemPair; - - protected ItemEventSchema(Integer trackId, String schema, String eventName, Pair itemPair, - Map properties) { - this.trackId = trackId; - this.schema = schema; - this.eventName = eventName; - this.properties = properties; - this.itemPair = itemPair; - } - - public static IEBuilder init() { - return new IEBuilder(); - } - - public static class IEBuilder { - private String schema; - private String eventName; - private Integer trackId; - private Map properties = new HashMap<>(); - private Pair itemPair; - public ItemEventSchema start() throws InvalidArgumentException { - SensorsAnalyticsUtil.assertSchema(schema); - SensorsAnalyticsUtil.assertEventItemPair(itemPair); - SensorsAnalyticsUtil.assertKey("event_name", eventName); - SensorsAnalyticsUtil.assertSchemaProperties(properties, null); - this.trackId = SensorsAnalyticsUtil.getTrackId(properties, String.format("[event=%s,schema=%s]", - eventName, schema)); - - return new ItemEventSchema(trackId, schema, eventName, itemPair, properties); - } + private String eventName; - public IEBuilder setSchema(@NonNull String schema) { - this.schema = schema; - return this; - } + private Map properties; - public IEBuilder setEventName(@NonNull String eventName) { - this.eventName = eventName; - return this; - } + private Integer trackId; - public IEBuilder setItemPair(@NonNull String itemId, @NonNull String value) { - this.itemPair = Pair.of(itemId, value); - return this; - } + private Pair itemPair; - public IEBuilder addProperties(@NonNull Map properties) { - this.properties.putAll(properties); - return this; + protected ItemEventSchema( + Integer trackId, + String schema, + String eventName, + Pair itemPair, + Map properties) { + this.trackId = trackId; + this.schema = schema; + this.eventName = eventName; + this.properties = properties; + this.itemPair = itemPair; } - public IEBuilder addProperty(@NonNull String key, @NonNull String property) { - addPropertyObject(key, property); - return this; + public static IEBuilder init() { + return new IEBuilder(); } - public IEBuilder addProperty(@NonNull String key, boolean property) { - addPropertyObject(key, property); - return this; + public static class IEBuilder { + + private String schema; + private String eventName; + private Integer trackId; + private Map properties = new HashMap<>(); + private Pair itemPair; + + public ItemEventSchema start() throws InvalidArgumentException { + SensorsAnalyticsUtil.assertSchema(schema); + SensorsAnalyticsUtil.assertEventItemPair(itemPair); + SensorsAnalyticsUtil.assertKey("event_name", eventName); + SensorsAnalyticsUtil.assertSchemaProperties(properties, null); + this.trackId = + SensorsAnalyticsUtil.getTrackId( + properties, String.format("[event=%s,schema=%s]", eventName, schema)); + + return new ItemEventSchema(trackId, schema, eventName, itemPair, properties); + } + + public IEBuilder setSchema(@NonNull String schema) { + this.schema = schema; + return this; + } + + public IEBuilder setEventName(@NonNull String eventName) { + this.eventName = eventName; + return this; + } + + public IEBuilder setItemPair(@NonNull String itemId, @NonNull String value) { + this.itemPair = Pair.of(itemId, value); + return this; + } + + public IEBuilder addProperties(@NonNull Map properties) { + this.properties.putAll(properties); + return this; + } + + public IEBuilder addProperty(@NonNull String key, @NonNull String property) { + addPropertyObject(key, property); + return this; + } + + public IEBuilder addProperty(@NonNull String key, boolean property) { + addPropertyObject(key, property); + return this; + } + + public IEBuilder addProperty(@NonNull String key, @NonNull Number property) { + addPropertyObject(key, property); + return this; + } + + public IEBuilder addProperty(@NonNull String key, @NonNull Date property) { + addPropertyObject(key, property); + return this; + } + + public IEBuilder addProperty(@NonNull String key, @NonNull List property) { + addPropertyObject(key, property); + return this; + } + + private void addPropertyObject(@NonNull String key, @NonNull Object property) { + this.properties.put(key, property); + } } - public IEBuilder addProperty(@NonNull String key, @NonNull Number property) { - addPropertyObject(key, property); - return this; + public String getSchema() { + return schema; } - public IEBuilder addProperty(@NonNull String key, @NonNull Date property) { - addPropertyObject(key, property); - return this; + public String getEventName() { + return eventName; } - public IEBuilder addProperty(@NonNull String key, @NonNull List property) { - addPropertyObject(key, property); - return this; + public Map getProperties() { + return properties; } - private void addPropertyObject(@NonNull String key, @NonNull Object property) { - this.properties.put(key, property); + public Integer getTrackId() { + return trackId; } - } - - public String getSchema() { - return schema; - } - - public String getEventName() { - return eventName; - } - - public Map getProperties() { - return properties; - } - - public Integer getTrackId() { - return trackId; - } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/ItemSchema.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/ItemSchema.java index ba4438d..fe8cd23 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/ItemSchema.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/ItemSchema.java @@ -2,14 +2,12 @@ import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - -import lombok.Getter; -import lombok.NonNull; - import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import lombok.Getter; +import lombok.NonNull; /** * item schema @@ -21,108 +19,108 @@ @Getter public class ItemSchema { - private String schema; - - private String itemId; - - private Map properties; - - private Integer trackId; - - protected ItemSchema(Integer trackId, String schema, String itemId, Map properties) { - this.trackId = trackId; - this.schema = schema; - this.itemId = itemId; - this.properties = properties; - } - - public static ISBuilder init() { - return new ISBuilder(); - } - - public static class ISBuilder { private String schema; private String itemId; - private Map properties = new HashMap<>(); + private Map properties; private Integer trackId; - private ISBuilder() { + protected ItemSchema( + Integer trackId, String schema, String itemId, Map properties) { + this.trackId = trackId; + this.schema = schema; + this.itemId = itemId; + this.properties = properties; } - public ItemSchema start() throws InvalidArgumentException { - if (itemId == null) { - throw new InvalidArgumentException("The item id can not set null."); - } - SensorsAnalyticsUtil.assertValue("itemId", itemId); - SensorsAnalyticsUtil.assertSchema(schema); - SensorsAnalyticsUtil.assertSchemaProperties(properties, null); - this.trackId = - SensorsAnalyticsUtil.getTrackId(properties, String.format("[itemId=%s,schema=%s]", itemId, schema)); - return new ItemSchema(trackId, schema, itemId, properties); + public static ISBuilder init() { + return new ISBuilder(); } - public ISBuilder setSchema(@NonNull String schema) { - this.schema = schema; - return this; + public static class ISBuilder { + private String schema; + + private String itemId; + + private Map properties = new HashMap<>(); + + private Integer trackId; + + private ISBuilder() {} + + public ItemSchema start() throws InvalidArgumentException { + if (itemId == null) { + throw new InvalidArgumentException("The item id can not set null."); + } + SensorsAnalyticsUtil.assertValue("itemId", itemId); + SensorsAnalyticsUtil.assertSchema(schema); + SensorsAnalyticsUtil.assertSchemaProperties(properties, null); + this.trackId = + SensorsAnalyticsUtil.getTrackId( + properties, String.format("[itemId=%s,schema=%s]", itemId, schema)); + return new ItemSchema(trackId, schema, itemId, properties); + } + + public ISBuilder setSchema(@NonNull String schema) { + this.schema = schema; + return this; + } + + public ISBuilder setItemId(@NonNull String itemId) { + this.itemId = itemId; + return this; + } + + public ISBuilder addProperties(@NonNull Map properties) { + this.properties.putAll(properties); + return this; + } + + public ISBuilder addProperty(@NonNull String key, @NonNull String property) { + addPropertyObject(key, property); + return this; + } + + public ISBuilder addProperty(@NonNull String key, boolean property) { + addPropertyObject(key, property); + return this; + } + + public ISBuilder addProperty(@NonNull String key, @NonNull Number property) { + addPropertyObject(key, property); + return this; + } + + public ISBuilder addProperty(@NonNull String key, @NonNull Date property) { + addPropertyObject(key, property); + return this; + } + + public ISBuilder addProperty(@NonNull String key, @NonNull List property) { + addPropertyObject(key, property); + return this; + } + + private void addPropertyObject(@NonNull String key, @NonNull Object property) { + this.properties.put(key, property); + } } - public ISBuilder setItemId(@NonNull String itemId) { - this.itemId = itemId; - return this; + public String getSchema() { + return schema; } - public ISBuilder addProperties(@NonNull Map properties) { - this.properties.putAll(properties); - return this; + public String getItemId() { + return itemId; } - public ISBuilder addProperty(@NonNull String key, @NonNull String property) { - addPropertyObject(key, property); - return this; + public Map getProperties() { + return properties; } - public ISBuilder addProperty(@NonNull String key, boolean property) { - addPropertyObject(key, property); - return this; + public Integer getTrackId() { + return trackId; } - - public ISBuilder addProperty(@NonNull String key, @NonNull Number property) { - addPropertyObject(key, property); - return this; - } - - public ISBuilder addProperty(@NonNull String key, @NonNull Date property) { - addPropertyObject(key, property); - return this; - } - - public ISBuilder addProperty(@NonNull String key, @NonNull List property) { - addPropertyObject(key, property); - return this; - } - - private void addPropertyObject(@NonNull String key, @NonNull Object property) { - this.properties.put(key, property); - } - - } - - public String getSchema() { - return schema; - } - - public String getItemId() { - return itemId; - } - - public Map getProperties() { - return properties; - } - - public Integer getTrackId() { - return trackId; - } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/UserEventSchema.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/UserEventSchema.java index e16a35b..3f63028 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/UserEventSchema.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/UserEventSchema.java @@ -3,15 +3,13 @@ import com.sensorsdata.analytics.javasdk.SensorsConst; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - -import lombok.Getter; -import lombok.NonNull; - import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import lombok.Getter; +import lombok.NonNull; /** * user-event schema @@ -23,123 +21,123 @@ @Getter public class UserEventSchema { - private Integer trackId; - - private Long userId; - - private String eventName; - /** - * distinctId 标识,在 IDM3.0 里面,该参数可传可不传 - */ - private String distinctId; - /** - * 事件携带的属性集合 - */ - private Map propertyMap; - - private Map identityMap; - - - protected UserEventSchema(Map identityMap, String eventName, String distinctId, - Map propertyMap, Integer trackId, Long userId) { - this.eventName = eventName; - this.distinctId = distinctId; - this.propertyMap = propertyMap; - this.trackId = trackId; - this.identityMap = identityMap; - this.userId = userId; - } - - public Long getUserId() { - return userId; - } - - public static UESBuilder init() { - return new UESBuilder(); - } - - public static class UESBuilder { - private Map idMap = new LinkedHashMap<>(); - private Long userId; - private String distinctId; - private String eventName; - private Map properties = new HashMap<>(); private Integer trackId; - private UESBuilder() { - } - - public UserEventSchema start() throws InvalidArgumentException { - SensorsAnalyticsUtil.assertKey("event_name", eventName); - if (!properties.isEmpty()) { - SensorsAnalyticsUtil.assertSchemaProperties(properties, SensorsConst.TRACK_ACTION_TYPE); - } - this.trackId = SensorsAnalyticsUtil.getTrackId(properties, - String.format("[distinct_id=%s,event_name=%s]", distinctId, eventName)); - this.distinctId = SensorsAnalyticsUtil.checkUserInfo(userId, idMap, distinctId); - return new UserEventSchema(idMap, eventName, distinctId, properties, trackId, userId); - } - - public UESBuilder setUserId(@NonNull Long userId) { - this.userId = userId; - return this; - } - - public UESBuilder identityMap(@NonNull Map identityMap) { - this.idMap.putAll(identityMap); - return this; - } - - public UESBuilder addIdentityProperty(@NonNull String key, @NonNull String value) { - this.idMap.put(key, value); - return this; - } - - public UESBuilder setEventName(@NonNull String eventName) { - this.eventName = eventName; - return this; - } - - public UESBuilder setDistinctId(@NonNull String distinctId) { - this.distinctId = distinctId; - // IDM3.0 设置 distinctId,设置 $is_login_id = false,其实也可不设置 - return this; - } - - public UESBuilder addProperties(@NonNull Map properties) { - this.properties.putAll(properties); - return this; - } - - public UESBuilder addProperty(@NonNull String key, @NonNull String property) { - addPropertyObject(key, property); - return this; - } - - public UESBuilder addProperty(@NonNull String key, boolean property) { - addPropertyObject(key, property); - return this; - } + private Long userId; - public UESBuilder addProperty(@NonNull String key, @NonNull Number property) { - addPropertyObject(key, property); - return this; + private String eventName; + /** distinctId 标识,在 IDM3.0 里面,该参数可传可不传 */ + private String distinctId; + /** 事件携带的属性集合 */ + private Map propertyMap; + + private Map identityMap; + + protected UserEventSchema( + Map identityMap, + String eventName, + String distinctId, + Map propertyMap, + Integer trackId, + Long userId) { + this.eventName = eventName; + this.distinctId = distinctId; + this.propertyMap = propertyMap; + this.trackId = trackId; + this.identityMap = identityMap; + this.userId = userId; } - public UESBuilder addProperty(@NonNull String key, @NonNull Date property) { - addPropertyObject(key, property); - return this; + public Long getUserId() { + return userId; } - public UESBuilder addProperty(@NonNull String key, @NonNull List property) { - addPropertyObject(key, property); - return this; + public static UESBuilder init() { + return new UESBuilder(); } - private void addPropertyObject(@NonNull String key, @NonNull Object property) { - this.properties.put(key, property); + public static class UESBuilder { + private Map idMap = new LinkedHashMap<>(); + private Long userId; + private String distinctId; + private String eventName; + private Map properties = new HashMap<>(); + private Integer trackId; + + private UESBuilder() {} + + public UserEventSchema start() throws InvalidArgumentException { + SensorsAnalyticsUtil.assertKey("event_name", eventName); + if (!properties.isEmpty()) { + SensorsAnalyticsUtil.assertSchemaProperties( + properties, SensorsConst.TRACK_ACTION_TYPE); + } + this.trackId = + SensorsAnalyticsUtil.getTrackId( + properties, + String.format("[distinct_id=%s,event_name=%s]", distinctId, eventName)); + this.distinctId = SensorsAnalyticsUtil.checkUserInfo(userId, idMap, distinctId); + return new UserEventSchema(idMap, eventName, distinctId, properties, trackId, userId); + } + + public UESBuilder setUserId(@NonNull Long userId) { + this.userId = userId; + return this; + } + + public UESBuilder identityMap(@NonNull Map identityMap) { + this.idMap.putAll(identityMap); + return this; + } + + public UESBuilder addIdentityProperty(@NonNull String key, @NonNull String value) { + this.idMap.put(key, value); + return this; + } + + public UESBuilder setEventName(@NonNull String eventName) { + this.eventName = eventName; + return this; + } + + public UESBuilder setDistinctId(@NonNull String distinctId) { + this.distinctId = distinctId; + // IDM3.0 设置 distinctId,设置 $is_login_id = false,其实也可不设置 + return this; + } + + public UESBuilder addProperties(@NonNull Map properties) { + this.properties.putAll(properties); + return this; + } + + public UESBuilder addProperty(@NonNull String key, @NonNull String property) { + addPropertyObject(key, property); + return this; + } + + public UESBuilder addProperty(@NonNull String key, boolean property) { + addPropertyObject(key, property); + return this; + } + + public UESBuilder addProperty(@NonNull String key, @NonNull Number property) { + addPropertyObject(key, property); + return this; + } + + public UESBuilder addProperty(@NonNull String key, @NonNull Date property) { + addPropertyObject(key, property); + return this; + } + + public UESBuilder addProperty(@NonNull String key, @NonNull List property) { + addPropertyObject(key, property); + return this; + } + + private void addPropertyObject(@NonNull String key, @NonNull Object property) { + this.properties.put(key, property); + } } - - - } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/UserSchema.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/UserSchema.java index ca58f97..ad11d1d 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/UserSchema.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/bean/schema/UserSchema.java @@ -2,15 +2,13 @@ import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - -import lombok.Getter; -import lombok.NonNull; - import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import lombok.Getter; +import lombok.NonNull; /** * 用户相关 schema @@ -22,107 +20,113 @@ @Getter public class UserSchema { - private Long userId; - - private Map propertyMap; - - private String distinctId; - - private Integer trackId; - - private Map identityMap; - - protected UserSchema(Map identityMap, Map propertyMap, String distinctId, - Integer trackId, Long userId) { - this.userId = userId; - this.propertyMap = propertyMap; - this.distinctId = distinctId; - this.trackId = trackId; - this.identityMap = identityMap; - } - - public static USBuilder init() { - return new USBuilder(); - } - - public static class USBuilder { - private Map idMap = new LinkedHashMap<>(); - private String distinctId; - private Integer trackId; private Long userId; - private Map properties = new HashMap<>(); - - private USBuilder() { - } - - public UserSchema start() throws InvalidArgumentException { - this.distinctId = SensorsAnalyticsUtil.checkUserInfo(userId, idMap, distinctId); - this.trackId = - SensorsAnalyticsUtil.getTrackId(properties, String.format("[distinct_id=%s,user_id=%s]", distinctId, userId)); - return new UserSchema(idMap, properties, distinctId, trackId, userId); - } + private Map propertyMap; - public USBuilder setUserId(@NonNull Long userId) { - this.userId = userId; - return this; - } - - public USBuilder identityMap(@NonNull Map identityMap) { - this.idMap.putAll(identityMap); - return this; - } - - public USBuilder addIdentityProperty(@NonNull String key, @NonNull String value) { - this.idMap.put(key, value); - return this; - } - - - public USBuilder setDistinctId(@NonNull String distinctId) { - this.distinctId = distinctId; - // IDM3.0 设置 distinctId,设置 $is_login_id = false,其实也可不设置 - return this; - } - - public USBuilder addProperties(@NonNull Map properties) { - this.properties.putAll(properties); - return this; - } - - public USBuilder addProperty(@NonNull String key, @NonNull String property) { - addPropertyObject(key, property); - return this; - } + private String distinctId; - public USBuilder addProperty(@NonNull String key, boolean property) { - addPropertyObject(key, property); - return this; - } + private Integer trackId; - public USBuilder addProperty(@NonNull String key, @NonNull Number property) { - addPropertyObject(key, property); - return this; + private Map identityMap; + + protected UserSchema( + Map identityMap, + Map propertyMap, + String distinctId, + Integer trackId, + Long userId) { + this.userId = userId; + this.propertyMap = propertyMap; + this.distinctId = distinctId; + this.trackId = trackId; + this.identityMap = identityMap; } - public USBuilder addProperty(@NonNull String key, @NonNull Date property) { - addPropertyObject(key, property); - return this; + public static USBuilder init() { + return new USBuilder(); } - public USBuilder addProperty(@NonNull String key, @NonNull List property) { - addPropertyObject(key, property); - return this; + public static class USBuilder { + private Map idMap = new LinkedHashMap<>(); + private String distinctId; + private Integer trackId; + private Long userId; + private Map properties = new HashMap<>(); + + private USBuilder() {} + + public UserSchema start() throws InvalidArgumentException { + this.distinctId = SensorsAnalyticsUtil.checkUserInfo(userId, idMap, distinctId); + this.trackId = + SensorsAnalyticsUtil.getTrackId( + properties, + String.format("[distinct_id=%s,user_id=%s]", distinctId, userId)); + return new UserSchema(idMap, properties, distinctId, trackId, userId); + } + + public USBuilder setUserId(@NonNull Long userId) { + this.userId = userId; + return this; + } + + public USBuilder identityMap(@NonNull Map identityMap) { + this.idMap.putAll(identityMap); + return this; + } + + public USBuilder addIdentityProperty(@NonNull String key, @NonNull String value) { + this.idMap.put(key, value); + return this; + } + + public USBuilder addIdentityProperty(@NonNull String key, @NonNull List value) { + this.idMap.put(key, value); + return this; + } + + public USBuilder setDistinctId(@NonNull String distinctId) { + this.distinctId = distinctId; + // IDM3.0 设置 distinctId,设置 $is_login_id = false,其实也可不设置 + return this; + } + + public USBuilder addProperties(@NonNull Map properties) { + this.properties.putAll(properties); + return this; + } + + public USBuilder addProperty(@NonNull String key, @NonNull String property) { + addPropertyObject(key, property); + return this; + } + + public USBuilder addProperty(@NonNull String key, boolean property) { + addPropertyObject(key, property); + return this; + } + + public USBuilder addProperty(@NonNull String key, @NonNull Number property) { + addPropertyObject(key, property); + return this; + } + + public USBuilder addProperty(@NonNull String key, @NonNull Date property) { + addPropertyObject(key, property); + return this; + } + + public USBuilder addProperty(@NonNull String key, @NonNull List property) { + addPropertyObject(key, property); + return this; + } + + private void addPropertyObject(@NonNull String key, @NonNull Object property) { + this.properties.put(key, property); + } } - private void addPropertyObject(@NonNull String key, @NonNull Object property) { - this.properties.put(key, property); + public Long getUserId() { + return userId; } - - } - - public Long getUserId() { - return userId; - } - } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/common/Pair.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/common/Pair.java index edc6c74..3a43364 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/common/Pair.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/common/Pair.java @@ -9,45 +9,45 @@ */ public class Pair { - private final K key; + private final K key; - private final V value; + private final V value; - public K getKey() { - return key; - } - - public V getValue() { - return value; - } - - private Pair(K key, V value) { - this.key = key; - this.value = value; - } + public K getKey() { + return key; + } - @Override - public String toString() { - return key + "=" + value; - } + public V getValue() { + return value; + } + private Pair(K key, V value) { + this.key = key; + this.value = value; + } - public boolean equals(Object var1) { - return var1 instanceof Pair - && ((Pair) var1).getKey() == this.key - && this.value == ((Pair) var1).getValue(); - } + @Override + public String toString() { + return key + "=" + value; + } - public int hashCode() { - if (this.key == null) { - return this.value == null ? 0 : this.value.hashCode() + 1; - } else { - return this.value == null ? this.key.hashCode() + 2 : this.key.hashCode() * 17 + this.value.hashCode(); + public boolean equals(Object var1) { + return var1 instanceof Pair + && ((Pair) var1).getKey() == this.key + && this.value == ((Pair) var1).getValue(); } - } - public static Pair of(K key, V value) { - return new Pair<>(key, value); - } + public int hashCode() { + if (this.key == null) { + return this.value == null ? 0 : this.value.hashCode() + 1; + } else { + return this.value == null + ? this.key.hashCode() + 2 + : this.key.hashCode() * 17 + this.value.hashCode(); + } + } + public static Pair of(K key, V value) { + return new Pair<>(key, value); + } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/common/SchemaTypeEnum.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/common/SchemaTypeEnum.java index 4b7a7d7..9abf82e 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/common/SchemaTypeEnum.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/common/SchemaTypeEnum.java @@ -8,11 +8,10 @@ * @since 2022/06/14 14:55 */ public enum SchemaTypeEnum { - USER_EVENT, - ITEM_EVENT, - USER, - USER_ITEM, - ITEM, - DETAIL - + USER_EVENT, + ITEM_EVENT, + USER, + USER_ITEM, + ITEM, + DETAIL } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/common/SensorsDataTypeEnum.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/common/SensorsDataTypeEnum.java index 85e0317..33f31bb 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/common/SensorsDataTypeEnum.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/common/SensorsDataTypeEnum.java @@ -11,27 +11,26 @@ * @since 2022/06/15 17:34 */ public enum SensorsDataTypeEnum { - NUMBER, - STRING, - BOOLEAN, - DATE, - LIST, - UNKNOWN; + NUMBER, + STRING, + BOOLEAN, + DATE, + LIST, + UNKNOWN; - - public static SensorsDataTypeEnum getDataType(Object value) { - if (value instanceof Number) { - return SensorsDataTypeEnum.NUMBER; - } else if (value instanceof String) { - return SensorsDataTypeEnum.STRING; - } else if (value instanceof Boolean) { - return SensorsDataTypeEnum.BOOLEAN; - } else if (value instanceof Date) { - return SensorsDataTypeEnum.DATE; - } else if (value instanceof List) { - return SensorsDataTypeEnum.LIST; - } else { - return SensorsDataTypeEnum.UNKNOWN; + public static SensorsDataTypeEnum getDataType(Object value) { + if (value instanceof Number) { + return SensorsDataTypeEnum.NUMBER; + } else if (value instanceof String) { + return SensorsDataTypeEnum.STRING; + } else if (value instanceof Boolean) { + return SensorsDataTypeEnum.BOOLEAN; + } else if (value instanceof Date) { + return SensorsDataTypeEnum.DATE; + } else if (value instanceof List) { + return SensorsDataTypeEnum.LIST; + } else { + return SensorsDataTypeEnum.UNKNOWN; + } } - } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/BatchConsumer.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/BatchConsumer.java index 68bc05d..539d8db 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/BatchConsumer.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/BatchConsumer.java @@ -1,17 +1,15 @@ package com.sensorsdata.analytics.javasdk.consumer; -import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; - +import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; @Slf4j public class BatchConsumer implements Consumer { @@ -45,39 +43,79 @@ public BatchConsumer(final String serverUrl, final int bulkSize, final boolean t this(serverUrl, bulkSize, throwException, 3); } - public BatchConsumer(final String serverUrl, final int bulkSize, final boolean throwException, - final int timeoutSec) { + public BatchConsumer( + final String serverUrl, + final int bulkSize, + final boolean throwException, + final int timeoutSec) { this(serverUrl, bulkSize, 0, throwException, timeoutSec); } - public BatchConsumer(final String serverUrl, final int bulkSize, final int maxCacheSize, - final boolean throwException) { + public BatchConsumer( + final String serverUrl, + final int bulkSize, + final int maxCacheSize, + final boolean throwException) { this(serverUrl, bulkSize, maxCacheSize, throwException, 3); } - public BatchConsumer(final String serverUrl, final int bulkSize, final int maxCacheSize, - final boolean throwException, final int timeoutSec) { + public BatchConsumer( + final String serverUrl, + final int bulkSize, + final int maxCacheSize, + final boolean throwException, + final int timeoutSec) { this(HttpClients.custom(), serverUrl, bulkSize, maxCacheSize, throwException, timeoutSec); } - public BatchConsumer(HttpClientBuilder httpClientBuilder, final String serverUrl, final int bulkSize, final int maxCacheSize, - final boolean throwException, final int timeoutSec) { - this(httpClientBuilder, serverUrl, bulkSize, maxCacheSize, throwException, timeoutSec, new ArrayList()); + public BatchConsumer( + HttpClientBuilder httpClientBuilder, + final String serverUrl, + final int bulkSize, + final int maxCacheSize, + final boolean throwException, + final int timeoutSec) { + this( + httpClientBuilder, + serverUrl, + bulkSize, + maxCacheSize, + throwException, + timeoutSec, + new ArrayList()); } - - public BatchConsumer(final String serverUrl, final int bulkSize, final int maxCacheSize, - final boolean throwException, final int timeoutSec, List instantEvents) { - this(HttpClients.custom(), serverUrl, bulkSize, maxCacheSize, throwException, timeoutSec, instantEvents); + public BatchConsumer( + final String serverUrl, + final int bulkSize, + final int maxCacheSize, + final boolean throwException, + final int timeoutSec, + List instantEvents) { + this( + HttpClients.custom(), + serverUrl, + bulkSize, + maxCacheSize, + throwException, + timeoutSec, + instantEvents); } - public BatchConsumer(HttpClientBuilder httpClientBuilder, final String serverUrl, final int bulkSize, final int maxCacheSize, - final boolean throwException, final int timeoutSec, List instantEvents) { + public BatchConsumer( + HttpClientBuilder httpClientBuilder, + final String serverUrl, + final int bulkSize, + final int maxCacheSize, + final boolean throwException, + final int timeoutSec, + List instantEvents) { this.messageList = new LinkedList<>(); this.isInstantStatus = false; this.instantEvents = instantEvents; this.httpConsumer = new HttpConsumer(httpClientBuilder, serverUrl, Math.max(timeoutSec, 1)); - this.instantHttpConsumer = new InstantHttpConsumer(httpClientBuilder, serverUrl, Math.max(timeoutSec, 1)); + this.instantHttpConsumer = + new InstantHttpConsumer(httpClientBuilder, serverUrl, Math.max(timeoutSec, 1)); this.jsonMapper = SensorsAnalyticsUtil.getJsonObjectMapper(); this.bulkSize = Math.min(MAX_FLUSH_BULK_SIZE, Math.max(1, bulkSize)); if (maxCacheSize > MAX_CACHE_SIZE) { @@ -89,8 +127,11 @@ public BatchConsumer(HttpClientBuilder httpClientBuilder, final String serverUrl } this.throwException = throwException; log.info( - "Initialize BatchConsumer with params:[bulkSize:{},timeoutSec:{},maxCacheSize:{},throwException:{}]", - bulkSize, timeoutSec, maxCacheSize, throwException); + "Initialize BatchConsumer with params:[bulkSize:{},timeoutSec:{},maxCacheSize:{},throwException:{}]", + bulkSize, + timeoutSec, + maxCacheSize, + throwException); } @Override @@ -104,8 +145,10 @@ public void send(Map message) { log.debug("Successfully save data to cache,The cache current size is {}.", size); } if (size >= bulkSize) { - log.info("Flush was triggered because the cache size reached the threshold,cache size:{},bulkSize:{}.", - size, bulkSize); + log.info( + "Flush was triggered because the cache size reached the threshold,cache size:{},bulkSize:{}.", + size, + bulkSize); flush(); } } @@ -116,7 +159,8 @@ public void flush() { synchronized (messageList) { while (!messageList.isEmpty()) { String sendingData; - List> sendList = messageList.subList(0, Math.min(bulkSize, messageList.size())); + List> sendList = + messageList.subList(0, Math.min(bulkSize, messageList.size())); try { sendingData = jsonMapper.writeValueAsString(sendList); } catch (JsonProcessingException e) { @@ -160,7 +204,9 @@ private void dealInstantSignal(Map message) { /* * 如果当前是「instant」状态,且(message中不包含event 或者 event 不是「instant」的,则刷新,设置 「非instant」状态 */ - if (isInstantStatus && (!message.containsKey("event") || !instantEvents.contains(message.get("event")))) { + if (isInstantStatus + && (!message.containsKey("event") + || !instantEvents.contains(message.get("event")))) { flush(); isInstantStatus = false; } @@ -168,9 +214,11 @@ private void dealInstantSignal(Map message) { /* * 如果当前是 「非instant」状态,且(message中包含event 且 event 是「instant」的,则刷新,设置 「instant」状态 */ - if (!isInstantStatus && message.containsKey("event") && instantEvents.contains(message.get("event"))) { + if (!isInstantStatus + && message.containsKey("event") + && instantEvents.contains(message.get("event"))) { flush(); isInstantStatus = true; } } -} \ No newline at end of file +} diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/Callback.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/Callback.java index c337c1e..37b6bce 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/Callback.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/Callback.java @@ -10,11 +10,10 @@ * @since 2021/11/05 23:47 */ public interface Callback { - /** - * 返回发送失败的数据 - * - * @param failedData 失败数据 - */ - void onFailed(FailedData failedData); - + /** + * 返回发送失败的数据 + * + * @param failedData 失败数据 + */ + void onFailed(FailedData failedData); } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/ConcurrentLoggingConsumer.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/ConcurrentLoggingConsumer.java index 8949e0b..6729a66 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/ConcurrentLoggingConsumer.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/ConcurrentLoggingConsumer.java @@ -1,7 +1,5 @@ package com.sensorsdata.analytics.javasdk.consumer; -import lombok.extern.slf4j.Slf4j; - import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; @@ -10,6 +8,7 @@ import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; +import lombok.extern.slf4j.Slf4j; @Slf4j public class ConcurrentLoggingConsumer extends InnerLoggingConsumer { @@ -26,19 +25,17 @@ public ConcurrentLoggingConsumer(final String filenamePrefix, final String lockF this(filenamePrefix, lockFileName, 8192); } - public ConcurrentLoggingConsumer( - String filenamePrefix, - String lockFileName, - int bufferSize) { + public ConcurrentLoggingConsumer(String filenamePrefix, String lockFileName, int bufferSize) { this(filenamePrefix, lockFileName, bufferSize, LogSplitMode.DAY); } public ConcurrentLoggingConsumer( - String filenamePrefix, - String lockFileName, - int bufferSize, - LogSplitMode splitMode) { - super(new InnerLoggingFileWriterFactory(lockFileName), filenamePrefix, bufferSize, splitMode); + String filenamePrefix, String lockFileName, int bufferSize, LogSplitMode splitMode) { + super( + new InnerLoggingFileWriterFactory(lockFileName), + filenamePrefix, + bufferSize, + splitMode); } static class InnerLoggingFileWriterFactory implements LoggingFileWriterFactory { @@ -57,8 +54,8 @@ public LoggingFileWriter getFileWriter(String fileName, String scheduleFileName) @Override public void closeFileWriter(LoggingFileWriter writer) { - ConcurrentLoggingConsumer.InnerLoggingFileWriter - .removeInstance((ConcurrentLoggingConsumer.InnerLoggingFileWriter) writer); + ConcurrentLoggingConsumer.InnerLoggingFileWriter.removeInstance( + (ConcurrentLoggingConsumer.InnerLoggingFileWriter) writer); } } @@ -76,7 +73,8 @@ static class InnerLoggingFileWriter implements LoggingFileWriter { instances = new HashMap<>(); } - static InnerLoggingFileWriter getInstance(final String fileName, final String lockFileName) throws FileNotFoundException { + static InnerLoggingFileWriter getInstance(final String fileName, final String lockFileName) + throws FileNotFoundException { synchronized (instances) { if (!instances.containsKey(fileName)) { instances.put(fileName, new InnerLoggingFileWriter(fileName, lockFileName)); @@ -98,7 +96,8 @@ static void removeInstance(final InnerLoggingFileWriter writer) { } } - private InnerLoggingFileWriter(final String fileName, final String lockFileName) throws FileNotFoundException { + private InnerLoggingFileWriter(final String fileName, final String lockFileName) + throws FileNotFoundException { this.fileName = fileName; this.lockFileName = lockFileName; this.refCount = 0; @@ -157,4 +156,4 @@ private void initLock() throws FileNotFoundException { } } } -} \ No newline at end of file +} diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/ConsoleConsumer.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/ConsoleConsumer.java index 3ce1d00..2743f00 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/ConsoleConsumer.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/ConsoleConsumer.java @@ -1,13 +1,11 @@ package com.sensorsdata.analytics.javasdk.consumer; -import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.extern.slf4j.Slf4j; - +import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; import java.io.IOException; import java.io.Writer; import java.util.Map; +import lombok.extern.slf4j.Slf4j; @Slf4j public class ConsoleConsumer implements Consumer { @@ -49,4 +47,4 @@ public void flush() { public void close() { flush(); } -} \ No newline at end of file +} diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/Consumer.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/Consumer.java index d5842de..00e246f 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/Consumer.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/Consumer.java @@ -8,4 +8,4 @@ public interface Consumer { void flush(); void close(); -} \ No newline at end of file +} diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/DebugConsumer.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/DebugConsumer.java index 2e5fee6..6283599 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/DebugConsumer.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/DebugConsumer.java @@ -1,16 +1,9 @@ package com.sensorsdata.analytics.javasdk.consumer; -import com.sensorsdata.analytics.javasdk.exceptions.DebugModeException; -import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.client.utils.URIBuilder; - -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; - +import com.sensorsdata.analytics.javasdk.exceptions.DebugModeException; +import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; @@ -19,6 +12,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; @Slf4j public class DebugConsumer implements Consumer { @@ -29,7 +26,8 @@ public DebugConsumer(final String serverUrl, final boolean writeData) { this(HttpClients.custom(), serverUrl, writeData); } - public DebugConsumer(HttpClientBuilder httpClientBuilder, String serverUrl, final boolean writeData) { + public DebugConsumer( + HttpClientBuilder httpClientBuilder, String serverUrl, final boolean writeData) { String debugUrl; try { // 将 URI Path 替换成 Debug 模式的 '/debug' diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/FastBatchConsumer.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/FastBatchConsumer.java index b00f01a..8c939d8 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/FastBatchConsumer.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/FastBatchConsumer.java @@ -1,16 +1,10 @@ package com.sensorsdata.analytics.javasdk.consumer; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import com.sensorsdata.analytics.javasdk.bean.FailedData; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.NonNull; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; - import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -18,6 +12,10 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import lombok.NonNull; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; /** * 网络批量请求发送,异常快速返回模式 @@ -29,177 +27,247 @@ @Slf4j public class FastBatchConsumer implements Consumer { - private static final int MAX_CACHE_SIZE = 10000; - private static final int MIN_CACHE_SIZE = 1000; - private static final int MIN_BULK_SIZE = 1; - - - private final LinkedBlockingQueue> buffer; - private final HttpConsumer httpConsumer; - private final InstantHttpConsumer instantHttpConsumer; - private final ObjectMapper jsonMapper; - private final Callback callback; - private final int bulkSize; - private final ScheduledExecutorService executorService; - private List instantEvents; - private boolean isInstantStatus; - - public FastBatchConsumer(@NonNull String serverUrl, @NonNull Callback callback) { - this(serverUrl, false, callback); - } - - public FastBatchConsumer(@NonNull String serverUrl, int flushSec, final boolean timing, @NonNull Callback callback) { - this(serverUrl, timing, 50, 6000, flushSec, 3, callback); - } - - public FastBatchConsumer(@NonNull String serverUrl, final boolean timing, @NonNull Callback callback) { - this(serverUrl, timing, 50, callback); - } - - public FastBatchConsumer(@NonNull String serverUrl, final boolean timing, int bulkSize, @NonNull Callback callback) { - this(serverUrl, timing, bulkSize, 6000, callback); - } - - public FastBatchConsumer(@NonNull String serverUrl, final boolean timing, int bulkSize, int maxCacheSize, - @NonNull Callback callback) { - this(serverUrl, timing, bulkSize, maxCacheSize, 1, 3, callback); - } - - public FastBatchConsumer(@NonNull String serverUrl, final boolean timing, final int bulkSize, int maxCacheSize, - int flushSec, int timeoutSec, @NonNull Callback callback) { - this(HttpClients.custom(), serverUrl, timing, bulkSize, maxCacheSize, flushSec, timeoutSec, callback); - } - - public FastBatchConsumer(HttpClientBuilder httpClientBuilder, @NonNull String serverUrl, final boolean timing, final int bulkSize, int maxCacheSize, - int flushSec, int timeoutSec, @NonNull Callback callback) { - this(httpClientBuilder, serverUrl, timing, bulkSize, maxCacheSize, flushSec, timeoutSec, callback, new ArrayList()); - } - - public FastBatchConsumer(HttpClientBuilder httpClientBuilder, @NonNull String serverUrl, final boolean timing, final int bulkSize, int maxCacheSize, - int flushSec, int timeoutSec, @NonNull Callback callback, List instantEvents) { - this.buffer = - new LinkedBlockingQueue<>(Math.min(Math.max(MIN_CACHE_SIZE, maxCacheSize), MAX_CACHE_SIZE)); - this.httpConsumer = new HttpConsumer(httpClientBuilder, serverUrl, Math.max(timeoutSec, 1)); - this.instantHttpConsumer = new InstantHttpConsumer(httpClientBuilder, serverUrl, Math.max(timeoutSec, 1)); - - this.jsonMapper = SensorsAnalyticsUtil.getJsonObjectMapper(); - this.callback = callback; - this.bulkSize = Math.min(MIN_CACHE_SIZE, Math.max(bulkSize, MIN_BULK_SIZE)); - this.instantEvents = instantEvents; - - executorService = new ScheduledThreadPoolExecutor(1); - executorService.scheduleWithFixedDelay(new Runnable() { - @Override - public void run() { - if (timing) { - flush(); - } else { - if (buffer.size() >= bulkSize) { + private static final int MAX_CACHE_SIZE = 10000; + private static final int MIN_CACHE_SIZE = 1000; + private static final int MIN_BULK_SIZE = 1; + + private final LinkedBlockingQueue> buffer; + private final HttpConsumer httpConsumer; + private final InstantHttpConsumer instantHttpConsumer; + private final ObjectMapper jsonMapper; + private final Callback callback; + private final int bulkSize; + private final ScheduledExecutorService executorService; + private List instantEvents; + private boolean isInstantStatus; + + public FastBatchConsumer(@NonNull String serverUrl, @NonNull Callback callback) { + this(serverUrl, false, callback); + } + + public FastBatchConsumer( + @NonNull String serverUrl, + int flushSec, + final boolean timing, + @NonNull Callback callback) { + this(serverUrl, timing, 50, 6000, flushSec, 3, callback); + } + + public FastBatchConsumer( + @NonNull String serverUrl, final boolean timing, @NonNull Callback callback) { + this(serverUrl, timing, 50, callback); + } + + public FastBatchConsumer( + @NonNull String serverUrl, + final boolean timing, + int bulkSize, + @NonNull Callback callback) { + this(serverUrl, timing, bulkSize, 6000, callback); + } + + public FastBatchConsumer( + @NonNull String serverUrl, + final boolean timing, + int bulkSize, + int maxCacheSize, + @NonNull Callback callback) { + this(serverUrl, timing, bulkSize, maxCacheSize, 1, 3, callback); + } + + public FastBatchConsumer( + @NonNull String serverUrl, + final boolean timing, + final int bulkSize, + int maxCacheSize, + int flushSec, + int timeoutSec, + @NonNull Callback callback) { + this( + HttpClients.custom(), + serverUrl, + timing, + bulkSize, + maxCacheSize, + flushSec, + timeoutSec, + callback); + } + + public FastBatchConsumer( + HttpClientBuilder httpClientBuilder, + @NonNull String serverUrl, + final boolean timing, + final int bulkSize, + int maxCacheSize, + int flushSec, + int timeoutSec, + @NonNull Callback callback) { + this( + httpClientBuilder, + serverUrl, + timing, + bulkSize, + maxCacheSize, + flushSec, + timeoutSec, + callback, + new ArrayList()); + } + + public FastBatchConsumer( + HttpClientBuilder httpClientBuilder, + @NonNull String serverUrl, + final boolean timing, + final int bulkSize, + int maxCacheSize, + int flushSec, + int timeoutSec, + @NonNull Callback callback, + List instantEvents) { + this.buffer = + new LinkedBlockingQueue<>( + Math.min(Math.max(MIN_CACHE_SIZE, maxCacheSize), MAX_CACHE_SIZE)); + this.httpConsumer = new HttpConsumer(httpClientBuilder, serverUrl, Math.max(timeoutSec, 1)); + this.instantHttpConsumer = + new InstantHttpConsumer(httpClientBuilder, serverUrl, Math.max(timeoutSec, 1)); + + this.jsonMapper = SensorsAnalyticsUtil.getJsonObjectMapper(); + this.callback = callback; + this.bulkSize = Math.min(MIN_CACHE_SIZE, Math.max(bulkSize, MIN_BULK_SIZE)); + this.instantEvents = instantEvents; + + executorService = new ScheduledThreadPoolExecutor(1); + executorService.scheduleWithFixedDelay( + new Runnable() { + @Override + public void run() { + if (timing) { + flush(); + } else { + if (buffer.size() >= bulkSize) { + flush(); + } + } + } + }, + 1, + Math.max(flushSec, 1), + TimeUnit.SECONDS); + log.info( + "Initialize FastBatchConsumer with params:[timing:{};bulkSize:{};maxCacheSize:{};flushSec:{};timeoutSec:{}].", + timing, + bulkSize, + maxCacheSize, + flushSec, + timeoutSec); + } + + @Override + public void send(Map message) { + dealInstantSignal(message); + if (buffer.remainingCapacity() == 0) { flush(); - } } - } - }, 1, Math.max(flushSec, 1), TimeUnit.SECONDS); - log.info( - "Initialize FastBatchConsumer with params:[timing:{};bulkSize:{};maxCacheSize:{};flushSec:{};timeoutSec:{}].", - timing, bulkSize, maxCacheSize, flushSec, timeoutSec); - } - - @Override - public void send(Map message) { - dealInstantSignal(message); - if (buffer.remainingCapacity() == 0) { - flush(); + buffer.offer(message); + log.debug("Successfully save data to cache.The cache current size is {}.", buffer.size()); } - buffer.offer(message); - log.debug("Successfully save data to cache.The cache current size is {}.", buffer.size()); - } - private void dealInstantSignal(Map message) { + private void dealInstantSignal(Map message) { - /* - * 如果当前是「instant」状态,且(message中不包含event 或者 event 不是「instant」的,则刷新,设置 「非instant」状态 - */ - if (isInstantStatus && (!message.containsKey("event") || !instantEvents.contains(message.get("event")))) { - flush(); - isInstantStatus = false; + /* + * 如果当前是「instant」状态,且(message中不包含event 或者 event 不是「instant」的,则刷新,设置 「非instant」状态 + */ + if (isInstantStatus + && (!message.containsKey("event") + || !instantEvents.contains(message.get("event")))) { + flush(); + isInstantStatus = false; + } + + /* + * 如果当前是 「非instant」状态,且(message中包含event 且 event 是「instant」的,则刷新,设置 「instant」状态 + */ + if (!isInstantStatus + && message.containsKey("event") + && instantEvents.contains(message.get("event"))) { + flush(); + isInstantStatus = true; + } } - /* - * 如果当前是 「非instant」状态,且(message中包含event 且 event 是「instant」的,则刷新,设置 「instant」状态 + /** + * This method don't need to be called actively.Because instance will create scheduled thread to + * do. */ - if (!isInstantStatus && message.containsKey("event") && instantEvents.contains(message.get("event"))) { - flush(); - isInstantStatus = true; + @Override + public void flush() { + List> results = new ArrayList<>(); + buffer.drainTo(results); + if (results.isEmpty()) { + log.info("The Data of cache is empty when flush."); + return; + } + log.debug("Successfully get [{}] messages from the cache.", results.size()); + while (!results.isEmpty()) { + String sendingData; + List> sendList = + results.subList(0, Math.min(bulkSize, results.size())); + try { + sendingData = jsonMapper.writeValueAsString(sendList); + } catch (JsonProcessingException e) { + callback.onFailed( + new FailedData( + String.format("can't process json,message:%s.", e.getMessage()), + SensorsAnalyticsUtil.deepCopy(sendList))); + sendList.clear(); + log.error("Failed to process json.", e); + continue; + } + log.debug("Data will be sent.{}", sendingData); + try { + if (isInstantStatus) { + this.instantHttpConsumer.consume(sendingData); + } else { + this.httpConsumer.consume(sendingData); + } + } catch (Exception e) { + log.error("Failed to send data:{}.", sendingData, e); + callback.onFailed( + new FailedData( + String.format("failed to send data,message:%s.", e.getMessage()), + SensorsAnalyticsUtil.deepCopy(sendList))); + } + sendList.clear(); + } + log.debug("Finish flush."); } - } - - /** - * This method don't need to be called actively.Because instance will create scheduled thread to do. - */ - @Override - public void flush() { - List> results = new ArrayList<>(); - buffer.drainTo(results); - if (results.isEmpty()) { - log.info("The Data of cache is empty when flush."); - return; + + @Override + public void close() { + log.info("Call close method."); + this.httpConsumer.close(); + this.executorService.shutdown(); } - log.debug("Successfully get [{}] messages from the cache.", results.size()); - while (!results.isEmpty()) { - String sendingData; - List> sendList = results.subList(0, Math.min(bulkSize, results.size())); - try { - sendingData = jsonMapper.writeValueAsString(sendList); - } catch (JsonProcessingException e) { - callback.onFailed(new FailedData(String.format("can't process json,message:%s.", e.getMessage()), - SensorsAnalyticsUtil.deepCopy(sendList))); - sendList.clear(); - log.error("Failed to process json.", e); - continue; - } - log.debug("Data will be sent.{}", sendingData); - try { - if (isInstantStatus) { - this.instantHttpConsumer.consume(sendingData); - } else { - this.httpConsumer.consume(sendingData); + + /** + * 重发送 FastBatchConsumer 模式发送失败返回的数据 + * + * @param failedData 失败的数据集合 + * @return true:发送成功;false:发送失败 + */ + public boolean resendFailedData(@NonNull FailedData failedData) + throws InvalidArgumentException, JsonProcessingException { + SensorsAnalyticsUtil.assertFailedData(failedData); + final String sendData = jsonMapper.writeValueAsString(failedData.getFailedData()); + log.debug("Will be resent data.{}", sendData); + try { + this.httpConsumer.consume(sendData); + } catch (Exception e) { + log.error("failed to send data.data:{}.", sendData, e); + return false; } - } catch (Exception e) { - log.error("Failed to send data:{}.", sendingData, e); - callback.onFailed(new FailedData(String.format("failed to send data,message:%s.", e.getMessage()), - SensorsAnalyticsUtil.deepCopy(sendList))); - } - sendList.clear(); - } - log.debug("Finish flush."); - } - - @Override - public void close() { - log.info("Call close method."); - this.httpConsumer.close(); - this.executorService.shutdown(); - } - - /** - * 重发送 FastBatchConsumer 模式发送失败返回的数据 - * - * @param failedData 失败的数据集合 - * @return true:发送成功;false:发送失败 - */ - public boolean resendFailedData(@NonNull FailedData failedData) - throws InvalidArgumentException, JsonProcessingException { - SensorsAnalyticsUtil.assertFailedData(failedData); - final String sendData = jsonMapper.writeValueAsString(failedData.getFailedData()); - log.debug("Will be resent data.{}", sendData); - try { - this.httpConsumer.consume(sendData); - } catch (Exception e) { - log.error("failed to send data.data:{}.", sendData, e); - return false; + log.info("Successfully resend failed data."); + return true; } - log.info("Successfully resend failed data."); - return true; - } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/HttpConsumer.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/HttpConsumer.java index 773b04e..efe730d 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/HttpConsumer.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/HttpConsumer.java @@ -2,7 +2,15 @@ import com.sensorsdata.analytics.javasdk.SensorsConst; import com.sensorsdata.analytics.javasdk.util.Base64Coder; - +import java.io.ByteArrayOutputStream; +import java.io.Closeable; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.zip.GZIPOutputStream; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; @@ -15,16 +23,6 @@ import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.zip.GZIPOutputStream; - class HttpConsumer implements Closeable { CloseableHttpClient httpClient; final String serverUrl; @@ -44,7 +42,10 @@ public HttpConsumer(String serverUrl, Map httpHeaders) { this(HttpClients.custom(), serverUrl, httpHeaders, timeoutSec); } - public HttpConsumer(HttpClientBuilder httpClientBuilder, String serverUrl, Map httpHeaders) { + public HttpConsumer( + HttpClientBuilder httpClientBuilder, + String serverUrl, + Map httpHeaders) { this(httpClientBuilder, serverUrl, httpHeaders, 3); } @@ -52,36 +53,58 @@ public HttpConsumer(HttpClientBuilder httpClientBuilder, String serverUrl, int t this(httpClientBuilder, serverUrl, null, timeoutSec); } - HttpConsumer(HttpClientBuilder httpClientBuilder, String serverUrl, Map httpHeaders, int timeoutSec) { + HttpConsumer( + HttpClientBuilder httpClientBuilder, + String serverUrl, + Map httpHeaders, + int timeoutSec) { this.serverUrl = serverUrl.trim(); this.httpHeaders = httpHeaders; this.compressData = true; int timeout = timeoutSec * 1000; - this.requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout) - .setConnectTimeout(timeout).setSocketTimeout(timeout).build(); - this.httpClient = httpClientBuilder - .setUserAgent(String.format("SensorsAnalytics Java SDK %s", SensorsConst.SDK_VERSION)) - .setDefaultRequestConfig(requestConfig) - .build(); + this.requestConfig = + RequestConfig.custom() + .setConnectionRequestTimeout(timeout) + .setConnectTimeout(timeout) + .setSocketTimeout(timeout) + .build(); + this.httpClient = + httpClientBuilder + .setUserAgent( + String.format( + "SensorsAnalytics Java SDK %s", SensorsConst.SDK_VERSION)) + .setDefaultRequestConfig(requestConfig) + .build(); } void consume(final String data) throws IOException, HttpConsumerException { HttpUriRequest request = getHttpRequest(data); CloseableHttpResponse response = null; if (httpClient == null) { - httpClient = HttpClients.custom() - .setUserAgent(String.format("SensorsAnalytics Java SDK %s", SensorsConst.SDK_VERSION)) - .setDefaultRequestConfig(requestConfig) - .build(); + httpClient = + HttpClients.custom() + .setUserAgent( + String.format( + "SensorsAnalytics Java SDK %s", + SensorsConst.SDK_VERSION)) + .setDefaultRequestConfig(requestConfig) + .build(); } try { response = httpClient.execute(request); int httpStatusCode = response.getStatusLine().getStatusCode(); if (httpStatusCode < 200 || httpStatusCode >= 300) { - String httpContent = new String(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8); + String httpContent = + new String( + EntityUtils.toByteArray(response.getEntity()), + StandardCharsets.UTF_8); throw new HttpConsumerException( - String.format("Unexpected response %d from Sensors Analytics: %s", httpStatusCode, httpContent), data, - httpStatusCode, httpContent); + String.format( + "Unexpected response %d from Sensors Analytics: %s", + httpStatusCode, httpContent), + data, + httpStatusCode, + httpContent); } } finally { if (response != null) { @@ -123,12 +146,13 @@ List getNameValuePairs(String data) throws IOException { os.close(); nameValuePairs.add(new BasicNameValuePair("gzip", "1")); - nameValuePairs.add(new BasicNameValuePair("data_list", new String(Base64Coder.encode - (compressed)))); + nameValuePairs.add( + new BasicNameValuePair( + "data_list", new String(Base64Coder.encode(compressed)))); } else { nameValuePairs.add(new BasicNameValuePair("gzip", "0")); - nameValuePairs.add(new BasicNameValuePair("data_list", new String(Base64Coder.encode - (bytes)))); + nameValuePairs.add( + new BasicNameValuePair("data_list", new String(Base64Coder.encode(bytes)))); } return nameValuePairs; @@ -148,8 +172,8 @@ public synchronized void close() { static class HttpConsumerException extends Exception { - HttpConsumerException(String error, String sendingData, int httpStatusCode, String - httpContent) { + HttpConsumerException( + String error, String sendingData, int httpStatusCode, String httpContent) { super(error); this.sendingData = sendingData; this.httpStatusCode = httpStatusCode; diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/InnerLoggingConsumer.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/InnerLoggingConsumer.java index b6aaa67..a7045be 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/InnerLoggingConsumer.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/InnerLoggingConsumer.java @@ -1,15 +1,13 @@ package com.sensorsdata.analytics.javasdk.consumer; -import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.extern.slf4j.Slf4j; - +import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; import java.io.FileNotFoundException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; +import lombok.extern.slf4j.Slf4j; @Slf4j class InnerLoggingConsumer implements Consumer { @@ -26,9 +24,10 @@ class InnerLoggingConsumer implements Consumer { private LoggingFileWriter fileWriter; InnerLoggingConsumer( - LoggingFileWriterFactory fileWriterFactory, - String filenamePrefix, - int bufferSize, LogSplitMode splitMode) { + LoggingFileWriterFactory fileWriterFactory, + String filenamePrefix, + int bufferSize, + LogSplitMode splitMode) { this.fileWriterFactory = fileWriterFactory; this.filenamePrefix = filenamePrefix; this.jsonMapper = SensorsAnalyticsUtil.getJsonObjectMapper(); @@ -40,8 +39,10 @@ class InnerLoggingConsumer implements Consumer { this.simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); } log.info( - "Initialize LoggingConsumer with params:[filenamePrefix:{},bufferSize:{},splitMode:{}].", - filenamePrefix, bufferSize, splitMode); + "Initialize LoggingConsumer with params:[filenamePrefix:{},bufferSize:{},splitMode:{}].", + filenamePrefix, + bufferSize, + splitMode); } @Override @@ -55,14 +56,19 @@ public synchronized void send(Map message) { throw new RuntimeException("fail to process json", e); } } else { - log.error("Logging cache exceeded the allowed limitation,current cache size is {}.", - messageBuffer.length()); + log.error( + "Logging cache exceeded the allowed limitation,current cache size is {}.", + messageBuffer.length()); throw new RuntimeException("logging buffer exceeded the allowed limitation."); } - log.debug("Successfully save data to cache,The cache current size is {}.", messageBuffer.length()); + log.debug( + "Successfully save data to cache,The cache current size is {}.", + messageBuffer.length()); if (messageBuffer.length() >= bufferSize) { - log.info("Flush triggered because logging cache size reached the threshold,cache size:{},bulkSize:{}.", - messageBuffer.length(), bufferSize); + log.info( + "Flush triggered because logging cache size reached the threshold,cache size:{},bulkSize:{}.", + messageBuffer.length(), + bufferSize); flush(); } } @@ -82,7 +88,9 @@ public synchronized void flush() { if (fileWriter != null && !fileWriter.isValid(filename)) { this.fileWriterFactory.closeFileWriter(fileWriter); - log.info("The new file name [{}] is different from current file name,so update file writer.", filename); + log.info( + "The new file name [{}] is different from current file name,so update file writer.", + filename); fileWriter = null; } @@ -111,7 +119,6 @@ public synchronized void close() { } log.info("Call close method."); } - } interface LoggingFileWriter { @@ -128,5 +135,4 @@ LoggingFileWriter getFileWriter(final String fileName, final String scheduleFile throws FileNotFoundException; void closeFileWriter(LoggingFileWriter writer); - -} \ No newline at end of file +} diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/InstantHttpConsumer.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/InstantHttpConsumer.java index a0ebe40..814f694 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/InstantHttpConsumer.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/InstantHttpConsumer.java @@ -1,46 +1,51 @@ package com.sensorsdata.analytics.javasdk.consumer; +import java.io.IOException; +import java.util.List; +import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; -import java.io.IOException; -import java.util.List; -import java.util.Map; - -public class InstantHttpConsumer extends HttpConsumer{ - - public InstantHttpConsumer(String serverUrl, int timeoutSec) { - super(serverUrl, timeoutSec); - } - - public InstantHttpConsumer(String serverUrl, Map httpHeaders) { - super(serverUrl, httpHeaders); - } - - InstantHttpConsumer(String serverUrl, Map httpHeaders, int timeoutSec) { - super(serverUrl, httpHeaders, timeoutSec); - } - - public InstantHttpConsumer(HttpClientBuilder httpClientBuilder, String serverUrl, - Map httpHeaders) { - super(httpClientBuilder, serverUrl, httpHeaders); - } - - public InstantHttpConsumer(HttpClientBuilder httpClientBuilder, String serverUrl, int timeoutSec) { - super(httpClientBuilder, serverUrl, timeoutSec); - } - - InstantHttpConsumer(HttpClientBuilder httpClientBuilder, String serverUrl, Map httpHeaders, - int timeoutSec) { - super(httpClientBuilder, serverUrl, httpHeaders, timeoutSec); - } - - @Override - UrlEncodedFormEntity getHttpEntry(final String data) throws IOException { - List nameValuePairs = getNameValuePairs(data); - nameValuePairs.add(new BasicNameValuePair("instant_event", "true")); - return new UrlEncodedFormEntity(nameValuePairs); - } +public class InstantHttpConsumer extends HttpConsumer { + + public InstantHttpConsumer(String serverUrl, int timeoutSec) { + super(serverUrl, timeoutSec); + } + + public InstantHttpConsumer(String serverUrl, Map httpHeaders) { + super(serverUrl, httpHeaders); + } + + InstantHttpConsumer(String serverUrl, Map httpHeaders, int timeoutSec) { + super(serverUrl, httpHeaders, timeoutSec); + } + + public InstantHttpConsumer( + HttpClientBuilder httpClientBuilder, + String serverUrl, + Map httpHeaders) { + super(httpClientBuilder, serverUrl, httpHeaders); + } + + public InstantHttpConsumer( + HttpClientBuilder httpClientBuilder, String serverUrl, int timeoutSec) { + super(httpClientBuilder, serverUrl, timeoutSec); + } + + InstantHttpConsumer( + HttpClientBuilder httpClientBuilder, + String serverUrl, + Map httpHeaders, + int timeoutSec) { + super(httpClientBuilder, serverUrl, httpHeaders, timeoutSec); + } + + @Override + UrlEncodedFormEntity getHttpEntry(final String data) throws IOException { + List nameValuePairs = getNameValuePairs(data); + nameValuePairs.add(new BasicNameValuePair("instant_event", "true")); + return new UrlEncodedFormEntity(nameValuePairs); + } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/LogSplitMode.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/LogSplitMode.java index 9901f42..373b273 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/LogSplitMode.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/consumer/LogSplitMode.java @@ -1,5 +1,6 @@ package com.sensorsdata.analytics.javasdk.consumer; public enum LogSplitMode { - DAY, HOUR - } \ No newline at end of file + DAY, + HOUR +} diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/exceptions/DebugModeException.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/exceptions/DebugModeException.java index faa287d..7a169ae 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/exceptions/DebugModeException.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/exceptions/DebugModeException.java @@ -1,20 +1,17 @@ package com.sensorsdata.analytics.javasdk.exceptions; -/** - * Debug模式下的错误 - */ +/** Debug模式下的错误 */ public class DebugModeException extends RuntimeException { - public DebugModeException(String message) { - super(message); - } + public DebugModeException(String message) { + super(message); + } - public DebugModeException(Throwable error) { - super(error); - } - - public DebugModeException(String message, Throwable error) { - super(message, error); - } + public DebugModeException(Throwable error) { + super(error); + } + public DebugModeException(String message, Throwable error) { + super(message, error); + } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/exceptions/InvalidArgumentException.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/exceptions/InvalidArgumentException.java index 32ba38f..ff66ad0 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/exceptions/InvalidArgumentException.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/exceptions/InvalidArgumentException.java @@ -1,16 +1,13 @@ package com.sensorsdata.analytics.javasdk.exceptions; -/** - * 非法的DistinctID - */ +/** 非法的DistinctID */ public class InvalidArgumentException extends Exception { - public InvalidArgumentException(String message) { - super(message); - } - - public InvalidArgumentException(Throwable error) { - super(error); - } + public InvalidArgumentException(String message) { + super(message); + } + public InvalidArgumentException(Throwable error) { + super(error); + } } diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/util/Base64Coder.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/util/Base64Coder.java index 0596301..4c1c7db 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/util/Base64Coder.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/util/Base64Coder.java @@ -1,168 +1,154 @@ package com.sensorsdata.analytics.javasdk.util; -//Copyright 2003-2010 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland -//www.source-code.biz, www.inventec.ch/chdh +// Copyright 2003-2010 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland +// www.source-code.biz, www.inventec.ch/chdh // -//This module is multi-licensed and may be used under the terms -//of any of the following licenses: +// This module is multi-licensed and may be used under the terms +// of any of the following licenses: // -//EPL, Eclipse Public License, V1.0 or later, http://www.eclipse.org/legal -//LGPL, GNU Lesser General Public License, V2.1 or later, http://www.gnu.org/licenses/lgpl.html -//GPL, GNU General Public License, V2 or later, http://www.gnu.org/licenses/gpl.html -//AL, Apache License, V2.0 or later, http://www.apache.org/licenses -//BSD, BSD License, http://www.opensource.org/licenses/bsd-license.php +// EPL, Eclipse Public License, V1.0 or later, http://www.eclipse.org/legal +// LGPL, GNU Lesser General Public License, V2.1 or later, http://www.gnu.org/licenses/lgpl.html +// GPL, GNU General Public License, V2 or later, http://www.gnu.org/licenses/gpl.html +// AL, Apache License, V2.0 or later, http://www.apache.org/licenses +// BSD, BSD License, http://www.opensource.org/licenses/bsd-license.php // -//Please contact the author if you need another license. -//This module is provided "as is", without warranties of any kind. +// Please contact the author if you need another license. +// This module is provided "as is", without warranties of any kind. // // This file has been modified from it's original version by Mixpanel, Inc - public class Base64Coder { - // Mapping table from 6-bit nibbles to Base64 characters. - private static char[] map1 = new char[64]; - // Mapping table from Base64 characters to 6-bit nibbles. - private static byte[] map2 = new byte[128]; - - static { - int i = 0; - for (char c = 'A'; c <= 'Z'; c++) - map1[i++] = c; - for (char c = 'a'; c <= 'z'; c++) - map1[i++] = c; - for (char c = '0'; c <= '9'; c++) - map1[i++] = c; - map1[i++] = '+'; - map1[i++] = '/'; - } - - static { - for (int i = 0; i < map2.length; i++) - map2[i] = -1; - for (int i = 0; i < 64; i++) - map2[map1[i]] = (byte) i; - } + // Mapping table from 6-bit nibbles to Base64 characters. + private static char[] map1 = new char[64]; + // Mapping table from Base64 characters to 6-bit nibbles. + private static byte[] map2 = new byte[128]; - /** - * Encodes a string into Base64 format. - * No blanks or line breaks are inserted. - * - * @param s a String to be encoded. - * @return A String with the Base64 encoded data. - */ - public static String encodeString(String s) { - return new String(encode(s.getBytes())); - } + static { + int i = 0; + for (char c = 'A'; c <= 'Z'; c++) map1[i++] = c; + for (char c = 'a'; c <= 'z'; c++) map1[i++] = c; + for (char c = '0'; c <= '9'; c++) map1[i++] = c; + map1[i++] = '+'; + map1[i++] = '/'; + } - /** - * Encodes a byte array into Base64 format. - * No blanks or line breaks are inserted. - * - * @param in an array containing the data bytes to be encoded. - * @return A character array with the Base64 encoded data. - */ - public static char[] encode(byte[] in) { - return encode(in, in.length); - } + static { + for (int i = 0; i < map2.length; i++) map2[i] = -1; + for (int i = 0; i < 64; i++) map2[map1[i]] = (byte) i; + } - /** - * Encodes a byte array into Base64 format. - * No blanks or line breaks are inserted. - * - * @param in an array containing the data bytes to be encoded. - * @param iLen number of bytes to process in in. - * @return A character array with the Base64 encoded data. - */ - public static char[] encode(byte[] in, int iLen) { - int oDataLen = (iLen * 4 + 2) / 3; // output length without padding - int oLen = ((iLen + 2) / 3) * 4; // output length including padding - char[] out = new char[oLen]; - int ip = 0; - int op = 0; - while (ip < iLen) { - int i0 = in[ip++] & 0xff; - int i1 = ip < iLen ? in[ip++] & 0xff : 0; - int i2 = ip < iLen ? in[ip++] & 0xff : 0; - int o0 = i0 >>> 2; - int o1 = ((i0 & 3) << 4) | (i1 >>> 4); - int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); - int o3 = i2 & 0x3F; - out[op++] = map1[o0]; - out[op++] = map1[o1]; - out[op] = op < oDataLen ? map1[o2] : '='; - op++; - out[op] = op < oDataLen ? map1[o3] : '='; - op++; + /** + * Encodes a string into Base64 format. No blanks or line breaks are inserted. + * + * @param s a String to be encoded. + * @return A String with the Base64 encoded data. + */ + public static String encodeString(String s) { + return new String(encode(s.getBytes())); } - return out; - } - /** - * Decodes a string from Base64 format. - * - * @param s a Base64 String to be decoded. - * @return A String containing the decoded data. - * @throws IllegalArgumentException if the input is not valid Base64 encoded data. - */ - public static String decodeString(String s) { - return new String(decode(s)); - } + /** + * Encodes a byte array into Base64 format. No blanks or line breaks are inserted. + * + * @param in an array containing the data bytes to be encoded. + * @return A character array with the Base64 encoded data. + */ + public static char[] encode(byte[] in) { + return encode(in, in.length); + } - /** - * Decodes a byte array from Base64 format. - * - * @param s a Base64 String to be decoded. - * @return An array containing the decoded data bytes. - * @throws IllegalArgumentException if the input is not valid Base64 encoded data. - */ - public static byte[] decode(String s) { - return decode(s.toCharArray()); - } + /** + * Encodes a byte array into Base64 format. No blanks or line breaks are inserted. + * + * @param in an array containing the data bytes to be encoded. + * @param iLen number of bytes to process in in. + * @return A character array with the Base64 encoded data. + */ + public static char[] encode(byte[] in, int iLen) { + int oDataLen = (iLen * 4 + 2) / 3; // output length without padding + int oLen = ((iLen + 2) / 3) * 4; // output length including padding + char[] out = new char[oLen]; + int ip = 0; + int op = 0; + while (ip < iLen) { + int i0 = in[ip++] & 0xff; + int i1 = ip < iLen ? in[ip++] & 0xff : 0; + int i2 = ip < iLen ? in[ip++] & 0xff : 0; + int o0 = i0 >>> 2; + int o1 = ((i0 & 3) << 4) | (i1 >>> 4); + int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); + int o3 = i2 & 0x3F; + out[op++] = map1[o0]; + out[op++] = map1[o1]; + out[op] = op < oDataLen ? map1[o2] : '='; + op++; + out[op] = op < oDataLen ? map1[o3] : '='; + op++; + } + return out; + } - /** - * Decodes a byte array from Base64 format. - * No blanks or line breaks are allowed within the Base64 encoded data. - * - * @param in a character array containing the Base64 encoded data. - * @return An array containing the decoded data bytes. - * @throws IllegalArgumentException if the input is not valid Base64 encoded data. - */ - public static byte[] decode(char[] in) { - int iLen = in.length; - if (iLen % 4 != 0) - throw new IllegalArgumentException( - "Length of Base64 encoded input string is not a multiple of 4."); - while (iLen > 0 && in[iLen - 1] == '=') - iLen--; - int oLen = (iLen * 3) / 4; - byte[] out = new byte[oLen]; - int ip = 0; - int op = 0; - while (ip < iLen) { - int i0 = in[ip++]; - int i1 = in[ip++]; - int i2 = ip < iLen ? in[ip++] : 'A'; - int i3 = ip < iLen ? in[ip++] : 'A'; - if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) - throw new IllegalArgumentException("Illegal character in Base64 encoded data."); - int b0 = map2[i0]; - int b1 = map2[i1]; - int b2 = map2[i2]; - int b3 = map2[i3]; - if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) - throw new IllegalArgumentException("Illegal character in Base64 encoded data."); - int o0 = (b0 << 2) | (b1 >>> 4); - int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2); - int o2 = ((b2 & 3) << 6) | b3; - out[op++] = (byte) o0; - if (op < oLen) - out[op++] = (byte) o1; - if (op < oLen) - out[op++] = (byte) o2; + /** + * Decodes a string from Base64 format. + * + * @param s a Base64 String to be decoded. + * @return A String containing the decoded data. + * @throws IllegalArgumentException if the input is not valid Base64 encoded data. + */ + public static String decodeString(String s) { + return new String(decode(s)); } - return out; - } + /** + * Decodes a byte array from Base64 format. + * + * @param s a Base64 String to be decoded. + * @return An array containing the decoded data bytes. + * @throws IllegalArgumentException if the input is not valid Base64 encoded data. + */ + public static byte[] decode(String s) { + return decode(s.toCharArray()); + } -} // end class Base64Coder \ No newline at end of file + /** + * Decodes a byte array from Base64 format. No blanks or line breaks are allowed within the + * Base64 encoded data. + * + * @param in a character array containing the Base64 encoded data. + * @return An array containing the decoded data bytes. + * @throws IllegalArgumentException if the input is not valid Base64 encoded data. + */ + public static byte[] decode(char[] in) { + int iLen = in.length; + if (iLen % 4 != 0) + throw new IllegalArgumentException( + "Length of Base64 encoded input string is not a multiple of 4."); + while (iLen > 0 && in[iLen - 1] == '=') iLen--; + int oLen = (iLen * 3) / 4; + byte[] out = new byte[oLen]; + int ip = 0; + int op = 0; + while (ip < iLen) { + int i0 = in[ip++]; + int i1 = in[ip++]; + int i2 = ip < iLen ? in[ip++] : 'A'; + int i3 = ip < iLen ? in[ip++] : 'A'; + if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) + throw new IllegalArgumentException("Illegal character in Base64 encoded data."); + int b0 = map2[i0]; + int b1 = map2[i1]; + int b2 = map2[i2]; + int b3 = map2[i3]; + if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) + throw new IllegalArgumentException("Illegal character in Base64 encoded data."); + int o0 = (b0 << 2) | (b1 >>> 4); + int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2); + int o2 = ((b2 & 3) << 6) | b3; + out[op++] = (byte) o0; + if (op < oLen) out[op++] = (byte) o1; + if (op < oLen) out[op++] = (byte) o2; + } + return out; + } +} // end class Base64Coder diff --git a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/util/SensorsAnalyticsUtil.java b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/util/SensorsAnalyticsUtil.java index 8f3cb84..df042f8 100644 --- a/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/util/SensorsAnalyticsUtil.java +++ b/SensorsAnalyticsSDK/src/main/java/com/sensorsdata/analytics/javasdk/util/SensorsAnalyticsUtil.java @@ -13,18 +13,15 @@ import static com.sensorsdata.analytics.javasdk.SensorsConst.TRACK_SIGN_UP_ACTION_TYPE; import static com.sensorsdata.analytics.javasdk.SensorsConst.UNBIND_ID_ACTION_TYPE; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.sensorsdata.analytics.javasdk.SensorsConst; import com.sensorsdata.analytics.javasdk.bean.FailedData; import com.sensorsdata.analytics.javasdk.bean.SensorsAnalyticsIdentity; import com.sensorsdata.analytics.javasdk.common.Pair; import com.sensorsdata.analytics.javasdk.common.SensorsDataTypeEnum; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.PropertyNamingStrategy; -import lombok.extern.slf4j.Slf4j; - import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; @@ -35,399 +32,475 @@ import java.util.Random; import java.util.TimeZone; import java.util.regex.Pattern; +import lombok.extern.slf4j.Slf4j; @Slf4j public class SensorsAnalyticsUtil { - public static final Pattern KEY_PATTERN = Pattern.compile( - "^((?!^distinct_id$|^original_id$|^event_id$|^time$|^properties$|^id$|^first_id$|^second_id$|^users$|^events$|^event$|^user_id$|^date$|^datetime$|^user_group|^user_tag)[a-zA-Z_$][a-zA-Z\\d_$]{0,99})$", - Pattern.CASE_INSENSITIVE); + public static final Pattern KEY_PATTERN = + Pattern.compile( + "^((?!^distinct_id$|^original_id$|^event_id$|^time$|^properties$|^id$|^first_id$|^second_id$|^users$|^events$|^event$|^user_id$|^date$|^datetime$|^user_group|^user_tag)[a-zA-Z_$][a-zA-Z\\d_$]{0,99})$", + Pattern.CASE_INSENSITIVE); - public static String strJoin(String[] arr, String sep) { - StringBuilder sbStr = new StringBuilder(); - for (int i = 0, il = arr.length; i < il; i++) { - if (i > 0) - sbStr.append(sep); - sbStr.append(arr[i]); + public static String strJoin(String[] arr, String sep) { + StringBuilder sbStr = new StringBuilder(); + for (int i = 0, il = arr.length; i < il; i++) { + if (i > 0) sbStr.append(sep); + sbStr.append(arr[i]); + } + return sbStr.toString(); } - return sbStr.toString(); - } - - public static ObjectMapper getJsonObjectMapper() { - ObjectMapper jsonObjectMapper = new ObjectMapper(); - // 容忍json中出现未知的列 - jsonObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - // 兼容java中的驼峰的字段名命名 - jsonObjectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); - jsonObjectMapper.setTimeZone(TimeZone.getDefault()); - jsonObjectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")); - return jsonObjectMapper; - } - /** - * 校验 IDM 用户纬度数据是否合法 - * - * @param actionType 事件类型 - * @param identityMap 用户纬度数据集合 - * @throws InvalidArgumentException 不合法直接抛出异常 - */ - public static void assertIdentityMap(String actionType, Map identityMap) - throws InvalidArgumentException { - for (Map.Entry entry : identityMap.entrySet()) { - assertKey(actionType, entry.getKey()); - assertValue(actionType, entry.getValue()); + public static ObjectMapper getJsonObjectMapper() { + ObjectMapper jsonObjectMapper = new ObjectMapper(); + // 容忍json中出现未知的列 + jsonObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + // 兼容java中的驼峰的字段名命名 + jsonObjectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); + jsonObjectMapper.setTimeZone(TimeZone.getDefault()); + jsonObjectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")); + return jsonObjectMapper; } - } - /** - * 校验数据属性是否合法 - * - * @param eventType 事件类型 - * @param properties 数据属性集合 - * @throws InvalidArgumentException 不合法直接抛出异常 - */ - public static void assertProperties(String eventType, Map properties) - throws InvalidArgumentException { - if (null == properties) { - return; + /** + * 校验 IDM 用户纬度数据是否合法 + * + * @param actionType 事件类型 + * @param identityMap 用户纬度数据集合 + * @throws InvalidArgumentException 不合法直接抛出异常 + */ + public static void assertIdentityMap(String actionType, Map identityMap) + throws InvalidArgumentException { + for (Map.Entry entry : identityMap.entrySet()) { + assertKey(actionType, entry.getKey()); + assertValue(actionType, entry.getValue()); + } } - for (Map.Entry property : properties.entrySet()) { - if (property.getKey().equals("$is_login_id")) { - if (!(property.getValue() instanceof Boolean)) { - throw new InvalidArgumentException("The property value of '$is_login_id' should be Boolean."); + + /** + * 校验数据属性是否合法 + * + * @param eventType 事件类型 + * @param properties 数据属性集合 + * @throws InvalidArgumentException 不合法直接抛出异常 + */ + public static void assertProperties(String eventType, Map properties) + throws InvalidArgumentException { + if (null == properties) { + return; } - continue; - } + for (Map.Entry property : properties.entrySet()) { + if (property.getKey().equals("$is_login_id")) { + if (!(property.getValue() instanceof Boolean)) { + throw new InvalidArgumentException( + "The property value of '$is_login_id' should be Boolean."); + } + continue; + } - assertKey("property", property.getKey()); + assertKey("property", property.getKey()); - if (!(property.getValue() instanceof Number) && !(property.getValue() instanceof Date) - && !(property.getValue() instanceof String) && !(property.getValue() instanceof Boolean) - && !(property.getValue() instanceof List)) { - String type = property.getValue() == null ? "null" : property.getValue().getClass().toString(); - throw new InvalidArgumentException(String.format( - "The property '%s' should be a basic type: Number, String, Date, Boolean, List.The current type is %s.", - property.getKey(), type)); - } + if (!(property.getValue() instanceof Number) + && !(property.getValue() instanceof Date) + && !(property.getValue() instanceof String) + && !(property.getValue() instanceof Boolean) + && !(property.getValue() instanceof List)) { + String type = + property.getValue() == null + ? "null" + : property.getValue().getClass().toString(); + throw new InvalidArgumentException( + String.format( + "The property '%s' should be a basic type: Number, String, Date, Boolean, List.The current type is %s.", + property.getKey(), type)); + } - if (property.getKey().equals(SensorsConst.TIME_SYSTEM_ATTR) - && !(property.getValue() instanceof Date)) { - throw new InvalidArgumentException("The property '$time' should be a java.util.Date."); - } + if (property.getKey().equals(SensorsConst.TIME_SYSTEM_ATTR) + && !(property.getValue() instanceof Date)) { + throw new InvalidArgumentException( + "The property '$time' should be a java.util.Date."); + } - // List 类型的属性值,List 元素必须为 String 类型 - if (property.getValue() instanceof List && - !eventType.equals(SensorsConst.PROFILE_INCREMENT_ACTION_TYPE)) { - for (final ListIterator it = ((List) property.getValue()).listIterator(); it.hasNext(); ) { - Object element = it.next(); - if (!(element instanceof String)) { - throw new InvalidArgumentException( - String.format("The property '%s' should be a list of String.", property.getKey())); - } - if (((String) element).length() > 8192) { - it.set(((String) element).substring(0, 8192)); - } - } - } + // List 类型的属性值,List 元素必须为 String 类型 + if (property.getValue() instanceof List + && !eventType.equals(SensorsConst.PROFILE_INCREMENT_ACTION_TYPE)) { + for (final ListIterator it = + ((List) property.getValue()).listIterator(); + it.hasNext(); ) { + Object element = it.next(); + if (!(element instanceof String)) { + throw new InvalidArgumentException( + String.format( + "The property '%s' should be a list of String.", + property.getKey())); + } + if (((String) element).length() > 8192) { + it.set(((String) element).substring(0, 8192)); + } + } + } - // String 类型的属性值,长度不能超过 8192 - if (property.getValue() instanceof String) { - String value = (String) property.getValue(); - if (value.length() > 8192) { - property.setValue(value.substring(0, 8192)); - } - } + // String 类型的属性值,长度不能超过 8192 + if (property.getValue() instanceof String) { + String value = (String) property.getValue(); + if (value.length() > 8192) { + property.setValue(value.substring(0, 8192)); + } + } + + boolean isFilterKey = + property.getKey().equals(SensorsConst.PROJECT_SYSTEM_ATTR) + || property.getKey().equals(SensorsConst.TOKEN_SYSTEM_ATTR); - boolean isFilterKey = property.getKey().equals(SensorsConst.PROJECT_SYSTEM_ATTR) || - property.getKey().equals(SensorsConst.TOKEN_SYSTEM_ATTR); + if (eventType.equals(SensorsConst.PROFILE_INCREMENT_ACTION_TYPE)) { + if (!isFilterKey) { + if (!(property.getValue() instanceof Number)) { + String type = + property.getValue() == null + ? "null" + : property.getValue().getClass().toString(); + throw new InvalidArgumentException( + String.format( + "The property value of PROFILE_INCREMENT should be a Number.The current type is %s.", + type)); + } + } + } else if (eventType.equals(SensorsConst.PROFILE_APPEND_ACTION_TYPE)) { + if (!isFilterKey && !(property.getValue() instanceof List)) { + throw new InvalidArgumentException( + "The property value of PROFILE_APPEND should be a List."); + } + } + } + } - if (eventType.equals(SensorsConst.PROFILE_INCREMENT_ACTION_TYPE)) { - if (!isFilterKey) { - if (!(property.getValue() instanceof Number)) { - String type = property.getValue() == null ? "null" : property.getValue().getClass().toString(); + public static void assertValue(String type, String value) throws InvalidArgumentException { + if (value == null || value.length() < 1) { throw new InvalidArgumentException( - String.format("The property value of PROFILE_INCREMENT should be a Number.The current type is %s.", - type)); - } + String.format("The %s value is empty or null.", type)); } - } else if (eventType.equals(SensorsConst.PROFILE_APPEND_ACTION_TYPE)) { - if (!isFilterKey && !(property.getValue() instanceof List)) { - throw new InvalidArgumentException("The property value of PROFILE_APPEND should be a List."); + if (value.length() > 255) { + throw new InvalidArgumentException( + String.format("The %s value %s is too long, max length is 255.", type, value)); } - } } - } - public static void assertValue(String type, String value) throws InvalidArgumentException { - if (value == null || value.length() < 1) { - throw new InvalidArgumentException(String.format("The %s value is empty or null.", type)); - } - if (value.length() > 255) { - throw new InvalidArgumentException(String.format("The %s value %s is too long, max length is 255.", type, value)); + public static void assertValue(String type, Object value) throws InvalidArgumentException { + if (value instanceof String) { + assertValue(type, (String) value); + } else if (value instanceof List) { + if (((List) value).size() == 0) { + throw new InvalidArgumentException(String.format("%s value is empty.", type)); + } + for (Object o : (List) value) { + assertValue(type, (String) o); + } + } else { + throw new InvalidArgumentException( + String.format("Unsupported data type for the %s value", type)); + } } - } - public static void assertKey(String type, String key) throws InvalidArgumentException { - if (null == key || key.length() < 1) { - throw new InvalidArgumentException(String.format("The %s key is empty or null.", type)); - } - if (!(KEY_PATTERN.matcher(key).matches())) { - throw new InvalidArgumentException(String.format("The %s key '%s' is invalid.", type, key)); + public static void assertKey(String type, String key) throws InvalidArgumentException { + if (null == key || key.length() < 1) { + throw new InvalidArgumentException(String.format("The %s key is empty or null.", type)); + } + if (!(KEY_PATTERN.matcher(key).matches())) { + throw new InvalidArgumentException( + String.format("The %s key '%s' is invalid.", type, key)); + } } - } - public static Integer getTrackId(Map propertyMap, String message) { - try { - if (propertyMap.containsKey(SensorsConst.TRACK_ID)) { - return Integer.parseInt((String.valueOf(propertyMap.remove(SensorsConst.TRACK_ID)))); - } - return new Random().nextInt(); - } catch (Exception e) { - log.error("Failed Get Track ID. {} ", message, e); - return new Random().nextInt(); + public static Integer getTrackId(Map propertyMap, String message) { + try { + if (propertyMap.containsKey(SensorsConst.TRACK_ID)) { + return Integer.parseInt( + (String.valueOf(propertyMap.remove(SensorsConst.TRACK_ID)))); + } + return new Random().nextInt(); + } catch (Exception e) { + log.error("Failed Get Track ID. {} ", message, e); + return new Random().nextInt(); + } } - } - - public static String checkUserInfo(Long userId, Map identities, String distinctId) - throws InvalidArgumentException { - if (identities.isEmpty() && null == userId) { - throw new InvalidArgumentException("missing user info node(identities/user_id)."); - } - if (userId != null) { - if (distinctId != null) { - assertValue("distinct_id", distinctId); - return distinctId; - } else - return SensorsConst.USER_ID_PREFIX + userId; + public static String checkUserInfo( + Long userId, Map identities, String distinctId) + throws InvalidArgumentException { + if (identities.isEmpty() && null == userId) { + throw new InvalidArgumentException("missing user info node(identities/user_id)."); + } + if (userId != null) { + if (distinctId != null) { + assertValue("distinct_id", distinctId); + return distinctId; + } else return SensorsConst.USER_ID_PREFIX + userId; + } + Pair userPair = + checkIdentitiesAndGenerateDistinctId(distinctId, identities); + return userPair.getKey(); } - Pair userPair = checkIdentitiesAndGenerateDistinctId(distinctId, identities); - return userPair.getKey(); - } - - /** - * IDM3.0 校验 distinctId 和 identities 集合,并生成最终 distinctId - * - * @param distinctId 外部传入 - * @param identities 用户维度集合 - * @return 返回最终 distinctId 值和 isLoginId - */ - public static Pair checkIdentitiesAndGenerateDistinctId(String distinctId, - Map identities) throws InvalidArgumentException { - if (distinctId != null) { - assertValue("distinct_id", distinctId); - } - String tmpId = null; - //校验 idMap 是否正确,并尝试组装 distinct - for (Map.Entry entry : identities.entrySet()) { - assertKey(TRACK_ACTION_TYPE, entry.getKey()); - assertValue(TRACK_ACTION_TYPE, entry.getValue()); - if (tmpId == null && distinctId == null) { - tmpId = String.format("%s+%s", entry.getKey(), entry.getValue()); - if (tmpId.length() > 255) { - tmpId = null; + /** + * IDM3.0 校验 distinctId 和 identities 集合,并生成最终 distinctId + * + * @param distinctId 外部传入 + * @param identities 用户维度集合 + * @return 返回最终 distinctId 值和 isLoginId + */ + public static Pair checkIdentitiesAndGenerateDistinctId( + String distinctId, Map identities) throws InvalidArgumentException { + if (distinctId != null) { + assertValue("distinct_id", distinctId); } - } - } - boolean isLoginId = false; - String id = tmpId; - //没有主动设置,则使用 SDK 内部逻辑 - if (distinctId == null) { - //循环完毕,查看一下 map 中是否存在 $identity_login_id - if (identities.containsKey(SensorsAnalyticsIdentity.LOGIN_ID)) { - id = identities.get(SensorsAnalyticsIdentity.LOGIN_ID); - isLoginId = true; - } else if (tmpId == null) { // 不存在 $identity_login_id,并且 key+value 超长,使用第一个 value - id = identities.get(identities.keySet().iterator().next()); - } else {// 否则使用 key+value - id = tmpId; - } - } else { - id = distinctId; + String tmpId = null; + // 校验 idMap 是否正确,并尝试组装 distinct + for (Map.Entry entry : identities.entrySet()) { + assertKey(TRACK_ACTION_TYPE, entry.getKey()); + assertValue(TRACK_ACTION_TYPE, entry.getValue()); + if (tmpId == null && distinctId == null) { + tmpId = String.format("%s+%s", entry.getKey(), entry.getValue()); + if (tmpId.length() > 255) { + tmpId = null; + } + } + } + boolean isLoginId = false; + String id = tmpId; + // 没有主动设置,则使用 SDK 内部逻辑 + if (distinctId == null) { + // 循环完毕,查看一下 map 中是否存在 $identity_login_id + if (identities.containsKey(SensorsAnalyticsIdentity.LOGIN_ID)) { + id = (String) identities.get(SensorsAnalyticsIdentity.LOGIN_ID); + isLoginId = true; + } else if (tmpId == null) { // 不存在 $identity_login_id,并且 key+value 超长,使用第一个 value + Object obj = identities.get(identities.keySet().iterator().next()); + if (obj instanceof String) { + id = (String) obj; + } else if (obj instanceof List) { + // the list is not empty, otherwise there is a check fail before + id = (String) ((List) obj).get(0); + } + } else { // 否则使用 key+value + id = tmpId; + } + } else { + id = distinctId; + } + return Pair.of(id, isLoginId); } - return Pair.of(id, isLoginId); - } - public static void assertFailedData(FailedData failedData) throws InvalidArgumentException { - if (failedData.getFailedData() == null || failedData.getFailedData().isEmpty()) { - throw new InvalidArgumentException("Failed Data is null or empty."); - } - for (int i = 0; i < failedData.getFailedData().size(); i++) { - final Map dataMap = failedData.getFailedData().get(i); - if (verifyMapValueIsBlank(dataMap, "type")) { - throw new InvalidArgumentException( - String.format("The index [%d] of failed data list have not [type].", i)); - } - final String type = String.valueOf(dataMap.get("type")); - switch (type) { - case ITEM_SET_ACTION_TYPE: - case ITEM_DELETE_ACTION_TYPE: - if (verifyMapValueIsBlank(dataMap, "item_id")) { - throw new InvalidArgumentException( - String.format("The index [%d] of failed data list have not [item_id].", i)); - } - assertValue("item id", dataMap.get("item_id").toString()); - if (verifyMapValueIsBlank(dataMap, "item_type")) { - throw new InvalidArgumentException( - String.format("The index [%d] of failed data list have not [item_type].", i)); - } - assertValue("item type", dataMap.get("item_type").toString()); - break; - case TRACK_SIGN_UP_ACTION_TYPE: - if (verifyMapValueIsBlank(dataMap, "original_id")) { - throw new InvalidArgumentException( - String.format("The index [%d] of failed data list have not [original_id].", i)); - } - assertValue("Original Distinct Id", dataMap.get("original_id").toString()); - case BIND_ID_ACTION_TYPE: - case UNBIND_ID_ACTION_TYPE: - if (!TRACK_SIGN_UP_ACTION_TYPE.equals(type) && verifyMapValueIsBlank(dataMap, "identities")) { - throw new InvalidArgumentException( - String.format("The index [%d] of failed data list have not [identities].", i)); - } - case TRACK_ACTION_TYPE: - case PROFILE_SET_ACTION_TYPE: - case PROFILE_SET_ONCE_ACTION_TYPE: - case PROFILE_APPEND_ACTION_TYPE: - case PROFILE_INCREMENT_ACTION_TYPE: - case PROFILE_UNSET_ACTION_TYPE: - case PROFILE_DELETE_ACTION_TYPE: - if (verifyMapValueIsBlank(dataMap, "distinct_id")) { - throw new InvalidArgumentException( - String.format("The index [%d] of failed data list have not [distinct_id].", i)); - } - if (verifyMapValueIsBlank(dataMap, "_track_id") || !(dataMap.get("_track_id") instanceof Integer)) { - throw new InvalidArgumentException(String.format("The index [%d] of of failed data list is invalid.", i)); - } - assertValue("Distinct Id", dataMap.get("distinct_id").toString()); - break; - default: - throw new InvalidArgumentException( - String.format("The index [%d] of failed data list can not identify [action_type:%s].", i, type)); - } - if (dataMap.containsKey("properties")) { - if (!(dataMap.get("properties") instanceof Map)) { - throw new InvalidArgumentException( - String.format("The index [%d] of failed data list can not identify [properties:%s].", i, type)); + public static void assertFailedData(FailedData failedData) throws InvalidArgumentException { + if (failedData.getFailedData() == null || failedData.getFailedData().isEmpty()) { + throw new InvalidArgumentException("Failed Data is null or empty."); + } + for (int i = 0; i < failedData.getFailedData().size(); i++) { + final Map dataMap = failedData.getFailedData().get(i); + if (verifyMapValueIsBlank(dataMap, "type")) { + throw new InvalidArgumentException( + String.format("The index [%d] of failed data list have not [type].", i)); + } + final String type = String.valueOf(dataMap.get("type")); + switch (type) { + case ITEM_SET_ACTION_TYPE: + case ITEM_DELETE_ACTION_TYPE: + if (verifyMapValueIsBlank(dataMap, "item_id")) { + throw new InvalidArgumentException( + String.format( + "The index [%d] of failed data list have not [item_id].", + i)); + } + assertValue("item id", dataMap.get("item_id").toString()); + if (verifyMapValueIsBlank(dataMap, "item_type")) { + throw new InvalidArgumentException( + String.format( + "The index [%d] of failed data list have not [item_type].", + i)); + } + assertValue("item type", dataMap.get("item_type").toString()); + break; + case TRACK_SIGN_UP_ACTION_TYPE: + if (verifyMapValueIsBlank(dataMap, "original_id")) { + throw new InvalidArgumentException( + String.format( + "The index [%d] of failed data list have not [original_id].", + i)); + } + assertValue("Original Distinct Id", dataMap.get("original_id").toString()); + case BIND_ID_ACTION_TYPE: + case UNBIND_ID_ACTION_TYPE: + if (!TRACK_SIGN_UP_ACTION_TYPE.equals(type) + && verifyMapValueIsBlank(dataMap, "identities")) { + throw new InvalidArgumentException( + String.format( + "The index [%d] of failed data list have not [identities].", + i)); + } + case TRACK_ACTION_TYPE: + case PROFILE_SET_ACTION_TYPE: + case PROFILE_SET_ONCE_ACTION_TYPE: + case PROFILE_APPEND_ACTION_TYPE: + case PROFILE_INCREMENT_ACTION_TYPE: + case PROFILE_UNSET_ACTION_TYPE: + case PROFILE_DELETE_ACTION_TYPE: + if (verifyMapValueIsBlank(dataMap, "distinct_id")) { + throw new InvalidArgumentException( + String.format( + "The index [%d] of failed data list have not [distinct_id].", + i)); + } + if (verifyMapValueIsBlank(dataMap, "_track_id") + || !(dataMap.get("_track_id") instanceof Integer)) { + throw new InvalidArgumentException( + String.format( + "The index [%d] of of failed data list is invalid.", i)); + } + assertValue("Distinct Id", dataMap.get("distinct_id").toString()); + break; + default: + throw new InvalidArgumentException( + String.format( + "The index [%d] of failed data list can not identify [action_type:%s].", + i, type)); + } + if (dataMap.containsKey("properties")) { + if (!(dataMap.get("properties") instanceof Map)) { + throw new InvalidArgumentException( + String.format( + "The index [%d] of failed data list can not identify [properties:%s].", + i, type)); + } + assertProperties(type, (Map) dataMap.get("properties")); + } + if (!dataMap.containsKey("time")) { + dataMap.put("time", System.currentTimeMillis()); + } } - assertProperties(type, (Map) dataMap.get("properties")); - } - if (!dataMap.containsKey("time")) { - dataMap.put("time", System.currentTimeMillis()); - } } - } - public static List> deepCopy(List> source) { - if (source == null) { - return null; - } - List> newList = new ArrayList<>(source.size()); - for (Map objectMap : source) { - Map newMap = new HashMap<>(objectMap.size()); - newMap.putAll(objectMap); - newList.add(newMap); + public static List> deepCopy(List> source) { + if (source == null) { + return null; + } + List> newList = new ArrayList<>(source.size()); + for (Map objectMap : source) { + Map newMap = new HashMap<>(objectMap.size()); + newMap.putAll(objectMap); + newList.add(newMap); + } + return newList; } - return newList; - } - private static boolean verifyMapValueIsBlank(Map map, String key) { - return map == null || !map.containsKey(key) || map.get(key) == null; - } - - public static void assertSchema(String schema) throws InvalidArgumentException { - if (null == schema || "".equals(schema)) { - throw new InvalidArgumentException("The schema can not set null or empty."); - } - if (!KEY_PATTERN.matcher(schema).matches()) { - throw new InvalidArgumentException(String.format("Thr schema '%s' is invalid.", schema)); + private static boolean verifyMapValueIsBlank(Map map, String key) { + return map == null || !map.containsKey(key) || map.get(key) == null; } - } - public static void assertSchemaProperties(Map properties, String actionType) - throws InvalidArgumentException { - if (properties.isEmpty()) { - return; + public static void assertSchema(String schema) throws InvalidArgumentException { + if (null == schema || "".equals(schema)) { + throw new InvalidArgumentException("The schema can not set null or empty."); + } + if (!KEY_PATTERN.matcher(schema).matches()) { + throw new InvalidArgumentException( + String.format("Thr schema '%s' is invalid.", schema)); + } } - for (Map.Entry entry : properties.entrySet()) { - assertKey("property", entry.getKey()); - Object value = entry.getValue(); - if (SensorsConst.TIME_SYSTEM_ATTR.equals(entry.getKey()) && !(value instanceof Date)) { - throw new InvalidArgumentException("The property '$time' should be a java.util.Date."); - } - switch (SensorsDataTypeEnum.getDataType(value)) { - case NUMBER: - case BOOLEAN: - case DATE: - break; - case LIST: - List valueList = (List) value; - ListIterator listIterator = valueList.listIterator(); - while (listIterator.hasNext()) { - Object next = listIterator.next(); - if (!(next instanceof String)) { - throw new InvalidArgumentException( - String.format("The property '%s' should be a list of String.", entry.getKey())); + + public static void assertSchemaProperties(Map properties, String actionType) + throws InvalidArgumentException { + if (properties.isEmpty()) { + return; + } + for (Map.Entry entry : properties.entrySet()) { + assertKey("property", entry.getKey()); + Object value = entry.getValue(); + if (SensorsConst.TIME_SYSTEM_ATTR.equals(entry.getKey()) && !(value instanceof Date)) { + throw new InvalidArgumentException( + "The property '$time' should be a java.util.Date."); } - if (((String) next).length() > 8192) { - listIterator.set(((String) next).substring(0, 8192)); + switch (SensorsDataTypeEnum.getDataType(value)) { + case NUMBER: + case BOOLEAN: + case DATE: + break; + case LIST: + List valueList = (List) value; + ListIterator listIterator = valueList.listIterator(); + while (listIterator.hasNext()) { + Object next = listIterator.next(); + if (!(next instanceof String)) { + throw new InvalidArgumentException( + String.format( + "The property '%s' should be a list of String.", + entry.getKey())); + } + if (((String) next).length() > 8192) { + listIterator.set(((String) next).substring(0, 8192)); + } + } + break; + case STRING: + if (((String) value).length() > 8192) { + entry.setValue(((String) value).substring(0, 8192)); + } + break; + default: + throw new InvalidArgumentException( + String.format( + "The property '%s' should be a basic type: Number, String, Date, Boolean, List.The current type is %s.", + entry.getKey(), value.getClass().getName())); + } + // 处理 profileIncrement + if (PROFILE_INCREMENT_ACTION_TYPE.equals(actionType)) { + if ((!SensorsConst.PROJECT_SYSTEM_ATTR.equals(entry.getKey()) + && !SensorsConst.TOKEN_SYSTEM_ATTR.equals(entry.getKey())) + && !(value instanceof Number)) { + throw new InvalidArgumentException( + String.format( + "The property value of PROFILE_INCREMENT should be a Number.The current type is %s.", + value.getClass().getName())); + } + } + // 处理 profileAppend + if (PROFILE_APPEND_ACTION_TYPE.equals(actionType)) { + if ((!SensorsConst.PROJECT_SYSTEM_ATTR.equals(entry.getKey()) + && !SensorsConst.TOKEN_SYSTEM_ATTR.equals(entry.getKey())) + && !(value instanceof List)) { + throw new InvalidArgumentException( + String.format( + "The property value of PROFILE_APPEND should be a List.The current type is %s.", + value.getClass().getName())); + } + } + // 处理 profile_unset + if (PROFILE_UNSET_ACTION_TYPE.equals(actionType)) { + if (!(value instanceof Boolean) || !Boolean.parseBoolean(value.toString())) { + throw new InvalidArgumentException( + "The property value of " + entry.getKey() + " should be true."); + } } - } - break; - case STRING: - if (((String) value).length() > 8192) { - entry.setValue(((String) value).substring(0, 8192)); - } - break; - default: - throw new InvalidArgumentException(String.format( - "The property '%s' should be a basic type: Number, String, Date, Boolean, List.The current type is %s.", - entry.getKey(), value.getClass().getName())); - } - //处理 profileIncrement - if (PROFILE_INCREMENT_ACTION_TYPE.equals(actionType)) { - if ((!SensorsConst.PROJECT_SYSTEM_ATTR.equals(entry.getKey()) - && !SensorsConst.TOKEN_SYSTEM_ATTR.equals(entry.getKey())) && !(value instanceof Number)) { - throw new InvalidArgumentException( - String.format("The property value of PROFILE_INCREMENT should be a Number.The current type is %s.", - value.getClass().getName())); - } - } - //处理 profileAppend - if (PROFILE_APPEND_ACTION_TYPE.equals(actionType)) { - if ((!SensorsConst.PROJECT_SYSTEM_ATTR.equals(entry.getKey()) - && !SensorsConst.TOKEN_SYSTEM_ATTR.equals(entry.getKey())) && !(value instanceof List)) { - throw new InvalidArgumentException( - String.format("The property value of PROFILE_APPEND should be a List.The current type is %s.", - value.getClass().getName())); - } - } - //处理 profile_unset - if (PROFILE_UNSET_ACTION_TYPE.equals(actionType)) { - if (!(value instanceof Boolean) || !Boolean.parseBoolean(value.toString())) { - throw new InvalidArgumentException("The property value of " + entry.getKey() + " should be true."); } - } } - } - - public static String toString(Map identities) { - if (identities == null) { - return null; - } - StringBuilder res = new StringBuilder(""); - for (Map.Entry entry : identities.entrySet()) { - res.append("{").append(entry.getKey()).append(":").append(entry.getValue()).append("},"); + public static String toString(Map identities) { + if (identities == null) { + return null; + } + StringBuilder res = new StringBuilder(""); + for (Map.Entry entry : identities.entrySet()) { + res.append("{") + .append(entry.getKey()) + .append(":") + .append(entry.getValue()) + .append("},"); + } + return res.toString(); } - return res.toString(); - } - public static void assertEventItemPair(Pair itemPair) throws InvalidArgumentException { - if (itemPair == null) { - throw new InvalidArgumentException("item event record must be set item id info"); + public static void assertEventItemPair(Pair itemPair) + throws InvalidArgumentException { + if (itemPair == null) { + throw new InvalidArgumentException("item event record must be set item id info"); + } + assertKey("item event id", itemPair.getKey()); + assertValue("item event value", itemPair.getValue()); } - assertKey("item event id", itemPair.getKey()); - assertValue("item event value", itemPair.getValue()); - } -} \ No newline at end of file +} diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/BatchConsumerTestConstruct.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/BatchConsumerTestConstruct.java index bd18f68..0e2397a 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/BatchConsumerTestConstruct.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/BatchConsumerTestConstruct.java @@ -1,18 +1,14 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import com.sensorsdata.analytics.javasdk.consumer.BatchConsumer; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - import java.lang.reflect.Field; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * BatchConsumer 单测 @@ -23,289 +19,304 @@ */ public class BatchConsumerTestConstruct { - private BatchConsumer batchConsumer; - private SensorsAnalytics sa; - private List> messageList; -// private String serverUrl = "http://10.120.73.51:8106/sa?project=default&token="; - String serverUrl = "http://10.120.111.143:8106/sa?project=default"; + private BatchConsumer batchConsumer; + private SensorsAnalytics sa; + private List> messageList; + // private String serverUrl = "http://10.120.73.51:8106/sa?project=default&token="; + String serverUrl = "http://10.120.111.143:8106/sa?project=default"; + + @BeforeEach + public void init() throws NoSuchFieldException, IllegalAccessException { + // batchConsumer = new BatchConsumer("http://localhost:8016/sa", 1, 3, true); + // sa = new SensorsAnalytics(batchConsumer); + // Field field = batchConsumer.getClass().getDeclaredField("messageList"); + // field.setAccessible(true); + // messageList = (List>) field.get(batchConsumer); + } + + private void assertBlukSize(int bulkSizeExp) + throws InvalidArgumentException, NoSuchFieldException, IllegalAccessException, + InterruptedException { + Field field = batchConsumer.getClass().getDeclaredField("messageList"); + field.setAccessible(true); + messageList = (List>) field.get(batchConsumer); + + field = batchConsumer.getClass().getDeclaredField("bulkSize"); + field.setAccessible(true); + int bulkSizeRel = (Integer) field.get(batchConsumer); + + Assertions.assertEquals(bulkSizeExp, bulkSizeRel); + + for (int i = 0; i < (bulkSizeExp - 1); i++) { + sa.track("123", true, "test" + i, null); + } + Assertions.assertEquals(bulkSizeExp - 1, messageList.size()); + Thread.sleep(3000); + sa.track("123", true, "test" + (bulkSizeExp - 1), null); + Thread.sleep(3000); + Assertions.assertEquals(0, messageList.size()); + } + private void assertMaxCacheSize(int maxCacheSizeExp) + throws InvalidArgumentException, NoSuchFieldException, IllegalAccessException, + InterruptedException { + Field field = batchConsumer.getClass().getDeclaredField("messageList"); + field.setAccessible(true); + messageList = (List>) field.get(batchConsumer); + + field = batchConsumer.getClass().getDeclaredField("maxCacheSize"); + field.setAccessible(true); + int maxCacheSizeRel = (Integer) field.get(batchConsumer); + + Assertions.assertEquals(maxCacheSizeExp, maxCacheSizeRel); + + if (maxCacheSizeExp != 0) { + for (int i = 0; i < (maxCacheSizeExp); i++) { + sa.track("123", true, "test" + i, null); + } + // Assertions.assertEquals(maxCacheSizeExp, messageList.size()); + Assertions.assertTrue(maxCacheSizeExp > messageList.size()); + } + } - @Before - public void init() throws NoSuchFieldException, IllegalAccessException { -// batchConsumer = new BatchConsumer("http://localhost:8016/sa", 1, 3, true); -// sa = new SensorsAnalytics(batchConsumer); -// Field field = batchConsumer.getClass().getDeclaredField("messageList"); -// field.setAccessible(true); -// messageList = (List>) field.get(batchConsumer); - } + private void assertThrowException(Boolean throwExceptionExp) + throws NoSuchFieldException, IllegalAccessException { + Field field = batchConsumer.getClass().getDeclaredField("throwException"); + field.setAccessible(true); + Boolean throwExceptionRel = (Boolean) field.get(batchConsumer); + Assertions.assertEquals(throwExceptionExp, throwExceptionRel); + } + + /** 测试 BatchConsumer 构造函数 public BatchConsumer(final String serverUrl) */ + @Test + public void testBatchConsumer01() + throws NoSuchFieldException, IllegalAccessException, InterruptedException, + InvalidArgumentException { + int bulkSize = 50; + int maxCacheSize = 0; + boolean throwException = false; + + batchConsumer = new BatchConsumer(serverUrl); + sa = new SensorsAnalytics(batchConsumer); + + assertBlukSize(bulkSize); + + serverUrl = "http://localhost:8887/test"; + batchConsumer = new BatchConsumer(serverUrl); + assertMaxCacheSize(maxCacheSize); + assertThrowException(throwException); + } + + /** 测试 BatchConsumer 构造函数 public BatchConsumer(final String serverUrl, final int bulkSize) */ + @Test + public void testBatchConsumer02() + throws NoSuchFieldException, IllegalAccessException, InterruptedException, + InvalidArgumentException { + int bulkSize = 100; + int maxCacheSize = 0; + boolean throwException = false; + + batchConsumer = new BatchConsumer(serverUrl, bulkSize); + sa = new SensorsAnalytics(batchConsumer); + + assertBlukSize(bulkSize); + assertMaxCacheSize(maxCacheSize); + assertThrowException(throwException); + } - private void assertBlukSize(int bulkSizeExp) throws InvalidArgumentException, NoSuchFieldException, IllegalAccessException, InterruptedException{ - Field field = batchConsumer.getClass().getDeclaredField("messageList"); - field.setAccessible(true); - messageList = (List>) field.get(batchConsumer); + /** 测试 BatchConsumer 构造函数 public BatchConsumer(final String serverUrl, final int bulkSize) */ + @Test + public void testBatchConsumer02BlukSize() + throws NoSuchFieldException, IllegalAccessException, InterruptedException, + InvalidArgumentException { + int bulkSize = 100; + int maxCacheSize = 0; + boolean throwException = false; + + batchConsumer = new BatchConsumer(serverUrl, 0); + sa = new SensorsAnalytics(batchConsumer); + + assertBlukSize(1); + assertMaxCacheSize(maxCacheSize); + assertThrowException(throwException); + } - field = batchConsumer.getClass().getDeclaredField("bulkSize"); - field.setAccessible(true); - int bulkSizeRel = (Integer) field.get(batchConsumer); + /** + * 测试 BatchConsumer 构造函数 public BatchConsumer(final String serverUrl, final int bulkSize, final + * boolean throwException) + */ + @Test + public void testBatchConsumer03() + throws NoSuchFieldException, IllegalAccessException, InterruptedException, + InvalidArgumentException { + int bulkSize = 100; + int maxCacheSize = 0; + boolean throwException = true; + + batchConsumer = new BatchConsumer(serverUrl, bulkSize, throwException); + sa = new SensorsAnalytics(batchConsumer); + + assertBlukSize(bulkSize); + assertMaxCacheSize(maxCacheSize); + assertThrowException(throwException); + } - assertEquals(bulkSizeExp, bulkSizeRel); + /** + * 测试 BatchConsumer 构造函数 public BatchConsumer(final String serverUrl, final int bulkSize, final + * int maxCacheSize, final boolean throwException) + */ + @Test + public void testBatchConsumer04() + throws NoSuchFieldException, IllegalAccessException, InterruptedException, + InvalidArgumentException { + int bulkSize = 900; + int maxCacheSize = 4000; + boolean throwException = true; + + batchConsumer = new BatchConsumer(serverUrl, bulkSize, maxCacheSize, throwException); + sa = new SensorsAnalytics(batchConsumer); + + assertBlukSize(bulkSize); + + serverUrl = "http://localhost:8887/test"; + batchConsumer = new BatchConsumer(serverUrl, bulkSize, maxCacheSize, throwException); + assertMaxCacheSize(maxCacheSize); + assertThrowException(throwException); + } - for (int i = 0; i < (bulkSizeExp-1); i++){ - sa.track("123", true, "test" + i, null); + /** + * 测试 BatchConsumer 构造函数 public BatchConsumer(final String serverUrl, final int bulkSize, final + * int timeoutSec) + */ + @Test + public void testBatchConsumerTimeoutSec05() + throws NoSuchFieldException, IllegalAccessException, InterruptedException, + InvalidArgumentException { + int bulkSize = 100; + int maxCacheSize = 0; + int timeoutSec = 10; + boolean throwException = false; + + batchConsumer = new BatchConsumer(serverUrl, bulkSize, timeoutSec); + sa = new SensorsAnalytics(batchConsumer); + + assertBlukSize(bulkSize); + assertMaxCacheSize(maxCacheSize); + assertThrowException(throwException); } - assertEquals(bulkSizeExp-1, messageList.size()); - Thread.sleep(3000); - sa.track("123", true, "test" + (bulkSizeExp-1), null); - Thread.sleep(3000); - assertEquals(0, messageList.size()); - } - - private void assertMaxCacheSize(int maxCacheSizeExp) throws InvalidArgumentException, NoSuchFieldException, IllegalAccessException, InterruptedException{ - Field field = batchConsumer.getClass().getDeclaredField("messageList"); - field.setAccessible(true); - messageList = (List>) field.get(batchConsumer); - - field = batchConsumer.getClass().getDeclaredField("maxCacheSize"); - field.setAccessible(true); - int maxCacheSizeRel = (Integer) field.get(batchConsumer); - - assertEquals(maxCacheSizeExp, maxCacheSizeRel); - - if(maxCacheSizeExp != 0){ - for (int i = 0; i < (maxCacheSizeExp); i++){ - sa.track("123", true, "test" + i, null); - } -// assertEquals(maxCacheSizeExp, messageList.size()); - assertTrue(maxCacheSizeExp > messageList.size()); + + /** + * 测试 BatchConsumer 构造函数 timeoutSec 参数,需要使用 Charles 配合测试 public BatchConsumer(final String + * serverUrl, final int bulkSize, final int timeoutSec) + */ + @Test + public void testBatchConsumerTimeoutSec05AssertTimeout() + throws NoSuchFieldException, IllegalAccessException, InterruptedException, + InvalidArgumentException { + String serverUrl = "http://localhost:8887/test"; + int bulkSize = 100; + int timeoutSec = 5; + long start = 0, end; + + batchConsumer = new BatchConsumer(serverUrl, bulkSize, timeoutSec); + sa = new SensorsAnalytics(batchConsumer); + // try { + start = System.currentTimeMillis(); + sa.track("xc11", true, "Exent1"); + sa.flush(); + // }catch (Exception e){ + // end = System.currentTimeMillis(); + // Assertions.assertTrue((end-start) < timeoutSec*1000+200 && (end-start) > + // timeoutSec*1000-200); + // System.out.println("=========="); + // e.printStackTrace(); + // } } - } - - private void assertThrowException(Boolean throwExceptionExp) throws NoSuchFieldException, IllegalAccessException { - Field field = batchConsumer.getClass().getDeclaredField("throwException"); - field.setAccessible(true); - Boolean throwExceptionRel = (Boolean) field.get(batchConsumer); - - assertEquals(throwExceptionExp, throwExceptionRel); - } - - - /** - * 测试 BatchConsumer 构造函数 - * public BatchConsumer(final String serverUrl) - */ - @Test - public void testBatchConsumer01() throws NoSuchFieldException, IllegalAccessException, InterruptedException, InvalidArgumentException { - int bulkSize = 50; - int maxCacheSize = 0; - boolean throwException = false; - - batchConsumer = new BatchConsumer(serverUrl); - sa = new SensorsAnalytics(batchConsumer); - - assertBlukSize(bulkSize); - - serverUrl = "http://localhost:8887/test"; - batchConsumer = new BatchConsumer(serverUrl); - assertMaxCacheSize(maxCacheSize); - assertThrowException(throwException); - } - - /** - * 测试 BatchConsumer 构造函数 - * public BatchConsumer(final String serverUrl, final int bulkSize) - */ - @Test - public void testBatchConsumer02() throws NoSuchFieldException, IllegalAccessException, InterruptedException, InvalidArgumentException { - int bulkSize = 100; - int maxCacheSize = 0; - boolean throwException = false; - - batchConsumer = new BatchConsumer(serverUrl, bulkSize); - sa = new SensorsAnalytics(batchConsumer); - - assertBlukSize(bulkSize); - assertMaxCacheSize(maxCacheSize); - assertThrowException(throwException); - } - - /** - * 测试 BatchConsumer 构造函数 - * public BatchConsumer(final String serverUrl, final int bulkSize) - */ - @Test - public void testBatchConsumer02BlukSize() throws NoSuchFieldException, IllegalAccessException, InterruptedException, InvalidArgumentException { - int bulkSize = 100; - int maxCacheSize = 0; - boolean throwException = false; - - batchConsumer = new BatchConsumer(serverUrl, 0); - sa = new SensorsAnalytics(batchConsumer); - - assertBlukSize(1); - assertMaxCacheSize(maxCacheSize); - assertThrowException(throwException); - } - - /** - * 测试 BatchConsumer 构造函数 - * public BatchConsumer(final String serverUrl, final int bulkSize, final boolean throwException) - */ - @Test - public void testBatchConsumer03() throws NoSuchFieldException, IllegalAccessException, InterruptedException, InvalidArgumentException { - int bulkSize = 100; - int maxCacheSize = 0; - boolean throwException = true; - - batchConsumer = new BatchConsumer(serverUrl, bulkSize, throwException); - sa = new SensorsAnalytics(batchConsumer); - - assertBlukSize(bulkSize); - assertMaxCacheSize(maxCacheSize); - assertThrowException(throwException); - } /** - * 测试 BatchConsumer 构造函数 - * public BatchConsumer(final String serverUrl, final int bulkSize, final int maxCacheSize, final boolean throwException) - */ - @Test - public void testBatchConsumer04() throws NoSuchFieldException, IllegalAccessException, InterruptedException, InvalidArgumentException { - int bulkSize = 900; - int maxCacheSize = 4000; - boolean throwException = true; - - batchConsumer = new BatchConsumer(serverUrl,bulkSize,maxCacheSize, throwException); - sa = new SensorsAnalytics(batchConsumer); - - assertBlukSize(bulkSize); - - serverUrl = "http://localhost:8887/test"; - batchConsumer = new BatchConsumer(serverUrl, bulkSize, maxCacheSize, throwException); - assertMaxCacheSize(maxCacheSize); - assertThrowException(throwException); - } - - /** - * 测试 BatchConsumer 构造函数 - * public BatchConsumer(final String serverUrl, final int bulkSize, final int timeoutSec) - */ - @Test - public void testBatchConsumerTimeoutSec05() throws NoSuchFieldException, IllegalAccessException, InterruptedException, InvalidArgumentException { - int bulkSize = 100; - int maxCacheSize = 0; - int timeoutSec = 10; - boolean throwException = false; - - batchConsumer = new BatchConsumer(serverUrl, bulkSize, timeoutSec); - sa = new SensorsAnalytics(batchConsumer); - - assertBlukSize(bulkSize); - assertMaxCacheSize(maxCacheSize); - assertThrowException(throwException); - } - - /** - * 测试 BatchConsumer 构造函数 timeoutSec 参数,需要使用 Charles 配合测试 - * public BatchConsumer(final String serverUrl, final int bulkSize, final int timeoutSec) - */ - @Test - public void testBatchConsumerTimeoutSec05AssertTimeout() throws NoSuchFieldException, IllegalAccessException, InterruptedException, InvalidArgumentException { - String serverUrl = "http://localhost:8887/test"; - int bulkSize = 100; - int timeoutSec = 5; - long start = 0,end; - - batchConsumer = new BatchConsumer(serverUrl, bulkSize, timeoutSec); - sa = new SensorsAnalytics(batchConsumer); -// try { - start = System.currentTimeMillis(); - sa.track("xc11", true, "Exent1"); - sa.flush(); -// }catch (Exception e){ -// end = System.currentTimeMillis(); -// assertTrue((end-start) < timeoutSec*1000+200 && (end-start) > timeoutSec*1000-200); -// System.out.println("=========="); -// e.printStackTrace(); -// } - } - - /** - * 测试 BatchConsumer 构造函数 - * public BatchConsumer(String serverUrl, int bulkSize, int maxCacheSize, boolean throwException, int timeoutSec) - */ - @Test - public void testBatchConsumerTimeoutSec06() throws NoSuchFieldException, IllegalAccessException, InterruptedException, InvalidArgumentException { - int bulkSize = 100; - int timeoutSec = 5; - int maxCacheSize = 0; - boolean throwException = true; - - batchConsumer = new BatchConsumer(serverUrl, bulkSize, throwException, timeoutSec); - sa = new SensorsAnalytics(batchConsumer); - assertBlukSize(bulkSize); - assertMaxCacheSize(maxCacheSize); - assertThrowException(throwException); - } - - /** - * 测试 BatchConsumer 构造函数 timeoutSec 参数,需要使用 Charles 匹配 - * public BatchConsumer(final String serverUrl, final int bulkSize, final int timeoutSec) - */ - @Test - @Ignore - public void testBatchConsumerTimeoutSec06AssertTimeout() throws NoSuchFieldException, IllegalAccessException, InterruptedException, InvalidArgumentException { - String serverUrl = "http://localhost:8887/test"; - int bulkSize = 100; - int timeoutSec = 5; - int maxCacheSize = 4000; - boolean throwException = true; - - batchConsumer = new BatchConsumer(serverUrl, bulkSize, throwException, timeoutSec); - sa = new SensorsAnalytics(batchConsumer); - sa.track("xc11", true, "Exent1"); - sa.flush(); -// Thread.sleep(15*1000); - } - - /** - * 测试 BatchConsumer 构造函数 - * public BatchConsumer(String serverUrl, int bulkSize, int maxCacheSize, boolean throwException, int timeoutSec) - */ - @Test - public void testBatchConsumerTimeoutSec07() throws NoSuchFieldException, IllegalAccessException, InterruptedException, InvalidArgumentException { - int bulkSize = 100; - int timeoutSec = 5; - int maxCacheSize = 4000; - boolean throwException = true; - - batchConsumer = new BatchConsumer(serverUrl, bulkSize, maxCacheSize, throwException, timeoutSec); - sa = new SensorsAnalytics(batchConsumer); - assertBlukSize(bulkSize); - assertMaxCacheSize(maxCacheSize); - assertThrowException(throwException); - } - - /** - * 测试 BatchConsumer 构造函数 timeoutSec 参数,需要使用 Charles 匹配 - * public BatchConsumer(final String serverUrl, final int bulkSize, final int timeoutSec) - */ - @Test - @Ignore - public void testBatchConsumerTimeoutSec07AssertTimeout() throws NoSuchFieldException, IllegalAccessException, InterruptedException, InvalidArgumentException { - String serverUrl = "http://localhost:8887/test"; - int bulkSize = 100; - int timeoutSec = 5; - int maxCacheSize = 4000; - boolean throwException = true; - - batchConsumer = new BatchConsumer(serverUrl, bulkSize, maxCacheSize, throwException, timeoutSec); - sa = new SensorsAnalytics(batchConsumer); - sa.track("xc11", true, "Exent1"); - sa.flush(); - Thread.sleep(15*1000); - } + * 测试 BatchConsumer 构造函数 public BatchConsumer(String serverUrl, int bulkSize, int maxCacheSize, + * boolean throwException, int timeoutSec) + */ + @Test + public void testBatchConsumerTimeoutSec06() + throws NoSuchFieldException, IllegalAccessException, InterruptedException, + InvalidArgumentException { + int bulkSize = 100; + int timeoutSec = 5; + int maxCacheSize = 0; + boolean throwException = true; + + batchConsumer = new BatchConsumer(serverUrl, bulkSize, throwException, timeoutSec); + sa = new SensorsAnalytics(batchConsumer); + assertBlukSize(bulkSize); + assertMaxCacheSize(maxCacheSize); + assertThrowException(throwException); + } + /** + * 测试 BatchConsumer 构造函数 timeoutSec 参数,需要使用 Charles 匹配 public BatchConsumer(final String + * serverUrl, final int bulkSize, final int timeoutSec) + */ + @Test + @Disabled + public void testBatchConsumerTimeoutSec06AssertTimeout() + throws NoSuchFieldException, IllegalAccessException, InterruptedException, + InvalidArgumentException { + String serverUrl = "http://localhost:8887/test"; + int bulkSize = 100; + int timeoutSec = 5; + int maxCacheSize = 4000; + boolean throwException = true; + + batchConsumer = new BatchConsumer(serverUrl, bulkSize, throwException, timeoutSec); + sa = new SensorsAnalytics(batchConsumer); + sa.track("xc11", true, "Exent1"); + sa.flush(); + // Thread.sleep(15*1000); + } + /** + * 测试 BatchConsumer 构造函数 public BatchConsumer(String serverUrl, int bulkSize, int maxCacheSize, + * boolean throwException, int timeoutSec) + */ + @Test + public void testBatchConsumerTimeoutSec07() + throws NoSuchFieldException, IllegalAccessException, InterruptedException, + InvalidArgumentException { + int bulkSize = 100; + int timeoutSec = 5; + int maxCacheSize = 4000; + boolean throwException = true; + + batchConsumer = + new BatchConsumer(serverUrl, bulkSize, maxCacheSize, throwException, timeoutSec); + sa = new SensorsAnalytics(batchConsumer); + assertBlukSize(bulkSize); + assertMaxCacheSize(maxCacheSize); + assertThrowException(throwException); + } + /** + * 测试 BatchConsumer 构造函数 timeoutSec 参数,需要使用 Charles 匹配 public BatchConsumer(final String + * serverUrl, final int bulkSize, final int timeoutSec) + */ + @Test + @Disabled + public void testBatchConsumerTimeoutSec07AssertTimeout() + throws NoSuchFieldException, IllegalAccessException, InterruptedException, + InvalidArgumentException { + String serverUrl = "http://localhost:8887/test"; + int bulkSize = 100; + int timeoutSec = 5; + int maxCacheSize = 4000; + boolean throwException = true; + + batchConsumer = + new BatchConsumer(serverUrl, bulkSize, maxCacheSize, throwException, timeoutSec); + sa = new SensorsAnalytics(batchConsumer); + sa.track("xc11", true, "Exent1"); + sa.flush(); + Thread.sleep(15 * 1000); + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/ConcurrentLoggingConsumerTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/ConcurrentLoggingConsumerTest.java index cff239b..9b5a84a 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/ConcurrentLoggingConsumerTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/ConcurrentLoggingConsumerTest.java @@ -1,19 +1,14 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - import com.sensorsdata.analytics.javasdk.consumer.ConcurrentLoggingConsumer; import com.sensorsdata.analytics.javasdk.consumer.LogSplitMode; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Before; -import org.junit.Test; - import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * ConcurrentLoggingConsumer 单测 @@ -24,119 +19,119 @@ */ public class ConcurrentLoggingConsumerTest { - private ConcurrentLoggingConsumer consumer; - - private StringBuilder messageBuffer; - - @Before - public void init() throws NoSuchFieldException, IllegalAccessException { - consumer = new ConcurrentLoggingConsumer("file.log"); - Field field = consumer.getClass().getSuperclass().getDeclaredField("messageBuffer"); - field.setAccessible(true); - messageBuffer = (StringBuilder) field.get(consumer); - } - - @Test - public void checkSendData() { - assertEquals(0, messageBuffer.length()); - Map event = new HashMap<>(); - event.put("distinct_id", "12345"); - event.put("event", "test"); - event.put("type", "track"); - consumer.send(event); - assertNotNull(messageBuffer); - messageBuffer.setLength(0); - } - - @Test - public void checkInit() { - new ConcurrentLoggingConsumer("file.log"); - new ConcurrentLoggingConsumer("file.log", 30); - new ConcurrentLoggingConsumer("file.log", "lock.name", 20); - new ConcurrentLoggingConsumer("file.log", "lock.name", 20, LogSplitMode.DAY); - assertTrue(true); - } - - @Test - public void testInit01() throws InvalidArgumentException { - consumer = new ConcurrentLoggingConsumer("test.log"); - SensorsAnalytics sa = new SensorsAnalytics(consumer); - Map properties = new HashMap<>(); - properties.put("test", "test"); - properties.put("$project", "abc"); - properties.put("$token", "123"); - sa.track("123", true, "test", properties); - } - - @Test - public void testInit02() throws InvalidArgumentException { - consumer = new ConcurrentLoggingConsumer("test.log", 100); - SensorsAnalytics sa = new SensorsAnalytics(consumer); - Map properties = new HashMap<>(); - properties.put("test", "test"); - properties.put("$project", "abc"); - properties.put("$token", "123"); - sa.track("123", true, "test01", properties); - sa.track("123", true, "test01", properties); - } - - @Test - public void testInit03() throws InvalidArgumentException { - consumer = new ConcurrentLoggingConsumer("test.log", "lock.log"); - SensorsAnalytics sa = new SensorsAnalytics(consumer); - Map properties = new HashMap<>(); - properties.put("test", "test"); - properties.put("$project", "abc"); - properties.put("$token", "123"); - sa.track("123", true, "test01", properties); - sa.track("123", true, "test01", properties); - } - - @Test - public void testInit04() throws InvalidArgumentException { - consumer = new ConcurrentLoggingConsumer("test.log", "lock.log", 100); - SensorsAnalytics sa = new SensorsAnalytics(consumer); - Map properties = new HashMap<>(); - properties.put("test", "test"); - properties.put("$project", "abc"); - properties.put("$token", "123"); - sa.track("123", true, "test01", properties); - sa.track("123", true, "test01", properties); - } - - @Test - public void testInit05() throws InvalidArgumentException { - consumer = new ConcurrentLoggingConsumer("test.log", "lock.log", 100); - SensorsAnalytics sa = new SensorsAnalytics(consumer); - Map properties = new HashMap<>(); - properties.put("test", "test"); - properties.put("$project", "abc"); - properties.put("$token", "123"); - sa.track("123", true, "test01", properties); - sa.track("123", true, "test01", properties); - } - - @Test - public void testInit06() throws InvalidArgumentException { - consumer = new ConcurrentLoggingConsumer("test.log", "lock.log", 100, LogSplitMode.DAY); - SensorsAnalytics sa = new SensorsAnalytics(consumer); - Map properties = new HashMap<>(); - properties.put("test", "test"); - properties.put("$project", "abc"); - properties.put("$token", "123"); - sa.track("123", true, "test01", properties); - sa.track("123", true, "test01", properties); - } - - @Test - public void testInit07() throws InvalidArgumentException { - consumer = new ConcurrentLoggingConsumer("test.log", "lock.log", 100, LogSplitMode.HOUR); - SensorsAnalytics sa = new SensorsAnalytics(consumer); - Map properties = new HashMap<>(); - properties.put("test", "test"); - properties.put("$project", "abc"); - properties.put("$token", "123"); - sa.track("123", true, "test01", properties); - sa.track("123", true, "test01", properties); - } + private ConcurrentLoggingConsumer consumer; + + private StringBuilder messageBuffer; + + @BeforeEach + public void init() throws NoSuchFieldException, IllegalAccessException { + consumer = new ConcurrentLoggingConsumer("file.log"); + Field field = consumer.getClass().getSuperclass().getDeclaredField("messageBuffer"); + field.setAccessible(true); + messageBuffer = (StringBuilder) field.get(consumer); + } + + @Test + public void checkSendData() { + Assertions.assertEquals(0, messageBuffer.length()); + Map event = new HashMap<>(); + event.put("distinct_id", "12345"); + event.put("event", "test"); + event.put("type", "track"); + consumer.send(event); + Assertions.assertNotNull(messageBuffer); + messageBuffer.setLength(0); + } + + @Test + public void checkInit() { + new ConcurrentLoggingConsumer("file.log"); + new ConcurrentLoggingConsumer("file.log", 30); + new ConcurrentLoggingConsumer("file.log", "lock.name", 20); + new ConcurrentLoggingConsumer("file.log", "lock.name", 20, LogSplitMode.DAY); + Assertions.assertTrue(true); + } + + @Test + public void testInit01() throws InvalidArgumentException { + consumer = new ConcurrentLoggingConsumer("test.log"); + SensorsAnalytics sa = new SensorsAnalytics(consumer); + Map properties = new HashMap<>(); + properties.put("test", "test"); + properties.put("$project", "abc"); + properties.put("$token", "123"); + sa.track("123", true, "test", properties); + } + + @Test + public void testInit02() throws InvalidArgumentException { + consumer = new ConcurrentLoggingConsumer("test.log", 100); + SensorsAnalytics sa = new SensorsAnalytics(consumer); + Map properties = new HashMap<>(); + properties.put("test", "test"); + properties.put("$project", "abc"); + properties.put("$token", "123"); + sa.track("123", true, "test01", properties); + sa.track("123", true, "test01", properties); + } + + @Test + public void testInit03() throws InvalidArgumentException { + consumer = new ConcurrentLoggingConsumer("test.log", "lock.log"); + SensorsAnalytics sa = new SensorsAnalytics(consumer); + Map properties = new HashMap<>(); + properties.put("test", "test"); + properties.put("$project", "abc"); + properties.put("$token", "123"); + sa.track("123", true, "test01", properties); + sa.track("123", true, "test01", properties); + } + + @Test + public void testInit04() throws InvalidArgumentException { + consumer = new ConcurrentLoggingConsumer("test.log", "lock.log", 100); + SensorsAnalytics sa = new SensorsAnalytics(consumer); + Map properties = new HashMap<>(); + properties.put("test", "test"); + properties.put("$project", "abc"); + properties.put("$token", "123"); + sa.track("123", true, "test01", properties); + sa.track("123", true, "test01", properties); + } + + @Test + public void testInit05() throws InvalidArgumentException { + consumer = new ConcurrentLoggingConsumer("test.log", "lock.log", 100); + SensorsAnalytics sa = new SensorsAnalytics(consumer); + Map properties = new HashMap<>(); + properties.put("test", "test"); + properties.put("$project", "abc"); + properties.put("$token", "123"); + sa.track("123", true, "test01", properties); + sa.track("123", true, "test01", properties); + } + + @Test + public void testInit06() throws InvalidArgumentException { + consumer = new ConcurrentLoggingConsumer("test.log", "lock.log", 100, LogSplitMode.DAY); + SensorsAnalytics sa = new SensorsAnalytics(consumer); + Map properties = new HashMap<>(); + properties.put("test", "test"); + properties.put("$project", "abc"); + properties.put("$token", "123"); + sa.track("123", true, "test01", properties); + sa.track("123", true, "test01", properties); + } + + @Test + public void testInit07() throws InvalidArgumentException { + consumer = new ConcurrentLoggingConsumer("test.log", "lock.log", 100, LogSplitMode.HOUR); + SensorsAnalytics sa = new SensorsAnalytics(consumer); + Map properties = new HashMap<>(); + properties.put("test", "test"); + properties.put("$project", "abc"); + properties.put("$token", "123"); + sa.track("123", true, "test01", properties); + sa.track("123", true, "test01", properties); + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/DebugConsumerTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/DebugConsumerTest.java index 171b596..f5fbf92 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/DebugConsumerTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/DebugConsumerTest.java @@ -3,10 +3,8 @@ import com.sensorsdata.analytics.javasdk.bean.EventRecord; import com.sensorsdata.analytics.javasdk.consumer.DebugConsumer; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Test; - import java.util.Calendar; +import org.junit.jupiter.api.Test; /** * debugConsumer 单元测试 @@ -17,17 +15,20 @@ */ public class DebugConsumerTest extends SensorsBaseTest { - @Test - public void checkDataSend() throws InvalidArgumentException { - DebugConsumer consumer = new DebugConsumer("http://localhost:8888/sa", true); - SensorsAnalytics sa = new SensorsAnalytics(consumer); - EventRecord firstRecord = EventRecord.builder().setDistinctId("a123").isLoginId(Boolean.FALSE) - .setEventName("track") - .addProperty("$time", Calendar.getInstance().getTime()) - .addProperty("Channel", "baidu") - .addProperty("$project", "abc") - .addProperty("$token", "123") - .build(); - sa.track(firstRecord); - } + @Test + public void checkDataSend() throws InvalidArgumentException { + DebugConsumer consumer = new DebugConsumer("http://localhost:8888/sa", true); + SensorsAnalytics sa = new SensorsAnalytics(consumer); + EventRecord firstRecord = + EventRecord.builder() + .setDistinctId("a123") + .isLoginId(Boolean.FALSE) + .setEventName("track") + .addProperty("$time", Calendar.getInstance().getTime()) + .addProperty("Channel", "baidu") + .addProperty("$project", "abc") + .addProperty("$token", "123") + .build(); + sa.track(firstRecord); + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMBindTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMBindTest.java index 2fe221a..4c2d377 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMBindTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMBindTest.java @@ -3,12 +3,10 @@ import com.sensorsdata.analytics.javasdk.bean.SensorsAnalyticsIdentity; import com.sensorsdata.analytics.javasdk.bean.schema.IdentitySchema; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Assert; -import org.junit.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * bind/unbind 接口支持自定义属性 @@ -19,83 +17,87 @@ */ public class IDMBindTest extends SensorsBaseTest { - @Test - public void testIdMappingBind() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("$identity_mobile", "123") - .addIdentityProperty("$identity_email", "fz@163.com") - .build(); - Map properties = new HashMap<>(); - properties.put("$project", "abc"); - properties.put("$time_free", true); - properties.put("$token", "12345"); - sa.bind(properties, identity); - assertIDM3EventData(data); - Assert.assertTrue(data.containsKey("project")); - Assert.assertTrue(data.containsKey("time_free")); - Assert.assertTrue(data.containsKey("token")); - Assert.assertEquals("abc", data.get("project")); - Assert.assertEquals(true, data.get("time_free")); - Assert.assertEquals("12345", data.get("token")); - } - + @Test + public void testIdMappingBind() throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("$identity_mobile", "123") + .addIdentityProperty("$identity_email", "fz@163.com") + .build(); + Map properties = new HashMap<>(); + properties.put("$project", "abc"); + properties.put("$time_free", true); + properties.put("$token", "12345"); + sa.bind(properties, identity); + assertIDM3EventData(data); + Assertions.assertTrue(data.containsKey("project")); + Assertions.assertTrue(data.containsKey("time_free")); + Assertions.assertTrue(data.containsKey("token")); + Assertions.assertEquals("abc", data.get("project")); + Assertions.assertEquals(true, data.get("time_free")); + Assertions.assertEquals("12345", data.get("token")); + } - @Test - public void testBind() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("$identity_mobile", "123") - .addIdentityProperty("$identity_email", "fz@163.com") - .build(); - IdentitySchema schema = IdentitySchema.init() - .identityMap(identity.getIdentityMap()) - .addProperty("$project", "abc") - .addProperty("$time_free", true) - .addProperty("$token", "12345") - .build(); - sa.bind(schema); - assertUESData(data); - Assert.assertTrue(data.containsKey("project")); - Assert.assertTrue(data.containsKey("time_free")); - Assert.assertTrue(data.containsKey("token")); - Assert.assertEquals("abc", data.get("project")); - Assert.assertEquals(true, data.get("time_free")); - Assert.assertEquals("12345", data.get("token")); - } + @Test + public void testBind() throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("$identity_mobile", "123") + .addIdentityProperty("$identity_email", "fz@163.com") + .build(); + IdentitySchema schema = + IdentitySchema.init() + .identityMap(identity.getIdentityMap()) + .addProperty("$project", "abc") + .addProperty("$time_free", true) + .addProperty("$token", "12345") + .build(); + sa.bind(schema); + assertUESData(data); + Assertions.assertTrue(data.containsKey("project")); + Assertions.assertTrue(data.containsKey("time_free")); + Assertions.assertTrue(data.containsKey("token")); + Assertions.assertEquals("abc", data.get("project")); + Assertions.assertEquals(true, data.get("time_free")); + Assertions.assertEquals("12345", data.get("token")); + } - @Test - public void testUnbind() throws InvalidArgumentException { - Map properties = new HashMap<>(); - properties.put("$project", "abc"); - properties.put("$time_free", true); - properties.put("$token", "12345"); - sa.unbind("key1", "value1", properties); - assertIDM3EventData(data); - Assert.assertTrue(data.containsKey("project")); - Assert.assertTrue(data.containsKey("time_free")); - Assert.assertTrue(data.containsKey("token")); - Assert.assertEquals("abc", data.get("project")); - Assert.assertEquals(true, data.get("time_free")); - Assert.assertEquals("12345", data.get("token")); - } + @Test + public void testUnbind() throws InvalidArgumentException { + Map properties = new HashMap<>(); + properties.put("$project", "abc"); + properties.put("$time_free", true); + properties.put("$token", "12345"); + sa.unbind("key1", "value1", properties); + assertIDM3EventData(data); + Assertions.assertTrue(data.containsKey("project")); + Assertions.assertTrue(data.containsKey("time_free")); + Assertions.assertTrue(data.containsKey("token")); + Assertions.assertEquals("abc", data.get("project")); + Assertions.assertEquals(true, data.get("time_free")); + Assertions.assertEquals("12345", data.get("token")); + } - @Test - public void testUnbindSchema() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("$identity_email", "fz@163.com") - .build(); - IdentitySchema schema = IdentitySchema.init() - .identityMap(identity.getIdentityMap()) - .addProperty("$project", "abc") - .addProperty("$time_free", true) - .addProperty("$token", "12345") - .build(); - sa.unbind(schema); - assertUESData(data); - Assert.assertTrue(data.containsKey("project")); - Assert.assertTrue(data.containsKey("time_free")); - Assert.assertTrue(data.containsKey("token")); - Assert.assertEquals("abc", data.get("project")); - Assert.assertEquals(true, data.get("time_free")); - Assert.assertEquals("12345", data.get("token")); - } + @Test + public void testUnbindSchema() throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("$identity_email", "fz@163.com") + .build(); + IdentitySchema schema = + IdentitySchema.init() + .identityMap(identity.getIdentityMap()) + .addProperty("$project", "abc") + .addProperty("$time_free", true) + .addProperty("$token", "12345") + .build(); + sa.unbind(schema); + assertUESData(data); + Assertions.assertTrue(data.containsKey("project")); + Assertions.assertTrue(data.containsKey("time_free")); + Assertions.assertTrue(data.containsKey("token")); + Assertions.assertEquals("abc", data.get("project")); + Assertions.assertEquals(true, data.get("time_free")); + Assertions.assertEquals("12345", data.get("token")); + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackId1.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackId1.java index 543657b..c701e8f 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackId1.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackId1.java @@ -1,437 +1,401 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import com.sensorsdata.analytics.javasdk.bean.EventRecord; import com.sensorsdata.analytics.javasdk.bean.ItemRecord; import com.sensorsdata.analytics.javasdk.bean.UserRecord; import com.sensorsdata.analytics.javasdk.consumer.BatchConsumer; import com.sensorsdata.analytics.javasdk.consumer.ConcurrentLoggingConsumer; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Before; -import org.junit.Test; - import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -/** - * 适用于 v3.4.4+ 版本 - * 测试点:验证事件的 _track_id 正常由 $track_id 生成。 - * 无特殊情况,不在下面的 testcase 上一一说明 - */ +/** 适用于 v3.4.4+ 版本 测试点:验证事件的 _track_id 正常由 $track_id 生成。 无特殊情况,不在下面的 testcase 上一一说明 */ public class IDMappingModel1TrackId1 extends SensorsBaseTest { - private BatchConsumer batchConsumer; - - private List> messageList; - private ConcurrentLoggingConsumer consumer; - - private StringBuilder messageBuffer; - SensorsAnalytics sa; - - @Before - public void init() throws NoSuchFieldException, IllegalAccessException { - String url = "http://10.120.111.143:8106/sa?project=default"; - // 注意要设置 bulkSize 稍微大一点,这里设置为 100,否则超过 1 条就上报,messageList 里面拿不到事件数据 - batchConsumer = new BatchConsumer(url, 100, true, 3); - // 通过反射机制获取 BatchConsumer 的 messageList - Field field = batchConsumer.getClass().getDeclaredField("messageList"); // messageList 是 BatchConsumer 用来暂存事件数据的成员变量 - field.setAccessible(true); - messageList = (List>) field.get(batchConsumer); - sa = new SensorsAnalytics(batchConsumer); - } - - private void assertNotNullProp(){ - assertNotNull(messageList.get(0).get("time")); - assertNotNull(messageList.get(0).get("_track_id")); - assertNotNull(messageList.get(0).get("properties")); - } - - /** - * 校验调用 track 方法生成事件节点数是否完整 - */ - @Test - public void checkTrackEventLoginTrue() throws InvalidArgumentException { - Map properties = new HashMap<>(); - properties.put("$track_id", 111); - - sa.track("123", true, "test", properties); - assertNotNullProp(); - - assertEquals(111, messageList.get(0).get("_track_id")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - - } - - - /** - * 校验 trackSignup 记录节点 - */ - @Test - public void checkTrackSignUpProp() throws InvalidArgumentException { - Map properties = new HashMap<>(); - properties.put("number1", 1234); - properties.put("String1", "str"); - properties.put("boolean1", false); - properties.put("$track_id", 111); - sa.trackSignUp("123", "345", properties); - - assertNotNullProp(); - - assertEquals(111, messageList.get(0).get("_track_id")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - } - - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void checkProfileSetDataType() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - Map properties = new HashMap<>(); - properties.put("number1", 1234); - properties.put("date1", date); - properties.put("String1", "str"); - properties.put("boolean1", false); - properties.put("list1", list); - properties.put("$track_id", 111); - sa.profileSet("123", true, properties); - - assertNotNullProp(); - - assertEquals(111, messageList.get(0).get("_track_id")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - assertTrue(props.containsKey("number1")); // properties 包含其他自定义属性 - - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void checkProfileSetDataType01() throws InvalidArgumentException { - - sa.profileSet("123", true, "$track_id", 111); - assertNotNullProp(); - - assertEquals(111, messageList.get(0).get("_track_id")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - - } - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileSetOnceDataType() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - Map properties = new HashMap<>(); - properties.put("number1", 1234); - properties.put("date1", date); - properties.put("String1", "str"); - properties.put("boolean1", false); - properties.put("list1", list); - properties.put("$track_id", 111); - sa.profileSetOnce("123", true, properties); - - assertNotNullProp(); - - assertEquals(111, messageList.get(0).get("_track_id")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - assertTrue(props.containsKey("number1")); // properties 包含其他自定义属性 - - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileIncrement() throws InvalidArgumentException { - Map properties = new HashMap<>(); - properties.put("number1", 1234); - properties.put("$track_id", 111); - sa.profileIncrement("123", true, properties); - - assertNotNullProp(); - - assertEquals(111, messageList.get(0).get("_track_id")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - assertTrue(props.containsKey("number1")); // properties 包含其他自定义属性 - - - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileIncrement01() throws InvalidArgumentException { - sa.profileIncrement("123", true, "$track_id", 111); - - assertNotNullProp(); - - assertEquals(111, messageList.get(0).get("_track_id")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - } - - - @Test - public void testProfileAppend() throws InvalidArgumentException{ - List list = new ArrayList<>(); - list.add("aaa"); - list.add("bbb"); - Map properties = new HashMap<>(); - properties.put("list1", list); + private BatchConsumer batchConsumer; + + private List> messageList; + private ConcurrentLoggingConsumer consumer; + + private StringBuilder messageBuffer; + SensorsAnalytics sa; + + @BeforeEach + public void init() throws NoSuchFieldException, IllegalAccessException { + String url = "http://10.120.111.143:8106/sa?project=default"; + // 注意要设置 bulkSize 稍微大一点,这里设置为 100,否则超过 1 条就上报,messageList 里面拿不到事件数据 + batchConsumer = new BatchConsumer(url, 100, true, 3); + // 通过反射机制获取 BatchConsumer 的 messageList + Field field = + batchConsumer + .getClass() + .getDeclaredField( + "messageList"); // messageList 是 BatchConsumer 用来暂存事件数据的成员变量 + field.setAccessible(true); + messageList = (List>) field.get(batchConsumer); + sa = new SensorsAnalytics(batchConsumer); + } + + private void assertNotNullProp() { + Assertions.assertNotNull(messageList.get(0).get("time")); + Assertions.assertNotNull(messageList.get(0).get("_track_id")); + Assertions.assertNotNull(messageList.get(0).get("properties")); + } + + /** 校验调用 track 方法生成事件节点数是否完整 */ + @Test + public void checkTrackEventLoginTrue() throws InvalidArgumentException { + Map properties = new HashMap<>(); + properties.put("$track_id", 111); + + sa.track("123", true, "test", properties); + assertNotNullProp(); + + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } + + /** 校验 trackSignup 记录节点 */ + @Test + public void checkTrackSignUpProp() throws InvalidArgumentException { + Map properties = new HashMap<>(); + properties.put("number1", 1234); + properties.put("String1", "str"); + properties.put("boolean1", false); + properties.put("$track_id", 111); + sa.trackSignUp("123", "345", properties); + + assertNotNullProp(); - List listInt = new ArrayList<>(); - listInt.add(111); - properties.put("$track_id", listInt); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); - try { - sa.profileAppend("123", true, properties); - fail("[ERROR] profileAppend should throw InvalidArgumentException."); - }catch (Exception e){ - e.printStackTrace(); - assertEquals("The property '$track_id' should be a list of String.", e.getMessage()); + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id } - } + /** 校验自定义属性格式是否正常 */ + @Test + public void checkProfileSetDataType() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + Map properties = new HashMap<>(); + properties.put("number1", 1234); + properties.put("date1", date); + properties.put("String1", "str"); + properties.put("boolean1", false); + properties.put("list1", list); + properties.put("$track_id", 111); + sa.profileSet("123", true, properties); + + assertNotNullProp(); + + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Assertions.assertTrue(props.containsKey("number1")); // properties 包含其他自定义属性 + } + + /** 校验自定义属性格式是否正常 */ + @Test + public void checkProfileSetDataType01() throws InvalidArgumentException { - @Test - public void testProfileAppend01() throws InvalidArgumentException{ - sa.profileAppend("123", true, "$track_id", "111"); + sa.profileSet("123", true, "$track_id", 111); + assertNotNullProp(); - assertNotNullProp(); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); - assertNotEquals(111, messageList.get(0).get("_track_id")); + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileSetOnceDataType() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + Map properties = new HashMap<>(); + properties.put("number1", 1234); + properties.put("date1", date); + properties.put("String1", "str"); + properties.put("boolean1", false); + properties.put("list1", list); + properties.put("$track_id", 111); + sa.profileSetOnce("123", true, properties); + + assertNotNullProp(); + + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Assertions.assertTrue(props.containsKey("number1")); // properties 包含其他自定义属性 + } - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileIncrement() throws InvalidArgumentException { + Map properties = new HashMap<>(); + properties.put("number1", 1234); + properties.put("$track_id", 111); + sa.profileIncrement("123", true, properties); - } + assertNotNullProp(); - // profileUnset - @Test - public void testProfileUnset() { - Map properties = new HashMap<>(); - properties.put("list1", true); - properties.put("$track_id", 111); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); - try { - sa.profileUnset("123", true, properties); - fail("[ERROR] profileUnset should throw InvalidArgumentException."); - }catch (InvalidArgumentException e){ - assertEquals("The property value of $track_id should be true.", e.getMessage()); + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Assertions.assertTrue(props.containsKey("number1")); // properties 包含其他自定义属性 } - } - - // profileUnset - @Test - public void testProfileUnset01() throws InvalidArgumentException{ - sa.profileUnset("123", true, "$track_id"); - - assertNotNullProp(); - - assertNotEquals(111, messageList.get(0).get("_track_id")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - } - - // profileDelete - @Test - public void testProfileDelete() throws InvalidArgumentException{ - sa.profileDelete("123", true); - } - - @Test - public void testItemSet_Delete() throws Exception { - //物品纬度表上报 - String itemId = "product001", itemType = "mobile"; - ItemRecord addRecord = ItemRecord.builder().setItemId(itemId).setItemType(itemType) - .addProperty("color", "white") - .build(); - sa.itemSet(addRecord); - - //删除物品纬度信息 - ItemRecord deleteRecord = ItemRecord.builder().setItemId(itemId).setItemType(itemType) - .build(); - sa.itemDelete(deleteRecord); - sa.flush(); - } - - - - /** - * 校验 event Builder 模式生成数据用户属性是否正常 - */ - @Test - public void checkTrackEventBuilder() throws InvalidArgumentException { - EventRecord eventRecord = EventRecord.builder() - .setDistinctId("abc") - .isLoginId(false) - .setEventName("test") - .addProperty("$track_id", 111) - .build(); - sa.track(eventRecord); - - assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - } - - /** - * 校验 is_login_id 为 true 的事件属性 - */ - @Test - public void checkTrackEventBuilderLoginIdIsTrue() throws InvalidArgumentException { - EventRecord eventRecord = EventRecord.builder() - .setDistinctId("abc") - .isLoginId(true) - .setEventName("test") - .addProperty("$track_id", 111) - .build(); - sa.track(eventRecord); - - assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void checkProfileSetDataTypeEventBuilder() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("number1", 1234) - .addProperty("date1", date) - .addProperty("String1", "str") - .addProperty("boolean1", false) - .addProperty("list1", list) - .addProperty("$track_id", 111) - .build(); - sa.profileSet(userRecord); - - assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileSetOnceDataTypeEventBuilder() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("number1", 1234) - .addProperty("date1", date) - .addProperty("String1", "str") - .addProperty("boolean1", false) - .addProperty("list1", list) - .addProperty("$track_id", 111) - .build(); - sa.profileSetOnce(userRecord); - - assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileIncrementEventBuilder() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("number1", 1234) - .addProperty("$track_id", 111) - .build(); - sa.profileIncrement(userRecord); - - assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - } - - - // profileDeleteById - @Test - public void testProfileDeleteByIdEventBuilder() throws InvalidArgumentException{ - List list = new ArrayList<>(); - list.add("aaa"); - list.add("bbb"); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("list1", list) - .addProperty("$track_id", 111) - .build(); - sa.profileDelete(userRecord); - - assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - } + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileIncrement01() throws InvalidArgumentException { + sa.profileIncrement("123", true, "$track_id", 111); + + assertNotNullProp(); + + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } + + @Test + public void testProfileAppend() throws InvalidArgumentException { + List list = new ArrayList<>(); + list.add("aaa"); + list.add("bbb"); + Map properties = new HashMap<>(); + properties.put("list1", list); + + List listInt = new ArrayList<>(); + listInt.add(111); + properties.put("$track_id", listInt); + + try { + sa.profileAppend("123", true, properties); + Assertions.fail("[ERROR] profileAppend should throw InvalidArgumentException."); + } catch (Exception e) { + e.printStackTrace(); + Assertions.assertEquals( + "The property '$track_id' should be a list of String.", e.getMessage()); + } + } + + @Test + public void testProfileAppend01() throws InvalidArgumentException { + sa.profileAppend("123", true, "$track_id", "111"); + + assertNotNullProp(); + + Assertions.assertNotEquals(111, messageList.get(0).get("_track_id")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } + + // profileUnset + @Test + public void testProfileUnset() { + Map properties = new HashMap<>(); + properties.put("list1", true); + properties.put("$track_id", 111); + + try { + sa.profileUnset("123", true, properties); + Assertions.fail("[ERROR] profileUnset should throw InvalidArgumentException."); + } catch (InvalidArgumentException e) { + Assertions.assertEquals( + "The property value of $track_id should be true.", e.getMessage()); + } + } + + // profileUnset + @Test + public void testProfileUnset01() throws InvalidArgumentException { + sa.profileUnset("123", true, "$track_id"); + + assertNotNullProp(); + + Assertions.assertNotEquals(111, messageList.get(0).get("_track_id")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } + + // profileDelete + @Test + public void testProfileDelete() throws InvalidArgumentException { + sa.profileDelete("123", true); + } + + @Test + public void testItemSet_Delete() throws Exception { + // 物品纬度表上报 + String itemId = "product001", itemType = "mobile"; + ItemRecord addRecord = + ItemRecord.builder() + .setItemId(itemId) + .setItemType(itemType) + .addProperty("color", "white") + .build(); + sa.itemSet(addRecord); + + // 删除物品纬度信息 + ItemRecord deleteRecord = + ItemRecord.builder().setItemId(itemId).setItemType(itemType).build(); + sa.itemDelete(deleteRecord); + sa.flush(); + } + + /** 校验 event Builder 模式生成数据用户属性是否正常 */ + @Test + public void checkTrackEventBuilder() throws InvalidArgumentException { + EventRecord eventRecord = + EventRecord.builder() + .setDistinctId("abc") + .isLoginId(false) + .setEventName("test") + .addProperty("$track_id", 111) + .build(); + sa.track(eventRecord); + + assertNotNullProp(); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } + + /** 校验 is_login_id 为 true 的事件属性 */ + @Test + public void checkTrackEventBuilderLoginIdIsTrue() throws InvalidArgumentException { + EventRecord eventRecord = + EventRecord.builder() + .setDistinctId("abc") + .isLoginId(true) + .setEventName("test") + .addProperty("$track_id", 111) + .build(); + sa.track(eventRecord); + + assertNotNullProp(); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } + + /** 校验自定义属性格式是否正常 */ + @Test + public void checkProfileSetDataTypeEventBuilder() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("number1", 1234) + .addProperty("date1", date) + .addProperty("String1", "str") + .addProperty("boolean1", false) + .addProperty("list1", list) + .addProperty("$track_id", 111) + .build(); + sa.profileSet(userRecord); + + assertNotNullProp(); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } + + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileSetOnceDataTypeEventBuilder() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("number1", 1234) + .addProperty("date1", date) + .addProperty("String1", "str") + .addProperty("boolean1", false) + .addProperty("list1", list) + .addProperty("$track_id", 111) + .build(); + sa.profileSetOnce(userRecord); + + assertNotNullProp(); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } + + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileIncrementEventBuilder() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("number1", 1234) + .addProperty("$track_id", 111) + .build(); + sa.profileIncrement(userRecord); + + assertNotNullProp(); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } + + // profileDeleteById + @Test + public void testProfileDeleteByIdEventBuilder() throws InvalidArgumentException { + List list = new ArrayList<>(); + list.add("aaa"); + list.add("bbb"); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("list1", list) + .addProperty("$track_id", 111) + .build(); + sa.profileDelete(userRecord); + + assertNotNullProp(); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackIdAndTime.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackIdAndTime.java index 9086d37..b66d69e 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackIdAndTime.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackIdAndTime.java @@ -1,502 +1,479 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import com.sensorsdata.analytics.javasdk.bean.EventRecord; import com.sensorsdata.analytics.javasdk.bean.ItemRecord; import com.sensorsdata.analytics.javasdk.bean.UserRecord; import com.sensorsdata.analytics.javasdk.consumer.BatchConsumer; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Before; -import org.junit.Test; - import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** - * 适用于 v3.4.4+ 版本 - * 测试点:验证事件的 _track_id 正常由 $track_id 生成,time 由 $time 生成。 - * 无特殊情况,不在下面的 testcase 上一一说明 + * 适用于 v3.4.4+ 版本 测试点:验证事件的 _track_id 正常由 $track_id 生成,time 由 $time 生成。 无特殊情况,不在下面的 testcase 上一一说明 */ public class IDMappingModel1TrackIdAndTime extends SensorsBaseTest { - private BatchConsumer batchConsumer; - - private List> messageList; - SensorsAnalytics sa; - - @Before - public void init() throws NoSuchFieldException, IllegalAccessException { - - String url = "http://10.120.111.143:8106/sa?project=default"; - // 注意要设置 bulkSize 稍微大一点,这里设置为 100,否则超过 1 条就上报,messageList 里面拿不到事件数据 - batchConsumer = new BatchConsumer(url, 100, true, 3); - // 通过反射机制获取 BatchConsumer 的 messageList - Field field = batchConsumer.getClass().getDeclaredField("messageList"); // messageList 是 BatchConsumer 用来暂存事件数据的成员变量 - field.setAccessible(true); - messageList = (List>) field.get(batchConsumer); - sa = new SensorsAnalytics(batchConsumer); - } - - private void assertNotNullProp(){ - assertNotNull(messageList.get(0).get("time")); - assertNotNull(messageList.get(0).get("_track_id")); - assertNotNull(messageList.get(0).get("properties")); - } - - /** - * 校验调用 track 方法生成事件节点数是否完整 - */ - @Test - public void checkTrackEventLoginTrue() throws InvalidArgumentException { - Map properties = new HashMap<>(); - properties.put("$track_id", 111); - Date date = new Date(); - properties.put("$time", date); - sa.track("123", true, "test", properties); - assertNotNullProp(); + private BatchConsumer batchConsumer; + + private List> messageList; + SensorsAnalytics sa; + + @BeforeEach + public void init() throws NoSuchFieldException, IllegalAccessException { + + String url = "http://10.120.111.143:8106/sa?project=default"; + // 注意要设置 bulkSize 稍微大一点,这里设置为 100,否则超过 1 条就上报,messageList 里面拿不到事件数据 + batchConsumer = new BatchConsumer(url, 100, true, 3); + // 通过反射机制获取 BatchConsumer 的 messageList + Field field = + batchConsumer + .getClass() + .getDeclaredField( + "messageList"); // messageList 是 BatchConsumer 用来暂存事件数据的成员变量 + field.setAccessible(true); + messageList = (List>) field.get(batchConsumer); + sa = new SensorsAnalytics(batchConsumer); + } - assertEquals(111, messageList.get(0).get("_track_id")); - assertEquals(date.getTime(), messageList.get(0).get("time")); + private void assertNotNullProp() { + Assertions.assertNotNull(messageList.get(0).get("time")); + Assertions.assertNotNull(messageList.get(0).get("_track_id")); + Assertions.assertNotNull(messageList.get(0).get("properties")); + } - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + /** 校验调用 track 方法生成事件节点数是否完整 */ + @Test + public void checkTrackEventLoginTrue() throws InvalidArgumentException { + Map properties = new HashMap<>(); + properties.put("$track_id", 111); + Date date = new Date(); + properties.put("$time", date); + sa.track("123", true, "test", properties); + assertNotNullProp(); - } + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + Assertions.assertEquals(date.getTime(), messageList.get(0).get("time")); + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } - /** - * 校验 trackSignup 记录节点 - */ - @Test - public void checkTrackSignUpProp() throws InvalidArgumentException { - Map properties = new HashMap<>(); - properties.put("number1", 1234); - properties.put("String1", "str"); - properties.put("boolean1", false); - properties.put("$track_id", 111); - Date date = new Date(); - properties.put("$time", date); - sa.trackSignUp("123", "345", properties); - - assertNotNullProp(); - - assertEquals(111, messageList.get(0).get("_track_id")); - assertEquals(date.getTime(), messageList.get(0).get("time")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - } - - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void checkProfileSetDataType() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - Map properties = new HashMap<>(); - properties.put("number1", 1234); - properties.put("date1", date); - properties.put("String1", "str"); - properties.put("boolean1", false); - properties.put("list1", list); + /** 校验 trackSignup 记录节点 */ + @Test + public void checkTrackSignUpProp() throws InvalidArgumentException { + Map properties = new HashMap<>(); + properties.put("number1", 1234); + properties.put("String1", "str"); + properties.put("boolean1", false); properties.put("$track_id", 111); - properties.put("$time", date); - sa.profileSet("123", true, properties); - - assertNotNullProp(); - - assertEquals(111, messageList.get(0).get("_track_id")); - assertEquals(date.getTime(), messageList.get(0).get("time")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - assertTrue(props.containsKey("number1")); // properties 包含其他自定义属性 - - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void checkProfileSetDataType01() throws InvalidArgumentException { - - sa.profileSet("123", true, "$track_id", 111); - assertNotNullProp(); - - assertEquals(111, messageList.get(0).get("_track_id")); -// assertEquals(date.getTime(), messageList.get(0).get("time")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - - } - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileSetOnceDataType() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - Map properties = new HashMap<>(); - properties.put("number1", 1234); - properties.put("date1", date); - properties.put("String1", "str"); - properties.put("boolean1", false); - properties.put("list1", list); + Date date = new Date(); + properties.put("$time", date); + sa.trackSignUp("123", "345", properties); + + assertNotNullProp(); + + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + Assertions.assertEquals(date.getTime(), messageList.get(0).get("time")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } + + /** 校验自定义属性格式是否正常 */ + @Test + public void checkProfileSetDataType() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + Map properties = new HashMap<>(); + properties.put("number1", 1234); + properties.put("date1", date); + properties.put("String1", "str"); + properties.put("boolean1", false); + properties.put("list1", list); properties.put("$track_id", 111); - properties.put("$time", date); - sa.profileSetOnce("123", true, properties); + properties.put("$time", date); + sa.profileSet("123", true, properties); + + assertNotNullProp(); - assertNotNullProp(); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + Assertions.assertEquals(date.getTime(), messageList.get(0).get("time")); - assertEquals(111, messageList.get(0).get("_track_id")); - assertEquals(date.getTime(), messageList.get(0).get("time")); + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Assertions.assertTrue(props.containsKey("number1")); // properties 包含其他自定义属性 + } - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - assertTrue(props.containsKey("number1")); // properties 包含其他自定义属性 + /** 校验自定义属性格式是否正常 */ + @Test + public void checkProfileSetDataType01() throws InvalidArgumentException { - } + sa.profileSet("123", true, "$track_id", 111); + assertNotNullProp(); - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileIncrement() { - Map properties = new HashMap<>(); - properties.put("number1", 1234); - properties.put("$track_id", 111); - Date date = new Date(); - properties.put("$time", date); - try { - sa.profileIncrement("123", true, properties); - fail("[ERROR] profileIncrement should throw InvalidArgumentException."); - }catch (Exception e){ - e.printStackTrace(); - assertEquals("The property value of PROFILE_INCREMENT should be a Number.The current type is class java.util.Date.", e.getMessage()); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + // Assertions.assertEquals(date.getTime(), messageList.get(0).get("time")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id } - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileIncrement01(){ - Date date = new Date(); - try { - sa.profileIncrement("123", true, "$time", date.getTime()); - fail("[ERROR] profileIncrement should throw InvalidArgumentException."); - }catch (Exception e){ - e.printStackTrace(); - assertEquals("The property '$time' should be a java.util.Date.", e.getMessage()); + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileSetOnceDataType() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + Map properties = new HashMap<>(); + properties.put("number1", 1234); + properties.put("date1", date); + properties.put("String1", "str"); + properties.put("boolean1", false); + properties.put("list1", list); + properties.put("$track_id", 111); + properties.put("$time", date); + sa.profileSetOnce("123", true, properties); + + assertNotNullProp(); + + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + Assertions.assertEquals(date.getTime(), messageList.get(0).get("time")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Assertions.assertTrue(props.containsKey("number1")); // properties 包含其他自定义属性 } - } - - - @Test - public void testProfileAppend() { - List list = new ArrayList<>(); - list.add("aaa"); - list.add("bbb"); - Map properties = new HashMap<>(); - properties.put("list1", list); - - List listInt = new ArrayList<>(); - listInt.add(111); - properties.put("$track_id", listInt); - - try { - sa.profileAppend("123", true, properties); - fail("[ERROR] profileAppend should throw InvalidArgumentException."); - }catch (Exception e){ - e.printStackTrace(); - assertEquals("The property '$track_id' should be a list of String.", e.getMessage()); + + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileIncrement() { + Map properties = new HashMap<>(); + properties.put("number1", 1234); + properties.put("$track_id", 111); + Date date = new Date(); + properties.put("$time", date); + try { + sa.profileIncrement("123", true, properties); + Assertions.fail("[ERROR] profileIncrement should throw InvalidArgumentException."); + } catch (Exception e) { + e.printStackTrace(); + Assertions.assertEquals( + "The property value of PROFILE_INCREMENT should be a Number.The current type is class java.util.Date.", + e.getMessage()); + } } - } + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileIncrement01() { + Date date = new Date(); + try { + sa.profileIncrement("123", true, "$time", date.getTime()); + Assertions.fail("[ERROR] profileIncrement should throw InvalidArgumentException."); + } catch (Exception e) { + e.printStackTrace(); + Assertions.assertEquals( + "The property '$time' should be a java.util.Date.", e.getMessage()); + } + } - @Test - public void testProfileAppend01() throws InvalidArgumentException{ - sa.profileAppend("123", true, "$track_id", "111"); + @Test + public void testProfileAppend() { + List list = new ArrayList<>(); + list.add("aaa"); + list.add("bbb"); + Map properties = new HashMap<>(); + properties.put("list1", list); + + List listInt = new ArrayList<>(); + listInt.add(111); + properties.put("$track_id", listInt); + + try { + sa.profileAppend("123", true, properties); + Assertions.fail("[ERROR] profileAppend should throw InvalidArgumentException."); + } catch (Exception e) { + e.printStackTrace(); + Assertions.assertEquals( + "The property '$track_id' should be a list of String.", e.getMessage()); + } + } - assertNotNullProp(); + @Test + public void testProfileAppend01() throws InvalidArgumentException { + sa.profileAppend("123", true, "$track_id", "111"); - assertNotEquals(111, messageList.get(0).get("_track_id")); + assertNotNullProp(); - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Assertions.assertNotEquals(111, messageList.get(0).get("_track_id")); - } + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } - // profileUnset - @Test - public void testProfileUnset() { - Map properties = new HashMap<>(); - properties.put("list1", true); + // profileUnset + @Test + public void testProfileUnset() { + Map properties = new HashMap<>(); + properties.put("list1", true); properties.put("$track_id", 111); - Date date = new Date(); - properties.put("$time", date); - - try { - sa.profileUnset("123", true, properties); - fail("[ERROR] profileUnset should throw InvalidArgumentException."); - }catch (InvalidArgumentException e){ - assertEquals("The property value of $time should be true.", e.getMessage()); + Date date = new Date(); + properties.put("$time", date); + + try { + sa.profileUnset("123", true, properties); + Assertions.fail("[ERROR] profileUnset should throw InvalidArgumentException."); + } catch (InvalidArgumentException e) { + Assertions.assertEquals("The property value of $time should be true.", e.getMessage()); + } + } + + // profileUnset + @Test + public void testProfileUnset01() throws InvalidArgumentException { + sa.profileUnset("123", true, "$track_id"); + + assertNotNullProp(); + + Assertions.assertNotEquals(111, messageList.get(0).get("_track_id")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id } - } - - // profileUnset - @Test - public void testProfileUnset01() throws InvalidArgumentException{ - sa.profileUnset("123", true, "$track_id"); - - assertNotNullProp(); - - assertNotEquals(111, messageList.get(0).get("_track_id")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - - } - - // profileDelete - @Test - public void testProfileDelete() throws InvalidArgumentException{ - sa.profileDelete("123", true); - } - - @Test - public void testItemSet_Delete() throws Exception { - Date date = new Date(); - //物品纬度表上报 - String itemId = "product001", itemType = "mobile"; - ItemRecord addRecord = ItemRecord.builder().setItemId(itemId).setItemType(itemType) - .addProperty("color", "white") - .addProperty("$time", date) - .build(); - sa.itemSet(addRecord); - System.out.println(date.getTime()); - - //删除物品纬度信息 - ItemRecord deleteRecord = ItemRecord.builder().setItemId(itemId).setItemType(itemType) - .addProperty("$time", date) - .build(); - sa.itemDelete(deleteRecord); - sa.flush(); - } - - - - /** - * 校验 event Builder 模式生成数据用户属性是否正常 - */ - @Test - public void checkTrackEventBuilder() throws InvalidArgumentException { - Date date = new Date(); - EventRecord eventRecord = EventRecord.builder() - .setDistinctId("abc") - .isLoginId(false) - .setEventName("test") - .addProperty("$track_id", 111) - .addProperty("$time", date) - .build(); - sa.track(eventRecord); - - assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - assertEquals(date.getTime(), messageList.get(0).get("time")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - } - - /** - * 校验 is_login_id 为 true 的事件属性 - */ - @Test - public void checkTrackEventBuilderLoginIdIsTrue() throws InvalidArgumentException { - Date date = new Date(); - EventRecord eventRecord = EventRecord.builder() - .setDistinctId("abc") - .isLoginId(true) - .setEventName("test") - .addProperty("$track_id", 111) - .addProperty("$time", date) - .build(); - sa.track(eventRecord); - - assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - assertEquals(date.getTime(), messageList.get(0).get("time")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void checkProfileSetDataTypeEventBuilder() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("number1", 1234) - .addProperty("date1", date) - .addProperty("String1", "str") - .addProperty("boolean1", false) - .addProperty("list1", list) - .addProperty("$track_id", 111) - .addProperty("$time", date) - .build(); - sa.profileSet(userRecord); - - assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - assertEquals(date.getTime(), messageList.get(0).get("time")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileSetOnceDataTypeEventBuilder() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("number1", 1234) - .addProperty("date1", date) - .addProperty("String1", "str") - .addProperty("boolean1", false) - .addProperty("list1", list) - .addProperty("$track_id", 111) - .addProperty("$time", date) - .build(); - sa.profileSetOnce(userRecord); - - assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - assertEquals(date.getTime(), messageList.get(0).get("time")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileIncrementEventBuilder() { - Date date = new Date(); - List list = new ArrayList<>(); - list.add("aaa"); - list.add("bbb"); - try { - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("number1", 1234) - .addProperty("$track_id", 111) - .addProperty("$time", date) - .build(); - - sa.profileIncrement(userRecord); - fail("profileIncrement should throw InvalidArgumentException"); - }catch (InvalidArgumentException e){ - assertEquals("The property value of PROFILE_INCREMENT should be a Number.The current type is class java.util.Date.", e.getMessage()); + // profileDelete + @Test + public void testProfileDelete() throws InvalidArgumentException { + sa.profileDelete("123", true); } - } - - @Test - public void testProfileAppendByIdEventBuilder() throws InvalidArgumentException{ - Date date = new Date(); - List list = new ArrayList<>(); - list.add("aaa"); - list.add("bbb"); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("list1", list) - .addProperty("$track_id", 111) - .addProperty("$time", date) - .build(); - try { - sa.profileAppend(userRecord); - fail("profileAppend should throw InvalidArgumentException"); - }catch (InvalidArgumentException e){ - assertEquals("The property value of PROFILE_APPEND should be a List.", e.getMessage()); + + @Test + public void testItemSet_Delete() throws Exception { + Date date = new Date(); + // 物品纬度表上报 + String itemId = "product001", itemType = "mobile"; + ItemRecord addRecord = + ItemRecord.builder() + .setItemId(itemId) + .setItemType(itemType) + .addProperty("color", "white") + .addProperty("$time", date) + .build(); + sa.itemSet(addRecord); + System.out.println(date.getTime()); + + // 删除物品纬度信息 + ItemRecord deleteRecord = + ItemRecord.builder() + .setItemId(itemId) + .setItemType(itemType) + .addProperty("$time", date) + .build(); + sa.itemDelete(deleteRecord); + sa.flush(); + } + + /** 校验 event Builder 模式生成数据用户属性是否正常 */ + @Test + public void checkTrackEventBuilder() throws InvalidArgumentException { + Date date = new Date(); + EventRecord eventRecord = + EventRecord.builder() + .setDistinctId("abc") + .isLoginId(false) + .setEventName("test") + .addProperty("$track_id", 111) + .addProperty("$time", date) + .build(); + sa.track(eventRecord); + + assertNotNullProp(); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + Assertions.assertEquals(date.getTime(), messageList.get(0).get("time")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id } - } - - // profileUnsetById - @Test - public void testProfileUnsetByIdEventBuilder(){ - Date date = new Date(); - UserRecord userRecord = null; - try { - userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("$track_id", 111) - .addProperty("$time", date) - .build(); - sa.profileUnset(userRecord); - fail("profileUnset should throw InvalidArgumentException"); - }catch (InvalidArgumentException e){ - assertEquals("The property value of $time should be true.", e.getMessage()); + /** 校验 is_login_id 为 true 的事件属性 */ + @Test + public void checkTrackEventBuilderLoginIdIsTrue() throws InvalidArgumentException { + Date date = new Date(); + EventRecord eventRecord = + EventRecord.builder() + .setDistinctId("abc") + .isLoginId(true) + .setEventName("test") + .addProperty("$track_id", 111) + .addProperty("$time", date) + .build(); + sa.track(eventRecord); + + assertNotNullProp(); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + Assertions.assertEquals(date.getTime(), messageList.get(0).get("time")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id } - } - - // profileDeleteById - - @Test - public void testProfileDeleteByIdEventBuilder() throws InvalidArgumentException{ - Date date = new Date(); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("$track_id", 111) - .addProperty("$time", date) - .addProperty("abc", "acb") - .build(); - sa.profileDelete(userRecord); - - assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - assertEquals(date.getTime(), messageList.get(0).get("time")); - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - } + /** 校验自定义属性格式是否正常 */ + @Test + public void checkProfileSetDataTypeEventBuilder() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("number1", 1234) + .addProperty("date1", date) + .addProperty("String1", "str") + .addProperty("boolean1", false) + .addProperty("list1", list) + .addProperty("$track_id", 111) + .addProperty("$time", date) + .build(); + sa.profileSet(userRecord); + + assertNotNullProp(); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + Assertions.assertEquals(date.getTime(), messageList.get(0).get("time")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } + + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileSetOnceDataTypeEventBuilder() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("number1", 1234) + .addProperty("date1", date) + .addProperty("String1", "str") + .addProperty("boolean1", false) + .addProperty("list1", list) + .addProperty("$track_id", 111) + .addProperty("$time", date) + .build(); + sa.profileSetOnce(userRecord); + + assertNotNullProp(); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + Assertions.assertEquals(date.getTime(), messageList.get(0).get("time")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } + + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileIncrementEventBuilder() { + Date date = new Date(); + List list = new ArrayList<>(); + list.add("aaa"); + list.add("bbb"); + try { + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("number1", 1234) + .addProperty("$track_id", 111) + .addProperty("$time", date) + .build(); + + sa.profileIncrement(userRecord); + Assertions.fail("profileIncrement should throw InvalidArgumentException"); + } catch (InvalidArgumentException e) { + Assertions.assertEquals( + "The property value of PROFILE_INCREMENT should be a Number.The current type is class java.util.Date.", + e.getMessage()); + } + } + + @Test + public void testProfileAppendByIdEventBuilder() throws InvalidArgumentException { + Date date = new Date(); + List list = new ArrayList<>(); + list.add("aaa"); + list.add("bbb"); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("list1", list) + .addProperty("$track_id", 111) + .addProperty("$time", date) + .build(); + try { + sa.profileAppend(userRecord); + Assertions.fail("profileAppend should throw InvalidArgumentException"); + } catch (InvalidArgumentException e) { + Assertions.assertEquals( + "The property value of PROFILE_APPEND should be a List.", + e.getMessage()); + } + } + + // profileUnsetById + @Test + public void testProfileUnsetByIdEventBuilder() { + Date date = new Date(); + UserRecord userRecord = null; + try { + userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("$track_id", 111) + .addProperty("$time", date) + .build(); + sa.profileUnset(userRecord); + Assertions.fail("profileUnset should throw InvalidArgumentException"); + } catch (InvalidArgumentException e) { + Assertions.assertEquals("The property value of $time should be true.", e.getMessage()); + } + } + + // profileDeleteById + + @Test + public void testProfileDeleteByIdEventBuilder() throws InvalidArgumentException { + Date date = new Date(); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("$track_id", 111) + .addProperty("$time", date) + .addProperty("abc", "acb") + .build(); + sa.profileDelete(userRecord); + + assertNotNullProp(); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + Assertions.assertEquals(date.getTime(), messageList.get(0).get("time")); + + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackIdAndTimeDebugConsumer.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackIdAndTimeDebugConsumer.java index f841a02..f1b6ed7 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackIdAndTimeDebugConsumer.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackIdAndTimeDebugConsumer.java @@ -1,7 +1,5 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.fail; - import com.sensorsdata.analytics.javasdk.bean.EventRecord; import com.sensorsdata.analytics.javasdk.bean.ItemRecord; import com.sensorsdata.analytics.javasdk.bean.UserRecord; @@ -9,306 +7,291 @@ import com.sensorsdata.analytics.javasdk.consumer.ConcurrentLoggingConsumer; import com.sensorsdata.analytics.javasdk.consumer.DebugConsumer; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Before; -import org.junit.Test; - import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** - * 适用于 v3.4.4+ 版本 - * 测试点:验证事件的 _track_id 正常由 $track_id 生成,time 由 $time 生成。 - * 无特殊情况,不在下面的 testcase 上一一说明 + * 适用于 v3.4.4+ 版本 测试点:验证事件的 _track_id 正常由 $track_id 生成,time 由 $time 生成。 无特殊情况,不在下面的 testcase 上一一说明 */ public class IDMappingModel1TrackIdAndTimeDebugConsumer extends SensorsBaseTest { - private BatchConsumer batchConsumer; + private BatchConsumer batchConsumer; - private List> messageList; - private ConcurrentLoggingConsumer consumer; + private List> messageList; + private ConcurrentLoggingConsumer consumer; - private StringBuilder messageBuffer; - SensorsAnalytics sa; - - @Before - public void init() throws NoSuchFieldException, IllegalAccessException { - String url = "http://10.120.111.143:8106/sa?project=default"; - DebugConsumer consumer = new DebugConsumer(url, true); - sa = new SensorsAnalytics(consumer); - - } - - - /** - * 校验调用 track 方法生成事件节点数是否完整 - */ - @Test - public void checkTrackEventLoginTrue() throws InvalidArgumentException { - Map properties = new HashMap<>(); - properties.put("$track_id", 111); - Date date = new Date(); - properties.put("$time", date); - sa.track("123", true, "test", properties);} + private StringBuilder messageBuffer; + SensorsAnalytics sa; + @BeforeEach + public void init() throws NoSuchFieldException, IllegalAccessException { + String url = "http://10.120.111.143:8106/sa?project=default"; + DebugConsumer consumer = new DebugConsumer(url, true); + sa = new SensorsAnalytics(consumer); + } - /** - * 校验 trackSignup 记录节点 - */ - @Test - public void checkTrackSignUpProp() throws InvalidArgumentException { - Map properties = new HashMap<>(); - properties.put("number1", 1234); - properties.put("String1", "str"); - properties.put("boolean1", false); + /** 校验调用 track 方法生成事件节点数是否完整 */ + @Test + public void checkTrackEventLoginTrue() throws InvalidArgumentException { + Map properties = new HashMap<>(); properties.put("$track_id", 111); - Date date = new Date(); - properties.put("$time", date); - sa.trackSignUp("123", "345", properties);} - + Date date = new Date(); + properties.put("$time", date); + sa.track("123", true, "test", properties); + } - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void checkProfileSetDataType() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - Map properties = new HashMap<>(); - properties.put("number1", 1234); - properties.put("date1", date); - properties.put("String1", "str"); - properties.put("boolean1", false); - properties.put("list1", list); + /** 校验 trackSignup 记录节点 */ + @Test + public void checkTrackSignUpProp() throws InvalidArgumentException { + Map properties = new HashMap<>(); + properties.put("number1", 1234); + properties.put("String1", "str"); + properties.put("boolean1", false); properties.put("$track_id", 111); - properties.put("$time", date); - sa.profileSet("123", true, properties);} - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void checkProfileSetDataType01() throws InvalidArgumentException { - - sa.profileSet("123", true, "$track_id", 111); + Date date = new Date(); + properties.put("$time", date); + sa.trackSignUp("123", "345", properties); + } - } - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileSetOnceDataType() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - Map properties = new HashMap<>(); - properties.put("number1", 1234); - properties.put("date1", date); - properties.put("String1", "str"); - properties.put("boolean1", false); - properties.put("list1", list); + /** 校验自定义属性格式是否正常 */ + @Test + public void checkProfileSetDataType() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + Map properties = new HashMap<>(); + properties.put("number1", 1234); + properties.put("date1", date); + properties.put("String1", "str"); + properties.put("boolean1", false); + properties.put("list1", list); properties.put("$track_id", 111); - properties.put("$time", date); - sa.profileSetOnce("123", true, properties); - } - - - @Test - public void testProfileAppend() { - List list = new ArrayList<>(); - list.add("aaa"); - list.add("bbb"); - Map properties = new HashMap<>(); - properties.put("list1", list); - - List listInt = new ArrayList<>(); - listInt.add(111); - properties.put("$track_id", listInt); - - try { - sa.profileAppend("123", true, properties); - fail("[ERROR] profileAppend should throw InvalidArgumentException."); - }catch (Exception e){ - e.printStackTrace(); - + properties.put("$time", date); + sa.profileSet("123", true, properties); } - } - - @Test - public void testProfileAppend01() throws InvalidArgumentException{ - sa.profileAppend("123", true, "$track_id", "111");} + /** 校验自定义属性格式是否正常 */ + @Test + public void checkProfileSetDataType01() throws InvalidArgumentException { - // profileUnset - @Test - public void testProfileUnset() { - Map properties = new HashMap<>(); - properties.put("list1", true); + sa.profileSet("123", true, "$track_id", 111); + } + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileSetOnceDataType() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + Map properties = new HashMap<>(); + properties.put("number1", 1234); + properties.put("date1", date); + properties.put("String1", "str"); + properties.put("boolean1", false); + properties.put("list1", list); properties.put("$track_id", 111); - Date date = new Date(); - properties.put("$time", date); - - try { - sa.profileUnset("123", true, properties); - fail("[ERROR] profileUnset should throw InvalidArgumentException."); - }catch (InvalidArgumentException e){ - + properties.put("$time", date); + sa.profileSetOnce("123", true, properties); } - } - - // profileUnset - @Test - public void testProfileUnset01() throws InvalidArgumentException{ - sa.profileUnset("123", true, "$track_id");} - - // profileDelete - @Test - public void testProfileDelete() throws InvalidArgumentException{ - sa.profileDelete("123", true); - } + @Test + public void testProfileAppend() { + List list = new ArrayList<>(); + list.add("aaa"); + list.add("bbb"); + Map properties = new HashMap<>(); + properties.put("list1", list); + + List listInt = new ArrayList<>(); + listInt.add(111); + properties.put("$track_id", listInt); + + try { + sa.profileAppend("123", true, properties); + Assertions.fail("[ERROR] profileAppend should throw InvalidArgumentException."); + } catch (Exception e) { + e.printStackTrace(); + } + } - @Test - public void testItemSet_Delete() throws Exception { - Date date = new Date(); - //物品纬度表上报 - String itemId = "product001", itemType = "mobile"; - ItemRecord addRecord = ItemRecord.builder().setItemId(itemId).setItemType(itemType) - .addProperty("color", "white") - .addProperty("$time", date) - .build(); - sa.itemSet(addRecord); - System.out.println(date.getTime()); + @Test + public void testProfileAppend01() throws InvalidArgumentException { + sa.profileAppend("123", true, "$track_id", "111"); + } - //删除物品纬度信息 - ItemRecord deleteRecord = ItemRecord.builder().setItemId(itemId).setItemType(itemType) - .addProperty("$time", date) - .build(); - sa.itemDelete(deleteRecord); - sa.flush(); - } + // profileUnset + @Test + public void testProfileUnset() { + Map properties = new HashMap<>(); + properties.put("list1", true); + properties.put("$track_id", 111); + Date date = new Date(); + properties.put("$time", date); + try { + sa.profileUnset("123", true, properties); + Assertions.fail("[ERROR] profileUnset should throw InvalidArgumentException."); + } catch (InvalidArgumentException e) { + } + } - /** - * 校验 event Builder 模式生成数据用户属性是否正常 - */ - @Test - public void checkTrackEventBuilder() throws InvalidArgumentException { - Date date = new Date(); - EventRecord eventRecord = EventRecord.builder() - .setDistinctId("abc") - .isLoginId(false) - .setEventName("test") - .addProperty("$track_id", 111) - .addProperty("$time", date) - .build(); - sa.track(eventRecord);} + // profileUnset + @Test + public void testProfileUnset01() throws InvalidArgumentException { + sa.profileUnset("123", true, "$track_id"); + } - /** - * 校验 is_login_id 为 true 的事件属性 - */ - @Test - public void checkTrackEventBuilderLoginIdIsTrue() throws InvalidArgumentException { - Date date = new Date(); - EventRecord eventRecord = EventRecord.builder() - .setDistinctId("abc") - .isLoginId(true) - .setEventName("test") - .addProperty("$track_id", 111) - .addProperty("$time", date) - .build(); - sa.track(eventRecord);} + // profileDelete + @Test + public void testProfileDelete() throws InvalidArgumentException { + sa.profileDelete("123", true); + } - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void checkProfileSetDataTypeEventBuilder() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("number1", 1234) - .addProperty("date1", date) - .addProperty("String1", "str") - .addProperty("boolean1", false) - .addProperty("list1", list) - .addProperty("$track_id", 111) - .addProperty("$time", date) - .build(); - sa.profileSet(userRecord);} + @Test + public void testItemSet_Delete() throws Exception { + Date date = new Date(); + // 物品纬度表上报 + String itemId = "product001", itemType = "mobile"; + ItemRecord addRecord = + ItemRecord.builder() + .setItemId(itemId) + .setItemType(itemType) + .addProperty("color", "white") + .addProperty("$time", date) + .build(); + sa.itemSet(addRecord); + System.out.println(date.getTime()); + + // 删除物品纬度信息 + ItemRecord deleteRecord = + ItemRecord.builder() + .setItemId(itemId) + .setItemType(itemType) + .addProperty("$time", date) + .build(); + sa.itemDelete(deleteRecord); + sa.flush(); + } - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileSetOnceDataTypeEventBuilder() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("number1", 1234) - .addProperty("date1", date) - .addProperty("String1", "str") - .addProperty("boolean1", false) - .addProperty("list1", list) - .addProperty("$track_id", 111) - .addProperty("$time", date) - .build(); - sa.profileSetOnce(userRecord); - } + /** 校验 event Builder 模式生成数据用户属性是否正常 */ + @Test + public void checkTrackEventBuilder() throws InvalidArgumentException { + Date date = new Date(); + EventRecord eventRecord = + EventRecord.builder() + .setDistinctId("abc") + .isLoginId(false) + .setEventName("test") + .addProperty("$track_id", 111) + .addProperty("$time", date) + .build(); + sa.track(eventRecord); + } + /** 校验 is_login_id 为 true 的事件属性 */ + @Test + public void checkTrackEventBuilderLoginIdIsTrue() throws InvalidArgumentException { + Date date = new Date(); + EventRecord eventRecord = + EventRecord.builder() + .setDistinctId("abc") + .isLoginId(true) + .setEventName("test") + .addProperty("$track_id", 111) + .addProperty("$time", date) + .build(); + sa.track(eventRecord); + } - @Test - public void testProfileAppendByIdEventBuilder() throws InvalidArgumentException{ - Date date = new Date(); - List list = new ArrayList<>(); - list.add("aaa"); - list.add("bbb"); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("list1", list) - .addProperty("$track_id", 111) - .addProperty("$time", date) - .build(); - try { - sa.profileAppend(userRecord); - fail("profileAppend should throw InvalidArgumentException"); - }catch (InvalidArgumentException e){ - + /** 校验自定义属性格式是否正常 */ + @Test + public void checkProfileSetDataTypeEventBuilder() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("number1", 1234) + .addProperty("date1", date) + .addProperty("String1", "str") + .addProperty("boolean1", false) + .addProperty("list1", list) + .addProperty("$track_id", 111) + .addProperty("$time", date) + .build(); + sa.profileSet(userRecord); } - } + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileSetOnceDataTypeEventBuilder() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("number1", 1234) + .addProperty("date1", date) + .addProperty("String1", "str") + .addProperty("boolean1", false) + .addProperty("list1", list) + .addProperty("$track_id", 111) + .addProperty("$time", date) + .build(); + sa.profileSetOnce(userRecord); + } + @Test + public void testProfileAppendByIdEventBuilder() throws InvalidArgumentException { + Date date = new Date(); + List list = new ArrayList<>(); + list.add("aaa"); + list.add("bbb"); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("list1", list) + .addProperty("$track_id", 111) + .addProperty("$time", date) + .build(); + try { + sa.profileAppend(userRecord); + Assertions.fail("profileAppend should throw InvalidArgumentException"); + } catch (InvalidArgumentException e) { + + } + } - // profileDeleteById - @Test - public void testProfileDeleteByIdEventBuilder() throws InvalidArgumentException{ - Date date = new Date(); - List list = new ArrayList<>(); - list.add("aaa"); - list.add("bbb"); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("list1", list) - .addProperty("$track_id", 111) - .addProperty("$time", date) - .build(); - sa.profileDelete(userRecord); - } + // profileDeleteById + @Test + public void testProfileDeleteByIdEventBuilder() throws InvalidArgumentException { + Date date = new Date(); + List list = new ArrayList<>(); + list.add("aaa"); + list.add("bbb"); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("list1", list) + .addProperty("$track_id", 111) + .addProperty("$time", date) + .build(); + sa.profileDelete(userRecord); + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackIdDebugConsumer.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackIdDebugConsumer.java index a6c232e..9ea9975 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackIdDebugConsumer.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel1TrackIdDebugConsumer.java @@ -1,7 +1,5 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.fail; - import com.sensorsdata.analytics.javasdk.bean.EventRecord; import com.sensorsdata.analytics.javasdk.bean.ItemRecord; import com.sensorsdata.analytics.javasdk.bean.UserRecord; @@ -9,287 +7,260 @@ import com.sensorsdata.analytics.javasdk.consumer.ConcurrentLoggingConsumer; import com.sensorsdata.analytics.javasdk.consumer.DebugConsumer; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Before; -import org.junit.Test; - import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -/** - * 适用于 v3.4.4+ 版本 - * 测试点:验证事件的 _track_id 正常由 $track_id 生成。 - * 无特殊情况,不在下面的 testcase 上一一说明 - */ +/** 适用于 v3.4.4+ 版本 测试点:验证事件的 _track_id 正常由 $track_id 生成。 无特殊情况,不在下面的 testcase 上一一说明 */ public class IDMappingModel1TrackIdDebugConsumer extends SensorsBaseTest { - private BatchConsumer batchConsumer; - - private List> messageList; - private ConcurrentLoggingConsumer consumer; - - private StringBuilder messageBuffer; - SensorsAnalytics sa; - - @Before - public void init() { - String url = "http://10.120.111.143:8106/sa?project=default"; - DebugConsumer consumer = new DebugConsumer(url, true); - sa = new SensorsAnalytics(consumer); - } - - /** - * 校验调用 track 方法生成事件节点数是否完整 - */ - @Test - public void checkTrackEventLoginTrue() throws InvalidArgumentException { - Map properties = new HashMap<>(); - properties.put("$track_id", 111); - - sa.track("123", true, "test", properties); - } - - - /** - * 校验 trackSignup 记录节点 - */ - @Test - public void checkTrackSignUpProp() throws InvalidArgumentException { - Map properties = new HashMap<>(); - properties.put("number1", 1234); - properties.put("String1", "str"); - properties.put("boolean1", false); - properties.put("$track_id", 111); - sa.trackSignUp("123", "345", properties); - } - - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void checkProfileSetDataType() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - Map properties = new HashMap<>(); - properties.put("number1", 1234); - properties.put("date1", date); - properties.put("String1", "str"); - properties.put("boolean1", false); - properties.put("list1", list); - properties.put("$track_id", 111); - sa.profileSet("123", true, properties); - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void checkProfileSetDataType01() throws InvalidArgumentException { - - sa.profileSet("123", true, "$track_id", 111); - } - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileSetOnceDataType() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - Map properties = new HashMap<>(); - properties.put("number1", 1234); - properties.put("date1", date); - properties.put("String1", "str"); - properties.put("boolean1", false); - properties.put("list1", list); - properties.put("$track_id", 111); - sa.profileSetOnce("123", true, properties); - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileIncrement() throws InvalidArgumentException { - Map properties = new HashMap<>(); - properties.put("number1", 1234); - properties.put("$track_id", 111); - sa.profileIncrement("123", true, properties); - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileIncrement01() throws InvalidArgumentException { - sa.profileIncrement("123", true, "$track_id", 111); - } - - - @Test - public void testProfileAppend() throws InvalidArgumentException{ - List list = new ArrayList<>(); - list.add("aaa"); - list.add("bbb"); - Map properties = new HashMap<>(); - properties.put("list1", list); - - List listInt = new ArrayList<>(); - listInt.add(111); - properties.put("$track_id", listInt); - - try { - sa.profileAppend("123", true, properties); - fail("[ERROR] profileAppend should throw InvalidArgumentException."); - }catch (Exception e){ - e.printStackTrace(); - } - } - - @Test - public void testProfileAppend01() throws InvalidArgumentException{ - sa.profileAppend("123", true, "$track_id", "111"); - } - - // profileUnset - @Test - public void testProfileUnset() { - Map properties = new HashMap<>(); - properties.put("list1", true); - properties.put("$track_id", 111); - - try { - sa.profileUnset("123", true, properties); - fail("[ERROR] profileUnset should throw InvalidArgumentException."); - }catch (InvalidArgumentException e){ - } - } - - // profileUnset - @Test - public void testProfileUnset01() throws InvalidArgumentException{ - sa.profileUnset("123", true, "$track_id"); - } - - // profileDelete - @Test - public void testProfileDelete() throws InvalidArgumentException{ - sa.profileDelete("123", true); - } - - @Test - public void testItemSet_Delete() throws Exception { - //物品纬度表上报 - String itemId = "product001", itemType = "mobile"; - ItemRecord addRecord = ItemRecord.builder().setItemId(itemId).setItemType(itemType) - .addProperty("color", "white") - .build(); - sa.itemSet(addRecord); - - //删除物品纬度信息 - ItemRecord deleteRecord = ItemRecord.builder().setItemId(itemId).setItemType(itemType) - .build(); - sa.itemDelete(deleteRecord); - sa.flush(); - } - - - - /** - * 校验 event Builder 模式生成数据用户属性是否正常 - */ - @Test - public void checkTrackEventBuilder() throws InvalidArgumentException { - EventRecord eventRecord = EventRecord.builder() - .setDistinctId("abc") - .isLoginId(false) - .setEventName("test") - .addProperty("$track_id", 111) - .build(); - sa.track(eventRecord); - } - - /** - * 校验 is_login_id 为 true 的事件属性 - */ - @Test - public void checkTrackEventBuilderLoginIdIsTrue() throws InvalidArgumentException { - EventRecord eventRecord = EventRecord.builder() - .setDistinctId("abc") - .isLoginId(true) - .setEventName("test") - .addProperty("$track_id", 111) - .build(); - sa.track(eventRecord); - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void checkProfileSetDataTypeEventBuilder() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("number1", 1234) - .addProperty("date1", date) - .addProperty("String1", "str") - .addProperty("boolean1", false) - .addProperty("list1", list) - .addProperty("$track_id", 111) - .build(); - sa.profileSet(userRecord); - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileSetOnceDataTypeEventBuilder() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("number1", 1234) - .addProperty("date1", date) - .addProperty("String1", "str") - .addProperty("boolean1", false) - .addProperty("list1", list) - .addProperty("$track_id", 111) - .build(); - sa.profileSetOnce(userRecord); - } - - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void testProfileIncrementEventBuilder() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("number1", 1234) - .addProperty("$track_id", 111) - .build(); - sa.profileIncrement(userRecord); - } - + private BatchConsumer batchConsumer; + + private List> messageList; + private ConcurrentLoggingConsumer consumer; + + private StringBuilder messageBuffer; + SensorsAnalytics sa; + + @BeforeEach + public void init() { + String url = "http://10.120.111.143:8106/sa?project=default"; + DebugConsumer consumer = new DebugConsumer(url, true); + sa = new SensorsAnalytics(consumer); + } + + /** 校验调用 track 方法生成事件节点数是否完整 */ + @Test + public void checkTrackEventLoginTrue() throws InvalidArgumentException { + Map properties = new HashMap<>(); + properties.put("$track_id", 111); + + sa.track("123", true, "test", properties); + } + + /** 校验 trackSignup 记录节点 */ + @Test + public void checkTrackSignUpProp() throws InvalidArgumentException { + Map properties = new HashMap<>(); + properties.put("number1", 1234); + properties.put("String1", "str"); + properties.put("boolean1", false); + properties.put("$track_id", 111); + sa.trackSignUp("123", "345", properties); + } + + /** 校验自定义属性格式是否正常 */ + @Test + public void checkProfileSetDataType() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + Map properties = new HashMap<>(); + properties.put("number1", 1234); + properties.put("date1", date); + properties.put("String1", "str"); + properties.put("boolean1", false); + properties.put("list1", list); + properties.put("$track_id", 111); + sa.profileSet("123", true, properties); + } + + /** 校验自定义属性格式是否正常 */ + @Test + public void checkProfileSetDataType01() throws InvalidArgumentException { + + sa.profileSet("123", true, "$track_id", 111); + } + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileSetOnceDataType() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + Map properties = new HashMap<>(); + properties.put("number1", 1234); + properties.put("date1", date); + properties.put("String1", "str"); + properties.put("boolean1", false); + properties.put("list1", list); + properties.put("$track_id", 111); + sa.profileSetOnce("123", true, properties); + } + + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileIncrement() throws InvalidArgumentException { + Map properties = new HashMap<>(); + properties.put("number1", 1234); + properties.put("$track_id", 111); + sa.profileIncrement("123", true, properties); + } + + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileIncrement01() throws InvalidArgumentException { + sa.profileIncrement("123", true, "$track_id", 111); + } + + @Test + public void testProfileAppend() throws InvalidArgumentException { + List list = new ArrayList<>(); + list.add("aaa"); + list.add("bbb"); + Map properties = new HashMap<>(); + properties.put("list1", list); + + List listInt = new ArrayList<>(); + listInt.add(111); + properties.put("$track_id", listInt); + + try { + sa.profileAppend("123", true, properties); + Assertions.fail("[ERROR] profileAppend should throw InvalidArgumentException."); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testProfileAppend01() throws InvalidArgumentException { + sa.profileAppend("123", true, "$track_id", "111"); + } + + // profileUnset + @Test + public void testProfileUnset() { + Map properties = new HashMap<>(); + properties.put("list1", true); + properties.put("$track_id", 111); + + try { + sa.profileUnset("123", true, properties); + Assertions.fail("[ERROR] profileUnset should throw InvalidArgumentException."); + } catch (InvalidArgumentException e) { + } + } + + // profileUnset + @Test + public void testProfileUnset01() throws InvalidArgumentException { + sa.profileUnset("123", true, "$track_id"); + } + + // profileDelete + @Test + public void testProfileDelete() throws InvalidArgumentException { + sa.profileDelete("123", true); + } + + @Test + public void testItemSet_Delete() throws Exception { + // 物品纬度表上报 + String itemId = "product001", itemType = "mobile"; + ItemRecord addRecord = + ItemRecord.builder() + .setItemId(itemId) + .setItemType(itemType) + .addProperty("color", "white") + .build(); + sa.itemSet(addRecord); + + // 删除物品纬度信息 + ItemRecord deleteRecord = + ItemRecord.builder().setItemId(itemId).setItemType(itemType).build(); + sa.itemDelete(deleteRecord); + sa.flush(); + } + + /** 校验 event Builder 模式生成数据用户属性是否正常 */ + @Test + public void checkTrackEventBuilder() throws InvalidArgumentException { + EventRecord eventRecord = + EventRecord.builder() + .setDistinctId("abc") + .isLoginId(false) + .setEventName("test") + .addProperty("$track_id", 111) + .build(); + sa.track(eventRecord); + } + + /** 校验 is_login_id 为 true 的事件属性 */ + @Test + public void checkTrackEventBuilderLoginIdIsTrue() throws InvalidArgumentException { + EventRecord eventRecord = + EventRecord.builder() + .setDistinctId("abc") + .isLoginId(true) + .setEventName("test") + .addProperty("$track_id", 111) + .build(); + sa.track(eventRecord); + } + + /** 校验自定义属性格式是否正常 */ + @Test + public void checkProfileSetDataTypeEventBuilder() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("number1", 1234) + .addProperty("date1", date) + .addProperty("String1", "str") + .addProperty("boolean1", false) + .addProperty("list1", list) + .addProperty("$track_id", 111) + .build(); + sa.profileSet(userRecord); + } + + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileSetOnceDataTypeEventBuilder() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("number1", 1234) + .addProperty("date1", date) + .addProperty("String1", "str") + .addProperty("boolean1", false) + .addProperty("list1", list) + .addProperty("$track_id", 111) + .build(); + sa.profileSetOnce(userRecord); + } + + /** 校验自定义属性格式是否正常 */ + @Test + public void testProfileIncrementEventBuilder() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("number1", 1234) + .addProperty("$track_id", 111) + .build(); + sa.profileIncrement(userRecord); + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel3TestTrackIdAndTime.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel3TestTrackIdAndTime.java index 1032d06..8a837ec 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel3TestTrackIdAndTime.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingModel3TestTrackIdAndTime.java @@ -1,33 +1,23 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import com.sensorsdata.analytics.javasdk.bean.IDMEventRecord; import com.sensorsdata.analytics.javasdk.bean.IDMUserRecord; import com.sensorsdata.analytics.javasdk.bean.SensorsAnalyticsIdentity; import com.sensorsdata.analytics.javasdk.consumer.BatchConsumer; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** - * 适用于 v3.4.4+ 版本 - * 测试点:验证事件的 _track_id 正常由 $track_id 生成,time 由 $time 生成。 - * 无特殊情况,不在下面的 testcase 上一一说明 + * 适用于 v3.4.4+ 版本 测试点:验证事件的 _track_id 正常由 $track_id 生成,time 由 $time 生成。 无特殊情况,不在下面的 testcase 上一一说明 */ public class IDMappingModel3TestTrackIdAndTime extends SensorsBaseTest { private BatchConsumer batchConsumer; @@ -35,79 +25,79 @@ public class IDMappingModel3TestTrackIdAndTime extends SensorsBaseTest { private List> messageList; SensorsAnalytics saTmp; - @Before + @BeforeEach public void init() throws NoSuchFieldException, IllegalAccessException { String url = "http://10.120.111.143:8106/sa?project=default"; // 注意要设置 bulkSize 稍微大一点,这里设置为 100,否则超过 1 条就上报,messageList 里面拿不到事件数据 batchConsumer = new BatchConsumer(url, 100, true, 3); // 通过反射机制获取 BatchConsumer 的 messageList - Field field = batchConsumer.getClass().getDeclaredField("messageList"); // messageList 是 BatchConsumer 用来暂存事件数据的成员变量 + Field field = + batchConsumer + .getClass() + .getDeclaredField( + "messageList"); // messageList 是 BatchConsumer 用来暂存事件数据的成员变量 field.setAccessible(true); messageList = (List>) field.get(batchConsumer); saTmp = new SensorsAnalytics(batchConsumer); } - private void assertNotNullProp(){ - assertNotNull(messageList.get(0).get("identities")); - assertNotNull(messageList.get(0).get("time")); - assertNotNull(messageList.get(0).get("_track_id")); - assertNotNull(messageList.get(0).get("properties")); + private void assertNotNullProp() { + Assertions.assertNotNull(messageList.get(0).get("identities")); + Assertions.assertNotNull(messageList.get(0).get("time")); + Assertions.assertNotNull(messageList.get(0).get("_track_id")); + Assertions.assertNotNull(messageList.get(0).get("properties")); } @Test - public void testSingleIdentity() throws InvalidArgumentException{ - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "123") - .build(); + public void testSingleIdentity() throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "123") + .build(); Map properties = new HashMap<>(); properties.put("$track_id", 111); Date date = new Date(); properties.put("$time", date); saTmp.trackById(identity, "test", properties); - assertEquals(1, messageList.size()); + Assertions.assertEquals(1, messageList.size()); assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - assertEquals(date.getTime(), messageList.get(0).get("time")); + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + Assertions.assertEquals(date.getTime(), messageList.get(0).get("time")); - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id } - - /** - * 校验 ID-Mapping bind 接口 - */ + /** 校验 ID-Mapping bind 接口 */ @Test public void testIdMappingBind() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("$identity_mobile", "123") - .addIdentityProperty("$identity_email", "fz@163.com") - .build(); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("$identity_mobile", "123") + .addIdentityProperty("$identity_email", "fz@163.com") + .build(); saTmp.bind(identity); } - - /** - * 校验 ID-Mapping unbind 接口用户格式 - */ + /** 校验 ID-Mapping unbind 接口用户格式 */ @Test public void checkUnbindUserId() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("id_test1", "id_value1") - .build(); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("id_test1", "id_value1") + .build(); saTmp.unbind(identity); - } /** - * 【已知问题】https://jira.sensorsdata.cn/browse/SDK-4863 - * 【Java SDK】【_track_id】公共属性设置 $time, 属性中也带 $time,同时这条事件的 time 也会由 $time 生成 + * 【已知问题】https://jira.sensorsdata.cn/browse/SDK-4863 【Java SDK】【_track_id】公共属性设置 $time, 属性中也带 + * $time,同时这条事件的 time 也会由 $time 生成 */ @Test - @Ignore + @Disabled public void checkTrackByIdSuperProperties() throws InvalidArgumentException { Map properties = new HashMap<>(); properties.put("$track_id", 111); @@ -115,30 +105,32 @@ public void checkTrackByIdSuperProperties() throws InvalidArgumentException { properties.put("$time", date); properties.put("abc", 111); saTmp.registerSuperProperties(properties); - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("id_test1", "id_value1") - .build(); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("id_test1", "id_value1") + .build(); saTmp.trackById(identity, "eee", null); - assertEquals(1, messageList.size()); + Assertions.assertEquals(1, messageList.size()); assertNotNullProp(); - assertNotEquals(111, messageList.get(0).get("_track_id")); // 公共属性设置 $track_id 不生效的 - assertNotEquals(date.getTime(), messageList.get(0).get("time")); // 公共属性设置 $time 不生效的 - + Assertions.assertNotEquals( + 111, messageList.get(0).get("_track_id")); // 公共属性设置 $track_id 不生效的 + Assertions.assertNotEquals( + date.getTime(), messageList.get(0).get("time")); // 公共属性设置 $time 不生效的 - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - assertTrue(props.containsKey("abc")); // properties 包含其他自定义属性 + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Assertions.assertTrue(props.containsKey("abc")); // properties 包含其他自定义属性 } /** - * 【已知问题】https://jira.sensorsdata.cn/browse/SDK-4863 - * 【Java SDK】【_track_id】公共属性设置 $time, 属性中也带 $time,同时这条事件的 time 也会由 $time 生成 + * 【已知问题】https://jira.sensorsdata.cn/browse/SDK-4863 【Java SDK】【_track_id】公共属性设置 $time, 属性中也带 + * $time,同时这条事件的 time 也会由 $time 生成 */ @Test - @Ignore + @Disabled public void checkTrackByIdSuperProperties01() throws InvalidArgumentException { Map properties = new HashMap<>(); properties.put("$track_id", "aaa"); @@ -146,27 +138,29 @@ public void checkTrackByIdSuperProperties01() throws InvalidArgumentException { properties.put("$time", date); properties.put("abc", 111); saTmp.registerSuperProperties(properties); - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("id_test1", "id_value1") - .build(); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("id_test1", "id_value1") + .build(); saTmp.trackById(identity, "eee", null); - assertEquals(1, messageList.size()); + Assertions.assertEquals(1, messageList.size()); assertNotNullProp(); - assertNotEquals("aaa", messageList.get(0).get("_track_id")); // 公共属性设置 $track_id 不生效的 - assertNotEquals(date.getTime(), messageList.get(0).get("time")); // 公共属性设置 $time 不生效的 + Assertions.assertNotEquals( + "aaa", messageList.get(0).get("_track_id")); // 公共属性设置 $track_id 不生效的 + Assertions.assertNotEquals( + date.getTime(), messageList.get(0).get("time")); // 公共属性设置 $time 不生效的 - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - assertTrue(props.containsKey("abc")); // properties 包含其他自定义属性 + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Assertions.assertTrue(props.containsKey("abc")); // properties 包含其他自定义属性 } - /** - * 【已知问题】https://jira.sensorsdata.cn/browse/SDK-4863 - * 【Java SDK】【_track_id】公共属性设置 $time, 属性中也带 $time,同时这条事件的 time 也会由 $time 生成 + * 【已知问题】https://jira.sensorsdata.cn/browse/SDK-4863 【Java SDK】【_track_id】公共属性设置 $time, 属性中也带 + * $time,同时这条事件的 time 也会由 $time 生成 */ @Test public void checkBindSuperProperties() throws InvalidArgumentException { @@ -176,26 +170,27 @@ public void checkBindSuperProperties() throws InvalidArgumentException { properties.put("$time", date); properties.put("abc", 111); saTmp.registerSuperProperties(properties); - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("id_test1", "id_value1") - .addIdentityProperty("eee", "123") - .build(); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("id_test1", "id_value1") + .addIdentityProperty("eee", "123") + .build(); saTmp.bind(identity); - assertEquals(1, messageList.size()); + Assertions.assertEquals(1, messageList.size()); assertNotNullProp(); - assertNotEquals(111, messageList.get(0).get("_track_id")); // 公共属性设置 $track_id 不生效的 - - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - assertTrue(props.containsKey("abc")); // properties 包含其他自定义属性 + Assertions.assertNotEquals( + 111, messageList.get(0).get("_track_id")); // 公共属性设置 $track_id 不生效的 + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Assertions.assertTrue(props.containsKey("abc")); // properties 包含其他自定义属性 } /** - * 【已知问题】https://jira.sensorsdata.cn/browse/SDK-4863 - * 【Java SDK】【_track_id】公共属性设置 $time, 属性中也带 $time,同时这条事件的 time 也会由 $time 生成 + * 【已知问题】https://jira.sensorsdata.cn/browse/SDK-4863 【Java SDK】【_track_id】公共属性设置 $time, 属性中也带 + * $time,同时这条事件的 time 也会由 $time 生成 */ @Test public void checkUnbindSuperProperties() throws InvalidArgumentException { @@ -205,60 +200,65 @@ public void checkUnbindSuperProperties() throws InvalidArgumentException { properties.put("$time", date); properties.put("abc", 111); saTmp.registerSuperProperties(properties); - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("id_test1", "id_value1") - .build(); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("id_test1", "id_value1") + .build(); saTmp.unbind(identity); - assertEquals(1, messageList.size()); + Assertions.assertEquals(1, messageList.size()); assertNotNullProp(); - assertNotEquals(111, messageList.get(0).get("_track_id")); // 公共属性设置 $track_id 不生效的 + Assertions.assertNotEquals( + 111, messageList.get(0).get("_track_id")); // 公共属性设置 $track_id 不生效的 - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - assertTrue(props.containsKey("abc")); // properties 包含其他自定义属性 + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Assertions.assertTrue(props.containsKey("abc")); // properties 包含其他自定义属性 } /** - * v3.4.2 后新增接口 trackById(@NonNull IDMEventRecord idmEventRecord) 测试 - * 测试点:IDMEventRecord 传入正常 distinctId,identityMap 传入 $identity_login_id + * v3.4.2 后新增接口 trackById(@NonNull IDMEventRecord idmEventRecord) 测试 测试点:IDMEventRecord 传入正常 + * distinctId,identityMap 传入 $identity_login_id */ @Test - public void testTrackByIdIDMEventRecord() throws InvalidArgumentException { + public void testTrackByIdIDMEventRecord() throws InvalidArgumentException { Date date = new Date(); - IDMEventRecord record = IDMEventRecord.starter() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "123") - .setDistinctId("disId123") - .setEventName("test") - .addProperty("$track_id", 111) - .addProperty("$time", date) - .addProperty("abc", 111) - .build(); + IDMEventRecord record = + IDMEventRecord.starter() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "123") + .setDistinctId("disId123") + .setEventName("test") + .addProperty("$track_id", 111) + .addProperty("$time", date) + .addProperty("abc", 111) + .build(); saTmp.trackById(record); - assertEquals(1, messageList.size()); + Assertions.assertEquals(1, messageList.size()); assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - assertEquals(date.getTime(), messageList.get(0).get("time")); // 公共属性设置 $track_id 不生效的 + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + Assertions.assertEquals( + date.getTime(), messageList.get(0).get("time")); // 公共属性设置 $track_id 不生效的 - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - assertTrue(props.containsKey("abc")); // properties 包含其他自定义属性 + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Assertions.assertTrue(props.containsKey("abc")); // properties 包含其他自定义属性 } - /** * SensorsAnalyticsIdentity 传入 $identity_login_id + * * @throws InvalidArgumentException */ @Test public void testProfileSetById() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "123") - .build(); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "123") + .build(); Map properties = new HashMap<>(); properties.put("age", 1); properties.put("$track_id", 111); @@ -267,26 +267,29 @@ public void testProfileSetById() throws InvalidArgumentException { saTmp.profileSetById(identity, properties); - assertEquals(1, messageList.size()); + Assertions.assertEquals(1, messageList.size()); assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - assertEquals(date.getTime(), messageList.get(0).get("time")); // 公共属性设置 $track_id 不生效的 + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + Assertions.assertEquals( + date.getTime(), messageList.get(0).get("time")); // 公共属性设置 $track_id 不生效的 - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - assertTrue(props.containsKey("age")); // properties 包含其他自定义属性 + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Assertions.assertTrue(props.containsKey("age")); // properties 包含其他自定义属性 } /** * SensorsAnalyticsIdentity 传入 $identity_login_id + * * @throws InvalidArgumentException */ @Test public void testProfileSetOnesById00() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "123") - .build(); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "123") + .build(); Map properties = new HashMap<>(); properties.put("age", 1); properties.put("$track_id", 111); @@ -294,27 +297,30 @@ public void testProfileSetOnesById00() throws InvalidArgumentException { properties.put("$time", date); saTmp.profileSetOnceById(identity, properties); - assertEquals(1, messageList.size()); + Assertions.assertEquals(1, messageList.size()); assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - assertEquals(date.getTime(), messageList.get(0).get("time")); // 公共属性设置 $track_id 不生效的 + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + Assertions.assertEquals( + date.getTime(), messageList.get(0).get("time")); // 公共属性设置 $track_id 不生效的 - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - assertTrue(props.containsKey("age")); // properties 包含其他自定义属性 + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Assertions.assertTrue(props.containsKey("age")); // properties 包含其他自定义属性 } /** * SensorsAnalyticsIdentity 传入 $identity_login_id + * * @throws InvalidArgumentException */ @Test - public void testProfileIncrementById00(){ + public void testProfileIncrementById00() { try { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "123") - .build(); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "123") + .build(); Map properties = new HashMap<>(); properties.put("age", 1); properties.put("$track_id", 111); @@ -322,19 +328,22 @@ public void testProfileIncrementById00(){ properties.put("$time", date); saTmp.profileIncrementById(identity, properties); - fail("profileIncrementById should throw InvalidArgumentException."); - }catch (InvalidArgumentException e){ - assertEquals("The property value of PROFILE_INCREMENT should be a Number.The current type is class java.util.Date.", e.getMessage()); + Assertions.fail("profileIncrementById should throw InvalidArgumentException."); + } catch (InvalidArgumentException e) { + Assertions.assertEquals( + "The property value of PROFILE_INCREMENT should be a Number.The current type is class java.util.Date.", + e.getMessage()); e.printStackTrace(); } } @Test public void testProfileAppendById() { - try{ - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "123") - .build(); + try { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "123") + .build(); List list = new ArrayList<>(); list.add("apple"); list.add("orange"); @@ -345,20 +354,21 @@ public void testProfileAppendById() { properties.put("$time", date); saTmp.profileAppendById(identity, properties); - fail("profileAppendById should throw InvalidArgumentException."); - }catch(InvalidArgumentException e){ + Assertions.fail("profileAppendById should throw InvalidArgumentException."); + } catch (InvalidArgumentException e) { String msg = "The property value of PROFILE_APPEND should be a List."; - assertEquals(msg, e.getMessage()); + Assertions.assertEquals(msg, e.getMessage()); e.printStackTrace(); } } @Test public void testProfileUnsetById() { - try{ - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "123") - .build(); + try { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "123") + .build(); List list = new ArrayList<>(); list.add("apple"); list.add("orange"); @@ -370,10 +380,10 @@ public void testProfileUnsetById() { saTmp.profileUnsetById(identity, properties); - fail("profileUnsetById should throw InvalidArgumentException."); - }catch(InvalidArgumentException e){ + Assertions.fail("profileUnsetById should throw InvalidArgumentException."); + } catch (InvalidArgumentException e) { String msg = "The property value of [$time] should be true."; - assertEquals(msg, e.getMessage()); + Assertions.assertEquals(msg, e.getMessage()); e.printStackTrace(); } } @@ -382,73 +392,81 @@ public void testProfileUnsetById() { // TODO @Test public void testProfileDeleteById() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "123") - .build(); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "123") + .build(); saTmp.profileDeleteById(identity); } /** * IDMUserRecord 传入正常 distinctId,identityMap 传入 $identity_login_id + * * @throws InvalidArgumentException */ @Test public void testProfileSetByIdNew() throws InvalidArgumentException { // 新版本接口 Date date = new Date(); - IDMUserRecord userRecord = IDMUserRecord.starter() - .setDistinctId("xc001") //手动指定外层 distinct_id - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "dis123") //用户维度标识 - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "123@qq.com") //用户维度标识 - .addProperty("age", 1) // 设置埋点事件属性 - .addProperty("$track_id", 111) - .addProperty("$time", date) // 设置 $track_id - .build(); + IDMUserRecord userRecord = + IDMUserRecord.starter() + .setDistinctId("xc001") // 手动指定外层 distinct_id + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "dis123") // 用户维度标识 + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "123@qq.com") // 用户维度标识 + .addProperty("age", 1) // 设置埋点事件属性 + .addProperty("$track_id", 111) + .addProperty("$time", date) // 设置 $track_id + .build(); saTmp.profileSetById(userRecord); - assertEquals(1, messageList.size()); + Assertions.assertEquals(1, messageList.size()); assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - assertEquals(date.getTime(), messageList.get(0).get("time")); // 公共属性设置 $track_id 不生效的 + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + Assertions.assertEquals( + date.getTime(), messageList.get(0).get("time")); // 公共属性设置 $track_id 不生效的 - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - assertTrue(props.containsKey("age")); // properties 包含其他自定义属性 + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Assertions.assertTrue(props.containsKey("age")); // properties 包含其他自定义属性 } /** * IDMUserRecord 传入正常 distinctId,identityMap 传入 $identity_login_id + * * @throws InvalidArgumentException */ @Test public void testProfileSetOnceByIdNew() throws InvalidArgumentException { // 新版本接口 Date date = new Date(); - IDMUserRecord userRecord = IDMUserRecord.starter() - .setDistinctId("xc001") //手动指定外层 distinct_id - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "dis123") //用户维度标识 - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "123@qq.com") //用户维度标识 - .addProperty("age", 1) // 设置埋点事件属性 - .addProperty("$track_id", 111) - .addProperty("$time", date) // 设置 $track_id - .build(); + IDMUserRecord userRecord = + IDMUserRecord.starter() + .setDistinctId("xc001") // 手动指定外层 distinct_id + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "dis123") // 用户维度标识 + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "123@qq.com") // 用户维度标识 + .addProperty("age", 1) // 设置埋点事件属性 + .addProperty("$track_id", 111) + .addProperty("$time", date) // 设置 $track_id + .build(); saTmp.profileSetOnceById(userRecord); - assertEquals(1, messageList.size()); + Assertions.assertEquals(1, messageList.size()); assertNotNullProp(); - assertEquals(111, messageList.get(0).get("_track_id")); - assertEquals(date.getTime(), messageList.get(0).get("time")); // 公共属性设置 $track_id 不生效的 + Assertions.assertEquals(111, messageList.get(0).get("_track_id")); + Assertions.assertEquals( + date.getTime(), messageList.get(0).get("time")); // 公共属性设置 $track_id 不生效的 - Map props = (Map)messageList.get(0).get("properties"); - assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id - assertTrue(props.containsKey("age")); // properties 包含其他自定义属性 + Map props = (Map) messageList.get(0).get("properties"); + Assertions.assertFalse(props.containsKey("$track_id")); // properties 不包含 $track_id + Assertions.assertTrue(props.containsKey("age")); // properties 包含其他自定义属性 } /** * IDMUserRecord 传入正常 distinctId,identityMap 传入 $identity_login_id + * * @throws InvalidArgumentException */ @Test @@ -457,24 +475,30 @@ public void testProfileIncrementByIdNew() { Date date = new Date(); IDMUserRecord userRecord = null; try { - userRecord = IDMUserRecord.starter() - .setDistinctId("xc001") //手动指定外层 distinct_id - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "dis123") //用户维度标识 - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "123@qq.com") //用户维度标识 - .addProperty("age", 1) // 设置埋点事件属性 - .addProperty("$track_id", 111) - .addProperty("$time", date) // 设置 $track_id - .build(); + userRecord = + IDMUserRecord.starter() + .setDistinctId("xc001") // 手动指定外层 distinct_id + .addIdentityProperty( + SensorsAnalyticsIdentity.LOGIN_ID, "dis123") // 用户维度标识 + .addIdentityProperty( + SensorsAnalyticsIdentity.EMAIL, "123@qq.com") // 用户维度标识 + .addProperty("age", 1) // 设置埋点事件属性 + .addProperty("$track_id", 111) + .addProperty("$time", date) // 设置 $track_id + .build(); saTmp.profileIncrementById(userRecord); - fail("profileIncrementById should throw InvalidArgumentException."); + Assertions.fail("profileIncrementById should throw InvalidArgumentException."); } catch (InvalidArgumentException e) { - assertEquals("The property value of PROFILE_INCREMENT should be a Number.The current type is class java.util.Date.", e.getMessage()); + Assertions.assertEquals( + "The property value of PROFILE_INCREMENT should be a Number.The current type is class java.util.Date.", + e.getMessage()); e.printStackTrace(); } } /** * IDMUserRecord 传入正常 distinctId,identityMap 传入 $identity_login_id + * * @throws InvalidArgumentException */ @Test @@ -487,25 +511,29 @@ public void testProfileAppendByIdNew() { Date date = new Date(); IDMUserRecord userRecord = null; try { - userRecord = IDMUserRecord.starter() - .setDistinctId("xc001") //手动指定外层 distinct_id - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "dis123") //用户维度标识 - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "123@qq.com") //用户维度标识 - .addProperty("favorite", list) // 设置埋点事件属性 - .addProperty("$track_id", 111) - .addProperty("$time", date) // 设置 $track_id - .build(); + userRecord = + IDMUserRecord.starter() + .setDistinctId("xc001") // 手动指定外层 distinct_id + .addIdentityProperty( + SensorsAnalyticsIdentity.LOGIN_ID, "dis123") // 用户维度标识 + .addIdentityProperty( + SensorsAnalyticsIdentity.EMAIL, "123@qq.com") // 用户维度标识 + .addProperty("favorite", list) // 设置埋点事件属性 + .addProperty("$track_id", 111) + .addProperty("$time", date) // 设置 $track_id + .build(); saTmp.profileAppendById(userRecord); - fail("profileAppendById should throw InvalidArgumentException."); - }catch(InvalidArgumentException e){ + Assertions.fail("profileAppendById should throw InvalidArgumentException."); + } catch (InvalidArgumentException e) { String msg = "The property value of PROFILE_APPEND should be a List."; - assertEquals(msg, e.getMessage()); + Assertions.assertEquals(msg, e.getMessage()); e.printStackTrace(); } } /** * IDMUserRecord 传入正常 distinctId,identityMap 传入 $identity_login_id + * * @throws InvalidArgumentException */ @Test @@ -518,21 +546,23 @@ public void testProfileUnsetByIdNew() { Date date = new Date(); IDMUserRecord userRecord = null; try { - userRecord = IDMUserRecord.starter() - .setDistinctId("xc001") //手动指定外层 distinct_id - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "dis123") //用户维度标识 - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "123@qq.com") //用户维度标识 - .addProperty("favorite", true) // 设置埋点事件属性 - .addProperty("$track_id", 111) - .addProperty("$time", date) // 设置 $track_id - .build(); + userRecord = + IDMUserRecord.starter() + .setDistinctId("xc001") // 手动指定外层 distinct_id + .addIdentityProperty( + SensorsAnalyticsIdentity.LOGIN_ID, "dis123") // 用户维度标识 + .addIdentityProperty( + SensorsAnalyticsIdentity.EMAIL, "123@qq.com") // 用户维度标识 + .addProperty("favorite", true) // 设置埋点事件属性 + .addProperty("$track_id", 111) + .addProperty("$time", date) // 设置 $track_id + .build(); saTmp.profileUnsetById(userRecord); - fail("profileUnsetById should throw InvalidArgumentException."); - }catch(InvalidArgumentException e){ + Assertions.fail("profileUnsetById should throw InvalidArgumentException."); + } catch (InvalidArgumentException e) { String msg = "The property value of $time should be true."; - assertEquals(msg, e.getMessage()); + Assertions.assertEquals(msg, e.getMessage()); e.printStackTrace(); } } - } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingProfileTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingProfileTest.java index a2c27c6..143620d 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingProfileTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingProfileTest.java @@ -1,27 +1,15 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import com.sensorsdata.analytics.javasdk.bean.IDMEventRecord; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import com.sensorsdata.analytics.javasdk.bean.IDMUserRecord; import com.sensorsdata.analytics.javasdk.bean.SensorsAnalyticsIdentity; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Test; - import java.util.ArrayList; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** - * id-mapping profile 相关接口单元测试 - * 版本支持 3.3.0+ + * id-mapping profile 相关接口单元测试 版本支持 3.3.0+ * * @author fangzhuo * @version 1.0.0 @@ -29,218 +17,196 @@ */ public class IDMappingProfileTest extends SensorsBaseTest { - private final String loginId = "fz123"; - private final String email = "fz@163.com"; - - //------------------------------3.3.0---------------------------- - - /** - *

- * 用户使用 IDMUserRecord 调用 profileSetById 接口; - *

- * 期望生成的数据结构符合神策数据格式 - */ - @Test - public void checkProfileSetById() throws InvalidArgumentException { - final SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) - .build(); - sa.profileSetById(identity, "test", "ddd"); - assertIDM3UserData(data); - } - - /** - * 用户生成 IDM3.0 profile 数据的时候,不需要生成 super 里面的属性 - * 期望 properties 不产生 super 属性 - */ - @Test - public void checkProfileSuperProperties() throws InvalidArgumentException { - final SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) - .build(); - sa.profileSetById(identity, "test", "ddd"); - assertIDM3UserData(data); - Map properties = (Map) data.get("properties"); - assertEquals(2, properties.size()); - assertTrue(properties.containsKey("$is_login_id")); - assertTrue(properties.containsKey("test")); - } - - //------------------------------3.4.2---------------------------- - - /** - * 用户生成 IDM3.0 profile 数据的时候,不需要生成 super 里面的属性 - * 期望 properties 不产生 super 属性 - */ - @Test - public void checkProfileSuperProperties01() throws InvalidArgumentException { - IDMUserRecord userRecord = IDMUserRecord.starter() - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") - .addProperty("test", "ddd") - .build(); - sa.profileSetById(userRecord); - assertIDM3UserData(data); - Map properties = (Map) data.get("properties"); - assertEquals(1, properties.size()); - assertFalse(properties.containsKey("$is_login_id")); - assertTrue(properties.containsKey("test")); - } - - /** - *

- * 用户使用 IDMUserRecord 调用 profileSetById 接口; - *

- * 期望生成的数据结构符合神策数据格式 - */ - @Test - public void checkProfileSetById01() throws InvalidArgumentException { - IDMUserRecord userRecord = IDMUserRecord.starter() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) - .addProperty("hello", "dd") - .build(); - sa.profileSetById(userRecord); - assertIDM3UserData(data); - } - - /** - *

- * 用户携带 $identity_login_id 使用 IDMUserRecord 调用 profileSetById 接口; - *

- * 期望生成的数据结构,distinct_id 取值为 $identity_login_id - */ - @Test - public void checkProfileSetByIdWithLoginId() throws InvalidArgumentException { - IDMUserRecord userRecord = IDMUserRecord.starter() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) - .addProperty("hello", "dd") - .build(); - sa.profileSetById(userRecord); - assertEquals(loginId, data.get("distinct_id")); - } - - /** - *

- * 用户携带 $identity_login_id,设置 distinct_id 使用 IDMUserRecord 调用 profileSetById 接口; - *

- * 期望生成的数据结构,distinct_id 取值为 $identity_login_id - */ - @Test - public void checkProfileSetByIdWithLoginId01() throws InvalidArgumentException { - IDMUserRecord userRecord = IDMUserRecord.starter() - .setDistinctId("zzz") - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) - .addProperty("hello", "dd") - .build(); - sa.profileSetById(userRecord); - assertEquals("zzz", data.get("distinct_id")); - } - - /** - *

- * 用户使用 IDMUserRecord 调用 profileSetOnceById 接口; - *

- * 期望生成的数据结构符合神策数据格式 - */ - @Test - public void checkProfileSetOnceById() throws InvalidArgumentException { - IDMUserRecord userRecord = IDMUserRecord.starter() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) - .addProperty("hello", "dd") - .build(); - sa.profileSetOnceById(userRecord); - assertIDM3UserData(data); - } - - /** - *

- * 用户使用 IDMUserRecord 调用 profileIncrementById 接口; - *

- * 期望生成的数据结构符合神策数据格式 - */ - @Test - public void checkProfileIncrementById() throws InvalidArgumentException { - IDMUserRecord userRecord = IDMUserRecord.starter() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) - .addProperty("num", 33) - .build(); - sa.profileIncrementById(userRecord); - assertIDM3UserData(data); - } - - /** - *

- * 用户使用 IDMUserRecord 调用 profileIncrementById 接口; - *

- * 期望生成的数据结构符合神策数据格式 - */ - @Test - public void checkProfileAppendById() throws InvalidArgumentException { - ArrayList strings = new ArrayList<>(); - strings.add("movie"); - strings.add("swim"); - IDMUserRecord userRecord = IDMUserRecord.starter() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) - .addProperty("lists", strings) - .build(); - sa.profileAppendById(userRecord); - assertIDM3UserData(data); - } - - /** - *

- * 用户使用 IDMUserRecord 调用 profileUnsetById 接口; - *

- * 期望生成的数据结构符合神策数据格式 - */ - @Test - public void checkProfileUnsetById() throws InvalidArgumentException { - IDMUserRecord userRecord = IDMUserRecord.starter() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) - .build(); - sa.profileUnsetById(userRecord); - assertIDM3UserData(data); - } - - //------------------------------------bug fix 3.5.0 begin------------------------------- - - /** - * bug fix : 修复解绑可以传入多个用户ID - *

修复后的逻辑为:解绑只可以传入一个用户维度ID

- */ - @Test - public void checkUnbind() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("key1", "value1") - .addIdentityProperty("key2", "value2") - .build(); - try { - sa.unbind(identity); - fail("生成异常数据!"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("unbind user operation cannot input multiple or none identifiers")); + private final String loginId = "fz123"; + private final String email = "fz@163.com"; + + // ------------------------------3.3.0---------------------------- + + /** 用户使用 IDMUserRecord 调用 profileSetById 接口; 期望生成的数据结构符合神策数据格式 */ + @Test + public void checkProfileSetById() throws InvalidArgumentException { + final SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) + .build(); + sa.profileSetById(identity, "test", "ddd"); + assertIDM3UserData(data); + } + + /** 用户生成 IDM3.0 profile 数据的时候,不需要生成 super 里面的属性 期望 properties 不产生 super 属性 */ + @Test + public void checkProfileSuperProperties() throws InvalidArgumentException { + final SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) + .build(); + sa.profileSetById(identity, "test", "ddd"); + assertIDM3UserData(data); + Map properties = (Map) data.get("properties"); + Assertions.assertEquals(2, properties.size()); + Assertions.assertTrue(properties.containsKey("$is_login_id")); + Assertions.assertTrue(properties.containsKey("test")); + } + + // ------------------------------3.4.2---------------------------- + + /** 用户生成 IDM3.0 profile 数据的时候,不需要生成 super 里面的属性 期望 properties 不产生 super 属性 */ + @Test + public void checkProfileSuperProperties01() throws InvalidArgumentException { + IDMUserRecord userRecord = + IDMUserRecord.starter() + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") + .addProperty("test", "ddd") + .build(); + sa.profileSetById(userRecord); + assertIDM3UserData(data); + Map properties = (Map) data.get("properties"); + Assertions.assertEquals(1, properties.size()); + Assertions.assertFalse(properties.containsKey("$is_login_id")); + Assertions.assertTrue(properties.containsKey("test")); + } + + /** 用户使用 IDMUserRecord 调用 profileSetById 接口; 期望生成的数据结构符合神策数据格式 */ + @Test + public void checkProfileSetById01() throws InvalidArgumentException { + IDMUserRecord userRecord = + IDMUserRecord.starter() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) + .addProperty("hello", "dd") + .build(); + sa.profileSetById(userRecord); + assertIDM3UserData(data); + } + + /** + * 用户携带 $identity_login_id 使用 IDMUserRecord 调用 profileSetById 接口; 期望生成的数据结构,distinct_id 取值为 + * $identity_login_id + */ + @Test + public void checkProfileSetByIdWithLoginId() throws InvalidArgumentException { + IDMUserRecord userRecord = + IDMUserRecord.starter() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) + .addProperty("hello", "dd") + .build(); + sa.profileSetById(userRecord); + Assertions.assertEquals(loginId, data.get("distinct_id")); + } + + /** + * 用户携带 $identity_login_id,设置 distinct_id 使用 IDMUserRecord 调用 profileSetById 接口; + * 期望生成的数据结构,distinct_id 取值为 $identity_login_id + */ + @Test + public void checkProfileSetByIdWithLoginId01() throws InvalidArgumentException { + IDMUserRecord userRecord = + IDMUserRecord.starter() + .setDistinctId("zzz") + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) + .addProperty("hello", "dd") + .build(); + sa.profileSetById(userRecord); + Assertions.assertEquals("zzz", data.get("distinct_id")); + } + + /** 用户使用 IDMUserRecord 调用 profileSetOnceById 接口; 期望生成的数据结构符合神策数据格式 */ + @Test + public void checkProfileSetOnceById() throws InvalidArgumentException { + IDMUserRecord userRecord = + IDMUserRecord.starter() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) + .addProperty("hello", "dd") + .build(); + sa.profileSetOnceById(userRecord); + assertIDM3UserData(data); + } + + /** 用户使用 IDMUserRecord 调用 profileIncrementById 接口; 期望生成的数据结构符合神策数据格式 */ + @Test + public void checkProfileIncrementById() throws InvalidArgumentException { + IDMUserRecord userRecord = + IDMUserRecord.starter() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) + .addProperty("num", 33) + .build(); + sa.profileIncrementById(userRecord); + assertIDM3UserData(data); + } + + /** 用户使用 IDMUserRecord 调用 profileIncrementById 接口; 期望生成的数据结构符合神策数据格式 */ + @Test + public void checkProfileAppendById() throws InvalidArgumentException { + ArrayList strings = new ArrayList<>(); + strings.add("movie"); + strings.add("swim"); + IDMUserRecord userRecord = + IDMUserRecord.starter() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) + .addProperty("lists", strings) + .build(); + sa.profileAppendById(userRecord); + assertIDM3UserData(data); + } + + /** 用户使用 IDMUserRecord 调用 profileUnsetById 接口; 期望生成的数据结构符合神策数据格式 */ + @Test + public void checkProfileUnsetById() throws InvalidArgumentException { + IDMUserRecord userRecord = + IDMUserRecord.starter() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, loginId) + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, email) + .build(); + sa.profileUnsetById(userRecord); + assertIDM3UserData(data); } - //正常单个用户标识 - sa.unbind("key1", "value1"); - assertIDM3EventData(data); - - // 无用户标识 - SensorsAnalyticsIdentity noIdentity = SensorsAnalyticsIdentity.builder().build(); - try { - sa.unbind(noIdentity); - fail("生成异常数据!"); - } catch (Exception e) { - assertTrue(e.getMessage().contains("unbind user operation cannot input multiple or none identifiers")); + // ------------------------------------bug fix 3.5.0 begin------------------------------- + + /** + * bug fix : 修复解绑可以传入多个用户ID + * + *

修复后的逻辑为:解绑只可以传入一个用户维度ID + */ + @Test + public void checkUnbind() throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("key1", "value1") + .addIdentityProperty("key2", "value2") + .build(); + try { + sa.unbind(identity); + Assertions.fail("生成异常数据!"); + } catch (InvalidArgumentException e) { + Assertions.assertTrue( + e.getMessage() + .contains( + "unbind user operation cannot input multiple or none identifiers")); + } + + // 正常单个用户标识 + sa.unbind("key1", "value1"); + assertIDM3EventData(data); + + // 无用户标识 + SensorsAnalyticsIdentity noIdentity = SensorsAnalyticsIdentity.builder().build(); + try { + sa.unbind(noIdentity); + Assertions.fail("生成异常数据!"); + } catch (Exception e) { + Assertions.assertTrue( + e.getMessage() + .contains( + "unbind user operation cannot input multiple or none identifiers")); + } } - } - //------------------------------------bug fix 3.5.0 end------------------------------- + // ------------------------------------bug fix 3.5.0 end------------------------------- } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingTrackTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingTrackTest.java index 49c1d31..058b16f 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingTrackTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/IDMappingTrackTest.java @@ -1,25 +1,17 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import com.sensorsdata.analytics.javasdk.bean.IDMEventRecord; import com.sensorsdata.analytics.javasdk.bean.SensorsAnalyticsIdentity; import com.sensorsdata.analytics.javasdk.consumer.DebugConsumer; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Test; - import java.util.Date; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** - * Id-Mapping track 相关接口单元测试 - * 版本支持 3.3.0+ + * Id-Mapping track 相关接口单元测试 版本支持 3.3.0+ * * @author fangzhuo * @version 1.0.0 @@ -27,414 +19,362 @@ */ public class IDMappingTrackTest extends SensorsBaseTest { - /** - *

- * 校验 ID_Mapping trackById 接口,只传入单维度用户属性 - *

- * 期望生成 IDM3.0 数据格式,identities 节点数据和传入的用户维度信息保持一致 - */ - @Test - public void checkIdMappingEvent() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("login_id", "123") - .build(); - Map properties = new HashMap<>(); - properties.put("test", "test"); - properties.put("$project", "abc"); - properties.put("$token", "123"); - sa.trackById(identity, "test", properties); - assertIDM3EventData(data); - assertEquals("test", data.get("event")); - // 在 3.4.1 及以下版本 distinct_id 生成策略都是维度集合中 $identity_login_id 对应的值或者第一个标识对应的值 - // assertEquals("123", data.get("distinct_id")); - // 3.4.2 版本以上 distinct_id 生成策略调整 - assertEquals("login_id+123", data.get("distinct_id")); + /** 校验 ID_Mapping trackById 接口,只传入单维度用户属性 期望生成 IDM3.0 数据格式,identities 节点数据和传入的用户维度信息保持一致 */ + @Test + public void checkIdMappingEvent() throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder().addIdentityProperty("login_id", "123").build(); + Map properties = new HashMap<>(); + properties.put("test", "test"); + properties.put("$project", "abc"); + properties.put("$token", "123"); + sa.trackById(identity, "test", properties); + assertIDM3EventData(data); + Assertions.assertEquals("test", data.get("event")); + // 在 3.4.1 及以下版本 distinct_id 生成策略都是维度集合中 $identity_login_id 对应的值或者第一个标识对应的值 + // Assertions.assertEquals("123", data.get("distinct_id")); + // 3.4.2 版本以上 distinct_id 生成策略调整 + Assertions.assertEquals("login_id+123", data.get("distinct_id")); - Map prop = (Map)data.get("properties"); - assertFalse(data.containsKey("$is_login_id")); - assertNotNull(data.get("properties")); - assertNotNull(data.get("project")); - assertNotNull(data.get("token")); - } - - /** - *

- * 校验 ID_Mapping trackById 接口,只传入多维度用户属性 - *

- * 期望生成 IDM3.0 数据格式,identities 节点数据和传入的用户维度信息保持一致 - */ - @Test - public void checkIdMappingTrackMoreId() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("$identity_mobile", "123") - .addIdentityProperty("$identity_email", "fz@163.com") - .build(); - sa.trackById(identity, "view", null); - assertIDM3EventData(data); - assertTrue(data.get("identities") instanceof Map); - Map result = (Map) data.get("identities"); - assertEquals(2, result.size()); - assertEquals("123", result.get("$identity_mobile")); - assertEquals("fz@163.com", result.get("$identity_email")); - } + Map prop = (Map) data.get("properties"); + Assertions.assertFalse(data.containsKey("$is_login_id")); + Assertions.assertNotNull(data.get("properties")); + Assertions.assertNotNull(data.get("project")); + Assertions.assertNotNull(data.get("token")); + } - /** - *

- * 校验 ID_Mapping bind 接口,只传入多维度用户属性 - *

- * 期望生成 IDM3.0 数据格式,identities 节点数据和传入的用户维度信息保持一致 - */ - @Test - public void checkIdMappingBind() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("$identity_mobile", "123") - .addIdentityProperty("$identity_email", "fz@163.com") - .build(); - sa.bind(identity); - assertIDM3EventData(data); - assertTrue(data.get("identities") instanceof Map); - Map result = (Map) data.get("identities"); - assertEquals(2, result.size()); - assertEquals("123", result.get("$identity_mobile")); - assertEquals("fz@163.com", result.get("$identity_email")); - assertEquals("$BindID", data.get("event")); - assertEquals("track_id_bind", data.get("type")); - } + /** 校验 ID_Mapping trackById 接口,只传入多维度用户属性 期望生成 IDM3.0 数据格式,identities 节点数据和传入的用户维度信息保持一致 */ + @Test + public void checkIdMappingTrackMoreId() throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("$identity_mobile", "123") + .addIdentityProperty("$identity_email", "fz@163.com") + .build(); + sa.trackById(identity, "view", null); + assertIDM3EventData(data); + Assertions.assertTrue(data.get("identities") instanceof Map); + Map result = (Map) data.get("identities"); + Assertions.assertEquals(2, result.size()); + Assertions.assertEquals("123", result.get("$identity_mobile")); + Assertions.assertEquals("fz@163.com", result.get("$identity_email")); + } - /** - *

- * 校验 ID_Mapping bind 接口,只传入单维度用户属性 - *

- * 期望抛出参数不合法异常 - */ - @Test - public void checkIdMappingBindOneId() { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("$identity_mobile", "123") - .build(); - try { - sa.bind(identity); - fail(); - } catch (InvalidArgumentException e) { - assertTrue(true); + /** 校验 ID_Mapping bind 接口,只传入多维度用户属性 期望生成 IDM3.0 数据格式,identities 节点数据和传入的用户维度信息保持一致 */ + @Test + public void checkIdMappingBind() throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("$identity_mobile", "123") + .addIdentityProperty("$identity_email", "fz@163.com") + .build(); + sa.bind(identity); + assertIDM3EventData(data); + Assertions.assertTrue(data.get("identities") instanceof Map); + Map result = (Map) data.get("identities"); + Assertions.assertEquals(2, result.size()); + Assertions.assertEquals("123", result.get("$identity_mobile")); + Assertions.assertEquals("fz@163.com", result.get("$identity_email")); + Assertions.assertEquals("$BindID", data.get("event")); + Assertions.assertEquals("track_id_bind", data.get("type")); } - } - /** - *

- * 校验 ID_Mapping unbind 接口,最终数据格式 - *

- * 期望生成的数据结构中包含预期节点属性 - */ - @Test - public void checkUnbindUserId() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("id_test1", "id_value1") - .build(); - sa.unbind(identity); - assertIDM3EventData(data); - assertTrue(data.get("identities") instanceof Map); - Map result = (Map) data.get("identities"); - assertEquals("id_value1", result.get("id_test1")); - assertEquals("track_id_unbind", data.get("type")); - } + /** 校验 ID_Mapping bind 接口,只传入单维度用户属性 期望抛出参数不合法异常 */ + @Test + public void checkIdMappingBindOneId() { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("$identity_mobile", "123") + .build(); + try { + sa.bind(identity); + Assertions.fail(); + } catch (InvalidArgumentException e) { + Assertions.assertTrue(true); + } + } - /** - *

- * 校验 ID_Mapping trackById 接口,设置公共属性,最终事件中是否存在公共属性 - *

- * 期望生成的数据结构中存在公共属性 - */ - @Test - public void checkTrackByIdSuperProperties() throws InvalidArgumentException { - Map properties = new HashMap<>(); - properties.put("asd", "123"); - sa.registerSuperProperties(properties); - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("id_test1", "id_value1") - .build(); - sa.trackById(identity, "eee", null); - assertTrue(data.get("properties") instanceof Map); - Map result = (Map) data.get("properties"); - assertEquals("123", result.get("asd")); - } + /** 校验 ID_Mapping unbind 接口,最终数据格式 期望生成的数据结构中包含预期节点属性 */ + @Test + public void checkUnbindUserId() throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("id_test1", "id_value1") + .build(); + sa.unbind(identity); + assertIDM3EventData(data); + Assertions.assertTrue(data.get("identities") instanceof Map); + Map result = (Map) data.get("identities"); + Assertions.assertEquals("id_value1", result.get("id_test1")); + Assertions.assertEquals("track_id_unbind", data.get("type")); + } - /** - *

- * 校验 ID_Mapping bind 接口,设置公共属性,最终事件中是否存在公共属性 - *

- * 期望生成的数据结构中存在公共属性 - */ - @Test - public void checkBindSuperProperties() throws InvalidArgumentException { - Map properties = new HashMap<>(); - properties.put("asd", "123"); - sa.registerSuperProperties(properties); - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("id_test1", "id_value1") - .addIdentityProperty("eee", "123") - .build(); - sa.bind(identity); - assertTrue(data.get("properties") instanceof Map); - Map result = (Map) data.get("properties"); - assertEquals("123", result.get("asd")); - } + /** 校验 ID_Mapping trackById 接口,设置公共属性,最终事件中是否存在公共属性 期望生成的数据结构中存在公共属性 */ + @Test + public void checkTrackByIdSuperProperties() throws InvalidArgumentException { + Map properties = new HashMap<>(); + properties.put("asd", "123"); + sa.registerSuperProperties(properties); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("id_test1", "id_value1") + .build(); + sa.trackById(identity, "eee", null); + Assertions.assertTrue(data.get("properties") instanceof Map); + Map result = (Map) data.get("properties"); + Assertions.assertEquals("123", result.get("asd")); + } - /** - *

- * 校验 ID_Mapping unbind 接口,设置公共属性,最终事件中是否存在公共属性 - *

- * 期望生成的数据结构中存在公共属性 - */ - @Test - public void checkUnbindSuperProperties() throws InvalidArgumentException { - Map properties = new HashMap<>(); - properties.put("asd", "123"); - sa.registerSuperProperties(properties); - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("id_test1", "id_value1") - .build(); - sa.unbind(identity); - assertTrue(data.get("properties") instanceof Map); - Map result = (Map) data.get("properties"); - assertEquals("123", result.get("asd")); - } + /** 校验 ID_Mapping bind 接口,设置公共属性,最终事件中是否存在公共属性 期望生成的数据结构中存在公共属性 */ + @Test + public void checkBindSuperProperties() throws InvalidArgumentException { + Map properties = new HashMap<>(); + properties.put("asd", "123"); + sa.registerSuperProperties(properties); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("id_test1", "id_value1") + .addIdentityProperty("eee", "123") + .build(); + sa.bind(identity); + Assertions.assertTrue(data.get("properties") instanceof Map); + Map result = (Map) data.get("properties"); + Assertions.assertEquals("123", result.get("asd")); + } - /** - *

- * 用户维度标识携带 $identity_login_id 再调用 trackById 接口。生成事件; - *

- * 期望生成的数据结构中 distinct_id 为 $identity_login_id 对应的 value - */ - @Test - public void checkTrackByIdWithLoginId() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "fz123") - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") - .build(); - sa.trackById(identity, "test", null); - assertIDM3EventData(data); - assertDataLib(data.get("lib")); - assertEquals("fz123", data.get("distinct_id")); - } + /** 校验 ID_Mapping unbind 接口,设置公共属性,最终事件中是否存在公共属性 期望生成的数据结构中存在公共属性 */ + @Test + public void checkUnbindSuperProperties() throws InvalidArgumentException { + Map properties = new HashMap<>(); + properties.put("asd", "123"); + sa.registerSuperProperties(properties); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("id_test1", "id_value1") + .build(); + sa.unbind(identity); + Assertions.assertTrue(data.get("properties") instanceof Map); + Map result = (Map) data.get("properties"); + Assertions.assertEquals("123", result.get("asd")); + } - //----------------------3.4.2-------------------------- + /** + * 用户维度标识携带 $identity_login_id 再调用 trackById 接口。生成事件; 期望生成的数据结构中 distinct_id 为 + * $identity_login_id 对应的 value + */ + @Test + public void checkTrackByIdWithLoginId() throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "fz123") + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") + .build(); + sa.trackById(identity, "test", null); + assertIDM3EventData(data); + assertDataLib(data.get("lib")); + Assertions.assertEquals("fz123", data.get("distinct_id")); + } - /** - *

- * 用户维度标识不携带 $identity_login_id 再调用 trackById 接口。生成事件; - *

- * 期望生成的数据结构中 distinct_id 为维度集合中第一个标识 key+value - */ - @Test - public void checkTrackByIdWithoutLoginId() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("login_id", "fz123") - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") - .build(); - sa.trackById(identity, "test", null); - assertIDM3EventData(data); - assertDataLib(data.get("lib")); - assertEquals("login_id+fz123", data.get("distinct_id")); - } + // ----------------------3.4.2-------------------------- - /** - *

- * 用户维度标识携带 $identity_login_id,并且指定 distinctId; 使用 IDMEventRecord 调用 trackById 接口。生成事件; - *

- * 期望生成的数据结构中 distinct_id 为指定的 distinctId 对应的 value - */ - @Test - public void checkEventRecordWithLoginId() throws InvalidArgumentException { - IDMEventRecord eventRecord = IDMEventRecord.starter() - .setDistinctId("zzz") - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "fz123") - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") - .setEventName("test") - .addProperty("eee", "rrr") - .build(); - sa.trackById(eventRecord); - assertIDM3EventData(data); - assertEquals("zzz", data.get("distinct_id")); - } + /** + * 用户维度标识不携带 $identity_login_id 再调用 trackById 接口。生成事件; 期望生成的数据结构中 distinct_id 为维度集合中第一个标识 + * key+value + */ + @Test + public void checkTrackByIdWithoutLoginId() throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("login_id", "fz123") + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") + .build(); + sa.trackById(identity, "test", null); + assertIDM3EventData(data); + assertDataLib(data.get("lib")); + Assertions.assertEquals("login_id+fz123", data.get("distinct_id")); + } - /** - *

- * 用户维度标识不携带 $identity_login_id 使用 IDMEventRecord 调用 trackById 接口。生成事件; - *

- * 期望生成的数据结构中 distinct_id 为多维度标识集合中第一个 - */ - @Test - public void checkEventRecordWithoutLoginId() throws InvalidArgumentException { - IDMEventRecord eventRecord = IDMEventRecord.starter() - .addIdentityProperty("login_id", "fz123") - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") - .setEventName("test") - .addProperty("eee", "rrr") - .build(); - sa.trackById(eventRecord); - assertIDM3EventData(data); - assertEquals("login_id+fz123", data.get("distinct_id")); - } + /** + * 用户维度标识携带 $identity_login_id,并且指定 distinctId; 使用 IDMEventRecord 调用 trackById 接口。生成事件; + * 期望生成的数据结构中 distinct_id 为指定的 distinctId 对应的 value + */ + @Test + public void checkEventRecordWithLoginId() throws InvalidArgumentException { + IDMEventRecord eventRecord = + IDMEventRecord.starter() + .setDistinctId("zzz") + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "fz123") + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") + .setEventName("test") + .addProperty("eee", "rrr") + .build(); + sa.trackById(eventRecord); + assertIDM3EventData(data); + Assertions.assertEquals("zzz", data.get("distinct_id")); + } - /** - *

- * 用户维度标识不携带 $identity_login_id,传入 distinctId; 使用 IDMEventRecord 调用 trackById 接口。生成事件; - *

- * 期望生成的数据结构中 distinct_id 为 distinctId 对应的 value - */ - @Test - public void checkEventRecordWithoutLoginId1() throws InvalidArgumentException { - IDMEventRecord eventRecord = IDMEventRecord.starter() - .setDistinctId("zzz") - .addIdentityProperty("login_id", "fz123") - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") - .setEventName("test") - .addProperty("eee", "rrr") - .build(); - sa.trackById(eventRecord); - assertIDM3EventData(data); - assertEquals("zzz", data.get("distinct_id")); - } + /** + * 用户维度标识不携带 $identity_login_id 使用 IDMEventRecord 调用 trackById 接口。生成事件; 期望生成的数据结构中 distinct_id + * 为多维度标识集合中第一个 + */ + @Test + public void checkEventRecordWithoutLoginId() throws InvalidArgumentException { + IDMEventRecord eventRecord = + IDMEventRecord.starter() + .addIdentityProperty("login_id", "fz123") + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") + .setEventName("test") + .addProperty("eee", "rrr") + .build(); + sa.trackById(eventRecord); + assertIDM3EventData(data); + Assertions.assertEquals("login_id+fz123", data.get("distinct_id")); + } - /** - *

- * 用户维度标识携带 $identity_login_id 使用 IDMEventRecord 调用 bind 接口。生成事件; - *

- * 期望生成的数据结构中 distinct_id 为 $identity_login_id 对应的 value - */ - @Test - public void checkEventRecordBindWithLoginId() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "fz123") - .build(); - sa.bind(identity); - assertIDM3EventData(data); - assertEquals("fz123", data.get("distinct_id")); - } + /** + * 用户维度标识不携带 $identity_login_id,传入 distinctId; 使用 IDMEventRecord 调用 trackById 接口。生成事件; + * 期望生成的数据结构中 distinct_id 为 distinctId 对应的 value + */ + @Test + public void checkEventRecordWithoutLoginId1() throws InvalidArgumentException { + IDMEventRecord eventRecord = + IDMEventRecord.starter() + .setDistinctId("zzz") + .addIdentityProperty("login_id", "fz123") + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") + .setEventName("test") + .addProperty("eee", "rrr") + .build(); + sa.trackById(eventRecord); + assertIDM3EventData(data); + Assertions.assertEquals("zzz", data.get("distinct_id")); + } - /** - *

- * 用户维度标识不携带 $identity_login_id 使用 IDMEventRecord 调用 bind 接口。生成事件; - *

- * 期望生成的数据结构中 distinct_id 为多维度集合中多第一个标识 key+value - */ - @Test - public void checkEventRecordBindWithoutLoginId() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("login_id", "fz123") - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") - .build(); - sa.bind(identity); - assertIDM3EventData(data); - assertEquals("login_id+fz123", data.get("distinct_id")); - } + /** + * 用户维度标识携带 $identity_login_id 使用 IDMEventRecord 调用 bind 接口。生成事件; 期望生成的数据结构中 distinct_id 为 + * $identity_login_id 对应的 value + */ + @Test + public void checkEventRecordBindWithLoginId() throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "fz123") + .build(); + sa.bind(identity); + assertIDM3EventData(data); + Assertions.assertEquals("fz123", data.get("distinct_id")); + } - /** - *

- * 用户维度标识携带 $identity_login_id 使用 IDMEventRecord 调用 unbind 接口。生成事件; - *

- * 期望生成的数据结构中 distinct_id 为 $identity_login_id 对应的 value - */ - @Test - public void checkEventRecordUnbindWithLoginId() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "fz123") - .build(); - sa.unbind(identity); - assertIDM3EventData(data); - assertEquals("fz123", data.get("distinct_id")); - } + /** + * 用户维度标识不携带 $identity_login_id 使用 IDMEventRecord 调用 bind 接口。生成事件; 期望生成的数据结构中 distinct_id + * 为多维度集合中多第一个标识 key+value + */ + @Test + public void checkEventRecordBindWithoutLoginId() throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("login_id", "fz123") + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") + .build(); + sa.bind(identity); + assertIDM3EventData(data); + Assertions.assertEquals("login_id+fz123", data.get("distinct_id")); + } - /** - *

- * 用户维度标识不携带 $identity_login_id 使用 IDMEventRecord 调用 unbind 接口。生成事件; - *

- * 期望生成的数据结构中 distinct_id 为多维度集合中多第一个标识 key+value - */ - @Test - public void checkEventRecordUnbindWithoutLoginId() throws InvalidArgumentException { - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("login_id", "fz123") - .build(); - sa.unbind(identity); - assertIDM3EventData(data); - assertEquals("login_id+fz123", data.get("distinct_id")); - } + /** + * 用户维度标识携带 $identity_login_id 使用 IDMEventRecord 调用 unbind 接口。生成事件; 期望生成的数据结构中 distinct_id 为 + * $identity_login_id 对应的 value + */ + @Test + public void checkEventRecordUnbindWithLoginId() throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "fz123") + .build(); + sa.unbind(identity); + assertIDM3EventData(data); + Assertions.assertEquals("fz123", data.get("distinct_id")); + } - /** - *

- * 用户维度标识携带 $project,$token,$time 使用 IDMEventRecord 调用 trackById 接口。生成事件; - *

- * 期望生成的数据结构中,外层数据携带 project,token,time 节点;内层 properties 不携带相关参数 - */ - @Test - public void checkEventRecordWithPresetProperty() throws InvalidArgumentException { - Date time = new Date(); - IDMEventRecord eventRecord = IDMEventRecord.starter() - .addIdentityProperty("login_id", "fz123") - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") - .setEventName("test") - .addProperty("$project", "test") - .addProperty("$token", "er4eee") - .addProperty("$time", time) - .build(); - sa.trackById(eventRecord); - assertIDM3EventData(data); - assertEquals(time.getTime(), data.get("time")); - assertTrue(data.containsKey("project")); - assertEquals("test", data.get("project")); - assertTrue(data.containsKey("token")); - assertEquals("er4eee", data.get("token")); - final Map properties = (Map) data.get("properties"); - assertFalse(properties.containsKey("$project")); - assertFalse(properties.containsKey("$token")); - assertFalse(properties.containsKey("$time")); - } + /** + * 用户维度标识不携带 $identity_login_id 使用 IDMEventRecord 调用 unbind 接口。生成事件; 期望生成的数据结构中 distinct_id + * 为多维度集合中多第一个标识 key+value + */ + @Test + public void checkEventRecordUnbindWithoutLoginId() throws InvalidArgumentException { + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder().addIdentityProperty("login_id", "fz123").build(); + sa.unbind(identity); + assertIDM3EventData(data); + Assertions.assertEquals("login_id+fz123", data.get("distinct_id")); + } - /** - *

- * 用户构建的数据属性集合,使用 IDMEventRecord 调用 track 接口,SDK 处理之后并不删除用户的集合节点信息; - *

- * 期望生成的数据结构符合神策数据格式,并且外部的集合节点不改变 - */ - @Test - public void checkTrackEventDontDeleteMapNode() throws InvalidArgumentException { - Map propertiesMap = new HashMap<>(); - propertiesMap.put("hello", "fz"); - propertiesMap.put("$token", "er4eee"); - propertiesMap.put("$project", "test"); - IDMEventRecord eventRecord = IDMEventRecord.starter() - .addIdentityProperty("login_id", "fz123") - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") - .setEventName("test") - .addProperty("haha", "test") - .addProperties(propertiesMap) - .build(); - sa.trackById(eventRecord); - assertIDM3EventData(data); - assertTrue(propertiesMap.containsKey("hello")); - assertTrue(propertiesMap.containsKey("$token")); - assertTrue(propertiesMap.containsKey("$project")); - } + /** + * 用户维度标识携带 $project,$token,$time 使用 IDMEventRecord 调用 trackById 接口。生成事件; 期望生成的数据结构中,外层数据携带 + * project,token,time 节点;内层 properties 不携带相关参数 + */ + @Test + public void checkEventRecordWithPresetProperty() throws InvalidArgumentException { + Date time = new Date(); + IDMEventRecord eventRecord = + IDMEventRecord.starter() + .addIdentityProperty("login_id", "fz123") + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") + .setEventName("test") + .addProperty("$project", "test") + .addProperty("$token", "er4eee") + .addProperty("$time", time) + .build(); + sa.trackById(eventRecord); + assertIDM3EventData(data); + Assertions.assertEquals(time.getTime(), data.get("time")); + Assertions.assertTrue(data.containsKey("project")); + Assertions.assertEquals("test", data.get("project")); + Assertions.assertTrue(data.containsKey("token")); + Assertions.assertEquals("er4eee", data.get("token")); + final Map properties = (Map) data.get("properties"); + Assertions.assertFalse(properties.containsKey("$project")); + Assertions.assertFalse(properties.containsKey("$token")); + Assertions.assertFalse(properties.containsKey("$time")); + } - /** - *

- * 用户构建的数据属性集合,使用 IDMEventRecord 调用 track 接口,使用 debug 模式上报; - *

- * 期望生成的数据结构符合神策数据格式,并且服务端校验通过 - */ - @Test - public void checkTrackEventWithNet() throws InvalidArgumentException { - SensorsAnalytics sensors = new SensorsAnalytics(new DebugConsumer(url, true)); - IDMEventRecord eventRecord = IDMEventRecord.starter() - .addIdentityProperty("login_id", "fz123") - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") - .setEventName("test") - .addProperty("haha", "test") - .build(); - sensors.trackById(eventRecord); - } + /** + * 用户构建的数据属性集合,使用 IDMEventRecord 调用 track 接口,SDK 处理之后并不删除用户的集合节点信息; + * 期望生成的数据结构符合神策数据格式,并且外部的集合节点不改变 + */ + @Test + public void checkTrackEventDontDeleteMapNode() throws InvalidArgumentException { + Map propertiesMap = new HashMap<>(); + propertiesMap.put("hello", "fz"); + propertiesMap.put("$token", "er4eee"); + propertiesMap.put("$project", "test"); + IDMEventRecord eventRecord = + IDMEventRecord.starter() + .addIdentityProperty("login_id", "fz123") + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") + .setEventName("test") + .addProperty("haha", "test") + .addProperties(propertiesMap) + .build(); + sa.trackById(eventRecord); + assertIDM3EventData(data); + Assertions.assertTrue(propertiesMap.containsKey("hello")); + Assertions.assertTrue(propertiesMap.containsKey("$token")); + Assertions.assertTrue(propertiesMap.containsKey("$project")); + } + /** 用户构建的数据属性集合,使用 IDMEventRecord 调用 track 接口,使用 debug 模式上报; 期望生成的数据结构符合神策数据格式,并且服务端校验通过 */ + @Test + public void checkTrackEventWithNet() throws InvalidArgumentException { + SensorsAnalytics sensors = new SensorsAnalytics(new DebugConsumer(url, true)); + IDMEventRecord eventRecord = + IDMEventRecord.starter() + .addIdentityProperty("login_id", "fz123") + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") + .setEventName("test") + .addProperty("haha", "test") + .build(); + sensors.trackById(eventRecord); + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/InstantEventTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/InstantEventTest.java index 5e5dbde..1fedf46 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/InstantEventTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/InstantEventTest.java @@ -2,149 +2,219 @@ import com.sensorsdata.analytics.javasdk.bean.EventRecord; import com.sensorsdata.analytics.javasdk.bean.FailedData; -import com.sensorsdata.analytics.javasdk.bean.schema.ItemEventSchema; import com.sensorsdata.analytics.javasdk.consumer.BatchConsumer; import com.sensorsdata.analytics.javasdk.consumer.Callback; import com.sensorsdata.analytics.javasdk.consumer.FastBatchConsumer; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import lombok.NonNull; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; -import org.eclipse.jetty.client.HttpClient; -import org.junit.Assert; -import org.junit.Test; - import java.util.Arrays; +import org.apache.http.impl.client.HttpClients; +import org.junit.jupiter.api.Test; public class InstantEventTest extends SensorsBaseTest { - private static final String SCHEMA = "product_event"; - - private static final String EVENT_NAME = "cart"; - public void initBatchConsumer() { - BatchConsumer bc = new BatchConsumer("http://localhost:8888/instant", 50, 0, true, 3, Arrays.asList("test1", "test4")); - sa = new SensorsAnalytics(bc); - data = null; - res.clear(); - } + private static final String SCHEMA = "product_event"; - @Test - public void checkBatchConsumer() throws InvalidArgumentException { - initBatchConsumer(); - EventRecord event1 = EventRecord.builder().setEventName("test1").setDistinctId("1234").isLoginId(false).build(); - EventRecord event2 = EventRecord.builder().setEventName("test2").setDistinctId("1234").isLoginId(false).build(); - EventRecord event3 = EventRecord.builder().setEventName("test3").setDistinctId("1234").isLoginId(false).build(); - EventRecord event4 = EventRecord.builder().setEventName("test4").setDistinctId("1234").isLoginId(false).build(); - EventRecord event5 = EventRecord.builder().setEventName("test5").setDistinctId("1234").isLoginId(false).build(); + private static final String EVENT_NAME = "cart"; - sa.track(event1); + public void initBatchConsumer() { + BatchConsumer bc = + new BatchConsumer( + "http://localhost:8888/instant", + 50, + 0, + true, + 3, + Arrays.asList("test1", "test4")); + sa = new SensorsAnalytics(bc); + data = null; + res.clear(); + } - sa.flush(); - sa.track(event2); - sa.track(event3); - sa.track(event4); - sa.track(event5); - sa.flush(); + @Test + public void checkBatchConsumer() throws InvalidArgumentException { + initBatchConsumer(); + EventRecord event1 = + EventRecord.builder() + .setEventName("test1") + .setDistinctId("1234") + .isLoginId(false) + .build(); + EventRecord event2 = + EventRecord.builder() + .setEventName("test2") + .setDistinctId("1234") + .isLoginId(false) + .build(); + EventRecord event3 = + EventRecord.builder() + .setEventName("test3") + .setDistinctId("1234") + .isLoginId(false) + .build(); + EventRecord event4 = + EventRecord.builder() + .setEventName("test4") + .setDistinctId("1234") + .isLoginId(false) + .build(); + EventRecord event5 = + EventRecord.builder() + .setEventName("test5") + .setDistinctId("1234") + .isLoginId(false) + .build(); - } + sa.track(event1); - public void initFastBatchConsumer() { - FastBatchConsumer bc = new FastBatchConsumer(HttpClients.custom(), "http://localhost:8888/instant", - false , 50, 0, 3, 3, new Callback() { - @Override - public void onFailed(FailedData failedData) { - SensorsLogsUtil.setFailedData(failedData); - } - }, Arrays.asList("test1", "test4")); - sa = new SensorsAnalytics(bc); - data = null; - res.clear(); - } + sa.flush(); + sa.track(event2); + sa.track(event3); + sa.track(event4); + sa.track(event5); + sa.flush(); + } - @Test - public void checkFastBatchConsumer() throws InvalidArgumentException { - initFastBatchConsumer(); - EventRecord event1 = EventRecord.builder().setEventName("test1").setDistinctId("1234").isLoginId(false).build(); - EventRecord event2 = EventRecord.builder().setEventName("test2").setDistinctId("1234").isLoginId(false).build(); - EventRecord event3 = EventRecord.builder().setEventName("test3").setDistinctId("1234").isLoginId(false).build(); - EventRecord event4 = EventRecord.builder().setEventName("test4").setDistinctId("1234").isLoginId(false).build(); - EventRecord event5 = EventRecord.builder().setEventName("test5").setDistinctId("1234").isLoginId(false).build(); + public void initFastBatchConsumer() { + FastBatchConsumer bc = + new FastBatchConsumer( + HttpClients.custom(), + "http://localhost:8888/instant", + false, + 50, + 0, + 3, + 3, + new Callback() { + @Override + public void onFailed(FailedData failedData) { + SensorsLogsUtil.setFailedData(failedData); + } + }, + Arrays.asList("test1", "test4")); + sa = new SensorsAnalytics(bc); + data = null; + res.clear(); + } - sa.track(event1); + @Test + public void checkFastBatchConsumer() throws InvalidArgumentException { + initFastBatchConsumer(); + EventRecord event1 = + EventRecord.builder() + .setEventName("test1") + .setDistinctId("1234") + .isLoginId(false) + .build(); + EventRecord event2 = + EventRecord.builder() + .setEventName("test2") + .setDistinctId("1234") + .isLoginId(false) + .build(); + EventRecord event3 = + EventRecord.builder() + .setEventName("test3") + .setDistinctId("1234") + .isLoginId(false) + .build(); + EventRecord event4 = + EventRecord.builder() + .setEventName("test4") + .setDistinctId("1234") + .isLoginId(false) + .build(); + EventRecord event5 = + EventRecord.builder() + .setEventName("test5") + .setDistinctId("1234") + .isLoginId(false) + .build(); - sa.flush(); - sa.track(event2); - sa.track(event3); - sa.track(event4); - sa.track(event5); - sa.flush(); + sa.track(event1); - } -// -// public void initRemoteBatchConsumer() { -// FastBatchConsumer bc = new FastBatchConsumer(HttpClients.custom(), "http://10.120.213.104:8106/sa?project=default", -// false , 50, 0, 3, 3, new Callback() { -// @Override -// public void onFailed(FailedData failedData) { -// SensorsLogsUtil.setFailedData(failedData); -// } -// }, Arrays.asList("JavaSDKInstantEvent")); -// sa = new SensorsAnalytics(bc); -// data = null; -// res.clear(); -// } -// -// @Test -// public void checkRemoteBatchConsumer() throws InvalidArgumentException { -// initRemoteBatchConsumer(); -// EventRecord event1 = EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); -// EventRecord event2 = EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); -// EventRecord event3 = EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); -// EventRecord event4 = EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); -// EventRecord event5 = EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); -// -// sa.track(event1); -// -// sa.flush(); -// sa.track(event2); -// sa.track(event3); -// sa.track(event4); -// sa.track(event5); -// sa.flush(); -// -// } -// -// public void initRemoteFastBatchConsumer() { -// FastBatchConsumer bc = new FastBatchConsumer(HttpClients.custom(), "http://10.120.213.104:8106/sa?project=default", -// false , 50, 0, 3, 3, new Callback() { -// @Override -// public void onFailed(FailedData failedData) { -// SensorsLogsUtil.setFailedData(failedData); -// } -// }, Arrays.asList("JavaSDKInstantEvent")); -// sa = new SensorsAnalytics(bc); -// data = null; -// res.clear(); -// } -// -// @Test -// public void checkRemoteFastBatchConsumer() throws InvalidArgumentException { -// initRemoteFastBatchConsumer(); -// EventRecord event1 = EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); -// EventRecord event2 = EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); -// EventRecord event3 = EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); -// EventRecord event4 = EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); -// EventRecord event5 = EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); -// -// sa.track(event1); -// -// sa.flush(); -// sa.track(event2); -// sa.track(event3); -// sa.track(event4); -// sa.track(event5); -// sa.flush(); -// -// } + sa.flush(); + sa.track(event2); + sa.track(event3); + sa.track(event4); + sa.track(event5); + sa.flush(); + } + // + // public void initRemoteBatchConsumer() { + // FastBatchConsumer bc = new FastBatchConsumer(HttpClients.custom(), + // "http://10.120.213.104:8106/sa?project=default", + // false , 50, 0, 3, 3, new Callback() { + // @Override + // public void onFailed(FailedData failedData) { + // SensorsLogsUtil.setFailedData(failedData); + // } + // }, Arrays.asList("JavaSDKInstantEvent")); + // sa = new SensorsAnalytics(bc); + // data = null; + // res.clear(); + // } + // + // @Test + // public void checkRemoteBatchConsumer() throws InvalidArgumentException { + // initRemoteBatchConsumer(); + // EventRecord event1 = + // EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); + // EventRecord event2 = + // EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); + // EventRecord event3 = + // EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); + // EventRecord event4 = + // EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); + // EventRecord event5 = + // EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); + // + // sa.track(event1); + // + // sa.flush(); + // sa.track(event2); + // sa.track(event3); + // sa.track(event4); + // sa.track(event5); + // sa.flush(); + // + // } + // + // public void initRemoteFastBatchConsumer() { + // FastBatchConsumer bc = new FastBatchConsumer(HttpClients.custom(), + // "http://10.120.213.104:8106/sa?project=default", + // false , 50, 0, 3, 3, new Callback() { + // @Override + // public void onFailed(FailedData failedData) { + // SensorsLogsUtil.setFailedData(failedData); + // } + // }, Arrays.asList("JavaSDKInstantEvent")); + // sa = new SensorsAnalytics(bc); + // data = null; + // res.clear(); + // } + // + // @Test + // public void checkRemoteFastBatchConsumer() throws InvalidArgumentException { + // initRemoteFastBatchConsumer(); + // EventRecord event1 = + // EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); + // EventRecord event2 = + // EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); + // EventRecord event3 = + // EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); + // EventRecord event4 = + // EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); + // EventRecord event5 = + // EventRecord.builder().setEventName("JavaSDKInstantEvent").setDistinctId("o826p5zjQny5wKCAxRWss9bzWmlI").addProperty("myname", "qinglintest").isLoginId(false).build(); + // + // sa.track(event1); + // + // sa.flush(); + // sa.track(event2); + // sa.track(event3); + // sa.track(event4); + // sa.track(event5); + // sa.flush(); + // + // } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/InstantServlet.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/InstantServlet.java index b2d0453..7921824 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/InstantServlet.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/InstantServlet.java @@ -1,30 +1,14 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; -import org.junit.Assert; -import sun.misc.BASE64Decoder; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.util.zip.GZIPInputStream; - -import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class InstantServlet extends TestServlet { - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { - super.doPost(request, response); - System.out.println(request.getParameter("instant_event")); - } - + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws IOException { + super.doPost(request, response); + System.out.println(request.getParameter("instant_event")); + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/NormalModelTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/NormalModelTest.java index 70ef3c9..03eebfc 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/NormalModelTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/NormalModelTest.java @@ -1,21 +1,15 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - import com.sensorsdata.analytics.javasdk.bean.EventRecord; import com.sensorsdata.analytics.javasdk.bean.UserRecord; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Test; - import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * 普通模式校验 @@ -26,99 +20,91 @@ */ public class NormalModelTest extends SensorsBaseTest { - /** - * 校验调用 track 方法生成事件节点数是否完整 - */ - @Test - public void checkTrackEvent() throws InvalidArgumentException { - Map properties = new HashMap<>(); - properties.put("test", "test"); - properties.put("$project", "abc"); - properties.put("$token", "123"); - sa.track("123", true, "test", properties); - assertEventData(data); - } - - /** - * 校验 event Builder 模式生成数据用户属性是否正常 - */ - @Test - public void checkTrackEventBuilder() throws InvalidArgumentException { - EventRecord eventRecord = EventRecord.builder() - .setDistinctId("abc") - .isLoginId(false) - .setEventName("test") - .build(); - sa.track(eventRecord); - assertEquals("abc", data.get("distinct_id")); - assertNull(data.get("$is_login_id")); - Map result = (Map) data.get("properties"); - assertNull(result.get("$is_login_id")); - } + /** 校验调用 track 方法生成事件节点数是否完整 */ + @Test + public void checkTrackEvent() throws InvalidArgumentException { + Map properties = new HashMap<>(); + properties.put("test", "test"); + properties.put("$project", "abc"); + properties.put("$token", "123"); + sa.track("123", true, "test", properties); + assertEventData(data); + } - /** - * 校验 is_login_id 为 true 的事件属性 - */ - @Test - public void checkTrackEventBuilderLoginIdIsTrue() throws InvalidArgumentException { - EventRecord eventRecord = EventRecord.builder() - .setDistinctId("abc") - .isLoginId(true) - .setEventName("test") - .build(); - sa.track(eventRecord); - assertEquals("abc", data.get("distinct_id")); - assertNull(data.get("$is_login_id")); - Map result = (Map) data.get("properties"); - assertTrue((Boolean) result.get("$is_login_id")); - } + /** 校验 event Builder 模式生成数据用户属性是否正常 */ + @Test + public void checkTrackEventBuilder() throws InvalidArgumentException { + EventRecord eventRecord = + EventRecord.builder() + .setDistinctId("abc") + .isLoginId(false) + .setEventName("test") + .build(); + sa.track(eventRecord); + Assertions.assertEquals("abc", data.get("distinct_id")); + Assertions.assertNull(data.get("$is_login_id")); + Map result = (Map) data.get("properties"); + Assertions.assertNull(result.get("$is_login_id")); + } - /** - * 校验自定义属性格式是否正常 - */ - @Test - public void checkProfileSetDataType() throws InvalidArgumentException { - List list = new ArrayList<>(); - Date date = new Date(); - list.add("aaa"); - list.add("bbb"); - UserRecord userRecord = UserRecord.builder() - .setDistinctId("123") - .isLoginId(true) - .addProperty("number1", 1234) - .addProperty("date1", date) - .addProperty("String1", "str") - .addProperty("boolean1", false) - .addProperty("list1", list) - .build(); - sa.profileSet(userRecord); - Map result = (Map) data.get("properties"); - assertEquals(1234, result.get("number1")); - assertEquals(date, result.get("date1")); - assertEquals("str", result.get("String1")); - assertFalse((Boolean) result.get("boolean1")); - assertTrue(result.get("list1") instanceof List); - } + /** 校验 is_login_id 为 true 的事件属性 */ + @Test + public void checkTrackEventBuilderLoginIdIsTrue() throws InvalidArgumentException { + EventRecord eventRecord = + EventRecord.builder() + .setDistinctId("abc") + .isLoginId(true) + .setEventName("test") + .build(); + sa.track(eventRecord); + Assertions.assertEquals("abc", data.get("distinct_id")); + Assertions.assertNull(data.get("$is_login_id")); + Map result = (Map) data.get("properties"); + Assertions.assertTrue((Boolean) result.get("$is_login_id")); + } - /** - * 校验 trackSignup 记录节点 - */ - @Test - public void checkTrackSignUp() throws InvalidArgumentException { - sa.trackSignUp("123", "345"); - assertEventData(data); - } + /** 校验自定义属性格式是否正常 */ + @Test + public void checkProfileSetDataType() throws InvalidArgumentException { + List list = new ArrayList<>(); + Date date = new Date(); + list.add("aaa"); + list.add("bbb"); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("123") + .isLoginId(true) + .addProperty("number1", 1234) + .addProperty("date1", date) + .addProperty("String1", "str") + .addProperty("boolean1", false) + .addProperty("list1", list) + .build(); + sa.profileSet(userRecord); + Map result = (Map) data.get("properties"); + Assertions.assertEquals(1234, result.get("number1")); + Assertions.assertEquals(date, result.get("date1")); + Assertions.assertEquals("str", result.get("String1")); + Assertions.assertFalse((Boolean) result.get("boolean1")); + Assertions.assertTrue(result.get("list1") instanceof List); + } - @Test - public void checkCommonProperties() throws InvalidArgumentException { - Map map = new HashMap<>(); - map.put("key1", "value1"); - sa.registerSuperProperties(map); - Map properties = new HashMap<>(); - properties.put("key1", "value2"); - sa.track("123", true, "test1", properties); - assertEventData(data); - assertEquals("value2", ((Map) data.get("properties")).get("key1").toString()); - } + /** 校验 trackSignup 记录节点 */ + @Test + public void checkTrackSignUp() throws InvalidArgumentException { + sa.trackSignUp("123", "345"); + assertEventData(data); + } + @Test + public void checkCommonProperties() throws InvalidArgumentException { + Map map = new HashMap<>(); + map.put("key1", "value1"); + sa.registerSuperProperties(map); + Map properties = new HashMap<>(); + properties.put("key1", "value2"); + sa.track("123", true, "test1", properties); + assertEventData(data); + Assertions.assertEquals("value2", ((Map) data.get("properties")).get("key1").toString()); + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaDetailTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaDetailTest.java index fa5228a..e4291e5 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaDetailTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaDetailTest.java @@ -1,20 +1,17 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - import com.sensorsdata.analytics.javasdk.bean.SensorsAnalyticsIdentity; import com.sensorsdata.analytics.javasdk.bean.schema.DetailSchema; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Test; - import java.util.Date; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * detail 明细数据单元测试 - *

v3.6.3+ 版本开始支持

+ * + *

v3.6.3+ 版本开始支持 * * @author fangzhuo * @version 1.0.0 @@ -22,119 +19,133 @@ */ public class SchemaDetailTest extends SensorsBaseTest { - /** - * 测试 detail schema 数据生成逻辑是否正确 - */ - @Test - public void checkDetailSet() throws InvalidArgumentException { - DetailSchema detailSchema = - DetailSchema.init().setSchema("test").setDetailId("ee").addProperty("key1", "value1").start(); - sa.detailSet(detailSchema); - assertSchemaDataNode(data); - } + /** 测试 detail schema 数据生成逻辑是否正确 */ + @Test + public void checkDetailSet() throws InvalidArgumentException { + DetailSchema detailSchema = + DetailSchema.init() + .setSchema("test") + .setDetailId("ee") + .addProperty("key1", "value1") + .start(); + sa.detailSet(detailSchema); + assertSchemaDataNode(data); + } - /** - * 测试用户实体明细数据生成逻辑是否正常 - */ - @Test - public void checkUserDetailSet() throws InvalidArgumentException { - SensorsAnalyticsIdentity sensorsIdentities = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("user_key1", "user_value1") - .addIdentityProperty("user_key2", "user_value2") - .build(); - DetailSchema detailSchema = DetailSchema.init().setSchema("test").setDetailId("ee") - .identityMap(sensorsIdentities.getIdentityMap()) - .addProperty("key1", "value1") - .addProperty("key2", new Date()) - .start(); - sa.detailSet(detailSchema); - assertSchemaDataNode(data); - Object distinctId = ((Map) data.get("properties")).get("distinct_id"); - assertEquals("user_key1+user_value1", distinctId); - } + /** 测试用户实体明细数据生成逻辑是否正常 */ + @Test + public void checkUserDetailSet() throws InvalidArgumentException { + SensorsAnalyticsIdentity sensorsIdentities = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("user_key1", "user_value1") + .addIdentityProperty("user_key2", "user_value2") + .build(); + DetailSchema detailSchema = + DetailSchema.init() + .setSchema("test") + .setDetailId("ee") + .identityMap(sensorsIdentities.getIdentityMap()) + .addProperty("key1", "value1") + .addProperty("key2", new Date()) + .start(); + sa.detailSet(detailSchema); + assertSchemaDataNode(data); + Object distinctId = ((Map) data.get("properties")).get("distinct_id"); + Assertions.assertEquals("user_key1+user_value1", distinctId); + } - /** - * 测试item实体明细数据生成逻辑 - */ - @Test - public void checkItemDetailSet() throws InvalidArgumentException { - DetailSchema detailSchema = DetailSchema.init().setSchema("test").setDetailId("ee") - .setItemPair("item_key", "item_value") - .addProperty("key1", "value1") - .start(); - sa.detailSet(detailSchema); - assertSchemaDataNode(data); - } + /** 测试item实体明细数据生成逻辑 */ + @Test + public void checkItemDetailSet() throws InvalidArgumentException { + DetailSchema detailSchema = + DetailSchema.init() + .setSchema("test") + .setDetailId("ee") + .setItemPair("item_key", "item_value") + .addProperty("key1", "value1") + .start(); + sa.detailSet(detailSchema); + assertSchemaDataNode(data); + } - /** - * 手动指定 distinct_id,确认 distinct_id 是否为设置值 - */ - @Test - public void checkUserDistinctIdDetailSet() throws InvalidArgumentException { - SensorsAnalyticsIdentity sensorsIdentities = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("user_key1", "user_value1") - .addIdentityProperty("user_key2", "user_value2") - .build(); - DetailSchema detailSchema = DetailSchema.init().setSchema("test").setDetailId("ee") - .identityMap(sensorsIdentities.getIdentityMap()) - .setDistinctId("123") - .addProperty("key1", "value1") - .addProperty("key2", new Date()) - .start(); - sa.detailSet(detailSchema); - assertSchemaDataNode(data); - Object distinctId = ((Map) data.get("properties")).get("distinct_id"); - assertEquals("123", distinctId); - } + /** 手动指定 distinct_id,确认 distinct_id 是否为设置值 */ + @Test + public void checkUserDistinctIdDetailSet() throws InvalidArgumentException { + SensorsAnalyticsIdentity sensorsIdentities = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("user_key1", "user_value1") + .addIdentityProperty("user_key2", "user_value2") + .build(); + DetailSchema detailSchema = + DetailSchema.init() + .setSchema("test") + .setDetailId("ee") + .identityMap(sensorsIdentities.getIdentityMap()) + .setDistinctId("123") + .addProperty("key1", "value1") + .addProperty("key2", new Date()) + .start(); + sa.detailSet(detailSchema); + assertSchemaDataNode(data); + Object distinctId = ((Map) data.get("properties")).get("distinct_id"); + Assertions.assertEquals("123", distinctId); + } - /** - * 不传入 identities,然后设置 distinct_id,最终数据不应该出现该值 - */ - @Test - public void checkDistinctIdDetailSet() throws InvalidArgumentException { - DetailSchema detailSchema = DetailSchema.init().setSchema("test").setDetailId("ee") - .setDistinctId("123") - .addProperty("key1", "value1") - .addProperty("key2", new Date()) - .start(); - sa.detailSet(detailSchema); - assertSchemaDataNode(data); - assertFalse(((Map) data.get("properties")).containsKey("distinct_id")); - } + /** 不传入 identities,然后设置 distinct_id,最终数据不应该出现该值 */ + @Test + public void checkDistinctIdDetailSet() throws InvalidArgumentException { + DetailSchema detailSchema = + DetailSchema.init() + .setSchema("test") + .setDetailId("ee") + .setDistinctId("123") + .addProperty("key1", "value1") + .addProperty("key2", new Date()) + .start(); + sa.detailSet(detailSchema); + assertSchemaDataNode(data); + Assertions.assertFalse( + ((Map) data.get("properties")).containsKey("distinct_id")); + } - /** - * 同时传入 identities 和 itemPair 会导致抛出参数不合法异常 - */ - @Test - public void checkIdentitiesAndItemIdDetailSet() { - SensorsAnalyticsIdentity sensorsIdentities = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("user_key1", "user_value1") - .addIdentityProperty("user_key2", "user_value2") - .build(); - String message = ""; - try { - DetailSchema detailSchema = DetailSchema.init().setSchema("test").setDetailId("ee") - .identityMap(sensorsIdentities.getIdentityMap()) - .setItemPair("item_key", "item_value") - .setDistinctId("123") - .addProperty("key1", "value1") - .addProperty("key2", new Date()) - .start(); - } catch (InvalidArgumentException e) { - message = e.getMessage(); + /** 同时传入 identities 和 itemPair 会导致抛出参数不合法异常 */ + @Test + public void checkIdentitiesAndItemIdDetailSet() { + SensorsAnalyticsIdentity sensorsIdentities = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty("user_key1", "user_value1") + .addIdentityProperty("user_key2", "user_value2") + .build(); + String message = ""; + try { + DetailSchema detailSchema = + DetailSchema.init() + .setSchema("test") + .setDetailId("ee") + .identityMap(sensorsIdentities.getIdentityMap()) + .setItemPair("item_key", "item_value") + .setDistinctId("123") + .addProperty("key1", "value1") + .addProperty("key2", new Date()) + .start(); + } catch (InvalidArgumentException e) { + message = e.getMessage(); + } + Assertions.assertEquals("detail schema cannot both set identities and itemPair.", message); } - assertEquals("detail schema cannot both set identities and itemPair.", message); - } - @Test - public void checkDetailDelete() throws InvalidArgumentException { - DetailSchema detailSchema = DetailSchema.init().setSchema("test").setDetailId("ee") - .setItemPair("item_key", "item_value") - .setDistinctId("123") - .addProperty("key1", "value1") - .addProperty("key2", new Date()) - .start(); - sa.detailDelete(detailSchema); - assertSchemaDataNode(data); - } + @Test + public void checkDetailDelete() throws InvalidArgumentException { + DetailSchema detailSchema = + DetailSchema.init() + .setSchema("test") + .setDetailId("ee") + .setItemPair("item_key", "item_value") + .setDistinctId("123") + .addProperty("key1", "value1") + .addProperty("key2", new Date()) + .start(); + sa.detailDelete(detailSchema); + assertSchemaDataNode(data); + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaItemEventTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaItemEventTest.java index 0e34d48..0ceb574 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaItemEventTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaItemEventTest.java @@ -1,12 +1,9 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import com.sensorsdata.analytics.javasdk.bean.schema.ItemEventSchema; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * TODO @@ -17,35 +14,37 @@ */ public class SchemaItemEventTest extends SensorsBaseTest { - private static final String SCHEMA = "product_event"; - - private static final String EVENT_NAME = "cart"; - - @Test - public void checkItemEvent() throws InvalidArgumentException { - ItemEventSchema itemEventSchema = ItemEventSchema.init() - .setSchema(SCHEMA) - .setEventName(EVENT_NAME) - .setItemPair("production", "car") - .addProperty("key1", "value1") - .start(); - sa.track(itemEventSchema); - assertIESData(data); - } + private static final String SCHEMA = "product_event"; + + private static final String EVENT_NAME = "cart"; + + @Test + public void checkItemEvent() throws InvalidArgumentException { + ItemEventSchema itemEventSchema = + ItemEventSchema.init() + .setSchema(SCHEMA) + .setEventName(EVENT_NAME) + .setItemPair("production", "car") + .addProperty("key1", "value1") + .start(); + sa.track(itemEventSchema); + assertIESData(data); + } - @Test - public void checkInvalidEventItemKey() { - try { - ItemEventSchema itemEventSchema = ItemEventSchema.init() - .setEventName("aa") - .setSchema("sss") - .setItemPair("production", "car") - .addProperty("11age", "value") - .start(); - sa.track(itemEventSchema); - fail("生成异常数据"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("is invalid.")); + @Test + public void checkInvalidEventItemKey() { + try { + ItemEventSchema itemEventSchema = + ItemEventSchema.init() + .setEventName("aa") + .setSchema("sss") + .setItemPair("production", "car") + .addProperty("11age", "value") + .start(); + sa.track(itemEventSchema); + Assertions.fail("生成异常数据"); + } catch (InvalidArgumentException e) { + Assertions.assertTrue(e.getMessage().contains("is invalid.")); + } } - } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaItemTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaItemTest.java index 97606e3..e3aec7b 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaItemTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaItemTest.java @@ -2,8 +2,7 @@ import com.sensorsdata.analytics.javasdk.bean.schema.ItemSchema; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * TODO @@ -14,22 +13,21 @@ */ public class SchemaItemTest extends SensorsBaseTest { - private static final String ITEM_ID = "test11"; + private static final String ITEM_ID = "test11"; - private static final String SCHEMA = "item_schema"; + private static final String SCHEMA = "item_schema"; - /** - * 生成 itemSchema 格式数据 - */ - @Test - public void checkItemSet() throws InvalidArgumentException { - ItemSchema itemSchema = ItemSchema.init() - .setItemId(ITEM_ID) - .setSchema(SCHEMA) - .addProperty("key1", "value1") - .addProperty("key2", 22) - .start(); - sa.itemSet(itemSchema); - assertISData(data); - } + /** 生成 itemSchema 格式数据 */ + @Test + public void checkItemSet() throws InvalidArgumentException { + ItemSchema itemSchema = + ItemSchema.init() + .setItemId(ITEM_ID) + .setSchema(SCHEMA) + .addProperty("key1", "value1") + .addProperty("key2", 22) + .start(); + sa.itemSet(itemSchema); + assertISData(data); + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaUserEventTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaUserEventTest.java index e5fffc0..7cb4797 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaUserEventTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaUserEventTest.java @@ -1,19 +1,13 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import com.sensorsdata.analytics.javasdk.bean.SensorsAnalyticsIdentity; import com.sensorsdata.analytics.javasdk.bean.schema.IdentitySchema; import com.sensorsdata.analytics.javasdk.bean.schema.UserEventSchema; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Assert; -import org.junit.Test; - import java.util.Date; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * userEventSchema 单元测试 @@ -24,158 +18,165 @@ */ public class SchemaUserEventTest extends SensorsBaseTest { - private static final Long USER_ID = 12345L; - - private static final String EVENT_NAME = "testEvent"; - - private static final String DISTINCT_ID = "fz123"; - - /** - * 使用 userEventSchema 生成带 userId 数据 - * 期望:生成数据格式中用户信息节点为 userId - */ - @Test - public void checkUserEventSchemaWithUserId() throws InvalidArgumentException { - UserEventSchema userEventSchema = UserEventSchema.init() - .setUserId(USER_ID) - .setEventName(EVENT_NAME) - .addProperty("key1", "value1") - .addProperty("key2", 22) - .addProperty("$time", new Date()) - .start(); - sa.track(userEventSchema); - assertUESData(data); - } - - /** - * 构建携带 identities 的用户信息,distinct_id 值与 IDM3.0 生成逻辑保持一致 - * 期望:生成数据中 properties 内有 identities + distinct_id 节点;并且 distinct_id 的值为 $identity_login_id 的值 - */ - @Test - public void checkUserEventSchemaWithIdentities() throws InvalidArgumentException { - UserEventSchema userEventSchema = UserEventSchema.init() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, DISTINCT_ID) - .setEventName(EVENT_NAME) - .start(); - sa.track(userEventSchema); - assertUESData(data); - assertEventIdentitiesInfo(data, DISTINCT_ID); - } - - /** - * 校验用户绑定事件 - */ - @Test - public void checkSchemaBind() throws InvalidArgumentException { - IdentitySchema identitySchema = IdentitySchema.init().build(); - try { - sa.bind(identitySchema); - fail("生成异常数据"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("The identities is invalid,you should have at least two identities.")); + private static final Long USER_ID = 12345L; + + private static final String EVENT_NAME = "testEvent"; + + private static final String DISTINCT_ID = "fz123"; + + /** 使用 userEventSchema 生成带 userId 数据 期望:生成数据格式中用户信息节点为 userId */ + @Test + public void checkUserEventSchemaWithUserId() throws InvalidArgumentException { + UserEventSchema userEventSchema = + UserEventSchema.init() + .setUserId(USER_ID) + .setEventName(EVENT_NAME) + .addProperty("key1", "value1") + .addProperty("key2", 22) + .addProperty("$time", new Date()) + .start(); + sa.track(userEventSchema); + assertUESData(data); } - IdentitySchema oneIdentity = IdentitySchema.init() - .addIdentityProperty("key1", "value1") - .build(); - try { - sa.bind(oneIdentity); - fail("生成异常数据"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("The identities is invalid,you should have at least two identities.")); + /** + * 构建携带 identities 的用户信息,distinct_id 值与 IDM3.0 生成逻辑保持一致 期望:生成数据中 properties 内有 identities + + * distinct_id 节点;并且 distinct_id 的值为 $identity_login_id 的值 + */ + @Test + public void checkUserEventSchemaWithIdentities() throws InvalidArgumentException { + UserEventSchema userEventSchema = + UserEventSchema.init() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, DISTINCT_ID) + .setEventName(EVENT_NAME) + .start(); + sa.track(userEventSchema); + assertUESData(data); + assertEventIdentitiesInfo(data, DISTINCT_ID); } - IdentitySchema moreIdentity = IdentitySchema.init() - .addIdentityProperty("key1", "value1") - .addIdentityProperty("key2", "value2") - .build(); - sa.bind(moreIdentity); - assertUESData(data); - } - - @Test - public void checkSchemaUnbind() throws InvalidArgumentException { - IdentitySchema identitySchema = IdentitySchema.init().build(); - try { - sa.unbind(identitySchema); - fail("生成异常数据"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("unbind user operation cannot input multiple or none identifiers")); + /** 校验用户绑定事件 */ + @Test + public void checkSchemaBind() throws InvalidArgumentException { + IdentitySchema identitySchema = IdentitySchema.init().build(); + try { + sa.bind(identitySchema); + Assertions.fail("生成异常数据"); + } catch (InvalidArgumentException e) { + Assertions.assertTrue( + e.getMessage() + .contains( + "The identities is invalid,you should have at least two identities.")); + } + + IdentitySchema oneIdentity = + IdentitySchema.init().addIdentityProperty("key1", "value1").build(); + try { + sa.bind(oneIdentity); + Assertions.fail("生成异常数据"); + } catch (InvalidArgumentException e) { + Assertions.assertTrue( + e.getMessage() + .contains( + "The identities is invalid,you should have at least two identities.")); + } + + IdentitySchema moreIdentity = + IdentitySchema.init() + .addIdentityProperty("key1", "value1") + .addIdentityProperty("key2", "value2") + .build(); + sa.bind(moreIdentity); + assertUESData(data); } - IdentitySchema moreIdentity = IdentitySchema.init() - .addIdentityProperty("key1", "value1") - .addIdentityProperty("key2", "value2") - .build(); - - try { - sa.unbind(moreIdentity); - fail("生成异常数据"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("unbind user operation cannot input multiple or none identifiers")); + @Test + public void checkSchemaUnbind() throws InvalidArgumentException { + IdentitySchema identitySchema = IdentitySchema.init().build(); + try { + sa.unbind(identitySchema); + Assertions.fail("生成异常数据"); + } catch (InvalidArgumentException e) { + Assertions.assertTrue( + e.getMessage() + .contains( + "unbind user operation cannot input multiple or none identifiers")); + } + + IdentitySchema moreIdentity = + IdentitySchema.init() + .addIdentityProperty("key1", "value1") + .addIdentityProperty("key2", "value2") + .build(); + + try { + sa.unbind(moreIdentity); + Assertions.fail("生成异常数据"); + } catch (InvalidArgumentException e) { + Assertions.assertTrue( + e.getMessage() + .contains( + "unbind user operation cannot input multiple or none identifiers")); + } + + IdentitySchema oneIdentity = + IdentitySchema.init().addIdentityProperty("key1", "value1").build(); + sa.unbind(oneIdentity); + assertUESData(data); } + // ----------------------------------v3.5.2-------------------------------------- + + /** + * 支持 user 数据传入 userId 作为用户标识 + * + *

期望:用户数据传入 userId,最终节点中包含 userId 和 distinctId 信息 + */ + @Test + public void checkUserId() throws InvalidArgumentException { + UserEventSchema userEventSchema = + UserEventSchema.init().setUserId(123L).setEventName(EVENT_NAME).start(); + sa.track(userEventSchema); + assertUESData(data); + } - IdentitySchema oneIdentity = IdentitySchema.init() - .addIdentityProperty("key1", "value1") - .build(); - sa.unbind(oneIdentity); - assertUESData(data); - - - } - - - //----------------------------------v3.5.2-------------------------------------- - - /** - * 支持 user 数据传入 userId 作为用户标识 - *

期望:用户数据传入 userId,最终节点中包含 userId 和 distinctId 信息

- */ - @Test - public void checkUserId() throws InvalidArgumentException { - UserEventSchema userEventSchema = UserEventSchema.init() - .setUserId(123L) - .setEventName(EVENT_NAME) - .start(); - sa.track(userEventSchema); - assertUESData(data); - } - - /** - * 同时传入 userID 和 identities 节点 - *

期望:userId 优先级最高,两者同时传入,最终数据中存在 userId

- */ - @Test - public void checkUserIdAndIdentities() throws InvalidArgumentException { - UserEventSchema userEventSchema = UserEventSchema.init() - .setUserId(123L) - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "eee") - .setEventName(EVENT_NAME) - .start(); - sa.track(userEventSchema); - assertUESData(data); - Map properties = (Map) data.get("properties"); - assertTrue(properties.containsKey("user_id")); - assertEquals(123L, properties.get("user_id")); - } - - /** - * 同时传入 userID 和 distinctId 节点 - *

期望:最终数据节点中,以传入的 distinctId 为主

- */ - @Test - public void checkUserIdAndDistinctId() throws InvalidArgumentException { - UserEventSchema userEventSchema = UserEventSchema.init() - .setUserId(123L) - .setDistinctId("test") - .setEventName(EVENT_NAME) - .start(); - sa.track(userEventSchema); - assertUESData(data); - Map properties = (Map) data.get("properties"); - Assert.assertTrue(properties.containsKey("distinct_id")); - Assert.assertEquals("test", properties.get("distinct_id")); - } + /** + * 同时传入 userID 和 identities 节点 + * + *

期望:userId 优先级最高,两者同时传入,最终数据中存在 userId + */ + @Test + public void checkUserIdAndIdentities() throws InvalidArgumentException { + UserEventSchema userEventSchema = + UserEventSchema.init() + .setUserId(123L) + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "eee") + .setEventName(EVENT_NAME) + .start(); + sa.track(userEventSchema); + assertUESData(data); + Map properties = (Map) data.get("properties"); + Assertions.assertTrue(properties.containsKey("user_id")); + Assertions.assertEquals(123L, properties.get("user_id")); + } + /** + * 同时传入 userID 和 distinctId 节点 + * + *

期望:最终数据节点中,以传入的 distinctId 为主 + */ + @Test + public void checkUserIdAndDistinctId() throws InvalidArgumentException { + UserEventSchema userEventSchema = + UserEventSchema.init() + .setUserId(123L) + .setDistinctId("test") + .setEventName(EVENT_NAME) + .start(); + sa.track(userEventSchema); + assertUESData(data); + Map properties = (Map) data.get("properties"); + Assertions.assertTrue(properties.containsKey("distinct_id")); + Assertions.assertEquals("test", properties.get("distinct_id")); + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaUserTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaUserTest.java index 637fc1a..f1a4bcf 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaUserTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SchemaUserTest.java @@ -2,12 +2,11 @@ import com.sensorsdata.analytics.javasdk.bean.schema.UserSchema; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Assert; -import org.junit.Test; - import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * v3.4.5+ 用户 schema @@ -18,136 +17,152 @@ */ public class SchemaUserTest extends SensorsBaseTest { - private static final Long USER_ID = 12345L; - - private static final String DISTINCT_ID = "fz123"; - /** - * 用户 - */ - @Test - public void checkProfileSetTest() throws InvalidArgumentException { - UserSchema userSchema = UserSchema.init() - .addIdentityProperty("user1", "value1") - .addProperty("key1", "value1") - .addProperty("key2", 22) - .setDistinctId("aaa") - .start(); - sa.profileSet(userSchema); - assertUSData(data); - } - - - @Test - public void checkProfileSetOnce() throws InvalidArgumentException { - UserSchema userSchema = UserSchema.init() - .addIdentityProperty("login_id", DISTINCT_ID) - .addIdentityProperty("key1", "value1") - .setDistinctId("aaa") - .start(); - sa.profileSetOnce(userSchema); - assertUSData(data); - } - - @Test - public void checkProfileSetIncrement() throws InvalidArgumentException { - UserSchema userSchema = UserSchema.init() - .addIdentityProperty("login_id", DISTINCT_ID) - .addProperty("key1", 20) - .start(); - sa.profileIncrement(userSchema); - assertUSData(data); - } - - @Test - public void checkProfileAppend() throws InvalidArgumentException { - List others = new ArrayList<>(); - others.add("swim"); - others.add("run"); - UserSchema userSchema = UserSchema.init() - .addIdentityProperty("login_id", DISTINCT_ID) - .addProperty("key1", others) - .start(); - sa.profileAppend(userSchema); - assertUSData(data); - } - - @Test - public void checkProfileUnset() throws InvalidArgumentException { - UserSchema userSchema = UserSchema.init() - .addIdentityProperty("login_id", DISTINCT_ID) - .addProperty("key1", true) - .start(); - sa.profileUnset(userSchema); - assertUSData(data); - } - - /** - * 删除用户属性;只支持传入单个用户 - */ - @Test - public void checkProfileDeleteByUserId() throws InvalidArgumentException { - sa.profileDelete("key1", "value1"); - assertUSData(data); - } - - @Test - public void checkPreDefineProperties() throws InvalidArgumentException { - UserSchema userSchema = UserSchema.init() - .addIdentityProperty("key1", "value1") - .addProperty("$project", "abc") - .start(); - sa.profileSet(userSchema); - assertUSData(data); - - } - - //----------------------------------v3.5.2-------------------------------------- - - /** - * 支持 user 数据传入 userId 作为用户标识 - *

期望:用户数据传入 userId,最终节点中包含 userId 和 distinctId 信息

- */ - @Test - public void checkUserId() throws InvalidArgumentException { - UserSchema userSchema = UserSchema.init() - .setUserId(123L) - .addProperty("$project", "abc") - .start(); - sa.profileSet(userSchema); - assertUSData(data); - } - - /** - * 同时传入 userID 和 identities 节点 - *

期望:userId 优先级最高,两者同时传入,最终数据中存在 userId

- */ - @Test - public void checkUserIdAndIdentities() throws InvalidArgumentException { - UserSchema userSchema = UserSchema.init() - .setUserId(123L) - .addIdentityProperty("key1", "value1") - .addProperty("$project", "abc") - .start(); - sa.profileSet(userSchema); - assertUSData(data); - Assert.assertTrue(data.containsKey("id")); - } - - /** - * 同时传入 userID 和 distinctId 节点 - *

期望:最终数据节点中,以传入的 distinctId 为主

- */ - @Test - public void checkUserIdAndDistinctId() throws InvalidArgumentException { - UserSchema userSchema = UserSchema.init() - .setUserId(123L) - .setDistinctId("test") - .addIdentityProperty("key1", "value1") - .addProperty("$project", "abc") - .start(); - sa.profileSet(userSchema); - assertUSData(data); - Assert.assertTrue(data.containsKey("distinct_id")); - Assert.assertEquals("test", data.get("distinct_id")); - } + private static final Long USER_ID = 12345L; + + private static final String DISTINCT_ID = "fz123"; + /** 用户 */ + @Test + public void checkProfileSetTest() throws InvalidArgumentException { + UserSchema userSchema = + UserSchema.init() + .addIdentityProperty("user1", "value1") + .addProperty("key1", "value1") + .addProperty("key2", 22) + .setDistinctId("aaa") + .start(); + sa.profileSet(userSchema); + assertUSData(data); + } + + @Test + public void checkProfileSetTest2() throws InvalidArgumentException { + UserSchema userSchema = + UserSchema.init() + .addIdentityProperty("user1", Arrays.asList("value1", "value2")) + .addProperty("key1", "value1") + .addProperty("key2", 22) + .setDistinctId("aaa") + .start(); + sa.profileSet(userSchema); + assertUSData(data); + } + + @Test + public void checkProfileSetOnce() throws InvalidArgumentException { + UserSchema userSchema = + UserSchema.init() + .addIdentityProperty("login_id", DISTINCT_ID) + .addIdentityProperty("key1", "value1") + .setDistinctId("aaa") + .start(); + sa.profileSetOnce(userSchema); + assertUSData(data); + } + + @Test + public void checkProfileSetIncrement() throws InvalidArgumentException { + UserSchema userSchema = + UserSchema.init() + .addIdentityProperty("login_id", DISTINCT_ID) + .addProperty("key1", 20) + .start(); + sa.profileIncrement(userSchema); + assertUSData(data); + } + + @Test + public void checkProfileAppend() throws InvalidArgumentException { + List others = new ArrayList<>(); + others.add("swim"); + others.add("run"); + UserSchema userSchema = + UserSchema.init() + .addIdentityProperty("login_id", DISTINCT_ID) + .addProperty("key1", others) + .start(); + sa.profileAppend(userSchema); + assertUSData(data); + } + + @Test + public void checkProfileUnset() throws InvalidArgumentException { + UserSchema userSchema = + UserSchema.init() + .addIdentityProperty("login_id", DISTINCT_ID) + .addProperty("key1", true) + .start(); + sa.profileUnset(userSchema); + assertUSData(data); + } + + /** 删除用户属性;只支持传入单个用户 */ + @Test + public void checkProfileDeleteByUserId() throws InvalidArgumentException { + sa.profileDelete("key1", "value1"); + assertUSData(data); + } + + @Test + public void checkPreDefineProperties() throws InvalidArgumentException { + UserSchema userSchema = + UserSchema.init() + .addIdentityProperty("key1", "value1") + .addProperty("$project", "abc") + .start(); + sa.profileSet(userSchema); + assertUSData(data); + } + + // ----------------------------------v3.5.2-------------------------------------- + + /** + * 支持 user 数据传入 userId 作为用户标识 + * + *

期望:用户数据传入 userId,最终节点中包含 userId 和 distinctId 信息 + */ + @Test + public void checkUserId() throws InvalidArgumentException { + UserSchema userSchema = + UserSchema.init().setUserId(123L).addProperty("$project", "abc").start(); + sa.profileSet(userSchema); + assertUSData(data); + } + + /** + * 同时传入 userID 和 identities 节点 + * + *

期望:userId 优先级最高,两者同时传入,最终数据中存在 userId + */ + @Test + public void checkUserIdAndIdentities() throws InvalidArgumentException { + UserSchema userSchema = + UserSchema.init() + .setUserId(123L) + .addIdentityProperty("key1", "value1") + .addProperty("$project", "abc") + .start(); + sa.profileSet(userSchema); + assertUSData(data); + Assertions.assertTrue(data.containsKey("id")); + } + + /** + * 同时传入 userID 和 distinctId 节点 + * + *

期望:最终数据节点中,以传入的 distinctId 为主 + */ + @Test + public void checkUserIdAndDistinctId() throws InvalidArgumentException { + UserSchema userSchema = + UserSchema.init() + .setUserId(123L) + .setDistinctId("test") + .addIdentityProperty("key1", "value1") + .addProperty("$project", "abc") + .start(); + sa.profileSet(userSchema); + assertUSData(data); + Assertions.assertTrue(data.containsKey("distinct_id")); + Assertions.assertEquals("test", data.get("distinct_id")); + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SensorsAnalyticsUtilTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SensorsAnalyticsUtilTest.java index a19211f..de5681f 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SensorsAnalyticsUtilTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SensorsAnalyticsUtilTest.java @@ -1,19 +1,15 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import com.sensorsdata.analytics.javasdk.bean.FailedData; import com.sensorsdata.analytics.javasdk.bean.SensorsAnalyticsIdentity; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - -import org.junit.Test; - import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Random; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * 工具类测试 @@ -24,107 +20,107 @@ */ public class SensorsAnalyticsUtilTest { - @Test - public void checkAssertFailedDataWithNoTrackId() { - Map event = new HashMap<>(); - event.put("distinct_id", "12345"); - event.put("event", "test"); - event.put("type", "track"); - Map properties = new HashMap<>(); - properties.put("test", "test"); - event.put("properties", properties); - ArrayList> list = new ArrayList<>(); - list.add(event); - FailedData failedData = new FailedData("", list); - try { - SensorsAnalyticsUtil.assertFailedData(failedData); - fail(); - } catch (InvalidArgumentException e) { - assertTrue(true); + @Test + public void checkAssertFailedDataWithNoTrackId() { + Map event = new HashMap<>(); + event.put("distinct_id", "12345"); + event.put("event", "test"); + event.put("type", "track"); + Map properties = new HashMap<>(); + properties.put("test", "test"); + event.put("properties", properties); + ArrayList> list = new ArrayList<>(); + list.add(event); + FailedData failedData = new FailedData("", list); + try { + SensorsAnalyticsUtil.assertFailedData(failedData); + Assertions.fail(); + } catch (InvalidArgumentException e) { + Assertions.assertTrue(true); + } } - } - @Test - public void checkAssertFailedDataWithNoType() { - Map event = new HashMap<>(); - event.put("_track_id", new Random().nextInt()); - event.put("distinct_id", "12345"); - event.put("event", "test"); - Map properties = new HashMap<>(); - properties.put("test", "test"); - event.put("properties", properties); - ArrayList> list = new ArrayList<>(); - list.add(event); - FailedData failedData = new FailedData("", list); - try { - SensorsAnalyticsUtil.assertFailedData(failedData); - fail(); - } catch (InvalidArgumentException e) { - assertTrue(true); + @Test + public void checkAssertFailedDataWithNoType() { + Map event = new HashMap<>(); + event.put("_track_id", new Random().nextInt()); + event.put("distinct_id", "12345"); + event.put("event", "test"); + Map properties = new HashMap<>(); + properties.put("test", "test"); + event.put("properties", properties); + ArrayList> list = new ArrayList<>(); + list.add(event); + FailedData failedData = new FailedData("", list); + try { + SensorsAnalyticsUtil.assertFailedData(failedData); + Assertions.fail(); + } catch (InvalidArgumentException e) { + Assertions.assertTrue(true); + } } - } - @Test - public void checkAssertFailedDataWithInvalidPropertiesKey() { - Map event = new HashMap<>(); - event.put("_track_id", new Random().nextInt()); - event.put("distinct_id", "12345"); - event.put("event", "test"); - Map properties = new HashMap<>(); - properties.put("distinct_id", "test"); - event.put("properties", properties); - ArrayList> list = new ArrayList<>(); - list.add(event); - FailedData failedData = new FailedData("", list); - try { - SensorsAnalyticsUtil.assertFailedData(failedData); - fail(); - } catch (InvalidArgumentException e) { - assertTrue(true); + @Test + public void checkAssertFailedDataWithInvalidPropertiesKey() { + Map event = new HashMap<>(); + event.put("_track_id", new Random().nextInt()); + event.put("distinct_id", "12345"); + event.put("event", "test"); + Map properties = new HashMap<>(); + properties.put("distinct_id", "test"); + event.put("properties", properties); + ArrayList> list = new ArrayList<>(); + list.add(event); + FailedData failedData = new FailedData("", list); + try { + SensorsAnalyticsUtil.assertFailedData(failedData); + Assertions.fail(); + } catch (InvalidArgumentException e) { + Assertions.assertTrue(true); + } } - } - @Test - public void checkAssertIDMappingFailedData() { - Map event = new HashMap<>(); - event.put("_track_id", new Random().nextInt()); - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "12345") - .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") - .build(); - event.put("identities", identity.getIdentityMap()); - event.put("distinct_id", "12345"); - event.put("type", "track"); - event.put("event", "test"); - Map properties = new HashMap<>(); - properties.put("test", "test"); - event.put("properties", properties); - ArrayList> list = new ArrayList<>(); - list.add(event); - try { - SensorsAnalyticsUtil.assertFailedData(new FailedData("", list)); - } catch (InvalidArgumentException e) { - fail(); + @Test + public void checkAssertIDMappingFailedData() { + Map event = new HashMap<>(); + event.put("_track_id", new Random().nextInt()); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder() + .addIdentityProperty(SensorsAnalyticsIdentity.LOGIN_ID, "12345") + .addIdentityProperty(SensorsAnalyticsIdentity.EMAIL, "fz@163.com") + .build(); + event.put("identities", identity.getIdentityMap()); + event.put("distinct_id", "12345"); + event.put("type", "track"); + event.put("event", "test"); + Map properties = new HashMap<>(); + properties.put("test", "test"); + event.put("properties", properties); + ArrayList> list = new ArrayList<>(); + list.add(event); + try { + SensorsAnalyticsUtil.assertFailedData(new FailedData("", list)); + } catch (InvalidArgumentException e) { + Assertions.fail(); + } } - } - @Test - public void checkAssertFailedData() { - Map event = new HashMap<>(); - event.put("_track_id", new Random().nextInt()); - event.put("distinct_id", "12345"); - event.put("type", "track"); - event.put("event", "test"); - Map properties = new HashMap<>(); - properties.put("test", "test"); - event.put("properties", properties); - ArrayList> list = new ArrayList<>(); - list.add(event); - try { - SensorsAnalyticsUtil.assertFailedData(new FailedData("", list)); - } catch (InvalidArgumentException e) { - fail(); + @Test + public void checkAssertFailedData() { + Map event = new HashMap<>(); + event.put("_track_id", new Random().nextInt()); + event.put("distinct_id", "12345"); + event.put("type", "track"); + event.put("event", "test"); + Map properties = new HashMap<>(); + properties.put("test", "test"); + event.put("properties", properties); + ArrayList> list = new ArrayList<>(); + list.add(event); + try { + SensorsAnalyticsUtil.assertFailedData(new FailedData("", list)); + } catch (InvalidArgumentException e) { + Assertions.fail(); + } } - } - } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SensorsBaseTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SensorsBaseTest.java index 67e38ea..3759f18 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SensorsBaseTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SensorsBaseTest.java @@ -1,6 +1,5 @@ package com.sensorsdata.analytics.javasdk; - import static com.sensorsdata.analytics.javasdk.SensorsConst.LIB_DETAIL_SYSTEM_ATTR; import static com.sensorsdata.analytics.javasdk.SensorsConst.LIB_METHOD_SYSTEM_ATTR; import static com.sensorsdata.analytics.javasdk.SensorsConst.LIB_SYSTEM_ATTR; @@ -8,296 +7,280 @@ import static com.sensorsdata.analytics.javasdk.SensorsConst.PROPERTIES; import static com.sensorsdata.analytics.javasdk.SensorsConst.TIME_SYSTEM_ATTR; import static com.sensorsdata.analytics.javasdk.SensorsConst.TRACK_ID; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import com.sensorsdata.analytics.javasdk.consumer.Consumer; - -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +@Slf4j public class SensorsBaseTest { - /** - * 单元测试中若生成多条数据,则存放到该集合中 - */ - protected final List> res = new ArrayList<>(); - /** - * SDK 最后一次生成的数据集合 - */ - protected Map data = null; - /** - * 初始化 sa - */ - protected SensorsAnalytics sa = null; - /** - * mock server - */ - protected static Server server = null; + /** 单元测试中若生成多条数据,则存放到该集合中 */ + protected final List> res = new ArrayList<>(); + /** SDK 最后一次生成的数据集合 */ + protected Map data = null; + /** 初始化 sa */ + protected SensorsAnalytics sa = null; + /** mock server */ + protected static Server server = null; - protected String url = "http://localhost:8888/sa"; + protected String url = "http://localhost:8888/sa"; - protected static Set actionTypeSet = new HashSet<>(); + protected static Set actionTypeSet = new HashSet<>(); + class TestConsumer implements Consumer { - class TestConsumer implements Consumer { + @Override + public void send(Map message) { + data = message; + res.add(message); + } - @Override - public void send(Map message) { - data = message; - res.add(message); - } - - @Override - public void flush() { + @Override + public void flush() {} + @Override + public void close() {} } - @Override - public void close() { - + @BeforeAll + public static void mockABServer() throws Exception { + log.info("Before All"); + server = new Server(8888); + ServletContextHandler handler = new ServletContextHandler(); + handler.addServlet(new ServletHolder(new TestServlet()), "/debug"); + handler.addServlet(new ServletHolder(new TestServlet()), "/sa"); + handler.addServlet(new ServletHolder(new InstantServlet()), "/instant"); + + server.setHandler(handler); + server.start(); + actionTypeSet.add(SensorsConst.TRACK_ACTION_TYPE); + actionTypeSet.add(SensorsConst.TRACK_SIGN_UP_ACTION_TYPE); + actionTypeSet.add(SensorsConst.PROFILE_SET_ACTION_TYPE); + actionTypeSet.add(SensorsConst.PROFILE_INCREMENT_ACTION_TYPE); + actionTypeSet.add(SensorsConst.PROFILE_UNSET_ACTION_TYPE); + actionTypeSet.add(SensorsConst.PROFILE_SET_ONCE_ACTION_TYPE); + actionTypeSet.add(SensorsConst.PROFILE_APPEND_ACTION_TYPE); + actionTypeSet.add(SensorsConst.BIND_ID_ACTION_TYPE); + actionTypeSet.add(SensorsConst.UNBIND_ID_ACTION_TYPE); + actionTypeSet.add(SensorsConst.PROFILE_DELETE_ACTION_TYPE); + actionTypeSet.add(SensorsConst.ITEM_SET_ACTION_TYPE); + actionTypeSet.add(SensorsConst.ITEM_DELETE_ACTION_TYPE); + actionTypeSet.add(SensorsConst.DETAIL_SET_ACTION_TYPE); + actionTypeSet.add(SensorsConst.DETAIL_DELETE_ACTION_TYPE); } - } - - @BeforeClass - public static void mockABServer() throws Exception { - server = new Server(8888); - ServletContextHandler handler = new ServletContextHandler(); - handler.addServlet(new ServletHolder(new TestServlet()), "/debug"); - handler.addServlet(new ServletHolder(new TestServlet()), "/sa"); - handler.addServlet(new ServletHolder(new InstantServlet()), "/instant"); - - server.setHandler(handler); - server.start(); - actionTypeSet.add(SensorsConst.TRACK_ACTION_TYPE); - actionTypeSet.add(SensorsConst.TRACK_SIGN_UP_ACTION_TYPE); - actionTypeSet.add(SensorsConst.PROFILE_SET_ACTION_TYPE); - actionTypeSet.add(SensorsConst.PROFILE_INCREMENT_ACTION_TYPE); - actionTypeSet.add(SensorsConst.PROFILE_UNSET_ACTION_TYPE); - actionTypeSet.add(SensorsConst.PROFILE_SET_ONCE_ACTION_TYPE); - actionTypeSet.add(SensorsConst.PROFILE_APPEND_ACTION_TYPE); - actionTypeSet.add(SensorsConst.BIND_ID_ACTION_TYPE); - actionTypeSet.add(SensorsConst.UNBIND_ID_ACTION_TYPE); - actionTypeSet.add(SensorsConst.PROFILE_DELETE_ACTION_TYPE); - actionTypeSet.add(SensorsConst.ITEM_SET_ACTION_TYPE); - actionTypeSet.add(SensorsConst.ITEM_DELETE_ACTION_TYPE); - actionTypeSet.add(SensorsConst.DETAIL_SET_ACTION_TYPE); - actionTypeSet.add(SensorsConst.DETAIL_DELETE_ACTION_TYPE); - } - - @Test - public void checkServer() { - assertNotNull(server); - } - - @AfterClass - public static void closeMockServer() throws Exception { - if (server != null) { - server.stop(); + @Test + public void checkServer() { + Assertions.assertNotNull(server); } - } - - @Before - public void clearListAndInit() { - sa = new SensorsAnalytics(new TestConsumer()); - data = null; - res.clear(); - } - - /** - * 校验非 IDM 模式下 event 数据节点 - * properties 节点可能没有数据,所以需放到具体的单元测试里面去判断 - * - * @param data 数据节点 - */ - protected void assertEventData(Map data) { - assertUserData(data); - assertTrue("数据中没有 event 节点!", data.containsKey("event")); - } - - /** - * 校验非 IDM 模式下 user 数据节点 - * - * @param data 数据节点 - */ - protected void assertUserData(Map data) { - assertNotNull(data); - assertTrue("数据中没有 _track_id 节点!", data.containsKey("_track_id")); - assertTrue("数据中没有 lib 节点!", data.containsKey("lib")); - assertTrue("数据中没有 distinct_id 节点!", data.containsKey("distinct_id")); - assertTrue("数据中没有 time 节点!", data.containsKey("time")); - assertTrue("数据中没有 type 节点!", data.containsKey("type")); - - //增加各字段类型校验 - assertTrue("数据中 time 节点类型不正确!", data.get("time") instanceof Long); - assertTrue("数据中 _track_id 节点类型不正确!", data.get("_track_id") instanceof Integer); - assertTrue("数据中 distinct_id 节点类型不正确!", data.get("distinct_id") instanceof String); - assertTrue("数据中 type 节点类型不正确!", data.get("type") instanceof String); - assertTrue("数据中 lib 节点类型不正确!", data.get("lib") instanceof Map); + @AfterAll + public static void closeMockServer() throws Exception { + if (server != null) { + server.stop(); + } + } - assertFalse("数据中包含 item_id 节点!", data.containsKey("item_id")); - assertFalse("数据中包含 item_type 节点!", data.containsKey("item_type")); - if (data.containsKey(PROPERTIES)) { - assertProperties(data.get(PROPERTIES)); + @BeforeEach + public void clearListAndInit() { + log.info("Before Each, new sa"); + sa = new SensorsAnalytics(new TestConsumer()); + data = null; + res.clear(); } - } - /** - * 校验非 IDM 模式下 item 数据节点 - * - * @param data 数据节点 - */ - protected void assertItemData(Map data) { - assertNotNull(data); - assertTrue("item 数据中没有 lib 节点!", data.containsKey("lib")); - assertTrue("item 数据中没有 item_id 节点!", data.containsKey("item_id")); - assertTrue("item 数据中没有 item_type 节点!", data.containsKey("item_type")); - assertTrue("item 数据中没有 time 节点!", data.containsKey("time")); - assertTrue("item 数据中没有 type 节点!", data.containsKey("type")); - assertFalse("item 数据中包含 distinct_id 节点!", data.containsKey("distinct_id")); - assertFalse("item 数据中包含 _track_id 节点!", data.containsKey("_track_id")); - } + /** + * 校验非 IDM 模式下 event 数据节点 properties 节点可能没有数据,所以需放到具体的单元测试里面去判断 + * + * @param data 数据节点 + */ + protected void assertEventData(Map data) { + assertUserData(data); + Assertions.assertTrue(data.containsKey("event"), "数据中没有 event 节点!"); + } - /** - * 校验 IDM3.0 模式下 event 数据节点 - * - * @param data 数据节点 - */ - protected void assertIDM3EventData(Map data) { - assertEventData(data); - assertTrue("IDM3 数据中没有 identities 节点!", data.containsKey("identities")); - } + /** + * 校验非 IDM 模式下 user 数据节点 + * + * @param data 数据节点 + */ + protected void assertUserData(Map data) { + Assertions.assertNotNull(data); + Assertions.assertTrue(data.containsKey("_track_id"), "数据中没有 _track_id 节点!"); + Assertions.assertTrue(data.containsKey("lib"), "数据中没有 lib 节点!"); + Assertions.assertTrue(data.containsKey("distinct_id"), "数据中没有 distinct_id 节点!"); + Assertions.assertTrue(data.containsKey("time"), "数据中没有 time 节点!"); + Assertions.assertTrue(data.containsKey("type"), "数据中没有 type 节点!"); + + // 增加各字段类型校验 + Assertions.assertTrue(data.get("time") instanceof Long, "数据中 time 节点类型不正确!"); + Assertions.assertTrue(data.get("_track_id") instanceof Integer, "数据中 _track_id 节点类型不正确!"); + Assertions.assertTrue( + data.get("distinct_id") instanceof String, "数据中 distinct_id 节点类型不正确!"); + Assertions.assertTrue(data.get("type") instanceof String, "数据中 type 节点类型不正确!"); + Assertions.assertTrue(data.get("lib") instanceof Map, "数据中 lib 节点类型不正确!"); + + Assertions.assertFalse(data.containsKey("item_id"), "数据中包含 item_id 节点!"); + Assertions.assertFalse(data.containsKey("item_type"), "数据中包含 item_type 节点!"); + if (data.containsKey(PROPERTIES)) { + assertProperties(data.get(PROPERTIES)); + } + } - /** - * 校验 IDM3.0 模式下 user 数据节点 - * - * @param data 数据节点 - */ - protected void assertIDM3UserData(Map data) { - assertUserData(data); - assertTrue("IDM3 数据中没有 identities 节点!", data.containsKey("identities")); - } + /** + * 校验非 IDM 模式下 item 数据节点 + * + * @param data 数据节点 + */ + protected void assertItemData(Map data) { + Assertions.assertNotNull(data); + Assertions.assertTrue(data.containsKey("lib"), "item 数据中没有 lib 节点!"); + Assertions.assertTrue(data.containsKey("item_id"), "item 数据中没有 item_id 节点!"); + Assertions.assertTrue(data.containsKey("item_type"), "item 数据中没有 item_type 节点!"); + Assertions.assertTrue(data.containsKey("time"), "item 数据中没有 time 节点!"); + Assertions.assertTrue(data.containsKey("type"), "item 数据中没有 type 节点!"); + Assertions.assertFalse(data.containsKey("distinct_id"), "item 数据中包含 distinct_id 节点!"); + Assertions.assertFalse(data.containsKey("_track_id"), "item 数据中包含 _track_id 节点!"); + } - /** - * 校验 lib 内容 - * - * @param lib lib 信息集合 - */ - protected void assertDataLib(Object lib) { - assertTrue(lib instanceof Map); - Map libMap = (Map) lib; - assertFalse("数据中 lib 节点信息不存在!", libMap.isEmpty()); - assertTrue("lib 节点信息不存在 $lib 信息!", libMap.containsKey(LIB_SYSTEM_ATTR)); - assertTrue("lib 节点信息不存在 $lib_version 信息!", libMap.containsKey(LIB_VERSION_SYSTEM_ATTR)); - assertTrue("lib 节点信息不存在 $lib_method 信息!", libMap.containsKey(LIB_METHOD_SYSTEM_ATTR)); - assertTrue("lib 节点信息不存在 $lib_detail 信息!", libMap.containsKey(LIB_DETAIL_SYSTEM_ATTR)); + /** + * 校验 IDM3.0 模式下 event 数据节点 + * + * @param data 数据节点 + */ + protected void assertIDM3EventData(Map data) { + assertEventData(data); + Assertions.assertTrue(data.containsKey("identities"), "IDM3 数据中没有 identities 节点!"); + } - } + /** + * 校验 IDM3.0 模式下 user 数据节点 + * + * @param data 数据节点 + */ + protected void assertIDM3UserData(Map data) { + assertUserData(data); + Assertions.assertTrue(data.containsKey("identities"), "IDM3 数据中没有 identities 节点!"); + } - /** - * 校验 properties - * 校验原则:如果 properties 存在,判断 $time 和 $track_id 是否存在 - */ - protected void assertProperties(Object properties) { - assertTrue(properties instanceof Map); - Map propertiesMap = (Map) properties; - assertFalse("properties 中的 $time 属性并未删除", propertiesMap.containsKey(TIME_SYSTEM_ATTR)); - assertFalse("properties 中的 $track_id 属性并未删除", propertiesMap.containsKey(TRACK_ID)); - } + /** + * 校验 lib 内容 + * + * @param lib lib 信息集合 + */ + protected void assertDataLib(Object lib) { + Assertions.assertTrue(lib instanceof Map); + Map libMap = (Map) lib; + Assertions.assertFalse(libMap.isEmpty(), "数据中 lib 节点信息不存在!"); + Assertions.assertTrue(libMap.containsKey(LIB_SYSTEM_ATTR), "lib 节点信息不存在 $lib 信息!"); + Assertions.assertTrue( + libMap.containsKey(LIB_VERSION_SYSTEM_ATTR), "lib 节点信息不存在 $lib_version 信息!"); + Assertions.assertTrue( + libMap.containsKey(LIB_METHOD_SYSTEM_ATTR), "lib 节点信息不存在 $lib_method 信息!"); + Assertions.assertTrue( + libMap.containsKey(LIB_DETAIL_SYSTEM_ATTR), "lib 节点信息不存在 $lib_detail 信息!"); + } - /** - * 校验 userEventSchema 数据 - */ - protected void assertUESData(Map data) { - assertIESData(data); - Object properties = data.get("properties"); - assertTrue("数据节点 properties 类型不正确!", properties instanceof Map); - Map proMap = (Map) properties; - assertTrue("数据中用户信息节点(identities+distinct_id/user_id)丢失!", - (proMap.containsKey("identities") || proMap.containsKey("user_id")) && proMap.containsKey("distinct_id")); - } + /** 校验 properties 校验原则:如果 properties 存在,判断 $time 和 $track_id 是否存在 */ + protected void assertProperties(Object properties) { + Assertions.assertTrue(properties instanceof Map); + Map propertiesMap = (Map) properties; + Assertions.assertFalse( + propertiesMap.containsKey(TIME_SYSTEM_ATTR), "properties 中的 $time 属性并未删除"); + Assertions.assertFalse( + propertiesMap.containsKey(TRACK_ID), "properties 中的 $track_id 属性并未删除"); + } - protected void assertEventIdentitiesInfo(Map data, String expectDistinctId) { - Map proMap = (Map) data.get("properties"); - assertTrue(proMap.containsKey("identities")); - assertTrue(proMap.containsKey("distinct_id")); - assertEquals(expectDistinctId, proMap.get("distinct_id").toString()); - } + /** 校验 userEventSchema 数据 */ + protected void assertUESData(Map data) { + assertIESData(data); + Object properties = data.get("properties"); + Assertions.assertTrue(properties instanceof Map, "数据节点 properties 类型不正确!"); + Map proMap = (Map) properties; + Assertions.assertTrue( + (proMap.containsKey("identities") || proMap.containsKey("user_id")) + && proMap.containsKey("distinct_id"), + "数据中用户信息节点(identities+distinct_id/user_id)丢失!"); + } - /** - * 校验 itemEventSchema 数据 - */ - protected void assertIESData(Map data) { - assertSchemaDataNode(data); - assertTrue("数据节点中不存在 event 节点!", data.containsKey("event")); - assertTrue("数据节点中不存在 time 节点!", data.containsKey("time")); - assertTrue("数据节点个数不正常,可能丢失节点!", data.size() >= 8); - } + protected void assertEventIdentitiesInfo(Map data, String expectDistinctId) { + Map proMap = (Map) data.get("properties"); + Assertions.assertTrue(proMap.containsKey("identities")); + Assertions.assertTrue(proMap.containsKey("distinct_id")); + Assertions.assertEquals(expectDistinctId, proMap.get("distinct_id").toString()); + } - /** - * 校验 itemSchema 数据 - */ - protected void assertISData(Map data) { - assertSchemaDataNode(data); - assertTrue("数据节点中不存在 id 节点!", data.containsKey("id")); - assertNotNull("数据节点 id 不可为空!", data.get("id")); - assertTrue("数据节点个数不正常,可能丢失节点!", data.size() >= 8); - } + /** 校验 itemEventSchema 数据 */ + protected void assertIESData(Map data) { + assertSchemaDataNode(data); + Assertions.assertTrue(data.containsKey("event"), "数据节点中不存在 event 节点!"); + Assertions.assertTrue(data.containsKey("time"), "数据节点中不存在 time 节点!"); + Assertions.assertTrue(data.size() >= 8, "数据节点个数不正常,可能丢失节点!"); + } - /** - * 校验 UserSchema 数据 - */ - protected void assertUSData(Map data) { - assertSchemaDataNode(data); - assertTrue("数据中用户信息节点(identities+distinct_id/user_id)丢失!", - (data.containsKey("identities") || data.containsKey("id")) && data.containsKey("distinct_id")); - } + /** 校验 itemSchema 数据 */ + protected void assertISData(Map data) { + assertSchemaDataNode(data); + Assertions.assertTrue(data.containsKey("id"), "数据节点中不存在 id 节点!"); + Assertions.assertNotNull(data.get("id"), "数据节点 id 不可为空!"); + Assertions.assertTrue(data.size() >= 8, "数据节点个数不正常,可能丢失节点!"); + } - /** - * 校验 UserItemSchema 数据 - */ - protected void assertUISData(Map data) { - assertSchemaDataNode(data); - assertTrue("数据节点中 id 不可为空!", data.containsKey("id")); - Object properties = data.get("properties"); - assertTrue("数据节点 properties 类型不正确!", properties instanceof Map); - Map proMap = (Map) properties; - assertTrue("数据中用户信息节点(identities+distinct_id/user_id)丢失!", - (proMap.containsKey("identities") || proMap.containsKey("user_id")) && proMap.containsKey("distinct_id")); - assertTrue("数据节点 properties 内节点个数不正常!", proMap.size() >= 2); - } + /** 校验 UserSchema 数据 */ + protected void assertUSData(Map data) { + assertSchemaDataNode(data); + Assertions.assertTrue( + (data.containsKey("identities") || data.containsKey("id")) + && data.containsKey("distinct_id"), + "数据中用户信息节点(identities+distinct_id/user_id)丢失!"); + } - protected void assertSchemaDataNode(Map data) { - assertNotNull("数据节点为空!", data); - assertTrue("数据节点中不存在 version 节点!", data.containsKey("version")); - assertEquals("数据节点 version 值不正确!", SensorsConst.PROTOCOL_VERSION, data.get("version").toString()); - assertTrue("数据节点中不存在 type 节点!", data.containsKey("type")); - assertTrue("数据节点中 type 值不正确!", actionTypeSet.contains(data.get("type").toString())); - assertTrue("数据节点中不存在 schema 节点!", data.containsKey("schema")); - assertTrue("数据节点中 schema 值不正确!", data.get("schema") instanceof String); - assertTrue("数据节点中不存在 properties 节点!", data.containsKey("properties")); - assertTrue("数据节点中不存在 track_id 节点!", data.containsKey("_track_id")); - assertTrue("数据节点 track_id 值类型不正确!", data.get("_track_id") instanceof Integer); - assertTrue("数据节点中不存在 lib 节点!", data.containsKey("lib")); - assertTrue("数据节点中不存在 time 节点!", data.containsKey("time")); - assertTrue("数据节点中 time 节点类型不正确!", data.get("time") instanceof Long); - Object lib = data.get("lib"); - assertTrue("数据节点中 lib 节点类型不正确!", lib instanceof Map); - assertTrue("数据节点 lib 内节点个数异常!", ((Map) lib).size() >= 4); - } + /** 校验 UserItemSchema 数据 */ + protected void assertUISData(Map data) { + assertSchemaDataNode(data); + Assertions.assertTrue(data.containsKey("id"), "数据节点中 id 不可为空!"); + Object properties = data.get("properties"); + Assertions.assertTrue(properties instanceof Map, "数据节点 properties 类型不正确!"); + Map proMap = (Map) properties; + Assertions.assertTrue( + (proMap.containsKey("identities") || proMap.containsKey("user_id")) + && proMap.containsKey("distinct_id"), + "数据中用户信息节点(identities+distinct_id/user_id)丢失!"); + Assertions.assertTrue(proMap.size() >= 2, "数据节点 properties 内节点个数不正常!"); + } + protected void assertSchemaDataNode(Map data) { + Assertions.assertNotNull(data, "数据节点为空!"); + Assertions.assertTrue(data.containsKey("version"), "数据节点中不存在 version 节点!"); + Assertions.assertEquals( + SensorsConst.PROTOCOL_VERSION, + data.get("version").toString(), + "数据节点 version 值不正确!"); + Assertions.assertTrue(data.containsKey("type"), "数据节点中不存在 type 节点!"); + Assertions.assertTrue( + actionTypeSet.contains(data.get("type").toString()), "数据节点中 type 值不正确!"); + Assertions.assertTrue(data.containsKey("schema"), "数据节点中不存在 schema 节点!"); + Assertions.assertTrue(data.get("schema") instanceof String, "数据节点中 schema 值不正确!"); + Assertions.assertTrue(data.containsKey("properties"), "数据节点中不存在 properties 节点!"); + Assertions.assertTrue(data.containsKey("_track_id"), "数据节点中不存在 track_id 节点!"); + Assertions.assertTrue(data.get("_track_id") instanceof Integer, "数据节点 track_id 值类型不正确!"); + Assertions.assertTrue(data.containsKey("lib"), "数据节点中不存在 lib 节点!"); + Assertions.assertTrue(data.containsKey("time"), "数据节点中不存在 time 节点!"); + Assertions.assertTrue(data.get("time") instanceof Long, "数据节点中 time 节点类型不正确!"); + Object lib = data.get("lib"); + Assertions.assertTrue(lib instanceof Map, "数据节点中 lib 节点类型不正确!"); + Assertions.assertTrue(((Map) lib).size() >= 4, "数据节点 lib 内节点个数异常!"); + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SensorsLogsUtil.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SensorsLogsUtil.java index 22dbd26..0dc6c47 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SensorsLogsUtil.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/SensorsLogsUtil.java @@ -1,11 +1,9 @@ package com.sensorsdata.analytics.javasdk; +import com.fasterxml.jackson.core.JsonProcessingException; import com.sensorsdata.analytics.javasdk.bean.FailedData; import com.sensorsdata.analytics.javasdk.consumer.FastBatchConsumer; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import com.fasterxml.jackson.core.JsonProcessingException; - import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executors; @@ -14,13 +12,14 @@ public class SensorsLogsUtil { - //定义一个定时线程,用于定时检查容器中是否存在失败数据 - private static final ScheduledExecutorService resendService = Executors.newSingleThreadScheduledExecutor(); + // 定义一个定时线程,用于定时检查容器中是否存在失败数据 + private static final ScheduledExecutorService resendService = + Executors.newSingleThreadScheduledExecutor(); - //失败数据容器,(此处用于模式测试,生产中可能会有大量数据,因此不建议使用内存容器,建议持久化) + // 失败数据容器,(此处用于模式测试,生产中可能会有大量数据,因此不建议使用内存容器,建议持久化) private static final List failedDataList = new ArrayList<>(); - //往容器中保存数据 + // 往容器中保存数据 public static void setFailedData(FailedData failedData) { failedDataList.add(failedData); for (FailedData fd : failedDataList) { @@ -29,7 +28,7 @@ public static void setFailedData(FailedData failedData) { } } - //初始化重发送操作 + // 初始化重发送操作 public static void resend(FastBatchConsumer consumer) { resendService.scheduleWithFixedDelay(new ResendTask(consumer), 0, 1, TimeUnit.SECONDS); } @@ -58,7 +57,7 @@ public void run() { e.printStackTrace(); } System.out.println("resend success:" + isSend); - if(isSend){ + if (isSend) { failedDataList.remove(failedData); } } @@ -66,5 +65,3 @@ public void run() { } } } - - diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/TestServlet.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/TestServlet.java index b518d19..383d599 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/TestServlet.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/TestServlet.java @@ -1,23 +1,17 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; - import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; -import sun.misc.BASE64Decoder; - +import com.sensorsdata.analytics.javasdk.util.SensorsAnalyticsUtil; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.util.Base64; import java.util.zip.GZIPInputStream; - import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.junit.jupiter.api.Assertions; /** * 模拟服务端接收数据 @@ -28,41 +22,43 @@ */ public class TestServlet extends HttpServlet { - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { - String gzip = request.getParameter("gzip"); - assertEquals("1", gzip); - String dataList = request.getParameter("data_list"); - BASE64Decoder base64Decoder = new BASE64Decoder(); - byte[] bytes = base64Decoder.decodeBuffer(dataList); - byte[] data = decompressGzip(bytes); - ArrayNode arrayNode = (ArrayNode) SensorsAnalyticsUtil.getJsonObjectMapper().readTree(data); - for (JsonNode jsonNode : arrayNode) { - assertNotNull("数据为空!", jsonNode); - assertTrue("数据中没有 type 节点!", jsonNode.has("type")); - assertTrue("数据中没有 actionType 节点!", jsonNode.has("event")); - if (jsonNode.get("event").asText().startsWith("item")) { - assertTrue("item 数据没有 item_id 节点!", jsonNode.has("item_id")); - assertTrue("item 数据没有 item_type 节点!", jsonNode.has("item_type")); - } else { - assertTrue("event or profile 数据没有 _track_id 节点!", jsonNode.has("_track_id")); - assertTrue("event or profile 数据没有 lib 节点!", jsonNode.has("lib")); - assertTrue("event or profile 数据没有 time 节点!", jsonNode.has("time")); - assertTrue("event or profile 数据没有 distinct_id 节点!", jsonNode.has("distinct_id")); - } + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws IOException { + String gzip = request.getParameter("gzip"); + Assertions.assertEquals("1", gzip); + String dataList = request.getParameter("data_list"); + byte[] bytes = Base64.getDecoder().decode(dataList); + byte[] data = decompressGzip(bytes); + ArrayNode arrayNode = (ArrayNode) SensorsAnalyticsUtil.getJsonObjectMapper().readTree(data); + for (JsonNode jsonNode : arrayNode) { + Assertions.assertNotNull(jsonNode, "数据为空!"); + Assertions.assertTrue(jsonNode.has("type"), "数据中没有 type 节点!"); + Assertions.assertTrue(jsonNode.has("event"), "数据中没有 actionType 节点!"); + if (jsonNode.get("event").asText().startsWith("item")) { + Assertions.assertTrue(jsonNode.has("item_id"), "item 数据没有 item_id 节点!"); + Assertions.assertTrue(jsonNode.has("item_type"), "item 数据没有 item_type 节点!"); + } else { + Assertions.assertTrue( + jsonNode.has("_track_id"), "event or profile 数据没有 _track_id 节点!"); + Assertions.assertTrue(jsonNode.has("lib"), "event or profile 数据没有 lib 节点!"); + Assertions.assertTrue(jsonNode.has("time"), "event or profile 数据没有 time 节点!"); + Assertions.assertTrue( + jsonNode.has("distinct_id"), "event or profile 数据没有 distinct_id 节点!"); + } + } + response.setStatus(200); } - response.setStatus(200); - } - protected byte[] decompressGzip(byte[] gzipData) throws IOException { - byte[] bytes1 = new byte[1024]; - GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(gzipData)); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - int n; - while ((n = gis.read(bytes1)) != -1) { - bos.write(bytes1, 0, n); + protected byte[] decompressGzip(byte[] gzipData) throws IOException { + byte[] bytes1 = new byte[1024]; + GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(gzipData)); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + int n; + while ((n = gis.read(bytes1)) != -1) { + bos.write(bytes1, 0, n); + } + bos.close(); + return bos.toByteArray(); } - bos.close(); - return bos.toByteArray(); - } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/TimeFreeFieldTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/TimeFreeFieldTest.java index 142e7df..c4fa639 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/TimeFreeFieldTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/TimeFreeFieldTest.java @@ -1,8 +1,5 @@ package com.sensorsdata.analytics.javasdk; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import com.sensorsdata.analytics.javasdk.bean.EventRecord; import com.sensorsdata.analytics.javasdk.bean.IDMEventRecord; import com.sensorsdata.analytics.javasdk.bean.IDMUserRecord; @@ -14,17 +11,13 @@ import com.sensorsdata.analytics.javasdk.bean.schema.UserEventSchema; import com.sensorsdata.analytics.javasdk.bean.schema.UserSchema; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** - * 检查 time_free 生成逻辑 - * 1、公共属性中设置 - * 2、自定义属性中设置 - * 3、同时设置,以公共属性中设置为准 + * 检查 time_free 生成逻辑 1、公共属性中设置 2、自定义属性中设置 3、同时设置,以公共属性中设置为准 * * @author fangzhuo * @version 1.0.0 @@ -32,217 +25,246 @@ */ public class TimeFreeFieldTest extends SensorsBaseTest { - @Test - public void trackTest() throws InvalidArgumentException { - Map pro = new HashMap<>(); - pro.put("key1", "aaa"); - pro.put("$time_free", true); - sa.track("test1", true, "test", pro); - assertEventData(data); - Map properties = (Map) data.get("properties"); - assertTrue(data.containsKey("time_free")); - assertTrue(Boolean.parseBoolean(data.get("time_free").toString())); - assertTrue(properties.containsKey("key1")); - assertFalse(properties.containsKey("$time_free")); - } - - @Test - public void trackTest1() throws InvalidArgumentException { - Map pro = new HashMap<>(); - pro.put("key1", "aaa"); - pro.put("$time_free", true); - EventRecord eventRecord = - EventRecord.builder().setDistinctId("test1").isLoginId(false).setEventName("test").addProperties(pro).build(); - sa.track(eventRecord); - assertEventData(data); - Map properties = (Map) data.get("properties"); - assertTrue(data.containsKey("time_free")); - assertTrue(Boolean.parseBoolean(data.get("time_free").toString())); - assertTrue(properties.containsKey("key1")); - assertFalse(properties.containsKey("$time_free")); - } - - @Test - public void trackTest2() throws InvalidArgumentException { - Map pro = new HashMap<>(); - pro.put("key1", "aaa"); - pro.put("$time_free", false); - sa.track("test1", true, "test", pro); - assertEventData(data); - Map properties = (Map) data.get("properties"); - assertFalse(data.containsKey("time_free")); - assertFalse(properties.containsKey("$time_free")); - } - - @Test - public void profileTest() throws InvalidArgumentException { - Map pro = new HashMap<>(); - pro.put("key1", "aaa"); - pro.put("$time_free", true); - sa.profileSet("test1", true, pro); - assertUserData(data); - assertFalse(data.containsKey("time_free")); - Map properties = (Map) data.get("properties"); - assertFalse(properties.containsKey("$time_free")); - } - - @Test - public void profileTest1() throws InvalidArgumentException { - Map pro = new HashMap<>(); - pro.put("key1", "aaa"); - pro.put("$time_free", true); - UserRecord userRecord = UserRecord.builder().setDistinctId("test1").isLoginId(true).addProperties(pro).build(); - sa.profileSet(userRecord); - assertUserData(data); - assertFalse(data.containsKey("time_free")); - Map properties = (Map) data.get("properties"); - assertFalse(properties.containsKey("$time_free")); - } - - @Test - public void itemTest() throws InvalidArgumentException { - Map pro = new HashMap<>(); - pro.put("key1", "aaa"); - pro.put("$time_free", true); - sa.itemSet("test1", "aa1", pro); - assertItemData(data); - assertFalse(data.containsKey("time_free")); - Map properties = (Map) data.get("properties"); - assertFalse(properties.containsKey("$time_free")); - } - - @Test - public void itemTest1() throws InvalidArgumentException { - Map pro = new HashMap<>(); - pro.put("key1", "aaa"); - pro.put("$time_free", true); - ItemRecord itemRecord = ItemRecord.builder().setItemId("test1").setItemType("aa1").addProperties(pro).build(); - sa.itemSet(itemRecord); - assertItemData(data); - assertFalse(data.containsKey("time_free")); - Map properties = (Map) data.get("properties"); - assertFalse(properties.containsKey("$time_free")); - } - - @Test - public void IDMTrackTest() throws InvalidArgumentException { - IDMEventRecord eventRecord = IDMEventRecord.starter().setEventName("test1").setDistinctId("ee1") - .addIdentityProperty("test", "e22ee") - .addProperty("$time_free", true).build(); - sa.trackById(eventRecord); - assertIDM3EventData(data); - Map properties = (Map) data.get("properties"); - assertTrue(data.containsKey("time_free")); - assertTrue(Boolean.parseBoolean(data.get("time_free").toString())); - assertFalse(properties.containsKey("$time_free")); - } - - @Test - public void IDMTrackTest1() throws InvalidArgumentException { - Map pro = new HashMap<>(); - pro.put("key1", "aaa"); - pro.put("$time_free", true); - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("test1", "ee") - .build(); - sa.trackById(identity, "test1", pro); - assertIDM3EventData(data); - Map properties = (Map) data.get("properties"); - assertTrue(data.containsKey("time_free")); - assertTrue(Boolean.parseBoolean(data.get("time_free").toString())); - assertFalse(properties.containsKey("$time_free")); - } - - @Test - public void IDMTrackTest2() throws InvalidArgumentException { - Map pro = new HashMap<>(); - pro.put("key1", "aaa"); - pro.put("$time_free", false); - SensorsAnalyticsIdentity identity = SensorsAnalyticsIdentity.builder() - .addIdentityProperty("test1", "ee") - .build(); - sa.trackById(identity, "test1", pro); - assertIDM3EventData(data); - Map properties = (Map) data.get("properties"); - assertFalse(data.containsKey("time_free")); - assertFalse(properties.containsKey("$time_free")); - } - - @Test - public void IDMProfileTest() throws InvalidArgumentException { - Map pro = new HashMap<>(); - pro.put("key1", "aaa"); - pro.put("$time_free", true); - IDMUserRecord userRecord = IDMUserRecord.starter().addIdentityProperty("test1", "ee").addProperties(pro).build(); - sa.profileSetById(userRecord); - assertIDM3UserData(data); - assertFalse(data.containsKey("time_free")); - Map properties = (Map) data.get("properties"); - assertFalse(properties.containsKey("$time_free")); - } - - @Test - public void NGUserEventTrackTest() throws InvalidArgumentException { - Map pro = new HashMap<>(); - pro.put("key1", "aaa"); - pro.put("$time_free", true); - UserEventSchema userEventSchema = UserEventSchema.init().addIdentityProperty("key1", "ee1") - .setEventName("test1") - .addProperties(pro) - .start(); - sa.track(userEventSchema); - Map properties = (Map) data.get("properties"); - assertTrue(data.containsKey("time_free")); - assertTrue(Boolean.parseBoolean(data.get("time_free").toString())); - assertFalse(properties.containsKey("$time_free")); - } - - @Test - public void NGItemEventTrackTest() throws InvalidArgumentException { - ItemEventSchema itemEventSchema = ItemEventSchema.init().setSchema("test1") - .setItemPair("id_1", "ree") - .setEventName("test3") - .addProperty("$time_free", true) - .start(); - sa.track(itemEventSchema); - Map properties = (Map) data.get("properties"); - assertTrue(data.containsKey("time_free")); - assertTrue(Boolean.parseBoolean(data.get("time_free").toString())); - assertFalse(properties.containsKey("$time_free")); - } - - @Test - public void NGUserProfileTest() throws InvalidArgumentException { - UserSchema userSchema = UserSchema.init().setUserId(22L).addProperty("$time_free", true).start(); - sa.profileSet(userSchema); - Map properties = (Map) data.get("properties"); - assertFalse(data.containsKey("time_free")); - assertFalse(properties.containsKey("$time_free")); - } - - @Test - public void NGItemTest() throws InvalidArgumentException { - ItemSchema itemSchema = - ItemSchema.init().setSchema("test33").setItemId("ee2").addProperty("$time_free", true).start(); - sa.itemSet(itemSchema); - Map properties = (Map) data.get("properties"); - assertFalse(data.containsKey("time_free")); - assertFalse(properties.containsKey("$time_free")); - } - - @Test - public void checkCommonProtest() throws InvalidArgumentException { - Map pro = new HashMap<>(); - pro.put("key1", "aaa"); - pro.put("$time_free", true); - sa.registerSuperProperties(pro); - sa.track("test1", true, "test", null); - assertEventData(data); - Map properties = (Map) data.get("properties"); - assertTrue(data.containsKey("time_free")); - assertTrue(Boolean.parseBoolean(data.get("time_free").toString())); - assertTrue(properties.containsKey("key1")); - assertFalse(properties.containsKey("$time_free")); - } + @Test + public void trackTest() throws InvalidArgumentException { + Map pro = new HashMap<>(); + pro.put("key1", "aaa"); + pro.put("$time_free", true); + sa.track("test1", true, "test", pro); + assertEventData(data); + Map properties = (Map) data.get("properties"); + Assertions.assertTrue(data.containsKey("time_free")); + Assertions.assertTrue(Boolean.parseBoolean(data.get("time_free").toString())); + Assertions.assertTrue(properties.containsKey("key1")); + Assertions.assertFalse(properties.containsKey("$time_free")); + } + + @Test + public void trackTest1() throws InvalidArgumentException { + Map pro = new HashMap<>(); + pro.put("key1", "aaa"); + pro.put("$time_free", true); + EventRecord eventRecord = + EventRecord.builder() + .setDistinctId("test1") + .isLoginId(false) + .setEventName("test") + .addProperties(pro) + .build(); + sa.track(eventRecord); + assertEventData(data); + Map properties = (Map) data.get("properties"); + Assertions.assertTrue(data.containsKey("time_free")); + Assertions.assertTrue(Boolean.parseBoolean(data.get("time_free").toString())); + Assertions.assertTrue(properties.containsKey("key1")); + Assertions.assertFalse(properties.containsKey("$time_free")); + } + + @Test + public void trackTest2() throws InvalidArgumentException { + Map pro = new HashMap<>(); + pro.put("key1", "aaa"); + pro.put("$time_free", false); + sa.track("test1", true, "test", pro); + assertEventData(data); + Map properties = (Map) data.get("properties"); + Assertions.assertFalse(data.containsKey("time_free")); + Assertions.assertFalse(properties.containsKey("$time_free")); + } + + @Test + public void profileTest() throws InvalidArgumentException { + Map pro = new HashMap<>(); + pro.put("key1", "aaa"); + pro.put("$time_free", true); + sa.profileSet("test1", true, pro); + assertUserData(data); + Assertions.assertFalse(data.containsKey("time_free")); + Map properties = (Map) data.get("properties"); + Assertions.assertFalse(properties.containsKey("$time_free")); + } + + @Test + public void profileTest1() throws InvalidArgumentException { + Map pro = new HashMap<>(); + pro.put("key1", "aaa"); + pro.put("$time_free", true); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId("test1") + .isLoginId(true) + .addProperties(pro) + .build(); + sa.profileSet(userRecord); + assertUserData(data); + Assertions.assertFalse(data.containsKey("time_free")); + Map properties = (Map) data.get("properties"); + Assertions.assertFalse(properties.containsKey("$time_free")); + } + + @Test + public void itemTest() throws InvalidArgumentException { + Map pro = new HashMap<>(); + pro.put("key1", "aaa"); + pro.put("$time_free", true); + sa.itemSet("test1", "aa1", pro); + assertItemData(data); + Assertions.assertFalse(data.containsKey("time_free")); + Map properties = (Map) data.get("properties"); + Assertions.assertFalse(properties.containsKey("$time_free")); + } + + @Test + public void itemTest1() throws InvalidArgumentException { + Map pro = new HashMap<>(); + pro.put("key1", "aaa"); + pro.put("$time_free", true); + ItemRecord itemRecord = + ItemRecord.builder() + .setItemId("test1") + .setItemType("aa1") + .addProperties(pro) + .build(); + sa.itemSet(itemRecord); + assertItemData(data); + Assertions.assertFalse(data.containsKey("time_free")); + Map properties = (Map) data.get("properties"); + Assertions.assertFalse(properties.containsKey("$time_free")); + } + + @Test + public void IDMTrackTest() throws InvalidArgumentException { + IDMEventRecord eventRecord = + IDMEventRecord.starter() + .setEventName("test1") + .setDistinctId("ee1") + .addIdentityProperty("test", "e22ee") + .addProperty("$time_free", true) + .build(); + sa.trackById(eventRecord); + assertIDM3EventData(data); + Map properties = (Map) data.get("properties"); + Assertions.assertTrue(data.containsKey("time_free")); + Assertions.assertTrue(Boolean.parseBoolean(data.get("time_free").toString())); + Assertions.assertFalse(properties.containsKey("$time_free")); + } + + @Test + public void IDMTrackTest1() throws InvalidArgumentException { + Map pro = new HashMap<>(); + pro.put("key1", "aaa"); + pro.put("$time_free", true); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder().addIdentityProperty("test1", "ee").build(); + sa.trackById(identity, "test1", pro); + assertIDM3EventData(data); + Map properties = (Map) data.get("properties"); + Assertions.assertTrue(data.containsKey("time_free")); + Assertions.assertTrue(Boolean.parseBoolean(data.get("time_free").toString())); + Assertions.assertFalse(properties.containsKey("$time_free")); + } + + @Test + public void IDMTrackTest2() throws InvalidArgumentException { + Map pro = new HashMap<>(); + pro.put("key1", "aaa"); + pro.put("$time_free", false); + SensorsAnalyticsIdentity identity = + SensorsAnalyticsIdentity.builder().addIdentityProperty("test1", "ee").build(); + sa.trackById(identity, "test1", pro); + assertIDM3EventData(data); + Map properties = (Map) data.get("properties"); + Assertions.assertFalse(data.containsKey("time_free")); + Assertions.assertFalse(properties.containsKey("$time_free")); + } + + @Test + public void IDMProfileTest() throws InvalidArgumentException { + Map pro = new HashMap<>(); + pro.put("key1", "aaa"); + pro.put("$time_free", true); + IDMUserRecord userRecord = + IDMUserRecord.starter() + .addIdentityProperty("test1", "ee") + .addProperties(pro) + .build(); + sa.profileSetById(userRecord); + assertIDM3UserData(data); + Assertions.assertFalse(data.containsKey("time_free")); + Map properties = (Map) data.get("properties"); + Assertions.assertFalse(properties.containsKey("$time_free")); + } + + @Test + public void NGUserEventTrackTest() throws InvalidArgumentException { + Map pro = new HashMap<>(); + pro.put("key1", "aaa"); + pro.put("$time_free", true); + UserEventSchema userEventSchema = + UserEventSchema.init() + .addIdentityProperty("key1", "ee1") + .setEventName("test1") + .addProperties(pro) + .start(); + sa.track(userEventSchema); + Map properties = (Map) data.get("properties"); + Assertions.assertTrue(data.containsKey("time_free")); + Assertions.assertTrue(Boolean.parseBoolean(data.get("time_free").toString())); + Assertions.assertFalse(properties.containsKey("$time_free")); + } + + @Test + public void NGItemEventTrackTest() throws InvalidArgumentException { + ItemEventSchema itemEventSchema = + ItemEventSchema.init() + .setSchema("test1") + .setItemPair("id_1", "ree") + .setEventName("test3") + .addProperty("$time_free", true) + .start(); + sa.track(itemEventSchema); + Map properties = (Map) data.get("properties"); + Assertions.assertTrue(data.containsKey("time_free")); + Assertions.assertTrue(Boolean.parseBoolean(data.get("time_free").toString())); + Assertions.assertFalse(properties.containsKey("$time_free")); + } + + @Test + public void NGUserProfileTest() throws InvalidArgumentException { + UserSchema userSchema = + UserSchema.init().setUserId(22L).addProperty("$time_free", true).start(); + sa.profileSet(userSchema); + Map properties = (Map) data.get("properties"); + Assertions.assertFalse(data.containsKey("time_free")); + Assertions.assertFalse(properties.containsKey("$time_free")); + } + + @Test + public void NGItemTest() throws InvalidArgumentException { + ItemSchema itemSchema = + ItemSchema.init() + .setSchema("test33") + .setItemId("ee2") + .addProperty("$time_free", true) + .start(); + sa.itemSet(itemSchema); + Map properties = (Map) data.get("properties"); + Assertions.assertFalse(data.containsKey("time_free")); + Assertions.assertFalse(properties.containsKey("$time_free")); + } + @Test + public void checkCommonProtest() throws InvalidArgumentException { + Map pro = new HashMap<>(); + pro.put("key1", "aaa"); + pro.put("$time_free", true); + sa.registerSuperProperties(pro); + sa.track("test1", true, "test", null); + assertEventData(data); + Map properties = (Map) data.get("properties"); + Assertions.assertTrue(data.containsKey("time_free")); + Assertions.assertTrue(Boolean.parseBoolean(data.get("time_free").toString())); + Assertions.assertTrue(properties.containsKey("key1")); + Assertions.assertFalse(properties.containsKey("$time_free")); + } } diff --git a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/TrackIdModeTest.java b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/TrackIdModeTest.java index a1c88c2..3e97260 100644 --- a/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/TrackIdModeTest.java +++ b/SensorsAnalyticsSDK/src/test/java/com.sensorsdata.analytics.javasdk/TrackIdModeTest.java @@ -7,332 +7,312 @@ import com.sensorsdata.analytics.javasdk.bean.SensorsAnalyticsIdentity; import com.sensorsdata.analytics.javasdk.bean.UserRecord; import com.sensorsdata.analytics.javasdk.exceptions.InvalidArgumentException; - -import org.junit.BeforeClass; -import org.junit.Test; - import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; /** * 迁移 idMapping 1.0 逻辑和支持自定义 _track_id 单元测试 + * * @author luowenjie * @version 3.4.3 * @since 2022/04/20 15:50 */ -public class TrackIdModeTest extends SensorsBaseTest{ - private final static Map mp = new HashMap<>(); - private final String cookieId = "ABCDEF123456789"; - private final SensorsAnalyticsIdentity sensorsAnalyticsIdentity = - SensorsAnalyticsIdentity.builder().addIdentityProperty("cookeId",cookieId).build(); - +public class TrackIdModeTest extends SensorsBaseTest { + private static final Map mp = new HashMap<>(); + private final String cookieId = "ABCDEF123456789"; + private final SensorsAnalyticsIdentity sensorsAnalyticsIdentity = + SensorsAnalyticsIdentity.builder().addIdentityProperty("cookeId", cookieId).build(); - /** - * mp :作为 properties - * 功能: 填充 map - */ - @BeforeClass - public static void buildMap() { - mp.put("Channel", "baidu"); - mp.put("$time",new Date(1650785225)); - mp.put("$project", "default"); - mp.put("$token", "123"); - mp.put("$track_id",123); - } + /** mp :作为 properties 功能: 填充 map */ + @BeforeAll + public static void buildMap() { + mp.put("Channel", "baidu"); + mp.put("$time", new Date(1650785225)); + mp.put("$project", "default"); + mp.put("$token", "123"); + mp.put("$track_id", 123); + } - /** - * 测试功能:上报事件到 event 表 - * 测试预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void track() throws InvalidArgumentException { - EventRecord eventRecord = EventRecord.builder() - .setEventName("test1") - .isLoginId(false) - .addProperties(mp) - .setDistinctId(cookieId) - .build(); - sa.track(cookieId,false,"test1",mp); - assertEventData(data); - sa.track(eventRecord); - assertEventData(data); - sa.track(cookieId,false, "test"); - assertEventData(data); - } + /** 测试功能:上报事件到 event 表 测试预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id */ + @Test + public void track() throws InvalidArgumentException { + EventRecord eventRecord = + EventRecord.builder() + .setEventName("test1") + .isLoginId(false) + .addProperties(mp) + .setDistinctId(cookieId) + .build(); + sa.track(cookieId, false, "test1", mp); + assertEventData(data); + sa.track(eventRecord); + assertEventData(data); + sa.track(cookieId, false, "test"); + assertEventData(data); + } - /** - * 功能:检验 IDM 下上报事件属性 - * 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void trackById() throws InvalidArgumentException { - IDMEventRecord idmEventRecord = IDMEventRecord.starter() - .setEventName("trackById") - .addProperties(mp) - .addIdentityProperty("abc",cookieId) - .setDistinctId(cookieId) - .build(); - sa.trackById(idmEventRecord); - assertEventData(data); - sa.trackById(sensorsAnalyticsIdentity, "track", mp); - assertEventData(data); - } + /** 功能:检验 IDM 下上报事件属性 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id */ + @Test + public void trackById() throws InvalidArgumentException { + IDMEventRecord idmEventRecord = + IDMEventRecord.starter() + .setEventName("trackById") + .addProperties(mp) + .addIdentityProperty("abc", cookieId) + .setDistinctId(cookieId) + .build(); + sa.trackById(idmEventRecord); + assertEventData(data); + sa.trackById(sensorsAnalyticsIdentity, "track", mp); + assertEventData(data); + } - /** - * 功能:校验上报 $SignUp 事件 - * 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void trackSignup() throws InvalidArgumentException { - sa.trackSignUp("123","dada"); - assertEventData(data); - sa.trackSignUp("564","daxfad", mp); - assertEventData(data); - } + /** 功能:校验上报 $SignUp 事件 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id */ + @Test + public void trackSignup() throws InvalidArgumentException { + sa.trackSignUp("123", "dada"); + assertEventData(data); + sa.trackSignUp("564", "daxfad", mp); + assertEventData(data); + } - /** - * 功能:校验记录单个用户的属性信息 - * 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void profileSet() throws InvalidArgumentException { - UserRecord userRecord = UserRecord.builder().setDistinctId(cookieId) - .addProperties(mp) - .isLoginId(Boolean.FALSE) - .build(); - sa.profileSet(userRecord); - assertUserData(data); - sa.profileSet(cookieId,true,mp); - assertUserData(data); - sa.profileSet(cookieId,true, "$track_id",3131); - assertProperties(data); - } + /** 功能:校验记录单个用户的属性信息 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id */ + @Test + public void profileSet() throws InvalidArgumentException { + UserRecord userRecord = + UserRecord.builder() + .setDistinctId(cookieId) + .addProperties(mp) + .isLoginId(Boolean.FALSE) + .build(); + sa.profileSet(userRecord); + assertUserData(data); + sa.profileSet(cookieId, true, mp); + assertUserData(data); + sa.profileSet(cookieId, true, "$track_id", 3131); + assertProperties(data); + } - /** - * 功能:IDM 下校验记录单个用户的属性信息 - * 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void profileSetById() throws InvalidArgumentException { - IDMUserRecord userRecord = IDMUserRecord.starter().setDistinctId(cookieId) - .addProperties(mp) - .build(); - sa.profileSetById(userRecord); - assertUserData(data); - sa.profileSetById(sensorsAnalyticsIdentity,mp); - assertUserData(data); - sa.profileSetById(sensorsAnalyticsIdentity, "$track_id",123); - assertUserData(data); - } + /** 功能:IDM 下校验记录单个用户的属性信息 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id */ + @Test + public void profileSetById() throws InvalidArgumentException { + IDMUserRecord userRecord = + IDMUserRecord.starter().setDistinctId(cookieId).addProperties(mp).build(); + sa.profileSetById(userRecord); + assertUserData(data); + sa.profileSetById(sensorsAnalyticsIdentity, mp); + assertUserData(data); + sa.profileSetById(sensorsAnalyticsIdentity, "$track_id", 123); + assertUserData(data); + } - /** - * 功能:校验首次设置用户属性 - * 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void profileSetOnce() throws InvalidArgumentException { - UserRecord userRecord = UserRecord.builder().setDistinctId(cookieId) - .addProperties(mp) - .isLoginId(Boolean.FALSE) - .build(); - sa.profileSetOnce(userRecord); - assertUserData(data); - sa.profileSetOnce("ABCDEF123456789",false, mp); - assertUserData(data); - sa.profileSetOnce(cookieId, false, "$track_id",123); - assertUserData(data); - } + /** 功能:校验首次设置用户属性 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id */ + @Test + public void profileSetOnce() throws InvalidArgumentException { + UserRecord userRecord = + UserRecord.builder() + .setDistinctId(cookieId) + .addProperties(mp) + .isLoginId(Boolean.FALSE) + .build(); + sa.profileSetOnce(userRecord); + assertUserData(data); + sa.profileSetOnce("ABCDEF123456789", false, mp); + assertUserData(data); + sa.profileSetOnce(cookieId, false, "$track_id", 123); + assertUserData(data); + } - /** - * 功能:IDM 下校验首次设置用户属性 - * 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void profileSetOnceById() throws InvalidArgumentException { - IDMUserRecord userRecord = IDMUserRecord.starter().setDistinctId(cookieId) - .addProperties(mp) - .build(); - sa.profileSetOnceById(userRecord); - assertUserData(data); - sa.profileSetOnceById(sensorsAnalyticsIdentity, mp); - assertUserData(data); - sa.profileSetOnceById(sensorsAnalyticsIdentity, "$track_id", 123); - assertUserData(data); - } + /** 功能:IDM 下校验首次设置用户属性 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id */ + @Test + public void profileSetOnceById() throws InvalidArgumentException { + IDMUserRecord userRecord = + IDMUserRecord.starter().setDistinctId(cookieId).addProperties(mp).build(); + sa.profileSetOnceById(userRecord); + assertUserData(data); + sa.profileSetOnceById(sensorsAnalyticsIdentity, mp); + assertUserData(data); + sa.profileSetOnceById(sensorsAnalyticsIdentity, "$track_id", 123); + assertUserData(data); + } - /** - * 功能:校验删除指定用户已存在的一条或者多条属性 - * 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void profileUnset() throws InvalidArgumentException { - Map mp = new HashMap<>(); - mp.put("Channel", true); - UserRecord userRecord = UserRecord.builder().setDistinctId(cookieId) - .addProperties(mp) - .isLoginId(Boolean.FALSE) - .build(); - sa.profileUnset(userRecord); - assertUserData(data); - sa.profileUnset(cookieId,true,mp); - assertUserData(data); - sa.profileUnset(cookieId, true, "Channel"); - assertUserData(data); - } + /** 功能:校验删除指定用户已存在的一条或者多条属性 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id */ + @Test + public void profileUnset() throws InvalidArgumentException { + Map mp = new HashMap<>(); + mp.put("Channel", true); + UserRecord userRecord = + UserRecord.builder() + .setDistinctId(cookieId) + .addProperties(mp) + .isLoginId(Boolean.FALSE) + .build(); + sa.profileUnset(userRecord); + assertUserData(data); + sa.profileUnset(cookieId, true, mp); + assertUserData(data); + sa.profileUnset(cookieId, true, "Channel"); + assertUserData(data); + } - /** - * 功能:IDM 下校验删除指定用户已存在的一条或者多条属性 - * 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void profileUnsetById() throws InvalidArgumentException { - Map ma = new HashMap<>(); - ma.put("Channel", true); - IDMUserRecord idmUserRecord = IDMUserRecord.starter().setDistinctId(cookieId) - .addProperties(ma) - .build(); - sa.profileUnsetById(idmUserRecord); - assertUserData(data); - sa.profileUnsetById(sensorsAnalyticsIdentity, ma); - assertUserData(data); - sa.profileUnsetById(sensorsAnalyticsIdentity, "Channel"); - assertUserData(data); - } + /** + * 功能:IDM 下校验删除指定用户已存在的一条或者多条属性 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id + */ + @Test + public void profileUnsetById() throws InvalidArgumentException { + Map ma = new HashMap<>(); + ma.put("Channel", true); + IDMUserRecord idmUserRecord = + IDMUserRecord.starter().setDistinctId(cookieId).addProperties(ma).build(); + sa.profileUnsetById(idmUserRecord); + assertUserData(data); + sa.profileUnsetById(sensorsAnalyticsIdentity, ma); + assertUserData(data); + sa.profileUnsetById(sensorsAnalyticsIdentity, "Channel"); + assertUserData(data); + } - /** - * 功能:校验删除指定用户所有属性 - * 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void profileDelete() throws InvalidArgumentException { - UserRecord userRecord = UserRecord.builder() - .setDistinctId(cookieId) - .isLoginId(true) - .build(); - sa.profileDelete(cookieId, true); - assertUserData(data); - sa.profileDelete(userRecord); - assertUserData(data); - } + /** 功能:校验删除指定用户所有属性 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id */ + @Test + public void profileDelete() throws InvalidArgumentException { + UserRecord userRecord = + UserRecord.builder().setDistinctId(cookieId).isLoginId(true).build(); + sa.profileDelete(cookieId, true); + assertUserData(data); + sa.profileDelete(userRecord); + assertUserData(data); + } - /** - * 功能:IDM 下校验删除指定用户所有属性 - * 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void profileDeleteById() throws InvalidArgumentException { - sa.profileDeleteById(sensorsAnalyticsIdentity); - assertUserData(data); - } + /** 功能:IDM 下校验删除指定用户所有属性 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id */ + @Test + public void profileDeleteById() throws InvalidArgumentException { + sa.profileDeleteById(sensorsAnalyticsIdentity); + assertUserData(data); + } - /** - * 功能:校验为指定用户的一个或多个数组类型的属性追加字符串 - * 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void profileAppend() throws InvalidArgumentException { - List newInterest = new ArrayList<>(); - newInterest.add("ball"); - Map mp = new HashMap<>(); - mp.put("interest", newInterest); - UserRecord appendRecord = UserRecord.builder().setDistinctId(cookieId).isLoginId(Boolean.TRUE) - .addProperty("interest", newInterest) - .build(); - sa.profileAppend(appendRecord); - assertUserData(data); - sa.profileAppend(cookieId,false,mp); - assertUserData(data); - sa.profileAppend(cookieId,false, "interest", "ball"); - assertUserData(data); - } + /** + * 功能:校验为指定用户的一个或多个数组类型的属性追加字符串 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id + */ + @Test + public void profileAppend() throws InvalidArgumentException { + List newInterest = new ArrayList<>(); + newInterest.add("ball"); + Map mp = new HashMap<>(); + mp.put("interest", newInterest); + UserRecord appendRecord = + UserRecord.builder() + .setDistinctId(cookieId) + .isLoginId(Boolean.TRUE) + .addProperty("interest", newInterest) + .build(); + sa.profileAppend(appendRecord); + assertUserData(data); + sa.profileAppend(cookieId, false, mp); + assertUserData(data); + sa.profileAppend(cookieId, false, "interest", "ball"); + assertUserData(data); + } - /** - * 功能:IDM 下校验为指定用户的一个或多个数组类型的属性追加字符串 - * 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void profileAppendById() throws InvalidArgumentException { - List newInterest = new ArrayList<>(); - newInterest.add("ball"); - Map mp = new HashMap<>(); - mp.put("interest", newInterest); - IDMUserRecord idmUserRecord = IDMUserRecord.starter().setDistinctId(cookieId).addProperty("interest", newInterest).build(); - sa.profileAppendById(idmUserRecord); - assertUserData(data); - sa.profileAppendById(sensorsAnalyticsIdentity,mp); - assertUserData(data); - sa.profileAppendById(sensorsAnalyticsIdentity,"interest","ball"); - assertUserData(data); - } + /** + * 功能:IDM 下校验为指定用户的一个或多个数组类型的属性追加字符串 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 + * $track_id + */ + @Test + public void profileAppendById() throws InvalidArgumentException { + List newInterest = new ArrayList<>(); + newInterest.add("ball"); + Map mp = new HashMap<>(); + mp.put("interest", newInterest); + IDMUserRecord idmUserRecord = + IDMUserRecord.starter() + .setDistinctId(cookieId) + .addProperty("interest", newInterest) + .build(); + sa.profileAppendById(idmUserRecord); + assertUserData(data); + sa.profileAppendById(sensorsAnalyticsIdentity, mp); + assertUserData(data); + sa.profileAppendById(sensorsAnalyticsIdentity, "interest", "ball"); + assertUserData(data); + } - /** - * 功能:校验为指定用户的一个或多个数值类型的属性累加一个数值 - * 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void profileIncrement() throws InvalidArgumentException { - Map mp = new HashMap<>(); - mp.put("age",2); - UserRecord incrementRecord = UserRecord.builder().setDistinctId(cookieId).isLoginId(Boolean.TRUE) - .addProperty("age", 2) - .build(); - sa.profileIncrement(incrementRecord); - assertUserData(data); - sa.profileIncrement(cookieId,false,mp); - assertUserData(data); - sa.profileIncrement(cookieId,false,"age",2); - assertUserData(data); - } + /** + * 功能:校验为指定用户的一个或多个数值类型的属性累加一个数值 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id + */ + @Test + public void profileIncrement() throws InvalidArgumentException { + Map mp = new HashMap<>(); + mp.put("age", 2); + UserRecord incrementRecord = + UserRecord.builder() + .setDistinctId(cookieId) + .isLoginId(Boolean.TRUE) + .addProperty("age", 2) + .build(); + sa.profileIncrement(incrementRecord); + assertUserData(data); + sa.profileIncrement(cookieId, false, mp); + assertUserData(data); + sa.profileIncrement(cookieId, false, "age", 2); + assertUserData(data); + } - /** - * 功能:IDM 下校验为指定用户的一个或多个数值类型的属性累加一个数值 - * 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void profileIncrementById() throws InvalidArgumentException { - IDMUserRecord idmUserRecord = IDMUserRecord.starter().setDistinctId(cookieId).addProperty("age",2).build(); - Map mp = new HashMap<>(); - mp.put("age",2); - sa.profileIncrementById(idmUserRecord); - assertUserData(data); - sa.profileIncrementById(sensorsAnalyticsIdentity,mp); - assertUserData(data); - sa.profileIncrementById(sensorsAnalyticsIdentity,"age",2); - assertUserData(data); - } + /** + * 功能:IDM 下校验为指定用户的一个或多个数值类型的属性累加一个数值 预期:生成的数据符合神策格式,且 _track_id 存在,properties 中不包含 $time 和 + * $track_id + */ + @Test + public void profileIncrementById() throws InvalidArgumentException { + IDMUserRecord idmUserRecord = + IDMUserRecord.starter().setDistinctId(cookieId).addProperty("age", 2).build(); + Map mp = new HashMap<>(); + mp.put("age", 2); + sa.profileIncrementById(idmUserRecord); + assertUserData(data); + sa.profileIncrementById(sensorsAnalyticsIdentity, mp); + assertUserData(data); + sa.profileIncrementById(sensorsAnalyticsIdentity, "age", 2); + assertUserData(data); + } - /** - * 功能:校验增加 item 记录 - * 预期:生成的数据符合神策格式,且 _track_id 不存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void itemSet() throws InvalidArgumentException { - Map mp = new HashMap<>(); - mp.put("$track_id",123); - mp.put("$time", new Date(1650785226)); - ItemRecord itemRecord = ItemRecord.builder().setItemType("test").setItemId(cookieId).addProperties(mp).build(); - sa.itemSet(itemRecord); - assertItemData(data); - sa.itemSet("test",cookieId,mp); - assertItemData(data); - } + /** 功能:校验增加 item 记录 预期:生成的数据符合神策格式,且 _track_id 不存在,properties 中不包含 $time 和 $track_id */ + @Test + public void itemSet() throws InvalidArgumentException { + Map mp = new HashMap<>(); + mp.put("$track_id", 123); + mp.put("$time", new Date(1650785226)); + ItemRecord itemRecord = + ItemRecord.builder() + .setItemType("test") + .setItemId(cookieId) + .addProperties(mp) + .build(); + sa.itemSet(itemRecord); + assertItemData(data); + sa.itemSet("test", cookieId, mp); + assertItemData(data); + } - /** - * 功能:校验删除 item 记录 - * 预期:生成的数据符合神策格式,且 _track_id 不存在,properties 中不包含 $time 和 $track_id - */ - @Test - public void itemDelete() throws InvalidArgumentException { - Map mp = new HashMap<>(); - mp.put("$track_id",123); - mp.put("$time", new Date(1650785226)); - ItemRecord itemRecord = ItemRecord.builder().setItemType("test").setItemId(cookieId).addProperties(mp).build(); - sa.itemDelete(itemRecord); - assertItemData(data); - sa.itemDelete("test",cookieId,mp); - assertItemData(data); - } + /** 功能:校验删除 item 记录 预期:生成的数据符合神策格式,且 _track_id 不存在,properties 中不包含 $time 和 $track_id */ + @Test + public void itemDelete() throws InvalidArgumentException { + Map mp = new HashMap<>(); + mp.put("$track_id", 123); + mp.put("$time", new Date(1650785226)); + ItemRecord itemRecord = + ItemRecord.builder() + .setItemType("test") + .setItemId(cookieId) + .addProperties(mp) + .build(); + sa.itemDelete(itemRecord); + assertItemData(data); + sa.itemDelete("test", cookieId, mp); + assertItemData(data); + } }