From 535372cb504c934154e62971e8cddd5e354ca6f7 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Mon, 24 Jan 2022 12:26:25 -0800 Subject: [PATCH 01/80] chore: remove Jcenter deadline for old SDK versions (#461) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3bf5cac4f..c2aa60f86 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ following in your `build.gradle` and substitute `VERSION` for the latest SDK ver --- **NOTE** -[Bintray/JCenter will be shut down](https://jfrog.com/blog/into-the-sunset-bintray-jcenter-gocenter-and-chartcenter/). The publish repository has been migrated to MavenCentral for the SDK version 3.8.1 or later. Older versions will be available in JCenter until February 1st, 2022. +[Bintray/JCenter will be shut down](https://jfrog.com/blog/into-the-sunset-bintray-jcenter-gocenter-and-chartcenter/). The publish repository has been migrated to MavenCentral for the SDK version 3.8.1 or later. Older versions will be available in JCenter. --- From d4c37aea2f05e13f1051b668928cc2a348b14e9d Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Thu, 3 Feb 2022 11:19:07 -0800 Subject: [PATCH 02/80] fix(NotificationManager): add thread-safety to NotificationManager (#460) Fix NotificationManager to be thread-safe (add-handler and send-notifications can happen concurrently) --- .../ab/notification/NotificationManager.java | 25 ++++++++------ .../notification/NotificationManagerTest.java | 33 +++++++++++++++++++ 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/notification/NotificationManager.java b/core-api/src/main/java/com/optimizely/ab/notification/NotificationManager.java index 5254d76b8..7415e6b23 100644 --- a/core-api/src/main/java/com/optimizely/ab/notification/NotificationManager.java +++ b/core-api/src/main/java/com/optimizely/ab/notification/NotificationManager.java @@ -19,6 +19,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; @@ -33,7 +34,7 @@ public class NotificationManager { private static final Logger logger = LoggerFactory.getLogger(NotificationManager.class); - private final Map> handlers = new LinkedHashMap<>(); + private final Map> handlers = Collections.synchronizedMap(new LinkedHashMap<>()); private final AtomicInteger counter; public NotificationManager() { @@ -47,10 +48,12 @@ public NotificationManager(AtomicInteger counter) { public int addHandler(NotificationHandler newHandler) { // Prevent registering a duplicate listener. - for (NotificationHandler handler: handlers.values()) { - if (handler.equals(newHandler)) { - logger.warn("Notification listener was already added"); - return -1; + synchronized (handlers) { + for (NotificationHandler handler : handlers.values()) { + if (handler.equals(newHandler)) { + logger.warn("Notification listener was already added"); + return -1; + } } } @@ -61,11 +64,13 @@ public int addHandler(NotificationHandler newHandler) { } public void send(final T message) { - for (Map.Entry> handler: handlers.entrySet()) { - try { - handler.getValue().handle(message); - } catch (Exception e) { - logger.warn("Catching exception sending notification for class: {}, handler: {}", message.getClass(), handler.getKey()); + synchronized (handlers) { + for (Map.Entry> handler: handlers.entrySet()) { + try { + handler.getValue().handle(message); + } catch (Exception e) { + logger.warn("Catching exception sending notification for class: {}, handler: {}", message.getClass(), handler.getKey()); + } } } } diff --git a/core-api/src/test/java/com/optimizely/ab/notification/NotificationManagerTest.java b/core-api/src/test/java/com/optimizely/ab/notification/NotificationManagerTest.java index c51a84e3f..58767ac7a 100644 --- a/core-api/src/test/java/com/optimizely/ab/notification/NotificationManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/notification/NotificationManagerTest.java @@ -20,6 +20,11 @@ import org.junit.Test; import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.*; @@ -70,4 +75,32 @@ public void testSendWithError() { assertEquals(1, messages.size()); assertEquals("message1", messages.get(0).getMessage()); } + + @Test + public void testThreadSafety() throws InterruptedException { + int numThreads = 10; + int numRepeats = 2; + ExecutorService executor = Executors.newFixedThreadPool(numThreads); + CountDownLatch latch = new CountDownLatch(numThreads); + AtomicBoolean failedAlready = new AtomicBoolean(false); + + for(int i = 0; i < numThreads; i++) { + executor.execute(() -> { + try { + for (int j = 0; j < numRepeats; j++) { + if(!failedAlready.get()) { + notificationManager.addHandler(new TestNotificationHandler<>()); + notificationManager.send(new TestNotification("message1")); + } + } + } catch (Exception e) { + failedAlready.set(true); + } finally { + latch.countDown(); + } + }); + } + assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertEquals(numThreads * numRepeats, notificationManager.size()); + } } From 77fb91404052d4c93f685f2dadfbc280457e8d86 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Thu, 3 Feb 2022 12:03:25 -0800 Subject: [PATCH 03/80] prepare for release 3.10.1 (#462) --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d7d1bf62..ca3935252 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Optimizely Java X SDK Changelog +## [3.10.1] +February 3rd, 2022 + +### Fixes +- Fix NotificationManager to be thread-safe (add-handler and send-notifications can happen concurrently) ([#460](https://github.com/optimizely/java-sdk/pull/460)). + ## 3.10.0 January 10th, 2022 From 206ae8be0de9580863a05598a02c0337e0ea9ee4 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Tue, 15 Feb 2022 16:51:49 -0800 Subject: [PATCH 04/80] chore: fix http-httpclient module tests not included in travis (#464) --- build.gradle | 2 +- core-httpclient-impl/build.gradle | 4 ++++ .../test/java/com/optimizely/ab/OptimizelyHttpClientTest.java | 2 ++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index e0e14fa9d..4c167014f 100644 --- a/build.gradle +++ b/build.gradle @@ -16,7 +16,7 @@ allprojects { } jacoco { - toolVersion = '0.8.0' + toolVersion = '0.8.7' } } diff --git a/core-httpclient-impl/build.gradle b/core-httpclient-impl/build.gradle index 7e452d36e..b43c70269 100644 --- a/core-httpclient-impl/build.gradle +++ b/core-httpclient-impl/build.gradle @@ -5,3 +5,7 @@ dependencies { compile group: 'org.apache.httpcomponents', name: 'httpclient', version: httpClientVersion } + +task exhaustiveTest { + dependsOn('test') +} diff --git a/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyHttpClientTest.java b/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyHttpClientTest.java index 7dc61f0f9..4667bec34 100644 --- a/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyHttpClientTest.java +++ b/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyHttpClientTest.java @@ -40,6 +40,8 @@ public class OptimizelyHttpClientTest { @Before public void setUp() { System.setProperty("https.proxyHost", "localhost"); + // default port (80) returns 404 instead of HttpHostConnectException + System.setProperty("https.proxyPort", "12345"); } @After From d8df15987b0060880bd3795f319be4e032b1b9c5 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Tue, 15 Feb 2022 17:09:55 -0800 Subject: [PATCH 05/80] fix(audience): log debug instead of warning for missing attribute value (#463) --- .../ab/config/audience/match/ExactMatch.java | 6 ++-- .../match/SemanticVersionEqualsMatch.java | 3 +- .../match/SemanticVersionGEMatch.java | 3 +- .../match/SemanticVersionGTMatch.java | 3 +- .../match/SemanticVersionLEMatch.java | 3 +- .../match/SemanticVersionLTMatch.java | 3 +- .../AudienceConditionEvaluationTest.java | 36 ++++++++++++++----- .../audience/match/SemanticVersionTest.java | 15 ++++++-- 8 files changed, 55 insertions(+), 17 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/match/ExactMatch.java b/core-api/src/main/java/com/optimizely/ab/config/audience/match/ExactMatch.java index 5781ac892..d39d00c83 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/match/ExactMatch.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/match/ExactMatch.java @@ -1,6 +1,6 @@ /** * - * Copyright 2018-2020, Optimizely and contributors + * Copyright 2018-2020, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,6 +28,8 @@ class ExactMatch implements Match { @Nullable public Boolean eval(Object conditionValue, Object attributeValue) throws UnexpectedValueTypeException { + if (attributeValue == null) return null; + if (isValidNumber(attributeValue)) { if (isValidNumber(conditionValue)) { return NumberComparator.compareUnsafe(attributeValue, conditionValue) == 0; @@ -39,7 +41,7 @@ public Boolean eval(Object conditionValue, Object attributeValue) throws Unexpec throw new UnexpectedValueTypeException(); } - if (attributeValue == null || attributeValue.getClass() != conditionValue.getClass()) { + if (attributeValue.getClass() != conditionValue.getClass()) { return null; } diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionEqualsMatch.java b/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionEqualsMatch.java index ac0c8310b..58ecb4202 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionEqualsMatch.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionEqualsMatch.java @@ -1,6 +1,6 @@ /** * - * Copyright 2020, Optimizely and contributors + * Copyright 2020, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ class SemanticVersionEqualsMatch implements Match { @Nullable public Boolean eval(Object conditionValue, Object attributeValue) throws UnexpectedValueTypeException { + if (attributeValue == null) return null; // stay silent (no WARNING) when attribute value is missing or empty. return SemanticVersion.compare(attributeValue, conditionValue) == 0; } } diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionGEMatch.java b/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionGEMatch.java index 91f95d4cd..bad0b1e4f 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionGEMatch.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionGEMatch.java @@ -1,6 +1,6 @@ /** * - * Copyright 2020, Optimizely and contributors + * Copyright 2020, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ class SemanticVersionGEMatch implements Match { @Nullable public Boolean eval(Object conditionValue, Object attributeValue) throws UnexpectedValueTypeException { + if (attributeValue == null) return null; // stay silent (no WARNING) when attribute value is missing or empty. return SemanticVersion.compare(attributeValue, conditionValue) >= 0; } } diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionGTMatch.java b/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionGTMatch.java index 52513024c..7d403f693 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionGTMatch.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionGTMatch.java @@ -1,6 +1,6 @@ /** * - * Copyright 2020, Optimizely and contributors + * Copyright 2020, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ class SemanticVersionGTMatch implements Match { @Nullable public Boolean eval(Object conditionValue, Object attributeValue) throws UnexpectedValueTypeException { + if (attributeValue == null) return null; // stay silent (no WARNING) when attribute value is missing or empty. return SemanticVersion.compare(attributeValue, conditionValue) > 0; } } diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionLEMatch.java b/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionLEMatch.java index 4297d4545..b3aed672e 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionLEMatch.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionLEMatch.java @@ -1,6 +1,6 @@ /** * - * Copyright 2020, Optimizely and contributors + * Copyright 2020, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ class SemanticVersionLEMatch implements Match { @Nullable public Boolean eval(Object conditionValue, Object attributeValue) throws UnexpectedValueTypeException { + if (attributeValue == null) return null; // stay silent (no WARNING) when attribute value is missing or empty. return SemanticVersion.compare(attributeValue, conditionValue) <= 0; } } diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionLTMatch.java b/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionLTMatch.java index a35dcd2da..d65251f54 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionLTMatch.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/match/SemanticVersionLTMatch.java @@ -1,6 +1,6 @@ /** * - * Copyright 2020, Optimizely and contributors + * Copyright 2020, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ class SemanticVersionLTMatch implements Match { @Nullable public Boolean eval(Object conditionValue, Object attributeValue) throws UnexpectedValueTypeException { + if (attributeValue == null) return null; // stay silent (no WARNING) when attribute value is missing or empty. return SemanticVersion.compare(attributeValue, conditionValue) < 0; } } diff --git a/core-api/src/test/java/com/optimizely/ab/config/audience/AudienceConditionEvaluationTest.java b/core-api/src/test/java/com/optimizely/ab/config/audience/AudienceConditionEvaluationTest.java index 481be0f23..07a0c1ad1 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/audience/AudienceConditionEvaluationTest.java +++ b/core-api/src/test/java/com/optimizely/ab/config/audience/AudienceConditionEvaluationTest.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2020, Optimizely and contributors + * Copyright 2016-2020, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package com.optimizely.ab.config.audience; import ch.qos.logback.classic.Level; +import com.fasterxml.jackson.databind.deser.std.MapEntryDeserializer; import com.optimizely.ab.internal.LogbackVerifier; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.junit.Before; @@ -191,16 +192,35 @@ public void unexpectedAttributeTypeNull() throws Exception { "Audience condition \"{name='browser_type', type='custom_attribute', match='gt', value=20}\" evaluated to UNKNOWN because a null value was passed for user attribute \"browser_type\""); } - /** - * Verify that UserAttribute.evaluate returns null on missing attribute value. + * Verify that UserAttribute.evaluate returns null (and log debug message) on missing attribute value. */ @Test - public void missingAttribute() throws Exception { - UserAttribute testInstance = new UserAttribute("browser_type", "custom_attribute", "gt", 20); - assertNull(testInstance.evaluate(null, Collections.EMPTY_MAP)); - logbackVerifier.expectMessage(Level.DEBUG, - "Audience condition \"{name='browser_type', type='custom_attribute', match='gt', value=20}\" evaluated to UNKNOWN because no value was passed for user attribute \"browser_type\""); + public void missingAttribute_returnsNullAndLogDebugMessage() throws Exception { + // check with all valid value types for each match + + Map items = new HashMap<>(); + items.put("exact", new Object[]{"string", 123, true}); + items.put("substring", new Object[]{"string"}); + items.put("gt", new Object[]{123, 5.3}); + items.put("ge", new Object[]{123, 5.3}); + items.put("lt", new Object[]{123, 5.3}); + items.put("le", new Object[]{123, 5.3}); + items.put("semver_eq", new Object[]{"1.2.3"}); + items.put("semver_ge", new Object[]{"1.2.3"}); + items.put("semver_gt", new Object[]{"1.2.3"}); + items.put("semver_le", new Object[]{"1.2.3"}); + items.put("semver_lt", new Object[]{"1.2.3"}); + + for (Map.Entry entry : items.entrySet()) { + for (Object value : entry.getValue()) { + UserAttribute testInstance = new UserAttribute("n", "custom_attribute", entry.getKey(), value); + assertNull(testInstance.evaluate(null, Collections.EMPTY_MAP)); + String valueStr = (value instanceof String) ? ("'" + value + "'") : value.toString(); + logbackVerifier.expectMessage(Level.DEBUG, + "Audience condition \"{name='n', type='custom_attribute', match='" + entry.getKey() + "', value=" + valueStr + "}\" evaluated to UNKNOWN because no value was passed for user attribute \"n\""); + } + } } /** diff --git a/core-api/src/test/java/com/optimizely/ab/config/audience/match/SemanticVersionTest.java b/core-api/src/test/java/com/optimizely/ab/config/audience/match/SemanticVersionTest.java index 1b819d418..29383a7d7 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/audience/match/SemanticVersionTest.java +++ b/core-api/src/test/java/com/optimizely/ab/config/audience/match/SemanticVersionTest.java @@ -1,6 +1,6 @@ /** * - * Copyright 2020, Optimizely and contributors + * Copyright 2020, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,6 @@ public class SemanticVersionTest { @Rule public ExpectedException thrown = ExpectedException.none(); - @Test public void semanticVersionInvalidOnlyDash() throws Exception { thrown.expect(Exception.class); @@ -165,4 +164,16 @@ public void testGreaterThan() throws Exception { assertTrue(SemanticVersion.compare("3.7.1-prerelease-prerelease+rc", "3.7.1-prerelease+build") > 0); assertTrue(SemanticVersion.compare("3.7.1-beta.2", "3.7.1-beta.1") > 0); } + + @Test + public void testSilentForNullOrMissingAttributesValues() throws Exception { + // SemanticVersionMatcher will throw UnexpectedValueType exception for invalid condition or attribute values (this exception is handled to log WARNING messages). + // But, for missing (or null) attribute value, it should not throw the exception. + assertNull(new SemanticVersionEqualsMatch().eval("1.2.3", null)); + assertNull(new SemanticVersionGEMatch().eval("1.2.3", null)); + assertNull(new SemanticVersionGTMatch().eval("1.2.3", null)); + assertNull(new SemanticVersionLEMatch().eval("1.2.3", null)); + assertNull(new SemanticVersionLTMatch().eval("1.2.3", null)); + } + } From d3dfb974f14a74cf369243a48636210539101a05 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Thu, 3 Mar 2022 16:57:49 -0800 Subject: [PATCH 06/80] remove a separate settings.gradle from quickstart (#465) --- java-quickstart/gradle/wrapper/gradle-wrapper.properties | 2 +- java-quickstart/settings.gradle | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) delete mode 100644 java-quickstart/settings.gradle diff --git a/java-quickstart/gradle/wrapper/gradle-wrapper.properties b/java-quickstart/gradle/wrapper/gradle-wrapper.properties index 933b6473c..3c46198fc 100644 --- a/java-quickstart/gradle/wrapper/gradle-wrapper.properties +++ b/java-quickstart/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip diff --git a/java-quickstart/settings.gradle b/java-quickstart/settings.gradle deleted file mode 100644 index 8cd2bdccd..000000000 --- a/java-quickstart/settings.gradle +++ /dev/null @@ -1,2 +0,0 @@ -rootProject.name = 'java-quickstart' - From 81fdfb2dd4c099f44acd7ddf523de52d01c84fc3 Mon Sep 17 00:00:00 2001 From: Trisha Hanlon Date: Thu, 10 Mar 2022 16:54:16 -0600 Subject: [PATCH 07/80] Create README.md (#467) --- README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index c2aa60f86..62c75d880 100644 --- a/README.md +++ b/README.md @@ -16,14 +16,12 @@ Optimizely Rollouts is free feature flags for development teams. Easily roll out #### Gradle -The SDK is available through Bintray and is created with source and target compatibility of 1.8. The core-api and httpclient Bintray packages are [optimizely-sdk-core-api](https://bintray.com/optimizely/optimizely/optimizely-sdk-core-api) -and [optimizely-sdk-httpclient](https://bintray.com/optimizely/optimizely/optimizely-sdk-httpclient) respectively. To install, place the -following in your `build.gradle` and substitute `VERSION` for the latest SDK version available via MavenCentral. +The Java SDK is distributed through Maven Central and is created with source and target compatibility of Java 1.8. The `core-api` and `httpclient` packages are [optimizely-sdk-core-api](https://mvnrepository.com/artifact/com.optimizely.ab/core-api) and [optimizely-sdk-httpclient](https://mvnrepository.com/artifact/com.optimizely.ab/core-httpclient-impl), respectively. --- **NOTE** -[Bintray/JCenter will be shut down](https://jfrog.com/blog/into-the-sunset-bintray-jcenter-gocenter-and-chartcenter/). The publish repository has been migrated to MavenCentral for the SDK version 3.8.1 or later. Older versions will be available in JCenter. +Optimizely previously distributed the Java SDK through Bintray/JCenter. But, as of April 27, 2021, [Bintray/JCenter will become a read-only repository indefinitely](https://jfrog.com/blog/into-the-sunset-bintray-jcenter-gocenter-and-chartcenter/). The publish repository has been migrated to [MavenCentral](https://mvnrepository.com/artifact/com.optimizely.ab) for the SDK version 3.8.1 or later. --- From 336b610e60e17e7f2389633f19ed981215bcbfdd Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Tue, 15 Mar 2022 08:44:21 -0700 Subject: [PATCH 08/80] fix: add Optimizely builder option for client-engine info (#466) --- .../java/com/optimizely/ab/Optimizely.java | 20 +++++-- .../ab/event/internal/BuildVersionInfo.java | 20 ++++++- .../ab/event/internal/EventFactory.java | 4 +- .../ab/event/internal/payload/EventBatch.java | 4 +- .../optimizely/ab/OptimizelyBuilderTest.java | 55 ++++++++++++++++++- .../ab/event/internal/EventFactoryTest.java | 14 ++--- 6 files changed, 96 insertions(+), 21 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/Optimizely.java b/core-api/src/main/java/com/optimizely/ab/Optimizely.java index 7eae1a1d0..51335ec4f 100644 --- a/core-api/src/main/java/com/optimizely/ab/Optimizely.java +++ b/core-api/src/main/java/com/optimizely/ab/Optimizely.java @@ -25,10 +25,7 @@ import com.optimizely.ab.error.ErrorHandler; import com.optimizely.ab.error.NoOpErrorHandler; import com.optimizely.ab.event.*; -import com.optimizely.ab.event.internal.ClientEngineInfo; -import com.optimizely.ab.event.internal.EventFactory; -import com.optimizely.ab.event.internal.UserEvent; -import com.optimizely.ab.event.internal.UserEventFactory; +import com.optimizely.ab.event.internal.*; import com.optimizely.ab.event.internal.payload.EventBatch; import com.optimizely.ab.notification.*; import com.optimizely.ab.optimizelyconfig.OptimizelyConfig; @@ -1489,7 +1486,7 @@ public Builder withErrorHandler(ErrorHandler errorHandler) { } /** - * The withEventHandler has has been moved to the EventProcessor which takes a EventHandler in it's builder + * The withEventHandler has been moved to the EventProcessor which takes a EventHandler in it's builder * method. * {@link com.optimizely.ab.event.BatchEventProcessor.Builder#withEventHandler(com.optimizely.ab.event.EventHandler)} label} * Please use that builder method instead. @@ -1519,6 +1516,19 @@ public Builder withUserProfileService(UserProfileService userProfileService) { return this; } + /** + * Override the SDK name and version (for client SDKs like android-sdk wrapping the core java-sdk) to be included in events. + * + * @param clientEngine the client engine type. + * @param clientVersion the client SDK version. + * @return An Optimizely builder + */ + public Builder withClientInfo(EventBatch.ClientEngine clientEngine, String clientVersion) { + ClientEngineInfo.setClientEngine(clientEngine); + BuildVersionInfo.setClientVersion(clientVersion); + return this; + } + @Deprecated public Builder withClientEngine(EventBatch.ClientEngine clientEngine) { logger.info("Deprecated. In the future, set ClientEngine via ClientEngineInfo#setClientEngine."); diff --git a/core-api/src/main/java/com/optimizely/ab/event/internal/BuildVersionInfo.java b/core-api/src/main/java/com/optimizely/ab/event/internal/BuildVersionInfo.java index 3aea4d878..d5620b4e9 100644 --- a/core-api/src/main/java/com/optimizely/ab/event/internal/BuildVersionInfo.java +++ b/core-api/src/main/java/com/optimizely/ab/event/internal/BuildVersionInfo.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2017, 2019, Optimizely and contributors + * Copyright 2016-2017, 2019, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,13 +30,29 @@ /** * Helper class to retrieve the SDK version information. */ -@Immutable public final class BuildVersionInfo { private static final Logger logger = LoggerFactory.getLogger(BuildVersionInfo.class); + @Deprecated public final static String VERSION = readVersionNumber(); + // can be overridden by other wrapper client (android-sdk, etc) + + private static String clientVersion = readVersionNumber(); + + public static void setClientVersion(String version) { + if (version == null || version.isEmpty()) { + logger.warn("ClientVersion cannot be empty, defaulting to the core java-sdk version."); + return; + } + clientVersion = version; + } + + public static String getClientVersion() { + return clientVersion; + } + private static String readVersionNumber() { BufferedReader bufferedReader = null; try { diff --git a/core-api/src/main/java/com/optimizely/ab/event/internal/EventFactory.java b/core-api/src/main/java/com/optimizely/ab/event/internal/EventFactory.java index 5a881128d..f651be851 100644 --- a/core-api/src/main/java/com/optimizely/ab/event/internal/EventFactory.java +++ b/core-api/src/main/java/com/optimizely/ab/event/internal/EventFactory.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2020, Optimizely and contributors + * Copyright 2016-2020, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,7 +73,7 @@ public static LogEvent createLogEvent(List userEvents) { builder .setClientName(ClientEngineInfo.getClientEngine().getClientEngineValue()) - .setClientVersion(BuildVersionInfo.VERSION) + .setClientVersion(BuildVersionInfo.getClientVersion()) .setAccountId(projectConfig.getAccountId()) .setAnonymizeIp(projectConfig.getAnonymizeIP()) .setProjectId(projectConfig.getProjectId()) diff --git a/core-api/src/main/java/com/optimizely/ab/event/internal/payload/EventBatch.java b/core-api/src/main/java/com/optimizely/ab/event/internal/payload/EventBatch.java index fe06b631f..c50ee6288 100644 --- a/core-api/src/main/java/com/optimizely/ab/event/internal/payload/EventBatch.java +++ b/core-api/src/main/java/com/optimizely/ab/event/internal/payload/EventBatch.java @@ -1,6 +1,6 @@ /** * - * Copyright 2018-2019, Optimizely and contributors + * Copyright 2018-2019, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -165,7 +165,7 @@ public int hashCode() { public static class Builder { private String clientName = ClientEngine.JAVA_SDK.getClientEngineValue(); - private String clientVersion = BuildVersionInfo.VERSION; + private String clientVersion = BuildVersionInfo.getClientVersion(); private String accountId; private List visitors; private Boolean anonymizeIp; diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java index 932150337..91bb19e18 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2017, 2019, Optimizely and contributors + * Copyright 2016-2017, 2019, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,12 +20,17 @@ import com.optimizely.ab.config.*; import com.optimizely.ab.error.ErrorHandler; import com.optimizely.ab.error.NoOpErrorHandler; +import com.optimizely.ab.event.BatchEventProcessor; import com.optimizely.ab.event.EventHandler; +import com.optimizely.ab.event.LogEvent; +import com.optimizely.ab.event.internal.BuildVersionInfo; +import com.optimizely.ab.event.internal.payload.EventBatch; import com.optimizely.ab.optimizelydecision.OptimizelyDecideOption; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; @@ -34,11 +39,14 @@ import java.util.List; import static com.optimizely.ab.config.DatafileProjectConfigTestUtils.*; +import static junit.framework.Assert.assertEquals; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.*; +import static org.mockito.Mockito.never; /** * Tests for {@link Optimizely#builder(String, EventHandler)}. @@ -195,4 +203,45 @@ public void withDefaultDecideOptions() throws Exception { assertEquals(optimizelyClient.defaultDecideOptions.get(2), OptimizelyDecideOption.EXCLUDE_VARIABLES); } + @Test + public void withClientInfo() throws Exception { + Optimizely optimizely; + EventHandler eventHandler; + ArgumentCaptor argument = ArgumentCaptor.forClass(LogEvent.class); + + // default client-engine info (java-sdk) + + eventHandler = mock(EventHandler.class); + optimizely = Optimizely.builder(validConfigJsonV4(), eventHandler).build(); + optimizely.track("basic_event", "tester"); + + verify(eventHandler, timeout(5000)).dispatchEvent(argument.capture()); + assertEquals(argument.getValue().getEventBatch().getClientName(), "java-sdk"); + assertEquals(argument.getValue().getEventBatch().getClientVersion(), BuildVersionInfo.getClientVersion()); + + // invalid override with null inputs + + reset(eventHandler); + optimizely = Optimizely.builder(validConfigJsonV4(), eventHandler) + .withClientInfo(null, null) + .build(); + optimizely.track("basic_event", "tester"); + + verify(eventHandler, timeout(5000)).dispatchEvent(argument.capture()); + assertEquals(argument.getValue().getEventBatch().getClientName(), "java-sdk"); + assertEquals(argument.getValue().getEventBatch().getClientVersion(), BuildVersionInfo.getClientVersion()); + + // override client-engine info + + reset(eventHandler); + optimizely = Optimizely.builder(validConfigJsonV4(), eventHandler) + .withClientInfo(EventBatch.ClientEngine.ANDROID_SDK, "1.2.3") + .build(); + optimizely.track("basic_event", "tester"); + + verify(eventHandler, timeout(5000)).dispatchEvent(argument.capture()); + assertEquals(argument.getValue().getEventBatch().getClientName(), "android-sdk"); + assertEquals(argument.getValue().getEventBatch().getClientVersion(), "1.2.3"); + } + } diff --git a/core-api/src/test/java/com/optimizely/ab/event/internal/EventFactoryTest.java b/core-api/src/test/java/com/optimizely/ab/event/internal/EventFactoryTest.java index 1c5a48313..657bc4fbf 100644 --- a/core-api/src/test/java/com/optimizely/ab/event/internal/EventFactoryTest.java +++ b/core-api/src/test/java/com/optimizely/ab/event/internal/EventFactoryTest.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2020, Optimizely and contributors + * Copyright 2016-2020, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -157,7 +157,7 @@ public void createImpressionEventPassingUserAgentAttribute() throws Exception { assertThat(eventBatch.getAccountId(), is(validProjectConfig.getAccountId())); assertThat(eventBatch.getVisitors().get(0).getAttributes(), is(expectedUserFeatures)); assertThat(eventBatch.getClientName(), is(EventBatch.ClientEngine.JAVA_SDK.getClientEngineValue())); - assertThat(eventBatch.getClientVersion(), is(BuildVersionInfo.VERSION)); + assertThat(eventBatch.getClientVersion(), is(BuildVersionInfo.getClientVersion())); assertNull(eventBatch.getVisitors().get(0).getSessionId()); } @@ -224,7 +224,7 @@ public void createImpressionEvent() throws Exception { assertThat(eventBatch.getAccountId(), is(validProjectConfig.getAccountId())); assertThat(eventBatch.getVisitors().get(0).getAttributes(), is(expectedUserFeatures)); assertThat(eventBatch.getClientName(), is(EventBatch.ClientEngine.JAVA_SDK.getClientEngineValue())); - assertThat(eventBatch.getClientVersion(), is(BuildVersionInfo.VERSION)); + assertThat(eventBatch.getClientVersion(), is(BuildVersionInfo.getClientVersion())); assertNull(eventBatch.getVisitors().get(0).getSessionId()); } @@ -649,7 +649,7 @@ public void createConversionEvent() throws Exception { assertEquals(conversion.getAnonymizeIp(), validProjectConfig.getAnonymizeIP()); assertTrue(conversion.getEnrichDecisions()); assertEquals(conversion.getClientName(), EventBatch.ClientEngine.JAVA_SDK.getClientEngineValue()); - assertEquals(conversion.getClientVersion(), BuildVersionInfo.VERSION); + assertEquals(conversion.getClientVersion(), BuildVersionInfo.getClientVersion()); } /** @@ -717,7 +717,7 @@ public void createConversionEventPassingUserAgentAttribute() throws Exception { assertEquals(conversion.getAnonymizeIp(), validProjectConfig.getAnonymizeIP()); assertTrue(conversion.getEnrichDecisions()); assertEquals(conversion.getClientName(), EventBatch.ClientEngine.JAVA_SDK.getClientEngineValue()); - assertEquals(conversion.getClientVersion(), BuildVersionInfo.VERSION); + assertEquals(conversion.getClientVersion(), BuildVersionInfo.getClientVersion()); } /** @@ -961,7 +961,7 @@ public void createImpressionEventWithBucketingId() throws Exception { assertThat(impression.getVisitors().get(0).getAttributes(), is(expectedUserFeatures)); assertThat(impression.getClientName(), is(EventBatch.ClientEngine.JAVA_SDK.getClientEngineValue())); - assertThat(impression.getClientVersion(), is(BuildVersionInfo.VERSION)); + assertThat(impression.getClientVersion(), is(BuildVersionInfo.getClientVersion())); assertNull(impression.getVisitors().get(0).getSessionId()); } @@ -1034,7 +1034,7 @@ public void createConversionEventWithBucketingId() throws Exception { assertEquals(conversion.getAnonymizeIp(), validProjectConfig.getAnonymizeIP()); assertTrue(conversion.getEnrichDecisions()); assertEquals(conversion.getClientName(), EventBatch.ClientEngine.JAVA_SDK.getClientEngineValue()); - assertEquals(conversion.getClientVersion(), BuildVersionInfo.VERSION); + assertEquals(conversion.getClientVersion(), BuildVersionInfo.getClientVersion()); } From 0248dda3cad967c1a84ad63b725a0a2a2d08b2fd Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Thu, 17 Mar 2022 13:46:06 -0700 Subject: [PATCH 09/80] prepare for release 3.10.2 (#468) --- CHANGELOG.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ca3935252..50b9c6cf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,21 @@ # Optimizely Java X SDK Changelog +## [3.10.2] +March 17th, 2022 + +### Fixes + +- For some audience condition matchers (semantic-version, le, or ge), SDK logs WARNING messages when the attribute value is missing. This is fixed down to the DEBUG level to be consistent with other condition matchers ([#463](https://github.com/optimizely/java-sdk/pull/463)). +- Add an option to specify the client-engine version (android-sdk, etc) in the Optimizely builder ([#466](https://github.com/optimizely/java-sdk/pull/466)). + + ## [3.10.1] February 3rd, 2022 ### Fixes - Fix NotificationManager to be thread-safe (add-handler and send-notifications can happen concurrently) ([#460](https://github.com/optimizely/java-sdk/pull/460)). -## 3.10.0 +## [3.10.0] January 10th, 2022 ### New Features From 9dc90892641601fd38fe5f0365be5dfb8f0fc6e7 Mon Sep 17 00:00:00 2001 From: Trisha Hanlon Date: Thu, 7 Apr 2022 13:36:28 -0500 Subject: [PATCH 10/80] Updating doc urls (#471) * Updating doc urls * Updating to v4.0 for doc urls --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 62c75d880..376a8ec59 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,9 @@ Optimizely Java SDK This repository houses the Java SDK for use with Optimizely Full Stack and Optimizely Rollouts. -Optimizely Full Stack is A/B testing and feature flag management for product development teams. Experiment in any application. Make every feature on your roadmap an opportunity to learn. Learn more at https://www.optimizely.com/platform/full-stack/, or see the [documentation](https://docs.developers.optimizely.com/full-stack/docs). +Optimizely Full Stack is A/B testing and feature flag management for product development teams. Experiment in any application. Make every feature on your roadmap an opportunity to learn. Learn more at https://www.optimizely.com/platform/full-stack/, or see the [documentation](https://docs.developers.optimizely.com/experimentation/v4.0-full-stack/docs). -Optimizely Rollouts is free feature flags for development teams. Easily roll out and roll back features in any application without code deploys. Mitigate risk for every feature on your roadmap. Learn more at https://www.optimizely.com/rollouts/, or see the [documentation](https://docs.developers.optimizely.com/rollouts/docs). +Optimizely Rollouts is free feature flags for development teams. Easily roll out and roll back features in any application without code deploys. Mitigate risk for every feature on your roadmap. Learn more at https://www.optimizely.com/rollouts/, or see the [documentation](https://docs.developers.optimizely.com/experimentation/v3.1.0-full-stack/docs/introduction-to-rollouts). ## Getting Started @@ -57,7 +57,7 @@ To access the Feature Management configuration in the Optimizely dashboard, plea ### Using the SDK -See the Optimizely Full Stack [developer documentation](http://developers.optimizely.com/server/reference/index.html) to learn how to set +See the Optimizely Full Stack [developer documentation](https://docs.developers.optimizely.com/experimentation/v4.0-full-stack/docs/java-sdk) to learn how to set up your first Java project and use the SDK. ## Development From fcb5524b0df92a86b12d3e3ef67c61eb1473066c Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Fri, 15 Apr 2022 02:03:20 +0500 Subject: [PATCH 11/80] chore: removed travis yml and added git action support (#469) --- .github/workflows/build.yml | 40 ++++++++ .github/workflows/integration_test.yml | 56 ++++++++++++ .github/workflows/java.yml | 116 ++++++++++++++++++++++++ .github/workflows/source_clear_cron.yml | 16 ++++ .travis.yml | 92 ------------------- 5 files changed, 228 insertions(+), 92 deletions(-) create mode 100644 .github/workflows/build.yml create mode 100644 .github/workflows/integration_test.yml create mode 100644 .github/workflows/java.yml create mode 100644 .github/workflows/source_clear_cron.yml delete mode 100644 .travis.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 000000000..e7ba7782e --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,40 @@ +name: Reusable action of building snapshot and publish + +on: + workflow_call: + inputs: + action: + required: true + type: string + travis_tag: + required: true + type: string + secrets: + MAVEN_SIGNING_KEY_BASE64: + required: true + MAVEN_SIGNING_PASSPHRASE: + required: true + MAVEN_CENTRAL_USERNAME: + required: true + MAVEN_CENTRAL_PASSWORD: + required: true +jobs: + run_build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: set up JDK 8 + uses: actions/setup-java@v2 + with: + java-version: '8' + distribution: 'temurin' + cache: gradle + - name: Grant execute permission for gradlew + run: chmod +x gradlew + - name: ${{ inputs.action }} + env: + MAVEN_SIGNING_KEY_BASE64: ${{ secrets.MAVEN_SIGNING_KEY_BASE64 }} + MAVEN_SIGNING_PASSPHRASE: ${{ secrets.MAVEN_SIGNING_PASSPHRASE }} + MAVEN_CENTRAL_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }} + MAVEN_CENTRAL_PASSWORD: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} + run: TRAVIS_TAG=${{ inputs.travis_tag }} ./gradlew ${{ inputs.action }} diff --git a/.github/workflows/integration_test.yml b/.github/workflows/integration_test.yml new file mode 100644 index 000000000..e4d1c7e7d --- /dev/null +++ b/.github/workflows/integration_test.yml @@ -0,0 +1,56 @@ +name: Reusable action of running integration of production suite + +on: + workflow_call: + inputs: + FULLSTACK_TEST_REPO: + required: false + type: string + secrets: + CI_USER_TOKEN: + required: true + TRAVIS_COM_TOKEN: + required: true +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + with: + # You should create a personal access token and store it in your repository + token: ${{ secrets.CI_USER_TOKEN }} + repository: 'optimizely/travisci-tools' + path: 'home/runner/travisci-tools' + ref: 'master' + - name: set SDK Branch if PR + if: ${{ github.event_name == 'pull_request' }} + run: | + echo "SDK_BRANCH=${{ github.head_ref }}" >> $GITHUB_ENV + echo "TRAVIS_BRANCH=${{ github.head_ref }}" >> $GITHUB_ENV + - name: set SDK Branch if not pull request + if: ${{ github.event_name != 'pull_request' }} + run: | + echo "SDK_BRANCH=${{ github.ref_name }}" >> $GITHUB_ENV + echo "TRAVIS_BRANCH=${{ github.ref_name }}" >> $GITHUB_ENV + - name: Trigger build + env: + SDK: java + FULLSTACK_TEST_REPO: ${{ inputs.FULLSTACK_TEST_REPO }} + BUILD_NUMBER: ${{ github.run_id }} + TESTAPP_BRANCH: master + GITHUB_TOKEN: ${{ secrets.CI_USER_TOKEN }} + TRAVIS_EVENT_TYPE: ${{ github.event_name }} + GITHUB_CONTEXT: ${{ toJson(github) }} + TRAVIS_REPO_SLUG: ${{ github.repository }} + TRAVIS_PULL_REQUEST_SLUG: ${{ github.repository }} + UPSTREAM_REPO: ${{ github.repository }} + TRAVIS_COMMIT: ${{ github.sha }} + TRAVIS_PULL_REQUEST_SHA: ${{ github.event.pull_request.head.sha }} + TRAVIS_PULL_REQUEST: ${{ github.event.pull_request.number }} + UPSTREAM_SHA: ${{ github.sha }} + TRAVIS_COM_TOKEN: ${{ secrets.TRAVIS_COM_TOKEN }} + EVENT_MESSAGE: ${{ github.event.message }} + HOME: 'home/runner' + run: | + echo "$GITHUB_CONTEXT" + home/runner/travisci-tools/trigger-script-with-status-update.sh diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml new file mode 100644 index 000000000..a7c2eafe9 --- /dev/null +++ b/.github/workflows/java.yml @@ -0,0 +1,116 @@ + +name: Java CI with Gradle + +on: + push: + branches: [ master ] + tags: + - '*' + pull_request: + branches: [ master ] + workflow_dispatch: + inputs: + SNAPSHOT: + type: boolean + description: Set SNAPSHOT true to publish + +jobs: + lint_markdown_files: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: '2.6' + bundler-cache: true # runs 'bundle install' and caches installed gems automatically + - name: Install gem + run: | + gem install awesome_bot + - name: Run tests + run: find . -type f -name '*.md' -exec awesome_bot {} \; + + integration_tests: + uses: optimizely/java-sdk/.github/workflows/integration_test.yml@master + secrets: + CI_USER_TOKEN: ${{ secrets.CI_USER_TOKEN }} + TRAVIS_COM_TOKEN: ${{ secrets.TRAVIS_COM_TOKEN }} + + fullstack_production_suite: + uses: optimizely/java-sdk/.github/workflows/integration_test.yml@master + with: + FULLSTACK_TEST_REPO: ProdTesting + secrets: + CI_USER_TOKEN: ${{ secrets.CI_USER_TOKEN }} + TRAVIS_COM_TOKEN: ${{ secrets.TRAVIS_COM_TOKEN }} + + test: + if: startsWith(github.ref, 'refs/tags/') != true + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + jdk: [8, 9] + optimizely_default_parser: [GSON_CONFIG_PARSER, JACKSON_CONFIG_PARSER, JSON_CONFIG_PARSER, JSON_SIMPLE_CONFIG_PARSER] + steps: + - name: checkout + uses: actions/checkout@v2 + + - name: set up JDK ${{ matrix.jdk }} + uses: AdoptOpenJDK/install-jdk@v1 + with: + version: ${{ matrix.jdk }} + architecture: x64 + + - name: Grant execute permission for gradlew + run: chmod +x gradlew + + - name: Gradle cache + uses: actions/cache@v2 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*') }}-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties') }}-${{ hashFiles('**/buildSrc/**/*.kt') }} + + - name: run tests + id: unit_tests + env: + optimizely_default_parser: ${{ matrix.optimizely_default_parser }} + run: | + ./gradlew clean + ./gradlew exhaustiveTest + ./gradlew build + - name: Check on failures + if: steps.unit_tests.outcome != 'success' + run: | + cat /home/runner/java-sdk/core-api/build/reports/findbugs/main.html + cat /home/runner/java-sdk/core-api/build/reports/findbugs/test.html + - name: Check on success + if: steps.unit_tests.outcome == 'success' + run: | + ./gradlew coveralls uploadArchives --console plain + + publish: + if: startsWith(github.ref, 'refs/tags/') + uses: optimizely/java-sdk/.github/workflows/build.yml@master + with: + action: ship + travis_tag: ${GITHUB_REF#refs/*/} + secrets: + MAVEN_SIGNING_KEY_BASE64: ${{ secrets.MAVEN_SIGNING_KEY_BASE64 }} + MAVEN_SIGNING_PASSPHRASE: ${{ secrets.MAVEN_SIGNING_PASSPHRASE }} + MAVEN_CENTRAL_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }} + MAVEN_CENTRAL_PASSWORD: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} + + snapshot: + if: ${{ github.event.inputs.SNAPSHOT == 'true' && github.event_name == 'workflow_dispatch' }} + uses: optimizely/java-sdk/.github/workflows/build.yml@master + with: + action: ship + travis_tag: BB-SNAPSHOT + secrets: + MAVEN_SIGNING_KEY_BASE64: ${{ secrets.MAVEN_SIGNING_KEY_BASE64 }} + MAVEN_SIGNING_PASSPHRASE: ${{ secrets.MAVEN_SIGNING_PASSPHRASE }} + MAVEN_CENTRAL_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }} + MAVEN_CENTRAL_PASSWORD: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} diff --git a/.github/workflows/source_clear_cron.yml b/.github/workflows/source_clear_cron.yml new file mode 100644 index 000000000..54eca5358 --- /dev/null +++ b/.github/workflows/source_clear_cron.yml @@ -0,0 +1,16 @@ +name: Source clear + +on: + schedule: + # Runs "weekly" + - cron: '0 0 * * 0' + +jobs: + source_clear: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Source clear scan + env: + SRCCLR_API_TOKEN: ${{ secrets.SRCCLR_API_TOKEN }} + run: curl -sSL https://download.sourceclear.com/ci.sh | bash -s – scan diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 2735eacaf..000000000 --- a/.travis.yml +++ /dev/null @@ -1,92 +0,0 @@ -language: java -dist: trusty -jdk: - - openjdk8 - - oraclejdk8 - - oraclejdk9 -install: true -env: - - optimizely_default_parser=GSON_CONFIG_PARSER - - optimizely_default_parser=JACKSON_CONFIG_PARSER - - optimizely_default_parser=JSON_CONFIG_PARSER - - optimizely_default_parser=JSON_SIMPLE_CONFIG_PARSER -script: - - "./gradlew clean" - - "./gradlew exhaustiveTest" - - "./gradlew build" - -cache: - gradle: true - directories: - - "$HOME/.gradle/caches" - - "$HOME/.gradle/wrapper" -branches: - only: - - master - - /^\d+\.\d+\.(\d|[x])+(-SNAPSHOT|-alpha|-beta)?\d*$/ # trigger builds on tags which are semantically versioned to ship the SDK. -after_success: - - ./gradlew coveralls uploadArchives --console plain -after_failure: - - cat /home/travis/build/optimizely/java-sdk/core-api/build/reports/findbugs/main.html - - cat /home/travis/build/optimizely/java-sdk/core-api/build/reports/findbugs/test.html - -# Integration tests need to run first to reset the PR build status to pending -stages: - - 'Source Clear' - - 'Lint markdown files' - - 'Integration tests' - - 'Full stack production tests' - - 'Test' - - 'Publish' - - 'Snapshot' - -jobs: - include: - - stage: 'Lint markdown files' - os: linux - language: generic - install: gem install awesome_bot - script: - - find . -type f -name '*.md' -exec awesome_bot {} \; - notifications: - email: false - - - &integrationtest - stage: 'Integration tests' - merge_mode: replace - env: SDK=java SDK_BRANCH=$TRAVIS_PULL_REQUEST_BRANCH - cache: false - language: minimal - before_install: skip - install: skip - before_script: - - mkdir $HOME/travisci-tools && pushd $HOME/travisci-tools && git init && git pull https://$CI_USER_TOKEN@github.com/optimizely/travisci-tools.git && popd - script: - - $HOME/travisci-tools/trigger-script-with-status-update.sh - after_success: travis_terminate 0 - - - <<: *integrationtest - stage: 'Full stack production tests' - env: - SDK=java - SDK_BRANCH=$TRAVIS_PULL_REQUEST_BRANCH - FULLSTACK_TEST_REPO=ProdTesting - - - stage: 'Source Clear' - if: type = cron - install: skip - before_script: skip - script: skip - after_success: skip - - - stage: 'Publish' - if: tag IS present - script: - - ./gradlew ship - after_success: skip - - - stage: 'Snapshot' - if: env(SNAPSHOT) = true and type = api - script: - - TRAVIS_TAG=BB-SNAPSHOT ./gradlew ship - after_success: skip From 60188c6e52311f873fedafbcaeccb6ba45446790 Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Fri, 24 Jun 2022 00:04:34 +0500 Subject: [PATCH 12/80] Fixing the git action build ubuntu to 18.04 (#473) * test * test * test * adding travis yml to make sure everytest is working * test * test * commenting out gitaction build for now until github action resolves there issue * enabling only unit test for testing * test * test * test * test * test again * test * test * test * test * changed ubuntu version to 18.04 from latest * removing travis yml * reverted the changes * revert --- .github/workflows/build.yml | 2 +- .github/workflows/java.yml | 7 +++---- .../ab/config/DatafileProjectConfigTestUtils.java | 2 +- .../ab/config/parser/JacksonConfigParserTest.java | 1 + 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e7ba7782e..0cd965aad 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -20,7 +20,7 @@ on: required: true jobs: run_build: - runs-on: ubuntu-latest + runs-on: ubuntu-18.04 steps: - uses: actions/checkout@v2 - name: set up JDK 8 diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml index a7c2eafe9..bc866f898 100644 --- a/.github/workflows/java.yml +++ b/.github/workflows/java.yml @@ -1,4 +1,3 @@ - name: Java CI with Gradle on: @@ -46,7 +45,7 @@ jobs: test: if: startsWith(github.ref, 'refs/tags/') != true - runs-on: ubuntu-latest + runs-on: ubuntu-18.04 strategy: fail-fast: false matrix: @@ -82,12 +81,12 @@ jobs: ./gradlew exhaustiveTest ./gradlew build - name: Check on failures - if: steps.unit_tests.outcome != 'success' + if: always() && steps.unit_tests.outcome != 'success' run: | cat /home/runner/java-sdk/core-api/build/reports/findbugs/main.html cat /home/runner/java-sdk/core-api/build/reports/findbugs/test.html - name: Check on success - if: steps.unit_tests.outcome == 'success' + if: always() && steps.unit_tests.outcome == 'success' run: | ./gradlew coveralls uploadArchives --console plain diff --git a/core-api/src/test/java/com/optimizely/ab/config/DatafileProjectConfigTestUtils.java b/core-api/src/test/java/com/optimizely/ab/config/DatafileProjectConfigTestUtils.java index b96815a39..49eaac733 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/DatafileProjectConfigTestUtils.java +++ b/core-api/src/test/java/com/optimizely/ab/config/DatafileProjectConfigTestUtils.java @@ -491,7 +491,7 @@ private static void verifyExperiments(List actual, List assertThat(actualExperiment.getGroupId(), is(expectedExperiment.getGroupId())); assertThat(actualExperiment.getStatus(), is(expectedExperiment.getStatus())); assertThat(actualExperiment.getAudienceIds(), is(expectedExperiment.getAudienceIds())); - assertThat(actualExperiment.getAudienceConditions(), is(expectedExperiment.getAudienceConditions())); + assertEquals(actualExperiment.getAudienceConditions(), expectedExperiment.getAudienceConditions()); assertThat(actualExperiment.getUserIdToVariationKeyMap(), is(expectedExperiment.getUserIdToVariationKeyMap())); diff --git a/core-api/src/test/java/com/optimizely/ab/config/parser/JacksonConfigParserTest.java b/core-api/src/test/java/com/optimizely/ab/config/parser/JacksonConfigParserTest.java index e4e009e10..2e5dcb672 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/parser/JacksonConfigParserTest.java +++ b/core-api/src/test/java/com/optimizely/ab/config/parser/JacksonConfigParserTest.java @@ -69,6 +69,7 @@ public void parseProjectConfigV3() throws Exception { verifyProjectConfig(actual, expected); } + @SuppressFBWarnings("NP_NULL_PARAM_DEREF") @Test public void parseProjectConfigV4() throws Exception { JacksonConfigParser parser = new JacksonConfigParser(); From 60b11f81ef416c7985d0c59f92fc9aa45cfd02a3 Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Tue, 19 Jul 2022 04:21:36 +0500 Subject: [PATCH 13/80] feat: updated for fsc git action (#476) Updated gitactions.yaml --- .github/workflows/integration_test.yml | 14 +++++++------- .github/workflows/java.yml | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/integration_test.yml b/.github/workflows/integration_test.yml index e4d1c7e7d..9471458fc 100644 --- a/.github/workflows/integration_test.yml +++ b/.github/workflows/integration_test.yml @@ -15,7 +15,7 @@ jobs: test: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 with: # You should create a personal access token and store it in your repository token: ${{ secrets.CI_USER_TOKEN }} @@ -39,15 +39,15 @@ jobs: BUILD_NUMBER: ${{ github.run_id }} TESTAPP_BRANCH: master GITHUB_TOKEN: ${{ secrets.CI_USER_TOKEN }} - TRAVIS_EVENT_TYPE: ${{ github.event_name }} + EVENT_TYPE: ${{ github.event_name }} GITHUB_CONTEXT: ${{ toJson(github) }} - TRAVIS_REPO_SLUG: ${{ github.repository }} - TRAVIS_PULL_REQUEST_SLUG: ${{ github.repository }} + #REPO_SLUG: ${{ github.repository }} + PULL_REQUEST_SLUG: ${{ github.repository }} UPSTREAM_REPO: ${{ github.repository }} - TRAVIS_COMMIT: ${{ github.sha }} - TRAVIS_PULL_REQUEST_SHA: ${{ github.event.pull_request.head.sha }} - TRAVIS_PULL_REQUEST: ${{ github.event.pull_request.number }} + PULL_REQUEST_SHA: ${{ github.event.pull_request.head.sha }} + PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number }} UPSTREAM_SHA: ${{ github.sha }} + TOKEN: ${{ secrets.TRAVIS_COM_TOKEN }} TRAVIS_COM_TOKEN: ${{ secrets.TRAVIS_COM_TOKEN }} EVENT_MESSAGE: ${{ github.event.message }} HOME: 'home/runner' diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml index bc866f898..35ab54025 100644 --- a/.github/workflows/java.yml +++ b/.github/workflows/java.yml @@ -30,7 +30,7 @@ jobs: run: find . -type f -name '*.md' -exec awesome_bot {} \; integration_tests: - uses: optimizely/java-sdk/.github/workflows/integration_test.yml@master + uses: optimizely/java-sdk/.github/workflows/integration_test.yml@mnoman/fsc-gitaction-test secrets: CI_USER_TOKEN: ${{ secrets.CI_USER_TOKEN }} TRAVIS_COM_TOKEN: ${{ secrets.TRAVIS_COM_TOKEN }} From 6b9b965b7c9839335c98315f3d7a1d3bba2ae741 Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Fri, 22 Jul 2022 02:46:50 +0500 Subject: [PATCH 14/80] feat: Add ODP Segments support in Audience Evaluation (#474) ## Summary 1. Added ODP Segments support in Audience evaluation 2. Adding logic to parse Integrations from datafile and make odp host and key available in projectConfig. ## Test plan - Manually tested thoroughly. - Added New unit tests. - Existing unit tests pass. - Existing Full stack compatibility tests pass. ## JIRA [OASIS-8382](https://optimizely.atlassian.net/browse/OASIS-8382) --- .github/workflows/java.yml | 2 +- .../optimizely/ab/OptimizelyUserContext.java | 35 +- .../ab/bucketing/DecisionService.java | 4 +- .../ab/config/DatafileProjectConfig.java | 41 +- .../com/optimizely/ab/config/Integration.java | 67 ++ .../optimizely/ab/config/ProjectConfig.java | 6 + .../ab/config/audience/AndCondition.java | 7 +- .../ab/config/audience/AttributeType.java | 33 + .../config/audience/AudienceIdCondition.java | 9 +- .../ab/config/audience/Condition.java | 5 +- .../ab/config/audience/EmptyCondition.java | 5 +- .../ab/config/audience/NotCondition.java | 10 +- .../ab/config/audience/NullCondition.java | 5 +- .../ab/config/audience/OrCondition.java | 7 +- .../ab/config/audience/UserAttribute.java | 35 +- .../config/audience/match/MatchRegistry.java | 2 +- .../parser/DatafileGsonDeserializer.java | 10 +- .../parser/DatafileJacksonDeserializer.java | 9 +- .../ab/config/parser/JsonConfigParser.java | 24 +- .../config/parser/JsonSimpleConfigParser.java | 23 +- .../ab/internal/ExperimentUtils.java | 19 +- .../DatafileProjectConfigTestUtils.java | 20 +- .../ab/config/ValidProjectConfigV4.java | 7 +- .../AudienceConditionEvaluationTest.java | 782 ++++++++++++------ .../parser/DefaultConfigParserTest.java | 1 + .../config/parser/GsonConfigParserTest.java | 64 ++ .../parser/JacksonConfigParserTest.java | 64 ++ .../config/parser/JsonConfigParserTest.java | 63 ++ .../parser/JsonSimpleConfigParserTest.java | 64 ++ .../ab/internal/ExperimentUtilsTest.java | 27 +- .../OptimizelyConfigServiceTest.java | 3 +- .../com/optimizely/ab/testutils/OTUtils.java | 36 + .../config/valid-project-config-v4.json | 7 + 33 files changed, 1184 insertions(+), 312 deletions(-) create mode 100644 core-api/src/main/java/com/optimizely/ab/config/Integration.java create mode 100644 core-api/src/main/java/com/optimizely/ab/config/audience/AttributeType.java create mode 100644 core-api/src/test/java/com/optimizely/ab/testutils/OTUtils.java diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml index 35ab54025..af0dccf0a 100644 --- a/.github/workflows/java.yml +++ b/.github/workflows/java.yml @@ -45,7 +45,7 @@ jobs: test: if: startsWith(github.ref, 'refs/tags/') != true - runs-on: ubuntu-18.04 + runs-on: macos-latest strategy: fail-fast: false matrix: diff --git a/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java b/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java index d05df3bbb..e59c4f3aa 100644 --- a/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java +++ b/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java @@ -36,6 +36,8 @@ public class OptimizelyUserContext { @Nonnull private final Map attributes; + private List qualifiedSegments; + @Nonnull private final Optimizely optimizely; @@ -44,19 +46,14 @@ public class OptimizelyUserContext { public OptimizelyUserContext(@Nonnull Optimizely optimizely, @Nonnull String userId, @Nonnull Map attributes) { - this.optimizely = optimizely; - this.userId = userId; - if (attributes != null) { - this.attributes = Collections.synchronizedMap(new HashMap<>(attributes)); - } else { - this.attributes = Collections.synchronizedMap(new HashMap<>()); - } + this(optimizely, userId, attributes, Collections.EMPTY_MAP, null); } public OptimizelyUserContext(@Nonnull Optimizely optimizely, @Nonnull String userId, @Nonnull Map attributes, - @Nullable Map forcedDecisionsMap) { + @Nullable Map forcedDecisionsMap, + @Nullable List qualifiedSegments) { this.optimizely = optimizely; this.userId = userId; if (attributes != null) { @@ -65,8 +62,10 @@ public OptimizelyUserContext(@Nonnull Optimizely optimizely, this.attributes = Collections.synchronizedMap(new HashMap<>()); } if (forcedDecisionsMap != null) { - this.forcedDecisionsMap = new ConcurrentHashMap<>(forcedDecisionsMap); + this.forcedDecisionsMap = new ConcurrentHashMap<>(forcedDecisionsMap); } + + this.qualifiedSegments = Collections.synchronizedList( qualifiedSegments == null ? new LinkedList<>(): qualifiedSegments); } public OptimizelyUserContext(@Nonnull Optimizely optimizely, @Nonnull String userId) { @@ -86,7 +85,16 @@ public Optimizely getOptimizely() { } public OptimizelyUserContext copy() { - return new OptimizelyUserContext(optimizely, userId, attributes, forcedDecisionsMap); + return new OptimizelyUserContext(optimizely, userId, attributes, forcedDecisionsMap, qualifiedSegments); + } + + /** + * Returns true if the user is qualified for the given segment name + * @param segment A String segment key which will be checked in the qualified segments list that if it exists then user is qualified. + * @return boolean Is user qualified for a segment. + */ + public boolean isQualifiedFor(@Nonnull String segment) { + return qualifiedSegments.contains(segment); } /** @@ -265,7 +273,14 @@ public boolean removeAllForcedDecisions() { return true; } + public List getQualifiedSegments() { + return qualifiedSegments; + } + public void setQualifiedSegments(List qualifiedSegments) { + this.qualifiedSegments.clear(); + this.qualifiedSegments.addAll(qualifiedSegments); + } // Utils diff --git a/core-api/src/main/java/com/optimizely/ab/bucketing/DecisionService.java b/core-api/src/main/java/com/optimizely/ab/bucketing/DecisionService.java index c7ee0b3f3..84d47d03f 100644 --- a/core-api/src/main/java/com/optimizely/ab/bucketing/DecisionService.java +++ b/core-api/src/main/java/com/optimizely/ab/bucketing/DecisionService.java @@ -152,7 +152,7 @@ public DecisionResponse getVariation(@Nonnull Experiment experiment, } } - DecisionResponse decisionMeetAudience = ExperimentUtils.doesUserMeetAudienceConditions(projectConfig, experiment, user.getAttributes(), EXPERIMENT, experiment.getKey()); + DecisionResponse decisionMeetAudience = ExperimentUtils.doesUserMeetAudienceConditions(projectConfig, experiment, user, EXPERIMENT, experiment.getKey()); reasons.merge(decisionMeetAudience.getReasons()); if (decisionMeetAudience.getResult()) { String bucketingId = getBucketingId(user.getUserId(), user.getAttributes()); @@ -693,7 +693,7 @@ DecisionResponse getVariationFromDeliveryRule(@Nonnull DecisionResponse audienceDecisionResponse = ExperimentUtils.doesUserMeetAudienceConditions( projectConfig, rule, - user.getAttributes(), + user, RULE, String.valueOf(ruleIndex + 1) ); diff --git a/core-api/src/main/java/com/optimizely/ab/config/DatafileProjectConfig.java b/core-api/src/main/java/com/optimizely/ab/config/DatafileProjectConfig.java index 9620f5cbf..65edf5768 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/DatafileProjectConfig.java +++ b/core-api/src/main/java/com/optimizely/ab/config/DatafileProjectConfig.java @@ -63,6 +63,8 @@ public class DatafileProjectConfig implements ProjectConfig { private final boolean anonymizeIP; private final boolean sendFlagDecisions; private final Boolean botFiltering; + private final String hostForODP; + private final String publicKeyForODP; private final List attributes; private final List audiences; private final List typedAudiences; @@ -71,6 +73,7 @@ public class DatafileProjectConfig implements ProjectConfig { private final List featureFlags; private final List groups; private final List rollouts; + private final List integrations; // key to entity mappings private final Map attributeKeyMapping; @@ -121,6 +124,7 @@ public DatafileProjectConfig(String accountId, String projectId, String version, experiments, null, groups, + null, null ); } @@ -142,8 +146,8 @@ public DatafileProjectConfig(String accountId, List experiments, List featureFlags, List groups, - List rollouts) { - + List rollouts, + List integrations) { this.accountId = accountId; this.projectId = projectId; this.version = version; @@ -182,6 +186,24 @@ public DatafileProjectConfig(String accountId, allExperiments.addAll(aggregateGroupExperiments(groups)); this.experiments = Collections.unmodifiableList(allExperiments); + String publicKeyForODP = ""; + String hostForODP = ""; + if (integrations == null) { + this.integrations = Collections.emptyList(); + } else { + this.integrations = Collections.unmodifiableList(integrations); + for (Integration integration: this.integrations) { + if (integration.getKey().equals("odp")) { + hostForODP = integration.getHost(); + publicKeyForODP = integration.getPublicKey(); + break; + } + } + } + + this.publicKeyForODP = publicKeyForODP; + this.hostForODP = hostForODP; + Map variationIdToExperimentMap = new HashMap(); for (Experiment experiment : this.experiments) { for (Variation variation : experiment.getVariations()) { @@ -448,6 +470,11 @@ public List getTypedAudiences() { return typedAudiences; } + @Override + public List getIntegrations() { + return integrations; + } + @Override public Audience getAudience(String audienceId) { return audienceIdMapping.get(audienceId); @@ -524,6 +551,16 @@ public Variation getFlagVariationByKey(String flagKey, String variationKey) { return null; } + @Override + public String getHostForODP() { + return hostForODP; + } + + @Override + public String getPublicKeyForODP() { + return publicKeyForODP; + } + @Override public String toString() { return "ProjectConfig{" + diff --git a/core-api/src/main/java/com/optimizely/ab/config/Integration.java b/core-api/src/main/java/com/optimizely/ab/config/Integration.java new file mode 100644 index 000000000..ed24df625 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/config/Integration.java @@ -0,0 +1,67 @@ +/** + * + * Copyright 2022, Optimizely and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.config; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.annotation.concurrent.Immutable; + +/** + * Represents the Optimizely Integration configuration. + * + * @see Project JSON + */ +@Immutable +@JsonIgnoreProperties(ignoreUnknown = true) +public class Integration { + private final String key; + private final String host; + private final String publicKey; + + @JsonCreator + public Integration(@JsonProperty("key") String key, + @JsonProperty("host") String host, + @JsonProperty("publicKey") String publicKey) { + this.key = key; + this.host = host; + this.publicKey = publicKey; + } + + @Nonnull + public String getKey() { + return key; + } + + @Nullable + public String getHost() { return host; } + + @Nullable + public String getPublicKey() { return publicKey; } + + @Override + public String toString() { + return "Integration{" + + "key='" + key + '\'' + + ((this.host != null) ? (", host='" + host + '\'') : "") + + ((this.publicKey != null) ? (", publicKey='" + publicKey + '\'') : "") + + '}'; + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/config/ProjectConfig.java b/core-api/src/main/java/com/optimizely/ab/config/ProjectConfig.java index 10ebdc832..be512bd04 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/ProjectConfig.java +++ b/core-api/src/main/java/com/optimizely/ab/config/ProjectConfig.java @@ -83,6 +83,8 @@ Experiment getExperimentForKey(@Nonnull String experimentKey, List getTypedAudiences(); + List getIntegrations(); + Audience getAudience(String audienceId); Map getExperimentKeyMapping(); @@ -107,6 +109,10 @@ Experiment getExperimentForKey(@Nonnull String experimentKey, Variation getFlagVariationByKey(String flagKey, String variationKey); + String getHostForODP(); + + String getPublicKeyForODP(); + @Override String toString(); diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/AndCondition.java b/core-api/src/main/java/com/optimizely/ab/config/audience/AndCondition.java index f6561a65c..8d855e3e9 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/AndCondition.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/AndCondition.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2019, Optimizely and contributors + * Copyright 2016-2019, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ */ package com.optimizely.ab.config.audience; +import com.optimizely.ab.OptimizelyUserContext; import com.optimizely.ab.config.ProjectConfig; import javax.annotation.Nonnull; @@ -42,7 +43,7 @@ public List getConditions() { } @Nullable - public Boolean evaluate(ProjectConfig config, Map attributes) { + public Boolean evaluate(ProjectConfig config, OptimizelyUserContext user) { if (conditions == null) return null; boolean foundNull = false; // According to the matrix where: @@ -53,7 +54,7 @@ public Boolean evaluate(ProjectConfig config, Map attributes) { // true and true is true // null and null is null for (Condition condition : conditions) { - Boolean conditionEval = condition.evaluate(config, attributes); + Boolean conditionEval = condition.evaluate(config, user); if (conditionEval == null) { foundNull = true; } else if (!conditionEval) { // false with nulls or trues is false. diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/AttributeType.java b/core-api/src/main/java/com/optimizely/ab/config/audience/AttributeType.java new file mode 100644 index 000000000..2a1be3880 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/AttributeType.java @@ -0,0 +1,33 @@ +/** + * + * Copyright 2022, Optimizely and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.config.audience; + +public enum AttributeType { + CUSTOM_ATTRIBUTE("custom_attribute"), + THIRD_PARTY_DIMENSION("third_party_dimension"); + + private final String key; + + AttributeType(String key) { + this.key = key; + } + + @Override + public String toString() { + return key; + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/AudienceIdCondition.java b/core-api/src/main/java/com/optimizely/ab/config/audience/AudienceIdCondition.java index e07757016..4b3341d4c 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/AudienceIdCondition.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/AudienceIdCondition.java @@ -1,12 +1,12 @@ /** * - * Copyright 2018-2021, Optimizely and contributors + * Copyright 2018-2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,6 +19,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import com.optimizely.ab.OptimizelyUserContext; import com.optimizely.ab.config.ProjectConfig; import com.optimizely.ab.internal.InvalidAudienceCondition; import org.slf4j.Logger; @@ -71,7 +72,7 @@ public String getOperandOrId() { @Nullable @Override - public Boolean evaluate(ProjectConfig config, Map attributes) { + public Boolean evaluate(ProjectConfig config, OptimizelyUserContext user) { if (config != null) { audience = config.getAudienceIdMapping().get(audienceId); } @@ -80,7 +81,7 @@ public Boolean evaluate(ProjectConfig config, Map attributes) { return null; } logger.debug("Starting to evaluate audience \"{}\" with conditions: {}.", audience.getId(), audience.getConditions()); - Boolean result = audience.getConditions().evaluate(config, attributes); + Boolean result = audience.getConditions().evaluate(config, user); logger.debug("Audience \"{}\" evaluated to {}.", audience.getId(), result); return result; } diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/Condition.java b/core-api/src/main/java/com/optimizely/ab/config/audience/Condition.java index 11b7165b9..105c9b8e0 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/Condition.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/Condition.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2018, Optimizely and contributors + * Copyright 2016-2018, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ */ package com.optimizely.ab.config.audience; +import com.optimizely.ab.OptimizelyUserContext; import com.optimizely.ab.config.ProjectConfig; import javax.annotation.Nullable; @@ -27,7 +28,7 @@ public interface Condition { @Nullable - Boolean evaluate(ProjectConfig config, Map attributes); + Boolean evaluate(ProjectConfig config, OptimizelyUserContext user); String toJson(); diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/EmptyCondition.java b/core-api/src/main/java/com/optimizely/ab/config/audience/EmptyCondition.java index 9bb355a13..61e010317 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/EmptyCondition.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/EmptyCondition.java @@ -1,5 +1,5 @@ /** - * Copyright 2019, Optimizely Inc. and contributors + * Copyright 2019, 2022, Optimizely Inc. and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.optimizely.ab.config.audience; +import com.optimizely.ab.OptimizelyUserContext; import com.optimizely.ab.config.ProjectConfig; import javax.annotation.Nullable; @@ -23,7 +24,7 @@ public class EmptyCondition implements Condition { @Nullable @Override - public Boolean evaluate(ProjectConfig config, Map attributes) { + public Boolean evaluate(ProjectConfig config, OptimizelyUserContext user) { return true; } diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/NotCondition.java b/core-api/src/main/java/com/optimizely/ab/config/audience/NotCondition.java index cabc07812..9e4b2fb86 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/NotCondition.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/NotCondition.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2019, Optimizely and contributors + * Copyright 2016-2019, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,13 @@ */ package com.optimizely.ab.config.audience; +import com.optimizely.ab.OptimizelyUserContext; import com.optimizely.ab.config.ProjectConfig; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import javax.annotation.Nonnull; -import java.util.Map; -import java.util.StringJoiner; /** * Represents a 'Not' conditions condition operation. @@ -43,9 +42,8 @@ public Condition getCondition() { } @Nullable - public Boolean evaluate(ProjectConfig config, Map attributes) { - - Boolean conditionEval = condition == null ? null : condition.evaluate(config, attributes); + public Boolean evaluate(ProjectConfig config, OptimizelyUserContext user) { + Boolean conditionEval = condition == null ? null : condition.evaluate(config, user); return (conditionEval == null ? null : !conditionEval); } diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/NullCondition.java b/core-api/src/main/java/com/optimizely/ab/config/audience/NullCondition.java index 10633aed9..44ddee7ca 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/NullCondition.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/NullCondition.java @@ -1,5 +1,5 @@ /** - * Copyright 2019, Optimizely Inc. and contributors + * Copyright 2019, 2022, Optimizely Inc. and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ */ package com.optimizely.ab.config.audience; +import com.optimizely.ab.OptimizelyUserContext; import com.optimizely.ab.config.ProjectConfig; import javax.annotation.Nullable; @@ -23,7 +24,7 @@ public class NullCondition implements Condition { @Nullable @Override - public Boolean evaluate(ProjectConfig config, Map attributes) { + public Boolean evaluate(ProjectConfig config, OptimizelyUserContext user) { return null; } diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/OrCondition.java b/core-api/src/main/java/com/optimizely/ab/config/audience/OrCondition.java index 293687f66..12fbbb3b2 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/OrCondition.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/OrCondition.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2019, Optimizely and contributors + * Copyright 2016-2019, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ */ package com.optimizely.ab.config.audience; +import com.optimizely.ab.OptimizelyUserContext; import com.optimizely.ab.config.ProjectConfig; import javax.annotation.Nonnull; @@ -47,11 +48,11 @@ public List getConditions() { // false or false is false // null or null is null @Nullable - public Boolean evaluate(ProjectConfig config, Map attributes) { + public Boolean evaluate(ProjectConfig config, OptimizelyUserContext user) { if (conditions == null) return null; boolean foundNull = false; for (Condition condition : conditions) { - Boolean conditionEval = condition.evaluate(config, attributes); + Boolean conditionEval = condition.evaluate(config, user); if (conditionEval == null) { // true with falses and nulls is still true foundNull = true; } else if (conditionEval) { diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/UserAttribute.java b/core-api/src/main/java/com/optimizely/ab/config/audience/UserAttribute.java index ed029f89c..e7ff16f31 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/UserAttribute.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/UserAttribute.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2020, Optimizely and contributors + * Copyright 2016-2020, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import com.optimizely.ab.OptimizelyUserContext; import com.optimizely.ab.config.ProjectConfig; import com.optimizely.ab.config.audience.match.*; import org.slf4j.Logger; @@ -27,8 +28,10 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; -import java.util.Collections; -import java.util.Map; +import java.util.*; + +import static com.optimizely.ab.config.audience.AttributeType.CUSTOM_ATTRIBUTE; +import static com.optimizely.ab.config.audience.AttributeType.THIRD_PARTY_DIMENSION; /** * Represents a user attribute instance within an audience's conditions. @@ -36,13 +39,14 @@ @Immutable @JsonIgnoreProperties(ignoreUnknown = true) public class UserAttribute implements Condition { + public static final String QUALIFIED = "qualified"; private static final Logger logger = LoggerFactory.getLogger(UserAttribute.class); private final String name; private final String type; private final String match; private final Object value; - + private final static List ATTRIBUTE_TYPE = Arrays.asList(new String[]{CUSTOM_ATTRIBUTE.toString(), THIRD_PARTY_DIMENSION.toString()}); @JsonCreator public UserAttribute(@JsonProperty("name") @Nonnull String name, @JsonProperty("type") @Nonnull String type, @@ -71,19 +75,25 @@ public Object getValue() { } @Nullable - public Boolean evaluate(ProjectConfig config, Map attributes) { - if (attributes == null) { - attributes = Collections.emptyMap(); - } + public Boolean evaluate(ProjectConfig config, OptimizelyUserContext user) { + Map attributes = user.getAttributes(); // Valid for primitive types, but needs to change when a value is an object or an array Object userAttributeValue = attributes.get(name); - if (!"custom_attribute".equals(type)) { + if (!isValidType(type)) { logger.warn("Audience condition \"{}\" uses an unknown condition type. You may need to upgrade to a newer release of the Optimizely SDK.", this); return null; // unknown type } // check user attribute value is equal try { + // Handle qualified segments + if (QUALIFIED.equals(match)) { + if (value instanceof String) { + return user.isQualifiedFor(value.toString()); + } + throw new UnknownValueTypeException(); + } + // Handle other conditions Match matcher = MatchRegistry.getMatch(match); Boolean result = matcher.eval(value, userAttributeValue); if (result == null) { @@ -118,6 +128,13 @@ public Boolean evaluate(ProjectConfig config, Map attributes) { return null; } + private boolean isValidType(String type) { + if (ATTRIBUTE_TYPE.contains(type)) { + return true; + } + return false; + } + @Override public String getOperandOrId() { return null; diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/match/MatchRegistry.java b/core-api/src/main/java/com/optimizely/ab/config/audience/match/MatchRegistry.java index f78c35c8d..7563d2681 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/match/MatchRegistry.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/match/MatchRegistry.java @@ -1,6 +1,6 @@ /** * - * Copyright 2020-2021, Optimizely and contributors + * Copyright 2020-2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/core-api/src/main/java/com/optimizely/ab/config/parser/DatafileGsonDeserializer.java b/core-api/src/main/java/com/optimizely/ab/config/parser/DatafileGsonDeserializer.java index 26fe47330..f349805fa 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/parser/DatafileGsonDeserializer.java +++ b/core-api/src/main/java/com/optimizely/ab/config/parser/DatafileGsonDeserializer.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2021, Optimizely and contributors + * Copyright 2016-2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,6 +86,7 @@ public ProjectConfig deserialize(JsonElement json, Type typeOfT, JsonDeserializa List featureFlags = null; List rollouts = null; + List integrations = null; Boolean botFiltering = null; String sdkKey = null; String environmentKey = null; @@ -97,6 +98,10 @@ public ProjectConfig deserialize(JsonElement json, Type typeOfT, JsonDeserializa Type rolloutsType = new TypeToken>() { }.getType(); rollouts = context.deserialize(jsonObject.get("rollouts").getAsJsonArray(), rolloutsType); + if (jsonObject.has("integrations")) { + Type integrationsType = new TypeToken>() {}.getType(); + integrations = context.deserialize(jsonObject.get("integrations").getAsJsonArray(), integrationsType); + } if (jsonObject.has("sdkKey")) sdkKey = jsonObject.get("sdkKey").getAsString(); if (jsonObject.has("environmentKey")) @@ -124,7 +129,8 @@ public ProjectConfig deserialize(JsonElement json, Type typeOfT, JsonDeserializa experiments, featureFlags, groups, - rollouts + rollouts, + integrations ); } } diff --git a/core-api/src/main/java/com/optimizely/ab/config/parser/DatafileJacksonDeserializer.java b/core-api/src/main/java/com/optimizely/ab/config/parser/DatafileJacksonDeserializer.java index 4cded2ecb..4ef104428 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/parser/DatafileJacksonDeserializer.java +++ b/core-api/src/main/java/com/optimizely/ab/config/parser/DatafileJacksonDeserializer.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2021, Optimizely and contributors + * Copyright 2016-2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,6 +63,7 @@ public DatafileProjectConfig deserialize(JsonParser parser, DeserializationConte List featureFlags = null; List rollouts = null; + List integrations = null; String sdkKey = null; String environmentKey = null; Boolean botFiltering = null; @@ -70,6 +71,9 @@ public DatafileProjectConfig deserialize(JsonParser parser, DeserializationConte if (datafileVersion >= Integer.parseInt(DatafileProjectConfig.Version.V4.toString())) { featureFlags = JacksonHelpers.arrayNodeToList(node.get("featureFlags"), FeatureFlag.class, codec); rollouts = JacksonHelpers.arrayNodeToList(node.get("rollouts"), Rollout.class, codec); + if (node.hasNonNull("integrations")) { + integrations = JacksonHelpers.arrayNodeToList(node.get("integrations"), Integration.class, codec); + } if (node.hasNonNull("sdkKey")) { sdkKey = node.get("sdkKey").textValue(); } @@ -101,7 +105,8 @@ public DatafileProjectConfig deserialize(JsonParser parser, DeserializationConte experiments, featureFlags, groups, - rollouts + rollouts, + integrations ); } diff --git a/core-api/src/main/java/com/optimizely/ab/config/parser/JsonConfigParser.java b/core-api/src/main/java/com/optimizely/ab/config/parser/JsonConfigParser.java index c33f30a68..ea5101054 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/parser/JsonConfigParser.java +++ b/core-api/src/main/java/com/optimizely/ab/config/parser/JsonConfigParser.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2021, Optimizely and contributors + * Copyright 2016-2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,6 +72,7 @@ public ProjectConfig parseProjectConfig(@Nonnull String json) throws ConfigParse List featureFlags = null; List rollouts = null; + List integrations = null; String sdkKey = null; String environmentKey = null; Boolean botFiltering = null; @@ -79,6 +80,9 @@ public ProjectConfig parseProjectConfig(@Nonnull String json) throws ConfigParse if (datafileVersion >= Integer.parseInt(ProjectConfig.Version.V4.toString())) { featureFlags = parseFeatureFlags(rootObject.getJSONArray("featureFlags")); rollouts = parseRollouts(rootObject.getJSONArray("rollouts")); + if (rootObject.has("integrations")) { + integrations = parseIntegrations(rootObject.getJSONArray("integrations")); + } if (rootObject.has("sdkKey")) sdkKey = rootObject.getString("sdkKey"); if (rootObject.has("environmentKey")) @@ -106,7 +110,8 @@ public ProjectConfig parseProjectConfig(@Nonnull String json) throws ConfigParse experiments, featureFlags, groups, - rollouts + rollouts, + integrations ); } catch (RuntimeException e) { throw new ConfigParseException("Unable to parse datafile: " + json, e); @@ -399,6 +404,21 @@ private List parseRollouts(JSONArray rolloutsJson) { return rollouts; } + private List parseIntegrations(JSONArray integrationsJson) { + List integrations = new ArrayList(integrationsJson.length()); + + for (int i = 0; i < integrationsJson.length(); i++) { + Object obj = integrationsJson.get(i); + JSONObject integrationObject = (JSONObject) obj; + String key = integrationObject.getString("key"); + String host = integrationObject.has("host") ? integrationObject.getString("host") : null; + String publicKey = integrationObject.has("publicKey") ? integrationObject.getString("publicKey") : null; + integrations.add(new Integration(key, host, publicKey)); + } + + return integrations; + } + @Override public String toJson(Object src) { JSONObject json = (JSONObject)JsonHelpers.convertToJsonObject(src); diff --git a/core-api/src/main/java/com/optimizely/ab/config/parser/JsonSimpleConfigParser.java b/core-api/src/main/java/com/optimizely/ab/config/parser/JsonSimpleConfigParser.java index 751e651ca..c65eb6213 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/parser/JsonSimpleConfigParser.java +++ b/core-api/src/main/java/com/optimizely/ab/config/parser/JsonSimpleConfigParser.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2021, Optimizely and contributors + * Copyright 2016-2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,11 +81,15 @@ public ProjectConfig parseProjectConfig(@Nonnull String json) throws ConfigParse List featureFlags = null; List rollouts = null; + List integrations = null; Boolean botFiltering = null; boolean sendFlagDecisions = false; if (datafileVersion >= Integer.parseInt(DatafileProjectConfig.Version.V4.toString())) { featureFlags = parseFeatureFlags((JSONArray) rootObject.get("featureFlags")); rollouts = parseRollouts((JSONArray) rootObject.get("rollouts")); + if (rootObject.containsKey("integrations")) { + integrations = parseIntegrations((JSONArray) rootObject.get("integrations")); + } if (rootObject.containsKey("botFiltering")) botFiltering = (Boolean) rootObject.get("botFiltering"); if (rootObject.containsKey("sendFlagDecisions")) @@ -109,7 +113,8 @@ public ProjectConfig parseProjectConfig(@Nonnull String json) throws ConfigParse experiments, featureFlags, groups, - rollouts + rollouts, + integrations ); } catch (RuntimeException ex) { throw new ConfigParseException("Unable to parse datafile: " + json, ex); @@ -379,6 +384,20 @@ private List parseRollouts(JSONArray rolloutsJson) { return rollouts; } + private List parseIntegrations(JSONArray integrationsJson) { + List integrations = new ArrayList<>(integrationsJson.size()); + + for (Object obj : integrationsJson) { + JSONObject integrationObject = (JSONObject) obj; + String key = (String) integrationObject.get("key"); + String host = (String) integrationObject.get("host"); + String publicKey = (String) integrationObject.get("publicKey"); + integrations.add(new Integration(key, host, publicKey)); + } + + return integrations; + } + @Override public String toJson(Object src) { return JSONValue.toJSONString(src); diff --git a/core-api/src/main/java/com/optimizely/ab/internal/ExperimentUtils.java b/core-api/src/main/java/com/optimizely/ab/internal/ExperimentUtils.java index c1494bbda..8da421885 100644 --- a/core-api/src/main/java/com/optimizely/ab/internal/ExperimentUtils.java +++ b/core-api/src/main/java/com/optimizely/ab/internal/ExperimentUtils.java @@ -1,6 +1,6 @@ /** * - * Copyright 2017-2021, Optimizely and contributors + * Copyright 2017-2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ */ package com.optimizely.ab.internal; +import com.optimizely.ab.OptimizelyUserContext; import com.optimizely.ab.config.Experiment; import com.optimizely.ab.config.ProjectConfig; import com.optimizely.ab.config.audience.AudienceIdCondition; @@ -54,7 +55,7 @@ public static boolean isExperimentActive(@Nonnull Experiment experiment) { * * @param projectConfig the current projectConfig * @param experiment the experiment we are evaluating audiences for - * @param attributes the attributes of the user + * @param user the current OptimizelyUserContext * @param loggingEntityType It can be either experiment or rule. * @param loggingKey In case of loggingEntityType is experiment it will be experiment key or else it will be rule number. * @return whether the user meets the criteria for the experiment @@ -62,7 +63,7 @@ public static boolean isExperimentActive(@Nonnull Experiment experiment) { @Nonnull public static DecisionResponse doesUserMeetAudienceConditions(@Nonnull ProjectConfig projectConfig, @Nonnull Experiment experiment, - @Nonnull Map attributes, + @Nonnull OptimizelyUserContext user, @Nonnull String loggingEntityType, @Nonnull String loggingKey) { DecisionReasons reasons = DefaultDecisionReasons.newInstance(); @@ -70,9 +71,9 @@ public static DecisionResponse doesUserMeetAudienceConditions(@Nonnull DecisionResponse decisionResponse; if (experiment.getAudienceConditions() != null) { logger.debug("Evaluating audiences for {} \"{}\": {}.", loggingEntityType, loggingKey, experiment.getAudienceConditions()); - decisionResponse = evaluateAudienceConditions(projectConfig, experiment, attributes, loggingEntityType, loggingKey); + decisionResponse = evaluateAudienceConditions(projectConfig, experiment, user, loggingEntityType, loggingKey); } else { - decisionResponse = evaluateAudience(projectConfig, experiment, attributes, loggingEntityType, loggingKey); + decisionResponse = evaluateAudience(projectConfig, experiment, user, loggingEntityType, loggingKey); } Boolean resolveReturn = decisionResponse.getResult(); @@ -86,7 +87,7 @@ public static DecisionResponse doesUserMeetAudienceConditions(@Nonnull @Nonnull public static DecisionResponse evaluateAudience(@Nonnull ProjectConfig projectConfig, @Nonnull Experiment experiment, - @Nonnull Map attributes, + @Nonnull OptimizelyUserContext user, @Nonnull String loggingEntityType, @Nonnull String loggingKey) { DecisionReasons reasons = DefaultDecisionReasons.newInstance(); @@ -108,7 +109,7 @@ public static DecisionResponse evaluateAudience(@Nonnull ProjectConfig logger.debug("Evaluating audiences for {} \"{}\": {}.", loggingEntityType, loggingKey, conditions); - Boolean result = implicitOr.evaluate(projectConfig, attributes); + Boolean result = implicitOr.evaluate(projectConfig, user); String message = reasons.addInfo("Audiences for %s \"%s\" collectively evaluated to %s.", loggingEntityType, loggingKey, result); logger.info(message); @@ -118,7 +119,7 @@ public static DecisionResponse evaluateAudience(@Nonnull ProjectConfig @Nonnull public static DecisionResponse evaluateAudienceConditions(@Nonnull ProjectConfig projectConfig, @Nonnull Experiment experiment, - @Nonnull Map attributes, + @Nonnull OptimizelyUserContext user, @Nonnull String loggingEntityType, @Nonnull String loggingKey) { DecisionReasons reasons = DefaultDecisionReasons.newInstance(); @@ -128,7 +129,7 @@ public static DecisionResponse evaluateAudienceConditions(@Nonnull Proj Boolean result = null; try { - result = conditions.evaluate(projectConfig, attributes); + result = conditions.evaluate(projectConfig, user); String message = reasons.addInfo("Audiences for %s \"%s\" collectively evaluated to %s.", loggingEntityType, loggingKey, result); logger.info(message); } catch (Exception e) { diff --git a/core-api/src/test/java/com/optimizely/ab/config/DatafileProjectConfigTestUtils.java b/core-api/src/test/java/com/optimizely/ab/config/DatafileProjectConfigTestUtils.java index 49eaac733..9b65421bb 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/DatafileProjectConfigTestUtils.java +++ b/core-api/src/test/java/com/optimizely/ab/config/DatafileProjectConfigTestUtils.java @@ -474,6 +474,7 @@ public static void verifyProjectConfig(@CheckForNull ProjectConfig actual, @Nonn verifyFeatureFlags(actual.getFeatureFlags(), expected.getFeatureFlags()); verifyGroups(actual.getGroups(), expected.getGroups()); verifyRollouts(actual.getRollouts(), expected.getRollouts()); + verifyIntegrations(actual.getIntegrations(), expected.getIntegrations()); } /** @@ -491,7 +492,7 @@ private static void verifyExperiments(List actual, List assertThat(actualExperiment.getGroupId(), is(expectedExperiment.getGroupId())); assertThat(actualExperiment.getStatus(), is(expectedExperiment.getStatus())); assertThat(actualExperiment.getAudienceIds(), is(expectedExperiment.getAudienceIds())); - assertEquals(actualExperiment.getAudienceConditions(), expectedExperiment.getAudienceConditions()); + assertThat(actualExperiment.getAudienceConditions(), is(expectedExperiment.getAudienceConditions())); assertThat(actualExperiment.getUserIdToVariationKeyMap(), is(expectedExperiment.getUserIdToVariationKeyMap())); @@ -627,6 +628,23 @@ private static void verifyRollouts(List actual, List expected) } } + private static void verifyIntegrations(List actual, List expected) { + if (expected == null) { + assertNull(actual); + } else { + assertEquals(expected.size(), actual.size()); + + for (int i = 0; i < actual.size(); i++) { + Integration actualIntegrations = actual.get(i); + Integration expectedIntegration = expected.get(i); + + assertEquals(expectedIntegration.getKey(), actualIntegrations.getKey()); + assertEquals(expectedIntegration.getHost(), actualIntegrations.getHost()); + assertEquals(expectedIntegration.getPublicKey(), actualIntegrations.getPublicKey()); + } + } + } + /** * Verify that the provided variation-level feature variable usage instances are equivalent. */ diff --git a/core-api/src/test/java/com/optimizely/ab/config/ValidProjectConfigV4.java b/core-api/src/test/java/com/optimizely/ab/config/ValidProjectConfigV4.java index f8ea02231..0ed8d5945 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/ValidProjectConfigV4.java +++ b/core-api/src/test/java/com/optimizely/ab/config/ValidProjectConfigV4.java @@ -1360,6 +1360,7 @@ public class ValidProjectConfigV4 { VARIABLE_INTEGER_VARIABLE ) ); + public static final Integration odpIntegration = new Integration("odp", "https://example.com", "test-key"); public static ProjectConfig generateValidProjectConfigV4() { @@ -1429,6 +1430,9 @@ public static ProjectConfig generateValidProjectConfigV4() { rollouts.add(ROLLOUT_2); rollouts.add(ROLLOUT_3); + List integrations = new ArrayList<>(); + integrations.add(odpIntegration); + return new DatafileProjectConfig( ACCOUNT_ID, ANONYMIZE_IP, @@ -1446,7 +1450,8 @@ public static ProjectConfig generateValidProjectConfigV4() { experiments, featureFlags, groups, - rollouts + rollouts, + integrations ); } } diff --git a/core-api/src/test/java/com/optimizely/ab/config/audience/AudienceConditionEvaluationTest.java b/core-api/src/test/java/com/optimizely/ab/config/audience/AudienceConditionEvaluationTest.java index 07a0c1ad1..5a69b35ee 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/audience/AudienceConditionEvaluationTest.java +++ b/core-api/src/test/java/com/optimizely/ab/config/audience/AudienceConditionEvaluationTest.java @@ -17,13 +17,16 @@ package com.optimizely.ab.config.audience; import ch.qos.logback.classic.Level; -import com.fasterxml.jackson.databind.deser.std.MapEntryDeserializer; +import com.optimizely.ab.OptimizelyUserContext; import com.optimizely.ab.internal.LogbackVerifier; +import com.optimizely.ab.testutils.OTUtils; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.mockito.Mock; import org.mockito.internal.matchers.Or; +import org.mockito.internal.util.reflection.Whitebox; import java.math.BigInteger; import java.util.*; @@ -129,7 +132,7 @@ public void userAttributeEvaluateTrue() throws Exception { assertNull(testInstance.getMatch()); assertEquals(testInstance.getName(), "browser_type"); assertEquals(testInstance.getType(), "custom_attribute"); - assertTrue(testInstance.evaluate(null, testUserAttributes)); + assertTrue(testInstance.evaluate(null, OTUtils.user(testUserAttributes))); } /** @@ -138,7 +141,7 @@ public void userAttributeEvaluateTrue() throws Exception { @Test public void userAttributeEvaluateFalse() throws Exception { UserAttribute testInstance = new UserAttribute("browser_type", "custom_attribute", null, "firefox"); - assertFalse(testInstance.evaluate(null, testUserAttributes)); + assertFalse(testInstance.evaluate(null, OTUtils.user(testUserAttributes))); } /** @@ -147,7 +150,7 @@ public void userAttributeEvaluateFalse() throws Exception { @Test public void userAttributeUnknownAttribute() throws Exception { UserAttribute testInstance = new UserAttribute("unknown_dim", "custom_attribute", null, "unknown"); - assertFalse(testInstance.evaluate(null, testUserAttributes)); + assertFalse(testInstance.evaluate(null, OTUtils.user(testUserAttributes))); } /** @@ -156,7 +159,7 @@ public void userAttributeUnknownAttribute() throws Exception { @Test public void invalidMatchCondition() throws Exception { UserAttribute testInstance = new UserAttribute("browser_type", "unknown_dimension", null, "chrome"); - assertNull(testInstance.evaluate(null, testUserAttributes)); + assertNull(testInstance.evaluate(null, OTUtils.user(testUserAttributes))); } /** @@ -165,7 +168,7 @@ public void invalidMatchCondition() throws Exception { @Test public void invalidMatch() throws Exception { UserAttribute testInstance = new UserAttribute("browser_type", "custom_attribute", "blah", "chrome"); - assertNull(testInstance.evaluate(null, testUserAttributes)); + assertNull(testInstance.evaluate(null, OTUtils.user(testUserAttributes))); logbackVerifier.expectMessage(Level.WARN, "Audience condition \"{name='browser_type', type='custom_attribute', match='blah', value='chrome'}\" uses an unknown match type. You may need to upgrade to a newer release of the Optimizely SDK"); } @@ -176,7 +179,7 @@ public void invalidMatch() throws Exception { @Test public void unexpectedAttributeType() throws Exception { UserAttribute testInstance = new UserAttribute("browser_type", "custom_attribute", "gt", 20); - assertNull(testInstance.evaluate(null, testUserAttributes)); + assertNull(testInstance.evaluate(null, OTUtils.user(testUserAttributes))); logbackVerifier.expectMessage(Level.WARN, "Audience condition \"{name='browser_type', type='custom_attribute', match='gt', value=20}\" evaluated to UNKNOWN because a value of type \"java.lang.String\" was passed for user attribute \"browser_type\""); } @@ -187,7 +190,7 @@ public void unexpectedAttributeType() throws Exception { @Test public void unexpectedAttributeTypeNull() throws Exception { UserAttribute testInstance = new UserAttribute("browser_type", "custom_attribute", "gt", 20); - assertNull(testInstance.evaluate(null, Collections.singletonMap("browser_type", null))); + assertNull(testInstance.evaluate(null, OTUtils.user(Collections.singletonMap("browser_type", null)))); logbackVerifier.expectMessage(Level.DEBUG, "Audience condition \"{name='browser_type', type='custom_attribute', match='gt', value=20}\" evaluated to UNKNOWN because a null value was passed for user attribute \"browser_type\""); } @@ -215,7 +218,7 @@ public void missingAttribute_returnsNullAndLogDebugMessage() throws Exception { for (Map.Entry entry : items.entrySet()) { for (Object value : entry.getValue()) { UserAttribute testInstance = new UserAttribute("n", "custom_attribute", entry.getKey(), value); - assertNull(testInstance.evaluate(null, Collections.EMPTY_MAP)); + assertNull(testInstance.evaluate(null, OTUtils.user(Collections.EMPTY_MAP))); String valueStr = (value instanceof String) ? ("'" + value + "'") : value.toString(); logbackVerifier.expectMessage(Level.DEBUG, "Audience condition \"{name='n', type='custom_attribute', match='" + entry.getKey() + "', value=" + valueStr + "}\" evaluated to UNKNOWN because no value was passed for user attribute \"n\""); @@ -226,10 +229,11 @@ public void missingAttribute_returnsNullAndLogDebugMessage() throws Exception { /** * Verify that UserAttribute.evaluate returns null on passing null attribute object. */ + @SuppressFBWarnings("NP_NULL_PARAM_DEREF_NONVIRTUAL") @Test public void nullAttribute() throws Exception { UserAttribute testInstance = new UserAttribute("browser_type", "custom_attribute", "gt", 20); - assertNull(testInstance.evaluate(null, null)); + assertNull(testInstance.evaluate(null, OTUtils.user(null))); logbackVerifier.expectMessage(Level.DEBUG, "Audience condition \"{name='browser_type', type='custom_attribute', match='gt', value=20}\" evaluated to UNKNOWN because no value was passed for user attribute \"browser_type\""); } @@ -240,7 +244,7 @@ public void nullAttribute() throws Exception { @Test public void unknownConditionType() throws Exception { UserAttribute testInstance = new UserAttribute("browser_type", "blah", "exists", "firefox"); - assertNull(testInstance.evaluate(null, testUserAttributes)); + assertNull(testInstance.evaluate(null, OTUtils.user(testUserAttributes))); logbackVerifier.expectMessage(Level.WARN, "Audience condition \"{name='browser_type', type='blah', match='exists', value='firefox'}\" uses an unknown condition type. You may need to upgrade to a newer release of the Optimizely SDK."); } @@ -254,9 +258,9 @@ public void existsMatchConditionEmptyStringEvaluatesTrue() throws Exception { UserAttribute testInstance = new UserAttribute("browser_type", "custom_attribute", "exists", "firefox"); Map attributes = new HashMap<>(); attributes.put("browser_type", ""); - assertTrue(testInstance.evaluate(null, attributes)); + assertTrue(testInstance.evaluate(null, OTUtils.user(attributes))); attributes.put("browser_type", null); - assertFalse(testInstance.evaluate(null, attributes)); + assertFalse(testInstance.evaluate(null, OTUtils.user(attributes))); } /** @@ -266,16 +270,16 @@ public void existsMatchConditionEmptyStringEvaluatesTrue() throws Exception { @Test public void existsMatchConditionEvaluatesTrue() throws Exception { UserAttribute testInstance = new UserAttribute("browser_type", "custom_attribute", "exists", "firefox"); - assertTrue(testInstance.evaluate(null, testUserAttributes)); + assertTrue(testInstance.evaluate(null, OTUtils.user(testUserAttributes))); UserAttribute testInstanceBoolean = new UserAttribute("is_firefox", "custom_attribute", "exists", false); UserAttribute testInstanceInteger = new UserAttribute("num_size", "custom_attribute", "exists", 5); UserAttribute testInstanceDouble = new UserAttribute("num_counts", "custom_attribute", "exists", 4.55); UserAttribute testInstanceObject = new UserAttribute("meta_data", "custom_attribute", "exists", testUserAttributes); - assertTrue(testInstanceBoolean.evaluate(null, testTypedUserAttributes)); - assertTrue(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertTrue(testInstanceDouble.evaluate(null, testTypedUserAttributes)); - assertTrue(testInstanceObject.evaluate(null, testTypedUserAttributes)); + assertTrue(testInstanceBoolean.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertTrue(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertTrue(testInstanceDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertTrue(testInstanceObject.evaluate(null, OTUtils.user(testTypedUserAttributes))); } /** @@ -286,8 +290,8 @@ public void existsMatchConditionEvaluatesTrue() throws Exception { public void existsMatchConditionEvaluatesFalse() throws Exception { UserAttribute testInstance = new UserAttribute("bad_var", "custom_attribute", "exists", "chrome"); UserAttribute testInstanceNull = new UserAttribute("null_val", "custom_attribute", "exists", "chrome"); - assertFalse(testInstance.evaluate(null, testTypedUserAttributes)); - assertFalse(testInstanceNull.evaluate(null, testTypedUserAttributes)); + assertFalse(testInstance.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertFalse(testInstanceNull.evaluate(null, OTUtils.user(testTypedUserAttributes))); } /** @@ -302,11 +306,11 @@ public void exactMatchConditionEvaluatesTrue() { UserAttribute testInstanceFloat = new UserAttribute("num_size", "custom_attribute", "exact", (float) 3); UserAttribute testInstanceDouble = new UserAttribute("num_counts", "custom_attribute", "exact", 3.55); - assertTrue(testInstanceString.evaluate(null, testUserAttributes)); - assertTrue(testInstanceBoolean.evaluate(null, testTypedUserAttributes)); - assertTrue(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertTrue(testInstanceFloat.evaluate(null, Collections.singletonMap("num_size", (float) 3))); - assertTrue(testInstanceDouble.evaluate(null, testTypedUserAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testUserAttributes))); + assertTrue(testInstanceBoolean.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertTrue(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertTrue(testInstanceFloat.evaluate(null, OTUtils.user(Collections.singletonMap("num_size", (float) 3)))); + assertTrue(testInstanceDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); } /** @@ -339,22 +343,22 @@ public void exactMatchConditionEvaluatesNullWithInvalidUserAttr() { assertNull(testInstanceInteger.evaluate( null, - Collections.singletonMap("num_size", bigInteger))); + OTUtils.user(Collections.singletonMap("num_size", bigInteger)))); assertNull(testInstanceFloat.evaluate( null, - Collections.singletonMap("num_size", invalidFloatValue))); + OTUtils.user(Collections.singletonMap("num_size", invalidFloatValue)))); assertNull(testInstanceDouble.evaluate( null, - Collections.singletonMap("num_counts", infinitePositiveInfiniteDouble))); + OTUtils.user(Collections.singletonMap("num_counts", infinitePositiveInfiniteDouble)))); assertNull(testInstanceDouble.evaluate( null, - Collections.singletonMap("num_counts", infiniteNegativeInfiniteDouble))); + OTUtils.user(Collections.singletonMap("num_counts", infiniteNegativeInfiniteDouble)))); assertNull(testInstanceDouble.evaluate( - null, Collections.singletonMap("num_counts", - Collections.singletonMap("num_counts", infiniteNANDouble)))); + null, OTUtils.user(Collections.singletonMap("num_counts", + Collections.singletonMap("num_counts", infiniteNANDouble))))); assertNull(testInstanceDouble.evaluate( - null, Collections.singletonMap("num_counts", - Collections.singletonMap("num_counts", largeDouble)))); + null, OTUtils.user(Collections.singletonMap("num_counts", + Collections.singletonMap("num_counts", largeDouble))))); } /** @@ -372,10 +376,10 @@ public void invalidExactMatchConditionEvaluatesNull() { UserAttribute testInstanceNegativeInfiniteDouble = new UserAttribute("num_counts", "custom_attribute", "exact", infiniteNegativeInfiniteDouble); UserAttribute testInstanceNANDouble = new UserAttribute("num_counts", "custom_attribute", "exact", infiniteNANDouble); - assertNull(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertNull(testInstancePositiveInfinite.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNegativeInfiniteDouble.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNANDouble.evaluate(null, testTypedUserAttributes)); + assertNull(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstancePositiveInfinite.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNegativeInfiniteDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNANDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); } /** @@ -389,10 +393,10 @@ public void exactMatchConditionEvaluatesFalse() { UserAttribute testInstanceInteger = new UserAttribute("num_size", "custom_attribute", "exact", 5); UserAttribute testInstanceDouble = new UserAttribute("num_counts", "custom_attribute", "exact", 5.55); - assertFalse(testInstanceString.evaluate(null, testUserAttributes)); - assertFalse(testInstanceBoolean.evaluate(null, testTypedUserAttributes)); - assertFalse(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertFalse(testInstanceDouble.evaluate(null, testTypedUserAttributes)); + assertFalse(testInstanceString.evaluate(null, OTUtils.user(testUserAttributes))); + assertFalse(testInstanceBoolean.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertFalse(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertFalse(testInstanceDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); } /** @@ -408,15 +412,15 @@ public void exactMatchConditionEvaluatesNull() { UserAttribute testInstanceDouble = new UserAttribute("num_counts", "custom_attribute", "exact", "3.55"); UserAttribute testInstanceNull = new UserAttribute("null_val", "custom_attribute", "exact", "null_val"); - assertNull(testInstanceObject.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceString.evaluate(null, testUserAttributes)); - assertNull(testInstanceBoolean.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceDouble.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNull.evaluate(null, testTypedUserAttributes)); + assertNull(testInstanceObject.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceString.evaluate(null, OTUtils.user(testUserAttributes))); + assertNull(testInstanceBoolean.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNull.evaluate(null, OTUtils.user(testTypedUserAttributes))); Map attr = new HashMap<>(); attr.put("browser_type", "true"); - assertNull(testInstanceString.evaluate(null, attr)); + assertNull(testInstanceString.evaluate(null, OTUtils.user(attr))); } /** @@ -430,13 +434,13 @@ public void gtMatchConditionEvaluatesTrue() { UserAttribute testInstanceFloat = new UserAttribute("num_size", "custom_attribute", "gt", (float) 2); UserAttribute testInstanceDouble = new UserAttribute("num_counts", "custom_attribute", "gt", 2.55); - assertTrue(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertTrue(testInstanceFloat.evaluate(null, Collections.singletonMap("num_size", (float) 3))); - assertTrue(testInstanceDouble.evaluate(null, testTypedUserAttributes)); + assertTrue(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertTrue(testInstanceFloat.evaluate(null, OTUtils.user(Collections.singletonMap("num_size", (float) 3)))); + assertTrue(testInstanceDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); Map badAttributes = new HashMap<>(); badAttributes.put("num_size", "bobs burgers"); - assertNull(testInstanceInteger.evaluate(null, badAttributes)); + assertNull(testInstanceInteger.evaluate(null, OTUtils.user(badAttributes))); } /** @@ -470,22 +474,22 @@ public void gtMatchConditionEvaluatesNullWithInvalidUserAttr() { assertNull(testInstanceInteger.evaluate( null, - Collections.singletonMap("num_size", bigInteger))); + OTUtils.user(Collections.singletonMap("num_size", bigInteger)))); assertNull(testInstanceFloat.evaluate( null, - Collections.singletonMap("num_size", invalidFloatValue))); + OTUtils.user(Collections.singletonMap("num_size", invalidFloatValue)))); assertNull(testInstanceDouble.evaluate( null, - Collections.singletonMap("num_counts", infinitePositiveInfiniteDouble))); + OTUtils.user(Collections.singletonMap("num_counts", infinitePositiveInfiniteDouble)))); assertNull(testInstanceDouble.evaluate( null, - Collections.singletonMap("num_counts", infiniteNegativeInfiniteDouble))); + OTUtils.user(Collections.singletonMap("num_counts", infiniteNegativeInfiniteDouble)))); assertNull(testInstanceDouble.evaluate( - null, Collections.singletonMap("num_counts", - Collections.singletonMap("num_counts", infiniteNANDouble)))); + null, OTUtils.user(Collections.singletonMap("num_counts", + Collections.singletonMap("num_counts", infiniteNANDouble))))); assertNull(testInstanceDouble.evaluate( - null, Collections.singletonMap("num_counts", - Collections.singletonMap("num_counts", largeDouble)))); + null, OTUtils.user(Collections.singletonMap("num_counts", + Collections.singletonMap("num_counts", largeDouble))))); } /** @@ -503,10 +507,10 @@ public void gtMatchConditionEvaluatesNullWithInvalidAttr() { UserAttribute testInstanceNegativeInfiniteDouble = new UserAttribute("num_counts", "custom_attribute", "gt", infiniteNegativeInfiniteDouble); UserAttribute testInstanceNANDouble = new UserAttribute("num_counts", "custom_attribute", "gt", infiniteNANDouble); - assertNull(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertNull(testInstancePositiveInfinite.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNegativeInfiniteDouble.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNANDouble.evaluate(null, testTypedUserAttributes)); + assertNull(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstancePositiveInfinite.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNegativeInfiniteDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNANDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); } /** @@ -519,8 +523,8 @@ public void gtMatchConditionEvaluatesFalse() { UserAttribute testInstanceInteger = new UserAttribute("num_size", "custom_attribute", "gt", 5); UserAttribute testInstanceDouble = new UserAttribute("num_counts", "custom_attribute", "gt", 5.55); - assertFalse(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertFalse(testInstanceDouble.evaluate(null, testTypedUserAttributes)); + assertFalse(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertFalse(testInstanceDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); } /** @@ -534,10 +538,10 @@ public void gtMatchConditionEvaluatesNull() { UserAttribute testInstanceObject = new UserAttribute("meta_data", "custom_attribute", "gt", 3.5); UserAttribute testInstanceNull = new UserAttribute("null_val", "custom_attribute", "gt", 3.5); - assertNull(testInstanceString.evaluate(null, testUserAttributes)); - assertNull(testInstanceBoolean.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceObject.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNull.evaluate(null, testTypedUserAttributes)); + assertNull(testInstanceString.evaluate(null, OTUtils.user(testUserAttributes))); + assertNull(testInstanceBoolean.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceObject.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNull.evaluate(null, OTUtils.user(testTypedUserAttributes))); } @@ -552,13 +556,13 @@ public void geMatchConditionEvaluatesTrue() { UserAttribute testInstanceFloat = new UserAttribute("num_size", "custom_attribute", "ge", (float) 2); UserAttribute testInstanceDouble = new UserAttribute("num_counts", "custom_attribute", "ge", 2.55); - assertTrue(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertTrue(testInstanceFloat.evaluate(null, Collections.singletonMap("num_size", (float) 2))); - assertTrue(testInstanceDouble.evaluate(null, testTypedUserAttributes)); + assertTrue(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertTrue(testInstanceFloat.evaluate(null, OTUtils.user(Collections.singletonMap("num_size", (float) 2)))); + assertTrue(testInstanceDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); Map badAttributes = new HashMap<>(); badAttributes.put("num_size", "bobs burgers"); - assertNull(testInstanceInteger.evaluate(null, badAttributes)); + assertNull(testInstanceInteger.evaluate(null, OTUtils.user(badAttributes))); } /** @@ -592,22 +596,22 @@ public void geMatchConditionEvaluatesNullWithInvalidUserAttr() { assertNull(testInstanceInteger.evaluate( null, - Collections.singletonMap("num_size", bigInteger))); + OTUtils.user(Collections.singletonMap("num_size", bigInteger)))); assertNull(testInstanceFloat.evaluate( null, - Collections.singletonMap("num_size", invalidFloatValue))); + OTUtils.user(Collections.singletonMap("num_size", invalidFloatValue)))); assertNull(testInstanceDouble.evaluate( null, - Collections.singletonMap("num_counts", infinitePositiveInfiniteDouble))); + OTUtils.user(Collections.singletonMap("num_counts", infinitePositiveInfiniteDouble)))); assertNull(testInstanceDouble.evaluate( null, - Collections.singletonMap("num_counts", infiniteNegativeInfiniteDouble))); + OTUtils.user(Collections.singletonMap("num_counts", infiniteNegativeInfiniteDouble)))); assertNull(testInstanceDouble.evaluate( - null, Collections.singletonMap("num_counts", - Collections.singletonMap("num_counts", infiniteNANDouble)))); + null, OTUtils.user(Collections.singletonMap("num_counts", + Collections.singletonMap("num_counts", infiniteNANDouble))))); assertNull(testInstanceDouble.evaluate( - null, Collections.singletonMap("num_counts", - Collections.singletonMap("num_counts", largeDouble)))); + null, OTUtils.user(Collections.singletonMap("num_counts", + Collections.singletonMap("num_counts", largeDouble))))); } /** @@ -625,10 +629,10 @@ public void geMatchConditionEvaluatesNullWithInvalidAttr() { UserAttribute testInstanceNegativeInfiniteDouble = new UserAttribute("num_counts", "custom_attribute", "ge", infiniteNegativeInfiniteDouble); UserAttribute testInstanceNANDouble = new UserAttribute("num_counts", "custom_attribute", "ge", infiniteNANDouble); - assertNull(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertNull(testInstancePositiveInfinite.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNegativeInfiniteDouble.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNANDouble.evaluate(null, testTypedUserAttributes)); + assertNull(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstancePositiveInfinite.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNegativeInfiniteDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNANDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); } /** @@ -641,8 +645,8 @@ public void geMatchConditionEvaluatesFalse() { UserAttribute testInstanceInteger = new UserAttribute("num_size", "custom_attribute", "ge", 5); UserAttribute testInstanceDouble = new UserAttribute("num_counts", "custom_attribute", "ge", 5.55); - assertFalse(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertFalse(testInstanceDouble.evaluate(null, testTypedUserAttributes)); + assertFalse(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertFalse(testInstanceDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); } /** @@ -656,10 +660,10 @@ public void geMatchConditionEvaluatesNull() { UserAttribute testInstanceObject = new UserAttribute("meta_data", "custom_attribute", "ge", 3.5); UserAttribute testInstanceNull = new UserAttribute("null_val", "custom_attribute", "ge", 3.5); - assertNull(testInstanceString.evaluate(null, testUserAttributes)); - assertNull(testInstanceBoolean.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceObject.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNull.evaluate(null, testTypedUserAttributes)); + assertNull(testInstanceString.evaluate(null, OTUtils.user(testUserAttributes))); + assertNull(testInstanceBoolean.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceObject.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNull.evaluate(null, OTUtils.user(testTypedUserAttributes))); } @@ -673,8 +677,8 @@ public void ltMatchConditionEvaluatesTrue() { UserAttribute testInstanceInteger = new UserAttribute("num_size", "custom_attribute", "lt", 5); UserAttribute testInstanceDouble = new UserAttribute("num_counts", "custom_attribute", "lt", 5.55); - assertTrue(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertTrue(testInstanceDouble.evaluate(null, testTypedUserAttributes)); + assertTrue(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertTrue(testInstanceDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); } /** @@ -687,8 +691,8 @@ public void ltMatchConditionEvaluatesFalse() { UserAttribute testInstanceInteger = new UserAttribute("num_size", "custom_attribute", "lt", 2); UserAttribute testInstanceDouble = new UserAttribute("num_counts", "custom_attribute", "lt", 2.55); - assertFalse(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertFalse(testInstanceDouble.evaluate(null, testTypedUserAttributes)); + assertFalse(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertFalse(testInstanceDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); } /** @@ -702,10 +706,10 @@ public void ltMatchConditionEvaluatesNull() { UserAttribute testInstanceObject = new UserAttribute("meta_data", "custom_attribute", "lt", 3.5); UserAttribute testInstanceNull = new UserAttribute("null_val", "custom_attribute", "lt", 3.5); - assertNull(testInstanceString.evaluate(null, testUserAttributes)); - assertNull(testInstanceBoolean.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceObject.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNull.evaluate(null, testTypedUserAttributes)); + assertNull(testInstanceString.evaluate(null, OTUtils.user(testUserAttributes))); + assertNull(testInstanceBoolean.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceObject.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNull.evaluate(null, OTUtils.user(testTypedUserAttributes))); } /** @@ -739,22 +743,22 @@ public void ltMatchConditionEvaluatesNullWithInvalidUserAttr() { assertNull(testInstanceInteger.evaluate( null, - Collections.singletonMap("num_size", bigInteger))); + OTUtils.user(Collections.singletonMap("num_size", bigInteger)))); assertNull(testInstanceFloat.evaluate( null, - Collections.singletonMap("num_size", invalidFloatValue))); + OTUtils.user(Collections.singletonMap("num_size", invalidFloatValue)))); assertNull(testInstanceDouble.evaluate( null, - Collections.singletonMap("num_counts", infinitePositiveInfiniteDouble))); + OTUtils.user(Collections.singletonMap("num_counts", infinitePositiveInfiniteDouble)))); assertNull(testInstanceDouble.evaluate( null, - Collections.singletonMap("num_counts", infiniteNegativeInfiniteDouble))); + OTUtils.user(Collections.singletonMap("num_counts", infiniteNegativeInfiniteDouble)))); assertNull(testInstanceDouble.evaluate( - null, Collections.singletonMap("num_counts", - Collections.singletonMap("num_counts", infiniteNANDouble)))); + null, OTUtils.user(Collections.singletonMap("num_counts", + Collections.singletonMap("num_counts", infiniteNANDouble))))); assertNull(testInstanceDouble.evaluate( - null, Collections.singletonMap("num_counts", - Collections.singletonMap("num_counts", largeDouble)))); + null, OTUtils.user(Collections.singletonMap("num_counts", + Collections.singletonMap("num_counts", largeDouble))))); } /** @@ -772,10 +776,10 @@ public void ltMatchConditionEvaluatesNullWithInvalidAttributes() { UserAttribute testInstanceNegativeInfiniteDouble = new UserAttribute("num_counts", "custom_attribute", "lt", infiniteNegativeInfiniteDouble); UserAttribute testInstanceNANDouble = new UserAttribute("num_counts", "custom_attribute", "lt", infiniteNANDouble); - assertNull(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertNull(testInstancePositiveInfinite.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNegativeInfiniteDouble.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNANDouble.evaluate(null, testTypedUserAttributes)); + assertNull(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstancePositiveInfinite.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNegativeInfiniteDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNANDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); } @@ -789,8 +793,8 @@ public void leMatchConditionEvaluatesTrue() { UserAttribute testInstanceInteger = new UserAttribute("num_size", "custom_attribute", "le", 5); UserAttribute testInstanceDouble = new UserAttribute("num_counts", "custom_attribute", "le", 5.55); - assertTrue(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertTrue(testInstanceDouble.evaluate(null, Collections.singletonMap("num_counts", 5.55))); + assertTrue(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertTrue(testInstanceDouble.evaluate(null, OTUtils.user(Collections.singletonMap("num_counts", 5.55)))); } /** @@ -803,8 +807,8 @@ public void leMatchConditionEvaluatesFalse() { UserAttribute testInstanceInteger = new UserAttribute("num_size", "custom_attribute", "le", 2); UserAttribute testInstanceDouble = new UserAttribute("num_counts", "custom_attribute", "le", 2.55); - assertFalse(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertFalse(testInstanceDouble.evaluate(null, testTypedUserAttributes)); + assertFalse(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertFalse(testInstanceDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); } /** @@ -818,10 +822,10 @@ public void leMatchConditionEvaluatesNull() { UserAttribute testInstanceObject = new UserAttribute("meta_data", "custom_attribute", "le", 3.5); UserAttribute testInstanceNull = new UserAttribute("null_val", "custom_attribute", "le", 3.5); - assertNull(testInstanceString.evaluate(null, testUserAttributes)); - assertNull(testInstanceBoolean.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceObject.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNull.evaluate(null, testTypedUserAttributes)); + assertNull(testInstanceString.evaluate(null, OTUtils.user(testUserAttributes))); + assertNull(testInstanceBoolean.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceObject.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNull.evaluate(null, OTUtils.user(testTypedUserAttributes))); } /** @@ -855,22 +859,22 @@ public void leMatchConditionEvaluatesNullWithInvalidUserAttr() { assertNull(testInstanceInteger.evaluate( null, - Collections.singletonMap("num_size", bigInteger))); + OTUtils.user(Collections.singletonMap("num_size", bigInteger)))); assertNull(testInstanceFloat.evaluate( null, - Collections.singletonMap("num_size", invalidFloatValue))); + OTUtils.user(Collections.singletonMap("num_size", invalidFloatValue)))); assertNull(testInstanceDouble.evaluate( null, - Collections.singletonMap("num_counts", infinitePositiveInfiniteDouble))); + OTUtils.user(Collections.singletonMap("num_counts", infinitePositiveInfiniteDouble)))); assertNull(testInstanceDouble.evaluate( null, - Collections.singletonMap("num_counts", infiniteNegativeInfiniteDouble))); + OTUtils.user(Collections.singletonMap("num_counts", infiniteNegativeInfiniteDouble)))); assertNull(testInstanceDouble.evaluate( - null, Collections.singletonMap("num_counts", - Collections.singletonMap("num_counts", infiniteNANDouble)))); + null, OTUtils.user(Collections.singletonMap("num_counts", + Collections.singletonMap("num_counts", infiniteNANDouble))))); assertNull(testInstanceDouble.evaluate( - null, Collections.singletonMap("num_counts", - Collections.singletonMap("num_counts", largeDouble)))); + null, OTUtils.user(Collections.singletonMap("num_counts", + Collections.singletonMap("num_counts", largeDouble))))); } /** @@ -888,10 +892,10 @@ public void leMatchConditionEvaluatesNullWithInvalidAttributes() { UserAttribute testInstanceNegativeInfiniteDouble = new UserAttribute("num_counts", "custom_attribute", "le", infiniteNegativeInfiniteDouble); UserAttribute testInstanceNANDouble = new UserAttribute("num_counts", "custom_attribute", "le", infiniteNANDouble); - assertNull(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertNull(testInstancePositiveInfinite.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNegativeInfiniteDouble.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNANDouble.evaluate(null, testTypedUserAttributes)); + assertNull(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstancePositiveInfinite.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNegativeInfiniteDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNANDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); } /** @@ -901,7 +905,7 @@ public void leMatchConditionEvaluatesNullWithInvalidAttributes() { @Test public void substringMatchConditionEvaluatesTrue() { UserAttribute testInstanceString = new UserAttribute("browser_type", "custom_attribute", "substring", "chrome"); - assertTrue(testInstanceString.evaluate(null, testUserAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testUserAttributes))); } /** @@ -911,7 +915,7 @@ public void substringMatchConditionEvaluatesTrue() { @Test public void substringMatchConditionPartialMatchEvaluatesTrue() { UserAttribute testInstanceString = new UserAttribute("browser_type", "custom_attribute", "substring", "chro"); - assertTrue(testInstanceString.evaluate(null, testUserAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testUserAttributes))); } /** @@ -921,7 +925,7 @@ public void substringMatchConditionPartialMatchEvaluatesTrue() { @Test public void substringMatchConditionEvaluatesFalse() { UserAttribute testInstanceString = new UserAttribute("browser_type", "custom_attribute", "substring", "chr0me"); - assertFalse(testInstanceString.evaluate(null, testUserAttributes)); + assertFalse(testInstanceString.evaluate(null, OTUtils.user(testUserAttributes))); } /** @@ -936,11 +940,11 @@ public void substringMatchConditionEvaluatesNull() { UserAttribute testInstanceObject = new UserAttribute("meta_data", "custom_attribute", "substring", "chrome1"); UserAttribute testInstanceNull = new UserAttribute("null_val", "custom_attribute", "substring", "chrome1"); - assertNull(testInstanceBoolean.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceInteger.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceDouble.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceObject.evaluate(null, testTypedUserAttributes)); - assertNull(testInstanceNull.evaluate(null, testTypedUserAttributes)); + assertNull(testInstanceBoolean.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceInteger.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceDouble.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceObject.evaluate(null, OTUtils.user(testTypedUserAttributes))); + assertNull(testInstanceNull.evaluate(null, OTUtils.user(testTypedUserAttributes))); } //======== Semantic version evaluation tests ========// @@ -951,7 +955,7 @@ public void testSemanticVersionEqualsMatchInvalidInput() { Map testAttributes = new HashMap(); testAttributes.put("version", 2.0); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_eq", "2.0.0"); - assertNull(testInstanceString.evaluate(null, testAttributes)); + assertNull(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } @Test @@ -959,7 +963,7 @@ public void semanticVersionInvalidMajorShouldBeNumberOnly() { Map testAttributes = new HashMap(); testAttributes.put("version", "a.1.2"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_eq", "2.0.0"); - assertNull(testInstanceString.evaluate(null, testAttributes)); + assertNull(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } @Test @@ -967,7 +971,7 @@ public void semanticVersionInvalidMinorShouldBeNumberOnly() { Map testAttributes = new HashMap(); testAttributes.put("version", "1.b.2"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_eq", "2.0.0"); - assertNull(testInstanceString.evaluate(null, testAttributes)); + assertNull(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } @Test @@ -975,7 +979,7 @@ public void semanticVersionInvalidPatchShouldBeNumberOnly() { Map testAttributes = new HashMap(); testAttributes.put("version", "1.2.c"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_eq", "2.0.0"); - assertNull(testInstanceString.evaluate(null, testAttributes)); + assertNull(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test SemanticVersionEqualsMatch returns null if given invalid UserCondition Variable type @@ -984,7 +988,7 @@ public void testSemanticVersionEqualsMatchInvalidUserConditionVariable() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.0"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_eq", 2.0); - assertNull(testInstanceString.evaluate(null, testAttributes)); + assertNull(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test SemanticVersionGTMatch returns null if given invalid value type @@ -993,7 +997,7 @@ public void testSemanticVersionGTMatchInvalidInput() { Map testAttributes = new HashMap(); testAttributes.put("version", false); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_gt", "2.0.0"); - assertNull(testInstanceString.evaluate(null, testAttributes)); + assertNull(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test SemanticVersionGEMatch returns null if given invalid value type @@ -1002,7 +1006,7 @@ public void testSemanticVersionGEMatchInvalidInput() { Map testAttributes = new HashMap(); testAttributes.put("version", 2); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_ge", "2.0.0"); - assertNull(testInstanceString.evaluate(null, testAttributes)); + assertNull(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test SemanticVersionLTMatch returns null if given invalid value type @@ -1011,7 +1015,7 @@ public void testSemanticVersionLTMatchInvalidInput() { Map testAttributes = new HashMap(); testAttributes.put("version", 2); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_lt", "2.0.0"); - assertNull(testInstanceString.evaluate(null, testAttributes)); + assertNull(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test SemanticVersionLEMatch returns null if given invalid value type @@ -1020,7 +1024,7 @@ public void testSemanticVersionLEMatchInvalidInput() { Map testAttributes = new HashMap(); testAttributes.put("version", 2); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_le", "2.0.0"); - assertNull(testInstanceString.evaluate(null, testAttributes)); + assertNull(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test if not same when targetVersion is only major.minor.patch and version is major.minor @@ -1029,7 +1033,7 @@ public void testIsSemanticNotSameConditionValueMajorMinorPatch() { Map testAttributes = new HashMap(); testAttributes.put("version", "1.2"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_eq", "1.2.0"); - assertFalse(testInstanceString.evaluate(null, testAttributes)); + assertFalse(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test if same when target is only major but user condition checks only major.minor,patch @@ -1038,7 +1042,7 @@ public void testIsSemanticSameSingleDigit() { Map testAttributes = new HashMap(); testAttributes.put("version", "3.0.0"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_eq", "3"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test if greater when User value patch is greater even when its beta @@ -1047,7 +1051,7 @@ public void testIsSemanticGreaterWhenUserConditionComparesMajorMinorAndPatchVers Map testAttributes = new HashMap(); testAttributes.put("version", "3.1.1-beta"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_gt", "3.1.0"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test if greater when preRelease is greater alphabetically @@ -1056,7 +1060,7 @@ public void testIsSemanticGreaterWhenMajorMinorPatchReleaseVersionCharacter() { Map testAttributes = new HashMap(); testAttributes.put("version", "3.1.1-beta.y.1+1.1"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_gt", "3.1.1-beta.x.1+1.1"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test if greater when preRelease version number is greater @@ -1065,7 +1069,7 @@ public void testIsSemanticGreaterWhenMajorMinorPatchPreReleaseVersionNum() { Map testAttributes = new HashMap(); testAttributes.put("version", "3.1.1-beta.x.2+1.1"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_gt", "3.1.1-beta.x.1+1.1"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test if equals semantic version even when only same preRelease is passed in user attribute and no build meta @@ -1074,7 +1078,7 @@ public void testIsSemanticEqualWhenMajorMinorPatchPreReleaseVersionNum() { Map testAttributes = new HashMap(); testAttributes.put("version", "3.1.1-beta.x.1"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_eq", "3.1.1-beta.x.1"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test if not same @@ -1083,7 +1087,7 @@ public void testIsSemanticNotSameReturnsFalse() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.1.2"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_eq", "2.1.1"); - assertFalse(testInstanceString.evaluate(null, testAttributes)); + assertFalse(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test when target is full semantic version major.minor.patch @@ -1092,7 +1096,7 @@ public void testIsSemanticSameFull() { Map testAttributes = new HashMap(); testAttributes.put("version", "3.0.1"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_eq", "3.0.1"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test compare less when user condition checks only major.minor @@ -1101,7 +1105,7 @@ public void testIsSemanticLess() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.1.6"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_lt", "2.2"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // When user condition checks major.minor but target is major.minor.patch then its equals @@ -1110,7 +1114,7 @@ public void testIsSemanticLessFalse() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.1.0"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_lt", "2.1"); - assertFalse(testInstanceString.evaluate(null, testAttributes)); + assertFalse(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test compare less when target is full major.minor.patch @@ -1119,7 +1123,7 @@ public void testIsSemanticFullLess() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.1.6"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_lt", "2.1.9"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test compare greater when user condition checks only major.minor @@ -1128,7 +1132,7 @@ public void testIsSemanticMore() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.3.6"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_gt", "2.2"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test compare greater when both are major.minor.patch-beta but target is greater than user condition @@ -1137,7 +1141,7 @@ public void testIsSemanticMoreWhenBeta() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.3.6-beta"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_gt", "2.3.5-beta"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test compare greater when target is major.minor.patch @@ -1146,7 +1150,7 @@ public void testIsSemanticFullMore() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.1.7"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_gt", "2.1.6"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test compare greater when target is major.minor.patch is smaller then it returns false @@ -1155,7 +1159,7 @@ public void testSemanticVersionGTFullMoreReturnsFalse() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.1.9"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_gt", "2.1.10"); - assertFalse(testInstanceString.evaluate(null, testAttributes)); + assertFalse(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test compare equal when both are exactly same - major.minor.patch-beta @@ -1164,7 +1168,7 @@ public void testIsSemanticFullEqual() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.1.9-beta"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_eq", "2.1.9-beta"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test compare equal when both major.minor.patch is same, but due to beta user condition is smaller @@ -1173,7 +1177,7 @@ public void testIsSemanticLessWhenBeta() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.1.9"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_gt", "2.1.9-beta"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test compare greater when target is major.minor.patch-beta and user condition only compares major.minor.patch @@ -1182,7 +1186,7 @@ public void testIsSemanticGreaterBeta() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.1.9"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_gt", "2.1.9-beta"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test compare equal when target is major.minor.patch @@ -1191,7 +1195,7 @@ public void testIsSemanticLessEqualsWhenEqualsReturnsTrue() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.1.9"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_le", "2.1.9"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test compare less when target is major.minor.patch @@ -1200,7 +1204,7 @@ public void testIsSemanticLessEqualsWhenLessReturnsTrue() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.132.9"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_le", "2.233.91"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test compare less when target is major.minor.patch @@ -1209,7 +1213,7 @@ public void testIsSemanticLessEqualsWhenGreaterReturnsFalse() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.233.91"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_le", "2.132.009"); - assertFalse(testInstanceString.evaluate(null, testAttributes)); + assertFalse(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test compare equal when target is major.minor.patch @@ -1218,7 +1222,7 @@ public void testIsSemanticGreaterEqualsWhenEqualsReturnsTrue() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.1.9"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_ge", "2.1.9"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test compare less when target is major.minor.patch @@ -1227,7 +1231,7 @@ public void testIsSemanticGreaterEqualsWhenLessReturnsTrue() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.233.91"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_ge", "2.132.9"); - assertTrue(testInstanceString.evaluate(null, testAttributes)); + assertTrue(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } // Test compare less when target is major.minor.patch @@ -1236,7 +1240,7 @@ public void testIsSemanticGreaterEqualsWhenLessReturnsFalse() { Map testAttributes = new HashMap(); testAttributes.put("version", "2.132.009"); UserAttribute testInstanceString = new UserAttribute("version", "custom_attribute", "semver_ge", "2.233.91"); - assertFalse(testInstanceString.evaluate(null, testAttributes)); + assertFalse(testInstanceString.evaluate(null, OTUtils.user(testAttributes))); } /** @@ -1245,7 +1249,7 @@ public void testIsSemanticGreaterEqualsWhenLessReturnsFalse() { @Test public void notConditionEvaluateNull() { NotCondition notCondition = new NotCondition(new NullCondition()); - assertNull(notCondition.evaluate(null, testUserAttributes)); + assertNull(notCondition.evaluate(null, OTUtils.user(testUserAttributes))); } /** @@ -1253,12 +1257,13 @@ public void notConditionEvaluateNull() { */ @Test public void notConditionEvaluateTrue() { + OptimizelyUserContext user = OTUtils.user(testUserAttributes); UserAttribute userAttribute = mock(UserAttribute.class); - when(userAttribute.evaluate(null, testUserAttributes)).thenReturn(false); + when(userAttribute.evaluate(null, user)).thenReturn(false); NotCondition notCondition = new NotCondition(userAttribute); - assertTrue(notCondition.evaluate(null, testUserAttributes)); - verify(userAttribute, times(1)).evaluate(null, testUserAttributes); + assertTrue(notCondition.evaluate(null, user)); + verify(userAttribute, times(1)).evaluate(null, user); } /** @@ -1266,12 +1271,13 @@ public void notConditionEvaluateTrue() { */ @Test public void notConditionEvaluateFalse() { + OptimizelyUserContext user = OTUtils.user(testUserAttributes); UserAttribute userAttribute = mock(UserAttribute.class); - when(userAttribute.evaluate(null, testUserAttributes)).thenReturn(true); + when(userAttribute.evaluate(null, user)).thenReturn(true); NotCondition notCondition = new NotCondition(userAttribute); - assertFalse(notCondition.evaluate(null, testUserAttributes)); - verify(userAttribute, times(1)).evaluate(null, testUserAttributes); + assertFalse(notCondition.evaluate(null, user)); + verify(userAttribute, times(1)).evaluate(null, user); } /** @@ -1279,21 +1285,22 @@ public void notConditionEvaluateFalse() { */ @Test public void orConditionEvaluateTrue() { + OptimizelyUserContext user = OTUtils.user(testUserAttributes); UserAttribute userAttribute1 = mock(UserAttribute.class); - when(userAttribute1.evaluate(null, testUserAttributes)).thenReturn(true); + when(userAttribute1.evaluate(null, user)).thenReturn(true); UserAttribute userAttribute2 = mock(UserAttribute.class); - when(userAttribute2.evaluate(null, testUserAttributes)).thenReturn(false); + when(userAttribute2.evaluate(null, user)).thenReturn(false); List conditions = new ArrayList(); conditions.add(userAttribute1); conditions.add(userAttribute2); OrCondition orCondition = new OrCondition(conditions); - assertTrue(orCondition.evaluate(null, testUserAttributes)); - verify(userAttribute1, times(1)).evaluate(null, testUserAttributes); + assertTrue(orCondition.evaluate(null, user)); + verify(userAttribute1, times(1)).evaluate(null, user); // shouldn't be called due to short-circuiting in 'Or' evaluation - verify(userAttribute2, times(0)).evaluate(null, testUserAttributes); + verify(userAttribute2, times(0)).evaluate(null, user); } /** @@ -1301,21 +1308,22 @@ public void orConditionEvaluateTrue() { */ @Test public void orConditionEvaluateTrueWithNullAndTrue() { + OptimizelyUserContext user = OTUtils.user(testUserAttributes); UserAttribute userAttribute1 = mock(UserAttribute.class); - when(userAttribute1.evaluate(null, testUserAttributes)).thenReturn(null); + when(userAttribute1.evaluate(null, user)).thenReturn(null); UserAttribute userAttribute2 = mock(UserAttribute.class); - when(userAttribute2.evaluate(null, testUserAttributes)).thenReturn(true); + when(userAttribute2.evaluate(null, user)).thenReturn(true); List conditions = new ArrayList(); conditions.add(userAttribute1); conditions.add(userAttribute2); OrCondition orCondition = new OrCondition(conditions); - assertTrue(orCondition.evaluate(null, testUserAttributes)); - verify(userAttribute1, times(1)).evaluate(null, testUserAttributes); + assertTrue(orCondition.evaluate(null, user)); + verify(userAttribute1, times(1)).evaluate(null, user); // shouldn't be called due to short-circuiting in 'Or' evaluation - verify(userAttribute2, times(1)).evaluate(null, testUserAttributes); + verify(userAttribute2, times(1)).evaluate(null, user); } /** @@ -1323,21 +1331,22 @@ public void orConditionEvaluateTrueWithNullAndTrue() { */ @Test public void orConditionEvaluateNullWithNullAndFalse() { + OptimizelyUserContext user = OTUtils.user(testUserAttributes); UserAttribute userAttribute1 = mock(UserAttribute.class); - when(userAttribute1.evaluate(null, testUserAttributes)).thenReturn(null); + when(userAttribute1.evaluate(null, user)).thenReturn(null); UserAttribute userAttribute2 = mock(UserAttribute.class); - when(userAttribute2.evaluate(null, testUserAttributes)).thenReturn(false); + when(userAttribute2.evaluate(null, user)).thenReturn(false); List conditions = new ArrayList(); conditions.add(userAttribute1); conditions.add(userAttribute2); OrCondition orCondition = new OrCondition(conditions); - assertNull(orCondition.evaluate(null, testUserAttributes)); - verify(userAttribute1, times(1)).evaluate(null, testUserAttributes); + assertNull(orCondition.evaluate(null, user)); + verify(userAttribute1, times(1)).evaluate(null, user); // shouldn't be called due to short-circuiting in 'Or' evaluation - verify(userAttribute2, times(1)).evaluate(null, testUserAttributes); + verify(userAttribute2, times(1)).evaluate(null, user); } /** @@ -1345,21 +1354,22 @@ public void orConditionEvaluateNullWithNullAndFalse() { */ @Test public void orConditionEvaluateFalseWithFalseAndFalse() { + OptimizelyUserContext user = OTUtils.user(testUserAttributes); UserAttribute userAttribute1 = mock(UserAttribute.class); - when(userAttribute1.evaluate(null, testUserAttributes)).thenReturn(false); + when(userAttribute1.evaluate(null, user)).thenReturn(false); UserAttribute userAttribute2 = mock(UserAttribute.class); - when(userAttribute2.evaluate(null, testUserAttributes)).thenReturn(false); + when(userAttribute2.evaluate(null, user)).thenReturn(false); List conditions = new ArrayList(); conditions.add(userAttribute1); conditions.add(userAttribute2); OrCondition orCondition = new OrCondition(conditions); - assertFalse(orCondition.evaluate(null, testUserAttributes)); - verify(userAttribute1, times(1)).evaluate(null, testUserAttributes); + assertFalse(orCondition.evaluate(null, user)); + verify(userAttribute1, times(1)).evaluate(null, user); // shouldn't be called due to short-circuiting in 'Or' evaluation - verify(userAttribute2, times(1)).evaluate(null, testUserAttributes); + verify(userAttribute2, times(1)).evaluate(null, user); } /** @@ -1367,20 +1377,21 @@ public void orConditionEvaluateFalseWithFalseAndFalse() { */ @Test public void orConditionEvaluateFalse() { + OptimizelyUserContext user = OTUtils.user(testUserAttributes); UserAttribute userAttribute1 = mock(UserAttribute.class); - when(userAttribute1.evaluate(null, testUserAttributes)).thenReturn(false); + when(userAttribute1.evaluate(null, user)).thenReturn(false); UserAttribute userAttribute2 = mock(UserAttribute.class); - when(userAttribute2.evaluate(null, testUserAttributes)).thenReturn(false); + when(userAttribute2.evaluate(null, user)).thenReturn(false); List conditions = new ArrayList(); conditions.add(userAttribute1); conditions.add(userAttribute2); OrCondition orCondition = new OrCondition(conditions); - assertFalse(orCondition.evaluate(null, testUserAttributes)); - verify(userAttribute1, times(1)).evaluate(null, testUserAttributes); - verify(userAttribute2, times(1)).evaluate(null, testUserAttributes); + assertFalse(orCondition.evaluate(null, user)); + verify(userAttribute1, times(1)).evaluate(null, user); + verify(userAttribute2, times(1)).evaluate(null, user); } /** @@ -1388,20 +1399,21 @@ public void orConditionEvaluateFalse() { */ @Test public void andConditionEvaluateTrue() { + OptimizelyUserContext user = OTUtils.user(testUserAttributes); OrCondition orCondition1 = mock(OrCondition.class); - when(orCondition1.evaluate(null, testUserAttributes)).thenReturn(true); + when(orCondition1.evaluate(null, user)).thenReturn(true); OrCondition orCondition2 = mock(OrCondition.class); - when(orCondition2.evaluate(null, testUserAttributes)).thenReturn(true); + when(orCondition2.evaluate(null, user)).thenReturn(true); List conditions = new ArrayList(); conditions.add(orCondition1); conditions.add(orCondition2); AndCondition andCondition = new AndCondition(conditions); - assertTrue(andCondition.evaluate(null, testUserAttributes)); - verify(orCondition1, times(1)).evaluate(null, testUserAttributes); - verify(orCondition2, times(1)).evaluate(null, testUserAttributes); + assertTrue(andCondition.evaluate(null, user)); + verify(orCondition1, times(1)).evaluate(null, user); + verify(orCondition2, times(1)).evaluate(null, user); } /** @@ -1409,20 +1421,21 @@ public void andConditionEvaluateTrue() { */ @Test public void andConditionEvaluateFalseWithNullAndFalse() { + OptimizelyUserContext user = OTUtils.user(testUserAttributes); OrCondition orCondition1 = mock(OrCondition.class); - when(orCondition1.evaluate(null, testUserAttributes)).thenReturn(null); + when(orCondition1.evaluate(null, user)).thenReturn(null); OrCondition orCondition2 = mock(OrCondition.class); - when(orCondition2.evaluate(null, testUserAttributes)).thenReturn(false); + when(orCondition2.evaluate(null, user)).thenReturn(false); List conditions = new ArrayList(); conditions.add(orCondition1); conditions.add(orCondition2); AndCondition andCondition = new AndCondition(conditions); - assertFalse(andCondition.evaluate(null, testUserAttributes)); - verify(orCondition1, times(1)).evaluate(null, testUserAttributes); - verify(orCondition2, times(1)).evaluate(null, testUserAttributes); + assertFalse(andCondition.evaluate(null, user)); + verify(orCondition1, times(1)).evaluate(null, user); + verify(orCondition2, times(1)).evaluate(null, user); } /** @@ -1430,20 +1443,21 @@ public void andConditionEvaluateFalseWithNullAndFalse() { */ @Test public void andConditionEvaluateNullWithNullAndTrue() { + OptimizelyUserContext user = OTUtils.user(testUserAttributes); OrCondition orCondition1 = mock(OrCondition.class); - when(orCondition1.evaluate(null, testUserAttributes)).thenReturn(null); + when(orCondition1.evaluate(null, user)).thenReturn(null); OrCondition orCondition2 = mock(OrCondition.class); - when(orCondition2.evaluate(null, testUserAttributes)).thenReturn(true); + when(orCondition2.evaluate(null, user)).thenReturn(true); List conditions = new ArrayList(); conditions.add(orCondition1); conditions.add(orCondition2); AndCondition andCondition = new AndCondition(conditions); - assertNull(andCondition.evaluate(null, testUserAttributes)); - verify(orCondition1, times(1)).evaluate(null, testUserAttributes); - verify(orCondition2, times(1)).evaluate(null, testUserAttributes); + assertNull(andCondition.evaluate(null, user)); + verify(orCondition1, times(1)).evaluate(null, user); + verify(orCondition2, times(1)).evaluate(null, user); } /** @@ -1451,11 +1465,12 @@ public void andConditionEvaluateNullWithNullAndTrue() { */ @Test public void andConditionEvaluateFalse() { + OptimizelyUserContext user = OTUtils.user(testUserAttributes); OrCondition orCondition1 = mock(OrCondition.class); - when(orCondition1.evaluate(null, testUserAttributes)).thenReturn(false); + when(orCondition1.evaluate(null, user)).thenReturn(false); OrCondition orCondition2 = mock(OrCondition.class); - when(orCondition2.evaluate(null, testUserAttributes)).thenReturn(true); + when(orCondition2.evaluate(null, user)).thenReturn(true); // and[false, true] List conditions = new ArrayList(); @@ -1463,13 +1478,13 @@ public void andConditionEvaluateFalse() { conditions.add(orCondition2); AndCondition andCondition = new AndCondition(conditions); - assertFalse(andCondition.evaluate(null, testUserAttributes)); - verify(orCondition1, times(1)).evaluate(null, testUserAttributes); + assertFalse(andCondition.evaluate(null, user)); + verify(orCondition1, times(1)).evaluate(null, user); // shouldn't be called due to short-circuiting in 'And' evaluation - verify(orCondition2, times(0)).evaluate(null, testUserAttributes); + verify(orCondition2, times(0)).evaluate(null, user); OrCondition orCondition3 = mock(OrCondition.class); - when(orCondition3.evaluate(null, testUserAttributes)).thenReturn(null); + when(orCondition3.evaluate(null, user)).thenReturn(null); // and[null, false] List conditions2 = new ArrayList(); @@ -1477,7 +1492,7 @@ public void andConditionEvaluateFalse() { conditions2.add(orCondition1); AndCondition andCondition2 = new AndCondition(conditions2); - assertFalse(andCondition2.evaluate(null, testUserAttributes)); + assertFalse(andCondition2.evaluate(null, user)); // and[true, false, null] List conditions3 = new ArrayList(); @@ -1486,7 +1501,310 @@ public void andConditionEvaluateFalse() { conditions3.add(orCondition1); AndCondition andCondition3 = new AndCondition(conditions3); - assertFalse(andCondition3.evaluate(null, testUserAttributes)); + assertFalse(andCondition3.evaluate(null, user)); + } + + /** + * Verify that with odp segment evaluator single ODP audience evaluates true + */ + @Test + public void singleODPAudienceEvaluateTrueIfSegmentExist() throws Exception { + + OptimizelyUserContext mockedUser = OTUtils.user(); + + UserAttribute testInstanceSingleAudience = new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-1"); + List userConditions = new ArrayList<>(); + userConditions.add(testInstanceSingleAudience); + AndCondition andCondition = new AndCondition(userConditions); + + // Should evaluate true if qualified segment exist + Whitebox.setInternalState(mockedUser, "qualifiedSegments", Collections.singletonList("odp-segment-1")); + + assertTrue(andCondition.evaluate(null, mockedUser)); + } + + /** + * Verify that with odp segment evaluator single ODP audience evaluates false + */ + @Test + public void singleODPAudienceEvaluateFalseIfSegmentNotExist() throws Exception { + + OptimizelyUserContext mockedUser = OTUtils.user(); + + UserAttribute testInstanceSingleAudience = new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-1"); + List userConditions = new ArrayList<>(); + userConditions.add(testInstanceSingleAudience); + AndCondition andCondition = new AndCondition(userConditions); + + // Should evaluate false if qualified segment does not exist + Whitebox.setInternalState(mockedUser, "qualifiedSegments", Collections.singletonList("odp-segment-2")); + + assertFalse(andCondition.evaluate(null, mockedUser)); + } + + /** + * Verify that with odp segment evaluator single ODP audience evaluates false when segments not provided + */ + @Test + public void singleODPAudienceEvaluateFalseIfSegmentNotProvided() throws Exception { + OptimizelyUserContext mockedUser = OTUtils.user(); + + UserAttribute testInstanceSingleAudience = new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-1"); + List userConditions = new ArrayList<>(); + userConditions.add(testInstanceSingleAudience); + AndCondition andCondition = new AndCondition(userConditions); + + // Should evaluate false if qualified segment does not exist + Whitebox.setInternalState(mockedUser, "qualifiedSegments", Collections.emptyList()); + + assertFalse(andCondition.evaluate(null, mockedUser)); + } + + /** + * Verify that with odp segment evaluator evaluates multiple ODP audience true when segment provided exist + */ + @Test + public void singleODPAudienceEvaluateMultipleOdpConditions() { + OptimizelyUserContext mockedUser = OTUtils.user(); + + Condition andCondition = createMultipleConditionAudienceAndOrODP(); + // Should evaluate correctly based on the given segments + List qualifiedSegments = new ArrayList<>(); + qualifiedSegments.add("odp-segment-1"); + qualifiedSegments.add("odp-segment-2"); + qualifiedSegments.add("odp-segment-3"); + + Whitebox.setInternalState(mockedUser, "qualifiedSegments", qualifiedSegments); + assertTrue(andCondition.evaluate(null, mockedUser)); + + qualifiedSegments = new ArrayList<>(); + qualifiedSegments.add("odp-segment-1"); + qualifiedSegments.add("odp-segment-2"); + qualifiedSegments.add("odp-segment-4"); + + Whitebox.setInternalState(mockedUser, "qualifiedSegments", qualifiedSegments); + assertTrue(andCondition.evaluate(null, mockedUser)); + + qualifiedSegments = new ArrayList<>(); + qualifiedSegments.add("odp-segment-1"); + qualifiedSegments.add("odp-segment-2"); + qualifiedSegments.add("odp-segment-3"); + qualifiedSegments.add("odp-segment-4"); + + Whitebox.setInternalState(mockedUser, "qualifiedSegments", qualifiedSegments); + assertTrue(andCondition.evaluate(null, mockedUser)); + } + + /** + * Verify that with odp segment evaluator evaluates multiple ODP audience true when segment provided exist + */ + @Test + public void singleODPAudienceEvaluateMultipleOdpConditionsEvaluateFalse() { + OptimizelyUserContext mockedUser = OTUtils.user(); + + Condition andCondition = createMultipleConditionAudienceAndOrODP(); + // Should evaluate correctly based on the given segments + List qualifiedSegments = new ArrayList<>(); + qualifiedSegments.add("odp-segment-1"); + qualifiedSegments.add("odp-segment-3"); + qualifiedSegments.add("odp-segment-4"); + + Whitebox.setInternalState(mockedUser, "qualifiedSegments", qualifiedSegments); + assertFalse(andCondition.evaluate(null, mockedUser)); + + qualifiedSegments = new ArrayList<>(); + qualifiedSegments.add("odp-segment-2"); + qualifiedSegments.add("odp-segment-3"); + qualifiedSegments.add("odp-segment-4"); + + Whitebox.setInternalState(mockedUser, "qualifiedSegments", qualifiedSegments); + assertFalse(andCondition.evaluate(null, mockedUser)); + } + + /** + * Verify that with odp segment evaluator evaluates multiple ODP audience with multiple conditions true or false when segment conditions meet + */ + @Test + public void multipleAudienceEvaluateMultipleOdpConditionsEvaluate() { + OptimizelyUserContext mockedUser = OTUtils.user(); + + // ["and", "1", "2"] + List audience1And2 = new ArrayList<>(); + audience1And2.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-1")); + audience1And2.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-2")); + AndCondition audienceCondition1 = new AndCondition(audience1And2); + + // ["and", "3", "4"] + List audience3And4 = new ArrayList<>(); + audience3And4.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-3")); + audience3And4.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-4")); + AndCondition audienceCondition2 = new AndCondition(audience3And4); + + // ["or", "5", "6"] + List audience5And6 = new ArrayList<>(); + audience5And6.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-5")); + audience5And6.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-6")); + OrCondition audienceCondition3 = new OrCondition(audience5And6); + + + //Scenario 1- ['or', '1', '2', '3'] + List conditions = new ArrayList<>(); + conditions.add(audienceCondition1); + conditions.add(audienceCondition2); + conditions.add(audienceCondition3); + + OrCondition implicitOr = new OrCondition(conditions); + // Should evaluate correctly based on the given segments + List qualifiedSegments = new ArrayList<>(); + qualifiedSegments.add("odp-segment-1"); + qualifiedSegments.add("odp-segment-2"); + + Whitebox.setInternalState(mockedUser, "qualifiedSegments", qualifiedSegments); + assertTrue(implicitOr.evaluate(null, mockedUser)); + + + //Scenario 2- ['and', '1', '2', '3'] + AndCondition implicitAnd = new AndCondition(conditions); + // Should evaluate correctly based on the given segments + qualifiedSegments = new ArrayList<>(); + qualifiedSegments.add("odp-segment-1"); + qualifiedSegments.add("odp-segment-2"); + + Whitebox.setInternalState(mockedUser, "qualifiedSegments", qualifiedSegments); + assertFalse(implicitAnd.evaluate(null, mockedUser)); + + // Should evaluate correctly based on the given segments + qualifiedSegments = new ArrayList<>(); + qualifiedSegments.add("odp-segment-1"); + qualifiedSegments.add("odp-segment-2"); + qualifiedSegments.add("odp-segment-3"); + qualifiedSegments.add("odp-segment-4"); + qualifiedSegments.add("odp-segment-6"); + + Whitebox.setInternalState(mockedUser, "qualifiedSegments", qualifiedSegments); + assertTrue(implicitAnd.evaluate(null, mockedUser)); + + + ////Scenario 3- ['and', '1', '2',['not', '3']] + conditions = new ArrayList<>(); + conditions.add(audienceCondition1); + conditions.add(audienceCondition2); + conditions.add(new NotCondition(audienceCondition3)); + implicitAnd = new AndCondition(conditions); + + // Should evaluate correctly based on the given segments + qualifiedSegments = new ArrayList<>(); + qualifiedSegments.add("odp-segment-1"); + qualifiedSegments.add("odp-segment-2"); + qualifiedSegments.add("odp-segment-3"); + qualifiedSegments.add("odp-segment-4"); + Whitebox.setInternalState(mockedUser, "qualifiedSegments", qualifiedSegments); + assertTrue(implicitAnd.evaluate(null, mockedUser)); + + // Should evaluate correctly based on the given segments + qualifiedSegments = new ArrayList<>(); + qualifiedSegments.add("odp-segment-1"); + qualifiedSegments.add("odp-segment-2"); + qualifiedSegments.add("odp-segment-3"); + qualifiedSegments.add("odp-segment-4"); + qualifiedSegments.add("odp-segment-5"); + Whitebox.setInternalState(mockedUser, "qualifiedSegments", qualifiedSegments); + assertFalse(implicitAnd.evaluate(null, mockedUser)); + } + + /** + * Verify that with odp segment evaluator evaluates multiple ODP audience with multiple type of evaluators + */ + @Test + public void multipleAudienceEvaluateMultipleOdpConditionsEvaluateWithMultipleTypeOfEvaluator() { + OptimizelyUserContext mockedUser = OTUtils.user(); + + // ["and", "1", "2"] + List audience1And2 = new ArrayList<>(); + audience1And2.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-1")); + audience1And2.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-2")); + AndCondition audienceCondition1 = new AndCondition(audience1And2); + + // ["and", "3", "4"] + List audience3And4 = new ArrayList<>(); + audience3And4.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-3")); + audience3And4.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-4")); + AndCondition audienceCondition2 = new AndCondition(audience3And4); + + // ["or", "chrome", "safari"] + List chromeUserAudience = new ArrayList<>(); + chromeUserAudience.add(new UserAttribute("browser_type", "custom_attribute", "exact", "chrome")); + chromeUserAudience.add(new UserAttribute("browser_type", "custom_attribute", "exact", "safari")); + OrCondition audienceCondition3 = new OrCondition(chromeUserAudience); + + + //Scenario 1- ['or', '1', '2', '3'] + List conditions = new ArrayList<>(); + conditions.add(audienceCondition1); + conditions.add(audienceCondition2); + conditions.add(audienceCondition3); + + OrCondition implicitOr = new OrCondition(conditions); + // Should evaluate correctly based on the given segments + List qualifiedSegments = new ArrayList<>(); + qualifiedSegments.add("odp-segment-1"); + qualifiedSegments.add("odp-segment-2"); + + Whitebox.setInternalState(mockedUser, "qualifiedSegments", qualifiedSegments); + assertTrue(implicitOr.evaluate(null, mockedUser)); + + + //Scenario 2- ['and', '1', '2', '3'] + AndCondition implicitAnd = new AndCondition(conditions); + // Should evaluate correctly based on the given segments + qualifiedSegments = new ArrayList<>(); + qualifiedSegments.add("odp-segment-1"); + qualifiedSegments.add("odp-segment-2"); + + mockedUser = OTUtils.user(Collections.singletonMap("browser_type", "chrome")); + Whitebox.setInternalState(mockedUser, "qualifiedSegments", qualifiedSegments); + assertFalse(implicitAnd.evaluate(null, mockedUser)); + + // Should evaluate correctly based on the given segments + qualifiedSegments = new ArrayList<>(); + qualifiedSegments.add("odp-segment-1"); + qualifiedSegments.add("odp-segment-2"); + qualifiedSegments.add("odp-segment-3"); + qualifiedSegments.add("odp-segment-4"); + + mockedUser = OTUtils.user(Collections.singletonMap("browser_type", "chrome")); + Whitebox.setInternalState(mockedUser, "qualifiedSegments", qualifiedSegments); + assertTrue(implicitAnd.evaluate(null, mockedUser)); + + // Should evaluate correctly based on the given segments + qualifiedSegments = new ArrayList<>(); + qualifiedSegments.add("odp-segment-1"); + qualifiedSegments.add("odp-segment-2"); + qualifiedSegments.add("odp-segment-3"); + qualifiedSegments.add("odp-segment-4"); + + mockedUser = OTUtils.user(Collections.singletonMap("browser_type", "not_chrome")); + Whitebox.setInternalState(mockedUser, "qualifiedSegments", qualifiedSegments); + assertFalse(implicitAnd.evaluate(null, mockedUser)); + } + + public Condition createMultipleConditionAudienceAndOrODP() { + UserAttribute testInstanceSingleAudience1 = new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-1"); + UserAttribute testInstanceSingleAudience2 = new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-2"); + UserAttribute testInstanceSingleAudience3 = new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-3"); + UserAttribute testInstanceSingleAudience4 = new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-4"); + + List userConditionsOR = new ArrayList<>(); + userConditionsOR.add(testInstanceSingleAudience3); + userConditionsOR.add(testInstanceSingleAudience4); + OrCondition orCondition = new OrCondition(userConditionsOR); + List userConditionsAnd = new ArrayList<>(); + userConditionsAnd.add(testInstanceSingleAudience1); + userConditionsAnd.add(testInstanceSingleAudience2); + userConditionsAnd.add(orCondition); + AndCondition andCondition = new AndCondition(userConditionsAnd); + + return andCondition; } /** @@ -1498,7 +1816,7 @@ public void andConditionEvaluateFalse() { // } /** - * Verify that {@link Condition#evaluate(com.optimizely.ab.config.ProjectConfig, java.util.Map)} + * Verify that {@link Condition#evaluate(com.optimizely.ab.config.ProjectConfig, com.optimizely.ab.OptimizelyUserContext)} * called when its attribute value is null * returns True when the user's attribute value is also null * True when the attribute is not in the map @@ -1518,8 +1836,8 @@ public void nullValueEvaluate() { attributeValue ); - assertNull(nullValueAttribute.evaluate(null, Collections.emptyMap())); - assertNull(nullValueAttribute.evaluate(null, Collections.singletonMap(attributeName, attributeValue))); - assertNull(nullValueAttribute.evaluate(null, (Collections.singletonMap(attributeName, "")))); + assertNull(nullValueAttribute.evaluate(null, OTUtils.user(Collections.emptyMap()))); + assertNull(nullValueAttribute.evaluate(null, OTUtils.user(Collections.singletonMap(attributeName, attributeValue)))); + assertNull(nullValueAttribute.evaluate(null, OTUtils.user((Collections.singletonMap(attributeName, ""))))); } } diff --git a/core-api/src/test/java/com/optimizely/ab/config/parser/DefaultConfigParserTest.java b/core-api/src/test/java/com/optimizely/ab/config/parser/DefaultConfigParserTest.java index dfc130f21..c43f29599 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/parser/DefaultConfigParserTest.java +++ b/core-api/src/test/java/com/optimizely/ab/config/parser/DefaultConfigParserTest.java @@ -20,6 +20,7 @@ import com.optimizely.ab.internal.PropertyUtils; import org.hamcrest.CoreMatchers; import org.junit.Assert; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; diff --git a/core-api/src/test/java/com/optimizely/ab/config/parser/GsonConfigParserTest.java b/core-api/src/test/java/com/optimizely/ab/config/parser/GsonConfigParserTest.java index 7cf4610ca..ea0d9cac8 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/parser/GsonConfigParserTest.java +++ b/core-api/src/test/java/com/optimizely/ab/config/parser/GsonConfigParserTest.java @@ -29,6 +29,7 @@ import com.optimizely.ab.config.audience.TypedAudience; import com.optimizely.ab.internal.InvalidAudienceCondition; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -312,6 +313,69 @@ public void nullJsonExceptionWrapping() throws Exception { parser.parseProjectConfig(null); } + @Test + public void integrationsArrayAbsent() throws Exception { + GsonConfigParser parser = new GsonConfigParser(); + ProjectConfig actual = parser.parseProjectConfig(nullFeatureEnabledConfigJsonV4()); + assertEquals(actual.getHostForODP(), ""); + assertEquals(actual.getPublicKeyForODP(), ""); + } + + @Test + public void integrationsArrayHasODP() throws Exception { + GsonConfigParser parser = new GsonConfigParser(); + ProjectConfig actual = parser.parseProjectConfig(validConfigJsonV4()); + assertEquals(actual.getHostForODP(), "https://example.com"); + assertEquals(actual.getPublicKeyForODP(), "test-key"); + } + + @Test + public void integrationsArrayHasOtherIntegration() throws Exception { + GsonConfigParser parser = new GsonConfigParser(); + String integrationsObject = ", \"integrations\": [" + + "{ \"key\": \"not-odp\", " + + "\"host\": \"https://example.com\", " + + "\"publicKey\": \"test-key\" }" + + "]}"; + String datafile = nullFeatureEnabledConfigJsonV4(); + datafile = datafile.substring(0, datafile.lastIndexOf("}")) + integrationsObject; + ProjectConfig actual = parser.parseProjectConfig(datafile); + assertEquals(actual.getIntegrations().size(), 1); + assertEquals(actual.getHostForODP(), ""); + assertEquals(actual.getPublicKeyForODP(), ""); + } + + @Test + public void integrationsArrayHasMissingHost() throws Exception { + GsonConfigParser parser = new GsonConfigParser(); + String integrationsObject = ", \"integrations\": [" + + "{ \"key\": \"odp\", " + + "\"publicKey\": \"test-key\" }" + + "]}"; + String datafile = nullFeatureEnabledConfigJsonV4(); + datafile = datafile.substring(0, datafile.lastIndexOf("}")) + integrationsObject; + ProjectConfig actual = parser.parseProjectConfig(datafile); + assertEquals(actual.getHostForODP(), null); + assertEquals(actual.getPublicKeyForODP(), "test-key"); + } + + @Test + public void integrationsArrayHasOtherKeys() throws Exception { + GsonConfigParser parser = new GsonConfigParser(); + String integrationsObject = ", \"integrations\": [" + + "{ \"key\": \"odp\", " + + "\"host\": \"https://example.com\", " + + "\"publicKey\": \"test-key\", " + + "\"new-key\": \"new-value\" }" + + "]}"; + String datafile = nullFeatureEnabledConfigJsonV4(); + datafile = datafile.substring(0, datafile.lastIndexOf("}")) + integrationsObject; + ProjectConfig actual = parser.parseProjectConfig(datafile); + assertEquals(actual.getIntegrations().size(), 1); + assertEquals(actual.getHostForODP(), "https://example.com"); + assertEquals(actual.getPublicKeyForODP(), "test-key"); + } + @Test public void testToJson() { Map map = new HashMap<>(); diff --git a/core-api/src/test/java/com/optimizely/ab/config/parser/JacksonConfigParserTest.java b/core-api/src/test/java/com/optimizely/ab/config/parser/JacksonConfigParserTest.java index 2e5dcb672..733ae49a5 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/parser/JacksonConfigParserTest.java +++ b/core-api/src/test/java/com/optimizely/ab/config/parser/JacksonConfigParserTest.java @@ -26,6 +26,7 @@ import com.optimizely.ab.config.audience.TypedAudience; import com.optimizely.ab.internal.InvalidAudienceCondition; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -304,6 +305,69 @@ public void nullJsonExceptionWrapping() throws Exception { parser.parseProjectConfig(null); } + @Test + public void integrationsArrayAbsent() throws Exception { + JacksonConfigParser parser = new JacksonConfigParser(); + ProjectConfig actual = parser.parseProjectConfig(nullFeatureEnabledConfigJsonV4()); + assertEquals(actual.getHostForODP(), ""); + assertEquals(actual.getPublicKeyForODP(), ""); + } + + @Test + public void integrationsArrayHasODP() throws Exception { + JacksonConfigParser parser = new JacksonConfigParser(); + ProjectConfig actual = parser.parseProjectConfig(validConfigJsonV4()); + assertEquals(actual.getHostForODP(), "https://example.com"); + assertEquals(actual.getPublicKeyForODP(), "test-key"); + } + + @Test + public void integrationsArrayHasOtherIntegration() throws Exception { + JacksonConfigParser parser = new JacksonConfigParser(); + String integrationsObject = ", \"integrations\": [" + + "{ \"key\": \"not-odp\", " + + "\"host\": \"https://example.com\", " + + "\"publicKey\": \"test-key\" }" + + "]}"; + String datafile = nullFeatureEnabledConfigJsonV4(); + datafile = datafile.substring(0, datafile.lastIndexOf("}")) + integrationsObject; + ProjectConfig actual = parser.parseProjectConfig(datafile); + assertEquals(actual.getIntegrations().size(), 1); + assertEquals(actual.getHostForODP(), ""); + assertEquals(actual.getPublicKeyForODP(), ""); + } + + @Test + public void integrationsArrayHasMissingHost() throws Exception { + JacksonConfigParser parser = new JacksonConfigParser(); + String integrationsObject = ", \"integrations\": [" + + "{ \"key\": \"odp\", " + + "\"publicKey\": \"test-key\" }" + + "]}"; + String datafile = nullFeatureEnabledConfigJsonV4(); + datafile = datafile.substring(0, datafile.lastIndexOf("}")) + integrationsObject; + ProjectConfig actual = parser.parseProjectConfig(datafile); + assertEquals(actual.getHostForODP(), null); + assertEquals(actual.getPublicKeyForODP(), "test-key"); + } + + @Test + public void integrationsArrayHasOtherKeys() throws Exception { + JacksonConfigParser parser = new JacksonConfigParser(); + String integrationsObject = ", \"integrations\": [" + + "{ \"key\": \"odp\", " + + "\"host\": \"https://example.com\", " + + "\"publicKey\": \"test-key\", " + + "\"new-key\": \"new-value\" }" + + "]}"; + String datafile = nullFeatureEnabledConfigJsonV4(); + datafile = datafile.substring(0, datafile.lastIndexOf("}")) + integrationsObject; + ProjectConfig actual = parser.parseProjectConfig(datafile); + assertEquals(actual.getIntegrations().size(), 1); + assertEquals(actual.getHostForODP(), "https://example.com"); + assertEquals(actual.getPublicKeyForODP(), "test-key"); + } + @Test public void testToJson() { Map map = new HashMap<>(); diff --git a/core-api/src/test/java/com/optimizely/ab/config/parser/JsonConfigParserTest.java b/core-api/src/test/java/com/optimizely/ab/config/parser/JsonConfigParserTest.java index d78f57e75..844d7448b 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/parser/JsonConfigParserTest.java +++ b/core-api/src/test/java/com/optimizely/ab/config/parser/JsonConfigParserTest.java @@ -27,6 +27,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.json.JSONArray; import org.json.JSONObject; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -255,6 +256,68 @@ public void nullJsonExceptionWrapping() throws Exception { parser.parseProjectConfig(null); } + @Test + public void integrationsArrayAbsent() throws Exception { + JsonConfigParser parser = new JsonConfigParser(); + ProjectConfig actual = parser.parseProjectConfig(nullFeatureEnabledConfigJsonV4()); + assertEquals(actual.getHostForODP(), ""); + assertEquals(actual.getPublicKeyForODP(), ""); + } + + @Test + public void integrationsArrayHasODP() throws Exception { + JsonConfigParser parser = new JsonConfigParser(); + ProjectConfig actual = parser.parseProjectConfig(validConfigJsonV4()); + assertEquals(actual.getHostForODP(), "https://example.com"); + assertEquals(actual.getPublicKeyForODP(), "test-key"); + } + + @Test + public void integrationsArrayHasOtherIntegration() throws Exception { + JsonConfigParser parser = new JsonConfigParser(); + String integrationsObject = ", \"integrations\": [" + + "{ \"key\": \"not-odp\", " + + "\"host\": \"https://example.com\", " + + "\"publicKey\": \"test-key\" }" + + "]}"; + String datafile = nullFeatureEnabledConfigJsonV4(); + datafile = datafile.substring(0, datafile.lastIndexOf("}")) + integrationsObject; + ProjectConfig actual = parser.parseProjectConfig(datafile); + assertEquals(actual.getIntegrations().size(), 1); + assertEquals(actual.getHostForODP(), ""); + assertEquals(actual.getPublicKeyForODP(), ""); + } + + @Test + public void integrationsArrayHasMissingHost() throws Exception { + JsonConfigParser parser = new JsonConfigParser(); + String integrationsObject = ", \"integrations\": [" + + "{ \"key\": \"odp\", " + + "\"publicKey\": \"test-key\" }" + + "]}"; + String datafile = nullFeatureEnabledConfigJsonV4(); + datafile = datafile.substring(0, datafile.lastIndexOf("}")) + integrationsObject; + ProjectConfig actual = parser.parseProjectConfig(datafile); + assertEquals(actual.getHostForODP(), null); + assertEquals(actual.getPublicKeyForODP(), "test-key"); + } + + @Test + public void integrationsArrayHasOtherKeys() throws Exception { + JsonConfigParser parser = new JsonConfigParser(); + String integrationsObject = ", \"integrations\": [" + + "{ \"key\": \"odp\", " + + "\"host\": \"https://example.com\", " + + "\"publicKey\": \"test-key\", " + + "\"new-key\": \"new-value\" }" + + "]}"; + String datafile = nullFeatureEnabledConfigJsonV4(); + datafile = datafile.substring(0, datafile.lastIndexOf("}")) + integrationsObject; + ProjectConfig actual = parser.parseProjectConfig(datafile); + assertEquals(actual.getIntegrations().size(), 1); + assertEquals(actual.getHostForODP(), "https://example.com"); + assertEquals(actual.getPublicKeyForODP(), "test-key"); + } @Test public void testToJson() { Map map = new HashMap<>(); diff --git a/core-api/src/test/java/com/optimizely/ab/config/parser/JsonSimpleConfigParserTest.java b/core-api/src/test/java/com/optimizely/ab/config/parser/JsonSimpleConfigParserTest.java index 6c5dca1eb..1844fa967 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/parser/JsonSimpleConfigParserTest.java +++ b/core-api/src/test/java/com/optimizely/ab/config/parser/JsonSimpleConfigParserTest.java @@ -27,6 +27,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.json.JSONArray; import org.json.JSONObject; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -254,6 +255,69 @@ public void nullJsonExceptionWrapping() throws Exception { parser.parseProjectConfig(null); } + @Test + public void integrationsArrayAbsent() throws Exception { + JsonSimpleConfigParser parser = new JsonSimpleConfigParser(); + ProjectConfig actual = parser.parseProjectConfig(nullFeatureEnabledConfigJsonV4()); + assertEquals(actual.getHostForODP(), ""); + assertEquals(actual.getPublicKeyForODP(), ""); + } + + @Test + public void integrationsArrayHasODP() throws Exception { + JsonSimpleConfigParser parser = new JsonSimpleConfigParser(); + ProjectConfig actual = parser.parseProjectConfig(validConfigJsonV4()); + assertEquals(actual.getHostForODP(), "https://example.com"); + assertEquals(actual.getPublicKeyForODP(), "test-key"); + } + + @Test + public void integrationsArrayHasOtherIntegration() throws Exception { + JsonSimpleConfigParser parser = new JsonSimpleConfigParser(); + String integrationsObject = ", \"integrations\": [" + + "{ \"key\": \"not-odp\", " + + "\"host\": \"https://example.com\", " + + "\"publicKey\": \"test-key\" }" + + "]}"; + String datafile = nullFeatureEnabledConfigJsonV4(); + datafile = datafile.substring(0, datafile.lastIndexOf("}")) + integrationsObject; + ProjectConfig actual = parser.parseProjectConfig(datafile); + assertEquals(actual.getIntegrations().size(), 1); + assertEquals(actual.getHostForODP(), ""); + assertEquals(actual.getPublicKeyForODP(), ""); + } + + @Test + public void integrationsArrayHasMissingHost() throws Exception { + JsonSimpleConfigParser parser = new JsonSimpleConfigParser(); + String integrationsObject = ", \"integrations\": [" + + "{ \"key\": \"odp\", " + + "\"publicKey\": \"test-key\" }" + + "]}"; + String datafile = nullFeatureEnabledConfigJsonV4(); + datafile = datafile.substring(0, datafile.lastIndexOf("}")) + integrationsObject; + ProjectConfig actual = parser.parseProjectConfig(datafile); + assertEquals(actual.getHostForODP(), null); + assertEquals(actual.getPublicKeyForODP(), "test-key"); + } + + @Test + public void integrationsArrayHasOtherKeys() throws Exception { + JsonSimpleConfigParser parser = new JsonSimpleConfigParser(); + String integrationsObject = ", \"integrations\": [" + + "{ \"key\": \"odp\", " + + "\"host\": \"https://example.com\", " + + "\"publicKey\": \"test-key\", " + + "\"new-key\": \"new-value\" }" + + "]}"; + String datafile = nullFeatureEnabledConfigJsonV4(); + datafile = datafile.substring(0, datafile.lastIndexOf("}")) + integrationsObject; + ProjectConfig actual = parser.parseProjectConfig(datafile); + assertEquals(actual.getIntegrations().size(), 1); + assertEquals(actual.getHostForODP(), "https://example.com"); + assertEquals(actual.getPublicKeyForODP(), "test-key"); + } + @Test public void testToJson() { Map map = new HashMap<>(); diff --git a/core-api/src/test/java/com/optimizely/ab/internal/ExperimentUtilsTest.java b/core-api/src/test/java/com/optimizely/ab/internal/ExperimentUtilsTest.java index fd1529aaf..d7965ccac 100644 --- a/core-api/src/test/java/com/optimizely/ab/internal/ExperimentUtilsTest.java +++ b/core-api/src/test/java/com/optimizely/ab/internal/ExperimentUtilsTest.java @@ -1,12 +1,12 @@ /** * - * Copyright 2017, 2019-2020, Optimizely and contributors + * Copyright 2017, 2019-2020, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,6 +25,7 @@ import com.optimizely.ab.config.audience.Audience; import com.optimizely.ab.config.audience.Condition; import com.optimizely.ab.config.audience.TypedAudience; +import com.optimizely.ab.testutils.OTUtils; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.junit.BeforeClass; import org.junit.Rule; @@ -128,7 +129,7 @@ public void isExperimentActiveReturnsFalseWhenTheExperimentIsNotStarted() { @Test public void doesUserMeetAudienceConditionsReturnsTrueIfExperimentHasNoAudiences() { Experiment experiment = noAudienceProjectConfig.getExperiments().get(0); - assertTrue(doesUserMeetAudienceConditions(noAudienceProjectConfig, experiment, Collections.emptyMap(), RULE, "Everyone Else").getResult()); + assertTrue(doesUserMeetAudienceConditions(noAudienceProjectConfig, experiment, OTUtils.user(Collections.emptyMap()), RULE, "Everyone Else").getResult()); } /** @@ -138,7 +139,7 @@ public void doesUserMeetAudienceConditionsReturnsTrueIfExperimentHasNoAudiences( @Test public void doesUserMeetAudienceConditionsEvaluatesEvenIfExperimentHasAudiencesButUserHasNoAttributes() { Experiment experiment = projectConfig.getExperiments().get(0); - Boolean result = doesUserMeetAudienceConditions(projectConfig, experiment, Collections.emptyMap(), EXPERIMENT, experiment.getKey()).getResult(); + Boolean result = doesUserMeetAudienceConditions(projectConfig, experiment, OTUtils.user(Collections.emptyMap()), EXPERIMENT, experiment.getKey()).getResult(); assertTrue(result); logbackVerifier.expectMessage(Level.DEBUG, "Evaluating audiences for experiment \"etag1\": [100]."); @@ -154,11 +155,11 @@ public void doesUserMeetAudienceConditionsEvaluatesEvenIfExperimentHasAudiencesB * If the {@link Experiment} contains at least one {@link Audience}, but attributes is empty, * then {@link ExperimentUtils#doesUserMeetAudienceConditions(ProjectConfig, Experiment, Map, String, String)} should return false. */ - @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") + @SuppressFBWarnings("NP_NULL_PARAM_DEREF_NONVIRTUAL") @Test public void doesUserMeetAudienceConditionsEvaluatesEvenIfExperimentHasAudiencesButUserSendNullAttributes() throws Exception { Experiment experiment = projectConfig.getExperiments().get(0); - Boolean result = doesUserMeetAudienceConditions(projectConfig, experiment, null, EXPERIMENT, experiment.getKey()).getResult(); + Boolean result = doesUserMeetAudienceConditions(projectConfig, experiment, OTUtils.user(null), EXPERIMENT, experiment.getKey()).getResult(); assertTrue(result); logbackVerifier.expectMessage(Level.DEBUG, @@ -179,7 +180,7 @@ public void doesUserMeetAudienceConditionsEvaluatesEvenIfExperimentHasAudiencesB public void doesUserMeetAudienceConditionsEvaluatesExperimentHasTypedAudiences() { Experiment experiment = v4ProjectConfig.getExperiments().get(1); Map attribute = Collections.singletonMap("booleanKey", true); - Boolean result = doesUserMeetAudienceConditions(v4ProjectConfig, experiment, attribute, EXPERIMENT, experiment.getKey()).getResult(); + Boolean result = doesUserMeetAudienceConditions(v4ProjectConfig, experiment, OTUtils.user(attribute), EXPERIMENT, experiment.getKey()).getResult(); assertTrue(result); logbackVerifier.expectMessage(Level.DEBUG, @@ -200,7 +201,7 @@ public void doesUserMeetAudienceConditionsEvaluatesExperimentHasTypedAudiences() public void doesUserMeetAudienceConditionsReturnsTrueIfUserSatisfiesAnAudience() { Experiment experiment = projectConfig.getExperiments().get(0); Map attributes = Collections.singletonMap("browser_type", "chrome"); - Boolean result = doesUserMeetAudienceConditions(projectConfig, experiment, attributes, EXPERIMENT, experiment.getKey()).getResult(); + Boolean result = doesUserMeetAudienceConditions(projectConfig, experiment, OTUtils.user(attributes), EXPERIMENT, experiment.getKey()).getResult(); assertTrue(result); logbackVerifier.expectMessage(Level.DEBUG, @@ -221,7 +222,7 @@ public void doesUserMeetAudienceConditionsReturnsTrueIfUserSatisfiesAnAudience() public void doesUserMeetAudienceConditionsReturnsTrueIfUserDoesNotSatisfyAnyAudiences() { Experiment experiment = projectConfig.getExperiments().get(0); Map attributes = Collections.singletonMap("browser_type", "firefox"); - Boolean result = doesUserMeetAudienceConditions(projectConfig, experiment, attributes, EXPERIMENT, experiment.getKey()).getResult(); + Boolean result = doesUserMeetAudienceConditions(projectConfig, experiment, OTUtils.user(attributes), EXPERIMENT, experiment.getKey()).getResult(); assertFalse(result); logbackVerifier.expectMessage(Level.DEBUG, @@ -246,8 +247,8 @@ public void doesUserMeetAudienceConditionsHandlesNullValue() { AUDIENCE_WITH_MISSING_VALUE_VALUE); Map nonMatchingMap = Collections.singletonMap(ATTRIBUTE_NATIONALITY_KEY, "American"); - assertTrue(doesUserMeetAudienceConditions(v4ProjectConfig, experiment, satisfiesFirstCondition, EXPERIMENT, experiment.getKey()).getResult()); - assertFalse(doesUserMeetAudienceConditions(v4ProjectConfig, experiment, nonMatchingMap, EXPERIMENT, experiment.getKey()).getResult()); + assertTrue(doesUserMeetAudienceConditions(v4ProjectConfig, experiment, OTUtils.user(satisfiesFirstCondition), EXPERIMENT, experiment.getKey()).getResult()); + assertFalse(doesUserMeetAudienceConditions(v4ProjectConfig, experiment, OTUtils.user(nonMatchingMap), EXPERIMENT, experiment.getKey()).getResult()); } /** @@ -258,7 +259,7 @@ public void doesUserMeetAudienceConditionsHandlesNullValueAttributesWithNull() { Experiment experiment = v4ProjectConfig.getExperimentKeyMapping().get(EXPERIMENT_WITH_MALFORMED_AUDIENCE_KEY); Map attributesWithNull = Collections.singletonMap(ATTRIBUTE_NATIONALITY_KEY, null); - assertFalse(doesUserMeetAudienceConditions(v4ProjectConfig, experiment, attributesWithNull, EXPERIMENT, experiment.getKey()).getResult()); + assertFalse(doesUserMeetAudienceConditions(v4ProjectConfig, experiment, OTUtils.user(attributesWithNull), EXPERIMENT, experiment.getKey()).getResult()); logbackVerifier.expectMessage(Level.DEBUG, "Starting to evaluate audience \"2196265320\" with conditions: [and, [or, [or, {name='nationality', type='custom_attribute', match='null', value='English'}, {name='nationality', type='custom_attribute', match='null', value=null}]]]."); @@ -279,7 +280,7 @@ public void doesUserMeetAudienceConditionsHandlesNullConditionValue() { Map attributesEmpty = Collections.emptyMap(); // It should explicitly be set to null otherwise we will return false on empty maps - assertFalse(doesUserMeetAudienceConditions(v4ProjectConfig, experiment, attributesEmpty, EXPERIMENT, experiment.getKey()).getResult()); + assertFalse(doesUserMeetAudienceConditions(v4ProjectConfig, experiment, OTUtils.user(attributesEmpty), EXPERIMENT, experiment.getKey()).getResult()); logbackVerifier.expectMessage(Level.DEBUG, "Starting to evaluate audience \"2196265320\" with conditions: [and, [or, [or, {name='nationality', type='custom_attribute', match='null', value='English'}, {name='nationality', type='custom_attribute', match='null', value=null}]]]."); diff --git a/core-api/src/test/java/com/optimizely/ab/optimizelyconfig/OptimizelyConfigServiceTest.java b/core-api/src/test/java/com/optimizely/ab/optimizelyconfig/OptimizelyConfigServiceTest.java index 426422ea3..29cbe3695 100644 --- a/core-api/src/test/java/com/optimizely/ab/optimizelyconfig/OptimizelyConfigServiceTest.java +++ b/core-api/src/test/java/com/optimizely/ab/optimizelyconfig/OptimizelyConfigServiceTest.java @@ -334,7 +334,8 @@ private ProjectConfig generateOptimizelyConfig() { ) ), Collections.emptyList(), - Collections.emptyList() + Collections.emptyList(), + Collections.emptyList() ); } diff --git a/core-api/src/test/java/com/optimizely/ab/testutils/OTUtils.java b/core-api/src/test/java/com/optimizely/ab/testutils/OTUtils.java new file mode 100644 index 000000000..36c184369 --- /dev/null +++ b/core-api/src/test/java/com/optimizely/ab/testutils/OTUtils.java @@ -0,0 +1,36 @@ +/** + * + * Copyright 2022, Optimizely and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.testutils; + +import com.optimizely.ab.*; +import java.util.Collections; +import java.util.Map; + +public class OTUtils { + public static OptimizelyUserContext user(String userId, Map attributes) { + Optimizely optimizely = new Optimizely.Builder().build(); + return new OptimizelyUserContext(optimizely, userId, attributes); + } + + public static OptimizelyUserContext user(Map attributes) { + return user("any-user", attributes); + } + + public static OptimizelyUserContext user() { + return user("any-user", Collections.emptyMap()); + } +} \ No newline at end of file diff --git a/core-api/src/test/resources/config/valid-project-config-v4.json b/core-api/src/test/resources/config/valid-project-config-v4.json index 01c927a5c..cc0de0908 100644 --- a/core-api/src/test/resources/config/valid-project-config-v4.json +++ b/core-api/src/test/resources/config/valid-project-config-v4.json @@ -945,5 +945,12 @@ } ] } + ], + "integrations": [ + { + "key": "odp", + "host": "https://example.com", + "publicKey": "test-key" + } ] } From 8bd6ea5af43120ae1928d00caa44aca67ea80f68 Mon Sep 17 00:00:00 2001 From: Zeeshan Ashraf <35262377+zashraf1985@users.noreply.github.com> Date: Fri, 22 Jul 2022 09:26:05 -0700 Subject: [PATCH 15/80] chore: Check Jira ticket number in PR description (#478) ## Summary Added a check to verify PR description contains a Jira ticket number. ## Ticket: [OASIS-8321](https://optimizely.atlassian.net/browse/OASIS-8321) --- .github/workflows/ticket_reference_check.yml | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 .github/workflows/ticket_reference_check.yml diff --git a/.github/workflows/ticket_reference_check.yml b/.github/workflows/ticket_reference_check.yml new file mode 100644 index 000000000..d2829e0c4 --- /dev/null +++ b/.github/workflows/ticket_reference_check.yml @@ -0,0 +1,16 @@ +name: Jira ticket reference check + +on: + pull_request: + types: [opened, edited, reopened, synchronize] + +jobs: + + jira_ticket_reference_check: + runs-on: ubuntu-latest + + steps: + - name: Check for Jira ticket reference + uses: optimizely/github-action-ticket-reference-checker-public@master + with: + bodyRegex: 'OASIS-(?\d+)' From 618377d9989e8a8883d3fb2e83bf63ca28ffc4db Mon Sep 17 00:00:00 2001 From: Zeeshan Ashraf <35262377+zashraf1985@users.noreply.github.com> Date: Tue, 2 Aug 2022 14:45:31 -0700 Subject: [PATCH 16/80] feat: Add ODP GraphQL Api Interface (#481) ## Summary 1. Added an ODPApiManager interface and its Default implementation that implements the graphQL call to fetch qualified segments. 2. The mechanism to get default parser is tightly coupled with Project Config module. I created a separate Factory class to get the default parser. This can be used by any future implementations that need a default parser. 3. Added parsing for all four supported parsers to parse valid and error responses. ## Test plan 1. Added new unit tests to test all the new code. 2. Existing unit tests pass 3. Existing Full stack compatibility suite tests pass ## Issues [OASIS-8384](https://optimizely.atlassian.net/browse/OASIS-8384) --- .../ab/internal/JsonParserProvider.java | 74 ++++++++ .../com/optimizely/ab/odp/ODPApiManager.java | 22 +++ .../ab/odp/parser/ResponseJsonParser.java | 22 +++ .../odp/parser/ResponseJsonParserFactory.java | 49 +++++ .../ab/odp/parser/impl/GsonParser.java | 62 ++++++ .../ab/odp/parser/impl/JacksonParser.java | 66 +++++++ .../ab/odp/parser/impl/JsonParser.java | 63 ++++++ .../ab/odp/parser/impl/JsonSimpleParser.java | 66 +++++++ .../ab/internal/JsonParserProviderTest.java | 46 +++++ .../parser/ResponseJsonParserFactoryTest.java | 51 +++++ .../ab/odp/parser/ResponseJsonParserTest.java | 92 +++++++++ .../ab/odp/DefaultODPApiManager.java | 179 ++++++++++++++++++ .../ab/internal/LogbackVerifier.java | 168 ++++++++++++++++ .../ab/odp/DefaultODPApiManagerTest.java | 116 ++++++++++++ 14 files changed, 1076 insertions(+) create mode 100644 core-api/src/main/java/com/optimizely/ab/internal/JsonParserProvider.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/parser/ResponseJsonParser.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactory.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/parser/impl/GsonParser.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JacksonParser.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonParser.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonSimpleParser.java create mode 100644 core-api/src/test/java/com/optimizely/ab/internal/JsonParserProviderTest.java create mode 100644 core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactoryTest.java create mode 100644 core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserTest.java create mode 100644 core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java create mode 100644 core-httpclient-impl/src/test/java/com/optimizely/ab/internal/LogbackVerifier.java create mode 100644 core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java diff --git a/core-api/src/main/java/com/optimizely/ab/internal/JsonParserProvider.java b/core-api/src/main/java/com/optimizely/ab/internal/JsonParserProvider.java new file mode 100644 index 000000000..6f6de6516 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/internal/JsonParserProvider.java @@ -0,0 +1,74 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.internal; + +import com.optimizely.ab.config.parser.MissingJsonParserException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public enum JsonParserProvider { + GSON_CONFIG_PARSER("com.google.gson.Gson"), + JACKSON_CONFIG_PARSER("com.fasterxml.jackson.databind.ObjectMapper" ), + JSON_CONFIG_PARSER("org.json.JSONObject"), + JSON_SIMPLE_CONFIG_PARSER("org.json.simple.JSONObject"); + + private static final Logger logger = LoggerFactory.getLogger(JsonParserProvider.class); + + private final String className; + + JsonParserProvider(String className) { + this.className = className; + } + + private boolean isAvailable() { + try { + Class.forName(className); + return true; + } catch (ClassNotFoundException e) { + return false; + } + } + + public static JsonParserProvider getDefaultParser() { + String defaultParserName = PropertyUtils.get("default_parser"); + + if (defaultParserName != null) { + try { + JsonParserProvider parser = JsonParserProvider.valueOf(defaultParserName); + if (parser.isAvailable()) { + logger.debug("using json parser: {}, based on override config", parser.className); + return parser; + } + + logger.warn("configured parser {} is not available in the classpath", defaultParserName); + } catch (IllegalArgumentException e) { + logger.warn("configured parser {} is not a valid value", defaultParserName); + } + } + + for (JsonParserProvider parser: JsonParserProvider.values()) { + if (!parser.isAvailable()) { + continue; + } + + logger.info("using json parser: {}", parser.className); + return parser; + } + + throw new MissingJsonParserException("unable to locate a JSON parser. " + + "Please see for more information"); + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java new file mode 100644 index 000000000..ed40e37fd --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java @@ -0,0 +1,22 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp; + +import java.util.List; + +public interface ODPApiManager { + String fetchQualifiedSegments(String apiKey, String apiEndpoint, String userKey, String userValue, List segmentsToCheck); +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/parser/ResponseJsonParser.java b/core-api/src/main/java/com/optimizely/ab/odp/parser/ResponseJsonParser.java new file mode 100644 index 000000000..d494a78d0 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/parser/ResponseJsonParser.java @@ -0,0 +1,22 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.parser; + +import java.util.List; + +public interface ResponseJsonParser { + public List parseQualifiedSegments(String responseJson); +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactory.java b/core-api/src/main/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactory.java new file mode 100644 index 000000000..7762cef0e --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactory.java @@ -0,0 +1,49 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.parser; + +import com.optimizely.ab.internal.JsonParserProvider; +import com.optimizely.ab.odp.parser.impl.GsonParser; +import com.optimizely.ab.odp.parser.impl.JacksonParser; +import com.optimizely.ab.odp.parser.impl.JsonParser; +import com.optimizely.ab.odp.parser.impl.JsonSimpleParser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ResponseJsonParserFactory { + private static final Logger logger = LoggerFactory.getLogger(ResponseJsonParserFactory.class); + + public static ResponseJsonParser getParser() { + JsonParserProvider parserProvider = JsonParserProvider.getDefaultParser(); + ResponseJsonParser jsonParser = null; + switch (parserProvider) { + case GSON_CONFIG_PARSER: + jsonParser = new GsonParser(); + break; + case JACKSON_CONFIG_PARSER: + jsonParser = new JacksonParser(); + break; + case JSON_CONFIG_PARSER: + jsonParser = new JsonParser(); + break; + case JSON_SIMPLE_CONFIG_PARSER: + jsonParser = new JsonSimpleParser(); + break; + } + logger.info("Using " + parserProvider.toString() + " parser"); + return jsonParser; + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/GsonParser.java b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/GsonParser.java new file mode 100644 index 000000000..b27d65078 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/GsonParser.java @@ -0,0 +1,62 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.parser.impl; + +import com.google.gson.*; +import com.google.gson.JsonParser; +import com.optimizely.ab.odp.parser.ResponseJsonParser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +public class GsonParser implements ResponseJsonParser { + private static final Logger logger = LoggerFactory.getLogger(GsonParser.class); + + @Override + public List parseQualifiedSegments(String responseJson) { + List parsedSegments = new ArrayList<>(); + try { + JsonObject root = JsonParser.parseString(responseJson).getAsJsonObject(); + + if (root.has("errors")) { + JsonArray errors = root.getAsJsonArray("errors"); + StringBuilder logMessage = new StringBuilder(); + for (int i = 0; i < errors.size(); i++) { + if (i > 0) { + logMessage.append(", "); + } + logMessage.append(errors.get(i).getAsJsonObject().get("message").getAsString()); + } + logger.error(logMessage.toString()); + return null; + } + + JsonArray edges = root.getAsJsonObject("data").getAsJsonObject("customer").getAsJsonObject("audiences").getAsJsonArray("edges"); + for (int i = 0; i < edges.size(); i++) { + JsonObject node = edges.get(i).getAsJsonObject().getAsJsonObject("node"); + if (node.has("state") && node.get("state").getAsString().equals("qualified")) { + parsedSegments.add(node.get("name").getAsString()); + } + } + return parsedSegments; + } catch (JsonSyntaxException e) { + logger.error("Error parsing qualified segments from response", e); + return null; + } + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JacksonParser.java b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JacksonParser.java new file mode 100644 index 000000000..f1a38eca7 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JacksonParser.java @@ -0,0 +1,66 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.parser.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.optimizely.ab.odp.parser.ResponseJsonParser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; + +import java.util.List; + +public class JacksonParser implements ResponseJsonParser { + private static final Logger logger = LoggerFactory.getLogger(JacksonParser.class); + + @Override + public List parseQualifiedSegments(String responseJson) { + ObjectMapper objectMapper = new ObjectMapper(); + List parsedSegments = new ArrayList<>(); + JsonNode root; + try { + root = objectMapper.readTree(responseJson); + + if (root.has("errors")) { + JsonNode errors = root.path("errors"); + StringBuilder logMessage = new StringBuilder(); + for (int i = 0; i < errors.size(); i++) { + if (i > 0) { + logMessage.append(", "); + } + logMessage.append(errors.get(i).path("message")); + } + logger.error(logMessage.toString()); + return null; + } + + JsonNode edges = root.path("data").path("customer").path("audiences").path("edges"); + for (JsonNode edgeNode : edges) { + String state = edgeNode.path("node").path("state").asText(); + if (state.equals("qualified")) { + parsedSegments.add(edgeNode.path("node").path("name").asText()); + } + } + return parsedSegments; + } catch (JsonProcessingException e) { + logger.error("Error parsing qualified segments from response", e); + return null; + } + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonParser.java b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonParser.java new file mode 100644 index 000000000..fcae748a4 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonParser.java @@ -0,0 +1,63 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.parser.impl; + +import com.optimizely.ab.odp.parser.ResponseJsonParser; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +public class JsonParser implements ResponseJsonParser { + private static final Logger logger = LoggerFactory.getLogger(JsonParser.class); + + @Override + public List parseQualifiedSegments(String responseJson) { + List parsedSegments = new ArrayList<>(); + try { + JSONObject root = new JSONObject(responseJson); + + if (root.has("errors")) { + JSONArray errors = root.getJSONArray("errors"); + StringBuilder logMessage = new StringBuilder(); + for (int i = 0; i < errors.length(); i++) { + if (i > 0) { + logMessage.append(", "); + } + logMessage.append(errors.getJSONObject(i).getString("message")); + } + logger.error(logMessage.toString()); + return null; + } + + JSONArray edges = root.getJSONObject("data").getJSONObject("customer").getJSONObject("audiences").getJSONArray("edges"); + for (int i = 0; i < edges.length(); i++) { + JSONObject node = edges.getJSONObject(i).getJSONObject("node"); + if (node.has("state") && node.getString("state").equals("qualified")) { + parsedSegments.add(node.getString("name")); + } + } + return parsedSegments; + } catch (JSONException e) { + logger.error("Error parsing qualified segments from response", e); + return null; + } + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonSimpleParser.java b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonSimpleParser.java new file mode 100644 index 000000000..1bee81b0a --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonSimpleParser.java @@ -0,0 +1,66 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.parser.impl; + +import com.optimizely.ab.odp.parser.ResponseJsonParser; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +public class JsonSimpleParser implements ResponseJsonParser { + private static final Logger logger = LoggerFactory.getLogger(JsonSimpleParser.class); + + @Override + public List parseQualifiedSegments(String responseJson) { + List parsedSegments = new ArrayList<>(); + JSONParser parser = new JSONParser(); + JSONObject root = null; + try { + root = (JSONObject) parser.parse(responseJson); + + if (root.containsKey("errors")) { + JSONArray errors = (JSONArray) root.get("errors"); + StringBuilder logMessage = new StringBuilder(); + for (int i = 0; i < errors.size(); i++) { + if (i > 0) { + logMessage.append(", "); + } + logMessage.append((String)((JSONObject) errors.get(i)).get("message")); + } + logger.error(logMessage.toString()); + return null; + } + + JSONArray edges = (JSONArray)((JSONObject)((JSONObject)(((JSONObject) root.get("data"))).get("customer")).get("audiences")).get("edges"); + for (int i = 0; i < edges.size(); i++) { + JSONObject node = (JSONObject) ((JSONObject) edges.get(i)).get("node"); + if (node.containsKey("state") && (node.get("state")).equals("qualified")) { + parsedSegments.add((String) node.get("name")); + } + } + return parsedSegments; + } catch (ParseException | NullPointerException e) { + logger.error("Error parsing qualified segments from response", e); + return null; + } + } +} diff --git a/core-api/src/test/java/com/optimizely/ab/internal/JsonParserProviderTest.java b/core-api/src/test/java/com/optimizely/ab/internal/JsonParserProviderTest.java new file mode 100644 index 000000000..a65e9b6f5 --- /dev/null +++ b/core-api/src/test/java/com/optimizely/ab/internal/JsonParserProviderTest.java @@ -0,0 +1,46 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.internal; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import static org.junit.Assert.*; + +public class JsonParserProviderTest { + @Before + @After + public void clearParserSystemProperty() { + PropertyUtils.clear("default_parser"); + } + + @Test + public void getGsonParserProviderWhenNoDefaultIsSet() { + assertEquals(JsonParserProvider.GSON_CONFIG_PARSER, JsonParserProvider.getDefaultParser()); + } + + @Test + public void getCorrectParserProviderWhenValidDefaultIsProvided() { + PropertyUtils.set("default_parser", "JSON_CONFIG_PARSER"); + assertEquals(JsonParserProvider.JSON_CONFIG_PARSER, JsonParserProvider.getDefaultParser()); + } + + @Test + public void getGsonParserWhenProvidedDefaultParserDoesNotExist() { + PropertyUtils.set("default_parser", "GARBAGE_VALUE"); + assertEquals(JsonParserProvider.GSON_CONFIG_PARSER, JsonParserProvider.getDefaultParser()); + } +} diff --git a/core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactoryTest.java b/core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactoryTest.java new file mode 100644 index 000000000..f5d8e8c89 --- /dev/null +++ b/core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactoryTest.java @@ -0,0 +1,51 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.parser; + +import com.optimizely.ab.internal.JsonParserProvider; +import com.optimizely.ab.internal.PropertyUtils; +import com.optimizely.ab.odp.parser.impl.GsonParser; +import com.optimizely.ab.odp.parser.impl.JsonParser; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class ResponseJsonParserFactoryTest { + @Before + @After + public void clearParserSystemProperty() { + PropertyUtils.clear("default_parser"); + } + + @Test + public void getGsonParserWhenNoDefaultIsSet() { + assertEquals(GsonParser.class, ResponseJsonParserFactory.getParser().getClass()); + } + + @Test + public void getCorrectParserWhenValidDefaultIsProvided() { + PropertyUtils.set("default_parser", "JSON_CONFIG_PARSER"); + assertEquals(JsonParser.class, ResponseJsonParserFactory.getParser().getClass()); + } + + @Test + public void getGsonParserWhenGivenDefaultParserDoesNotExist() { + PropertyUtils.set("default_parser", "GARBAGE_VALUE"); + assertEquals(GsonParser.class, ResponseJsonParserFactory.getParser().getClass()); + } +} diff --git a/core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserTest.java b/core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserTest.java new file mode 100644 index 000000000..1acd5cf15 --- /dev/null +++ b/core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserTest.java @@ -0,0 +1,92 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.parser; + +import ch.qos.logback.classic.Level; +import com.optimizely.ab.internal.LogbackVerifier; +import static junit.framework.TestCase.assertEquals; + +import com.optimizely.ab.odp.parser.impl.*; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.util.Arrays; +import java.util.List; + +@RunWith(Parameterized.class) +public class ResponseJsonParserTest { + private final ResponseJsonParser jsonParser; + + @Rule + public LogbackVerifier logbackVerifier = new LogbackVerifier(); + + public ResponseJsonParserTest(ResponseJsonParser jsonParser) { + super(); + this.jsonParser = jsonParser; + } + + @Parameterized.Parameters + public static List input() { + return Arrays.asList(new GsonParser(), new JsonParser(), new JsonSimpleParser(), new JacksonParser()); + } + + @Test + public void returnSegmentsListWhenResponseIsCorrect() { + String responseToParse = "{\"data\":{\"customer\":{\"audiences\":{\"edges\":[{\"node\":{\"name\":\"has_email\",\"state\":\"qualified\"}},{\"node\":{\"name\":\"has_email_opted_in\",\"state\":\"qualified\"}}]}}}}"; + List parsedSegments = jsonParser.parseQualifiedSegments(responseToParse); + assertEquals(Arrays.asList("has_email", "has_email_opted_in"), parsedSegments); + } + + @Test + public void excludeSegmentsWhenStateNotQualified() { + String responseToParse = "{\"data\":{\"customer\":{\"audiences\":{\"edges\":[{\"node\":{\"name\":\"has_email\",\"state\":\"qualified\"}},{\"node\":{\"name\":\"has_email_opted_in\",\"state\":\"not_qualified\"}}]}}}}"; + List parsedSegments = jsonParser.parseQualifiedSegments(responseToParse); + assertEquals(Arrays.asList("has_email"), parsedSegments); + } + + @Test + public void returnEmptyListWhenResponseHasEmptyArray() { + String responseToParse = "{\"data\":{\"customer\":{\"audiences\":{\"edges\":[]}}}}"; + List parsedSegments = jsonParser.parseQualifiedSegments(responseToParse); + assertEquals(Arrays.asList(), parsedSegments); + } + + @Test + public void returnNullWhenJsonFormatIsValidButUnexpectedData() { + String responseToParse = "{\"data\"\"consumer\":{\"randomKey\":{\"edges\":[{\"node\":{\"name\":\"has_email\",\"state\":\"qualified\"}},{\"node\":{\"name\":\"has_email_opted_in\",\"state\":\"qualified\"}}]}}}}"; + List parsedSegments = jsonParser.parseQualifiedSegments(responseToParse); + logbackVerifier.expectMessage(Level.ERROR, "Error parsing qualified segments from response"); + assertEquals(null, parsedSegments); + } + + @Test + public void returnNullWhenJsonIsMalformed() { + String responseToParse = "{\"data\"\"customer\":{\"audiences\":{\"edges\":[{\"node\":{\"name\":\"has_email\",\"state\":\"qualified\"}},{\"node\":{\"name\":\"has_email_opted_in\",\"state\":\"qualified\"}}]}}}}"; + List parsedSegments = jsonParser.parseQualifiedSegments(responseToParse); + logbackVerifier.expectMessage(Level.ERROR, "Error parsing qualified segments from response"); + assertEquals(null, parsedSegments); + } + + @Test + public void returnNullAndLogCorrectErrorWhenErrorResponseIsReturned() { + String responseToParse = "{\"errors\":[{\"message\":\"Exception while fetching data (/customer) : java.lang.RuntimeException: could not resolve _fs_user_id = wrong_id\",\"locations\":[{\"line\":2,\"column\":3}],\"path\":[\"customer\"],\"extensions\":{\"classification\":\"InvalidIdentifierException\"}}],\"data\":{\"customer\":null}}"; + List parsedSegments = jsonParser.parseQualifiedSegments(responseToParse); + logbackVerifier.expectMessage(Level.ERROR, "Exception while fetching data (/customer) : java.lang.RuntimeException: could not resolve _fs_user_id = wrong_id"); + assertEquals(null, parsedSegments); + } +} diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java new file mode 100644 index 000000000..f0703dcb0 --- /dev/null +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java @@ -0,0 +1,179 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp; + +import com.optimizely.ab.OptimizelyHttpClient; +import com.optimizely.ab.annotations.VisibleForTesting; +import org.apache.http.HttpStatus; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.List; + +public class DefaultODPApiManager implements ODPApiManager { + private static final Logger logger = LoggerFactory.getLogger(DefaultODPApiManager.class); + + private final OptimizelyHttpClient httpClient; + + public DefaultODPApiManager() { + this(OptimizelyHttpClient.builder().build()); + } + + @VisibleForTesting + DefaultODPApiManager(OptimizelyHttpClient httpClient) { + this.httpClient = httpClient; + } + + @VisibleForTesting + String getSegmentsStringForRequest(List segmentsList) { + StringBuilder segmentsString = new StringBuilder(); + for (int i = 0; i < segmentsList.size(); i++) { + if (i > 0) { + segmentsString.append(", "); + } + segmentsString.append("\\\"").append(segmentsList.get(i)).append("\\\""); + } + return segmentsString.toString(); + } + + // ODP GraphQL API + // - https://api.zaius.com/v3/graphql + // - test ODP public API key = "W4WzcEs-ABgXorzY7h1LCQ" + /* + + [GraphQL Request] + + // fetch info with fs_user_id for ["has_email", "has_email_opted_in", "push_on_sale"] segments + curl -i -H 'Content-Type: application/json' -H 'x-api-key: W4WzcEs-ABgXorzY7h1LCQ' -X POST -d '{"query":"query {customer(fs_user_id: \"tester-101\") {audiences(subset:[\"has_email\",\"has_email_opted_in\",\"push_on_sale\"]) {edges {node {name state}}}}}"}' https://api.zaius.com/v3/graphql + // fetch info with vuid for ["has_email", "has_email_opted_in", "push_on_sale"] segments + curl -i -H 'Content-Type: application/json' -H 'x-api-key: W4WzcEs-ABgXorzY7h1LCQ' -X POST -d '{"query":"query {customer(vuid: \"d66a9d81923d4d2f99d8f64338976322\") {audiences(subset:[\"has_email\",\"has_email_opted_in\",\"push_on_sale\"]) {edges {node {name state}}}}}"}' https://api.zaius.com/v3/graphql + query MyQuery { + customer(vuid: "d66a9d81923d4d2f99d8f64338976322") { + audiences(subset:["has_email","has_email_opted_in","push_on_sale"]) { + edges { + node { + name + state + } + } + } + } + } + [GraphQL Response] + + { + "data": { + "customer": { + "audiences": { + "edges": [ + { + "node": { + "name": "has_email", + "state": "qualified", + } + }, + { + "node": { + "name": "has_email_opted_in", + "state": "qualified", + } + }, + ... + ] + } + } + } + } + + [GraphQL Error Response] + { + "errors": [ + { + "message": "Exception while fetching data (/customer) : java.lang.RuntimeException: could not resolve _fs_user_id = asdsdaddddd", + "locations": [ + { + "line": 2, + "column": 3 + } + ], + "path": [ + "customer" + ], + "extensions": { + "classification": "InvalidIdentifierException" + } + } + ], + "data": { + "customer": null + } + } + */ + @Override + public String fetchQualifiedSegments(String apiKey, String apiEndpoint, String userKey, String userValue, List segmentsToCheck) { + HttpPost request = new HttpPost(apiEndpoint); + String segmentsString = getSegmentsStringForRequest(segmentsToCheck); + String requestPayload = String.format("{\"query\": \"query {customer(%s: \\\"%s\\\") {audiences(subset: [%s]) {edges {node {name state}}}}}\"}", userKey, userValue, segmentsString); + try { + request.setEntity(new StringEntity(requestPayload)); + } catch (UnsupportedEncodingException e) { + logger.warn("Error encoding request payload", e); + } + request.setHeader("x-api-key", apiKey); + request.setHeader("content-type", "application/json"); + + CloseableHttpResponse response = null; + try { + response = httpClient.execute(request); + } catch (IOException e) { + logger.error("Error retrieving response from ODP service", e); + return null; + } + + if (response.getStatusLine().getStatusCode() >= 400) { + StatusLine statusLine = response.getStatusLine(); + logger.error(String.format("Unexpected response from ODP server, Response code: %d, %s", statusLine.getStatusCode(), statusLine.getReasonPhrase())); + closeHttpResponse(response); + return null; + } + + try { + return EntityUtils.toString(response.getEntity()); + } catch (IOException e) { + logger.error("Error converting ODP segments response to string", e); + } finally { + closeHttpResponse(response); + } + return null; + } + + private static void closeHttpResponse(CloseableHttpResponse response) { + if (response != null) { + try { + response.close(); + } catch (IOException e) { + logger.warn(e.getLocalizedMessage()); + } + } + } +} diff --git a/core-httpclient-impl/src/test/java/com/optimizely/ab/internal/LogbackVerifier.java b/core-httpclient-impl/src/test/java/com/optimizely/ab/internal/LogbackVerifier.java new file mode 100644 index 000000000..25154e97d --- /dev/null +++ b/core-httpclient-impl/src/test/java/com/optimizely/ab/internal/LogbackVerifier.java @@ -0,0 +1,168 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.internal; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.classic.spi.IThrowableProxy; +import ch.qos.logback.core.AppenderBase; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; +import org.slf4j.LoggerFactory; + +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; + +import static org.junit.Assert.fail; + +/** + * TODO As a usability improvement we should require expected messages be added after the message are expected to be + * logged. This will allow us to map the failure immediately back to the test line number as opposed to the async + * validation now that happens at the end of each individual test. + * + * From http://techblog.kenshoo.com/2013/08/junit-rule-for-verifying-logback-logging.html + */ +public class LogbackVerifier implements TestRule { + + private List expectedEvents = new LinkedList(); + + private CaptureAppender appender; + + @Override + public Statement apply(final Statement base, Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + before(); + try { + base.evaluate(); + verify(); + } finally { + after(); + } + } + }; + } + + public void expectMessage(Level level) { + expectMessage(level, ""); + } + + public void expectMessage(Level level, String msg) { + expectMessage(level, msg, (Class) null); + } + + public void expectMessage(Level level, String msg, Class throwableClass) { + expectMessage(level, msg, null, 1); + } + + public void expectMessage(Level level, String msg, int times) { + expectMessage(level, msg, null, times); + } + + public void expectMessage(Level level, + String msg, + Class throwableClass, + int times) { + for (int i = 0; i < times; i++) { + expectedEvents.add(new ExpectedLogEvent(level, msg, throwableClass)); + } + } + + private void before() { + appender = new CaptureAppender(); + appender.setName("MOCK"); + appender.start(); + ((Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).addAppender(appender); + } + + private void verify() throws Throwable { + ListIterator actualIterator = appender.getEvents().listIterator(); + + for (final ExpectedLogEvent expectedEvent : expectedEvents) { + boolean found = false; + while (actualIterator.hasNext()) { + ILoggingEvent actual = actualIterator.next(); + + if (expectedEvent.matches(actual)) { + found = true; + break; + } + } + + if (!found) { + fail(expectedEvent.toString()); + } + } + } + + private void after() { + ((Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).detachAppender(appender); + } + + private static class CaptureAppender extends AppenderBase { + + List actualLoggingEvent = new LinkedList<>(); + + @Override + protected void append(ILoggingEvent eventObject) { + actualLoggingEvent.add(eventObject); + } + + public List getEvents() { + return actualLoggingEvent; + } + } + + private final static class ExpectedLogEvent { + private final String message; + private final Level level; + private final Class throwableClass; + + private ExpectedLogEvent(Level level, + String message, + Class throwableClass) { + this.message = message; + this.level = level; + this.throwableClass = throwableClass; + } + + private boolean matches(ILoggingEvent actual) { + boolean match = actual.getFormattedMessage().contains(message); + match &= actual.getLevel().equals(level); + match &= matchThrowables(actual); + return match; + } + + private boolean matchThrowables(ILoggingEvent actual) { + IThrowableProxy eventProxy = actual.getThrowableProxy(); + return throwableClass == null || eventProxy != null && throwableClass.getName().equals(eventProxy.getClassName()); + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("ExpectedLogEvent{"); + sb.append("level=").append(level); + sb.append(", message='").append(message).append('\''); + sb.append(", throwableClass=").append(throwableClass); + sb.append('}'); + return sb.toString(); + } + } +} diff --git a/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java b/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java new file mode 100644 index 000000000..c81af2dce --- /dev/null +++ b/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java @@ -0,0 +1,116 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp; + +import ch.qos.logback.classic.Level; +import com.optimizely.ab.OptimizelyHttpClient; +import com.optimizely.ab.internal.LogbackVerifier; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.util.EntityUtils; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +import java.util.ArrayList; +import java.util.Arrays; + +import static org.junit.Assert.*; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.*; + +public class DefaultODPApiManagerTest { + private static final String validResponse = "{\"data\":{\"customer\":{\"audiences\":{\"edges\":[{\"node\":{\"name\":\"has_email\",\"state\":\"qualified\"}},{\"node\":{\"name\":\"has_email_opted_in\",\"state\":\"qualified\"}}]}}}}"; + + @Rule + public LogbackVerifier logbackVerifier = new LogbackVerifier(); + + OptimizelyHttpClient mockHttpClient; + + @Before + public void setUp() throws Exception { + setupHttpClient(200); + } + + private void setupHttpClient(int statusCode) throws Exception { + mockHttpClient = mock(OptimizelyHttpClient.class); + CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class); + StatusLine statusLine = mock(StatusLine.class); + + when(statusLine.getStatusCode()).thenReturn(statusCode); + when(httpResponse.getStatusLine()).thenReturn(statusLine); + when(httpResponse.getEntity()).thenReturn(new StringEntity(validResponse)); + + when(mockHttpClient.execute(any(HttpPost.class))) + .thenReturn(httpResponse); + } + + @Test + public void generateCorrectSegmentsStringWhenListHasOneItem() { + DefaultODPApiManager apiManager = new DefaultODPApiManager(); + String expected = "\\\"only_segment\\\""; + String actual = apiManager.getSegmentsStringForRequest(Arrays.asList("only_segment")); + assertEquals(expected, actual); + } + + @Test + public void generateCorrectSegmentsStringWhenListHasMultipleItems() { + DefaultODPApiManager apiManager = new DefaultODPApiManager(); + String expected = "\\\"segment_1\\\", \\\"segment_2\\\", \\\"segment_3\\\""; + String actual = apiManager.getSegmentsStringForRequest(Arrays.asList("segment_1", "segment_2", "segment_3")); + assertEquals(expected, actual); + } + + @Test + public void generateEmptyStringWhenGivenListIsEmpty() { + DefaultODPApiManager apiManager = new DefaultODPApiManager(); + String actual = apiManager.getSegmentsStringForRequest(new ArrayList<>()); + assertEquals("", actual); + } + + @Test + public void generateCorrectRequestBody() throws Exception { + ODPApiManager apiManager = new DefaultODPApiManager(mockHttpClient); + apiManager.fetchQualifiedSegments("key", "endPoint", "fs_user_id", "test_user", Arrays.asList("segment_1", "segment_2")); + verify(mockHttpClient, times(1)).execute(any(HttpPost.class)); + + String expectedResponse = "{\"query\": \"query {customer(fs_user_id: \\\"test_user\\\") {audiences(subset: [\\\"segment_1\\\", \\\"segment_2\\\"]) {edges {node {name state}}}}}\"}"; + ArgumentCaptor request = ArgumentCaptor.forClass(HttpPost.class); + verify(mockHttpClient).execute(request.capture()); + assertEquals(expectedResponse, EntityUtils.toString(request.getValue().getEntity())); + } + + @Test + public void returnResponseStringWhenStatusIs200() throws Exception { + ODPApiManager apiManager = new DefaultODPApiManager(mockHttpClient); + String responseString = apiManager.fetchQualifiedSegments("key", "endPoint", "fs_user_id", "test_user", Arrays.asList("segment_1", "segment_2")); + verify(mockHttpClient, times(1)).execute(any(HttpPost.class)); + assertEquals(validResponse, responseString); + } + + @Test + public void returnNullWhenStatusIsNot200AndLogError() throws Exception { + setupHttpClient(500); + ODPApiManager apiManager = new DefaultODPApiManager(mockHttpClient); + String responseString = apiManager.fetchQualifiedSegments("key", "endPoint", "fs_user_id", "test_user", Arrays.asList("segment_1", "segment_2")); + verify(mockHttpClient, times(1)).execute(any(HttpPost.class)); + logbackVerifier.expectMessage(Level.ERROR, "Unexpected response from ODP server, Response code: 500, null"); + assertEquals(null, responseString); + } +} From fb06ca737d63de0ca960252fe9ce9b43d754e5b5 Mon Sep 17 00:00:00 2001 From: Zeeshan Ashraf <35262377+zashraf1985@users.noreply.github.com> Date: Fri, 5 Aug 2022 12:03:23 -0700 Subject: [PATCH 17/80] feat: Added a generic LRUCache interface and a default implementation (#482) ## Summary Added an interface for a generic LRUCache and a default Implementation. ## Test plan - All existing tests pass. - Added unit tests for the default cache implementation. ## Issues [OASIS-8385](https://optimizely.atlassian.net/browse/OASIS-8385) --- .../com/optimizely/ab/internal/Cache.java | 25 +++ .../ab/internal/DefaultLRUCache.java | 96 ++++++++++ .../ab/internal/DefaultLRUCacheTest.java | 172 ++++++++++++++++++ 3 files changed, 293 insertions(+) create mode 100644 core-api/src/main/java/com/optimizely/ab/internal/Cache.java create mode 100644 core-api/src/main/java/com/optimizely/ab/internal/DefaultLRUCache.java create mode 100644 core-api/src/test/java/com/optimizely/ab/internal/DefaultLRUCacheTest.java diff --git a/core-api/src/main/java/com/optimizely/ab/internal/Cache.java b/core-api/src/main/java/com/optimizely/ab/internal/Cache.java new file mode 100644 index 000000000..ba667ebd2 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/internal/Cache.java @@ -0,0 +1,25 @@ +/** + * + * Copyright 2022, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.internal; + +public interface Cache { + int DEFAULT_MAX_SIZE = 10000; + int DEFAULT_TIMEOUT_SECONDS = 600; + void save(String key, T value); + T lookup(String key); + void reset(); +} diff --git a/core-api/src/main/java/com/optimizely/ab/internal/DefaultLRUCache.java b/core-api/src/main/java/com/optimizely/ab/internal/DefaultLRUCache.java new file mode 100644 index 000000000..a531c5c83 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/internal/DefaultLRUCache.java @@ -0,0 +1,96 @@ +/** + * + * Copyright 2022, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.internal; + +import com.optimizely.ab.annotations.VisibleForTesting; + +import java.util.*; + +public class DefaultLRUCache implements Cache { + + private final Object lock = new Object(); + + private final Integer maxSize; + + private final Long timeoutMillis; + + @VisibleForTesting + final LinkedHashMap linkedHashMap = new LinkedHashMap(16, 0.75f, true) { + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return this.size() > maxSize; + } + }; + + public DefaultLRUCache() { + this(DEFAULT_MAX_SIZE, DEFAULT_TIMEOUT_SECONDS); + } + + public DefaultLRUCache(Integer maxSize, Integer timeoutSeconds) { + this.maxSize = maxSize < 0 ? Integer.valueOf(0) : maxSize; + this.timeoutMillis = (timeoutSeconds < 0) ? 0 : (timeoutSeconds * 1000L); + } + + public void save(String key, T value) { + if (maxSize == 0) { + // Cache is disabled when maxSize = 0 + return; + } + + synchronized (lock) { + linkedHashMap.put(key, new CacheEntity(value)); + } + } + + public T lookup(String key) { + if (maxSize == 0) { + // Cache is disabled when maxSize = 0 + return null; + } + + synchronized (lock) { + if (linkedHashMap.containsKey(key)) { + CacheEntity entity = linkedHashMap.get(key); + Long nowMs = new Date().getTime(); + + // ttl = 0 means entities never expire. + if (timeoutMillis == 0 || (nowMs - entity.timestamp < timeoutMillis)) { + return entity.value; + } + + linkedHashMap.remove(key); + } + return null; + } + } + + public void reset() { + synchronized (lock) { + linkedHashMap.clear(); + } + } + + private class CacheEntity { + public T value; + public Long timestamp; + + public CacheEntity(T value) { + this.value = value; + this.timestamp = new Date().getTime(); + } + } +} diff --git a/core-api/src/test/java/com/optimizely/ab/internal/DefaultLRUCacheTest.java b/core-api/src/test/java/com/optimizely/ab/internal/DefaultLRUCacheTest.java new file mode 100644 index 000000000..79aa96ff3 --- /dev/null +++ b/core-api/src/test/java/com/optimizely/ab/internal/DefaultLRUCacheTest.java @@ -0,0 +1,172 @@ +/** + * + * Copyright 2022, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.internal; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; + +public class DefaultLRUCacheTest { + + @Test + public void createSaveAndLookupOneItem() { + Cache cache = new DefaultLRUCache<>(); + assertNull(cache.lookup("key1")); + cache.save("key1", "value1"); + assertEquals("value1", cache.lookup("key1")); + } + + @Test + public void saveAndLookupMultipleItems() { + DefaultLRUCache> cache = new DefaultLRUCache<>(); + + cache.save("user1", Arrays.asList("segment1", "segment2")); + cache.save("user2", Arrays.asList("segment3", "segment4")); + cache.save("user3", Arrays.asList("segment5", "segment6")); + + String[] itemKeys = cache.linkedHashMap.keySet().toArray(new String[0]); + assertEquals("user1", itemKeys[0]); + assertEquals("user2", itemKeys[1]); + assertEquals("user3", itemKeys[2]); + + assertEquals(Arrays.asList("segment1", "segment2"), cache.lookup("user1")); + + itemKeys = cache.linkedHashMap.keySet().toArray(new String[0]); + // Lookup should move user1 to bottom of the list and push up others. + assertEquals("user2", itemKeys[0]); + assertEquals("user3", itemKeys[1]); + assertEquals("user1", itemKeys[2]); + + assertEquals(Arrays.asList("segment3", "segment4"), cache.lookup("user2")); + + itemKeys = cache.linkedHashMap.keySet().toArray(new String[0]); + // Lookup should move user2 to bottom of the list and push up others. + assertEquals("user3", itemKeys[0]); + assertEquals("user1", itemKeys[1]); + assertEquals("user2", itemKeys[2]); + + assertEquals(Arrays.asList("segment5", "segment6"), cache.lookup("user3")); + + itemKeys = cache.linkedHashMap.keySet().toArray(new String[0]); + // Lookup should move user3 to bottom of the list and push up others. + assertEquals("user1", itemKeys[0]); + assertEquals("user2", itemKeys[1]); + assertEquals("user3", itemKeys[2]); + } + + @Test + public void saveShouldReorderList() { + DefaultLRUCache> cache = new DefaultLRUCache<>(); + + cache.save("user1", Arrays.asList("segment1", "segment2")); + cache.save("user2", Arrays.asList("segment3", "segment4")); + cache.save("user3", Arrays.asList("segment5", "segment6")); + + String[] itemKeys = cache.linkedHashMap.keySet().toArray(new String[0]); + assertEquals("user1", itemKeys[0]); + assertEquals("user2", itemKeys[1]); + assertEquals("user3", itemKeys[2]); + + cache.save("user1", Arrays.asList("segment1", "segment2")); + + itemKeys = cache.linkedHashMap.keySet().toArray(new String[0]); + // save should move user1 to bottom of the list and push up others. + assertEquals("user2", itemKeys[0]); + assertEquals("user3", itemKeys[1]); + assertEquals("user1", itemKeys[2]); + + cache.save("user2", Arrays.asList("segment3", "segment4")); + + itemKeys = cache.linkedHashMap.keySet().toArray(new String[0]); + // save should move user2 to bottom of the list and push up others. + assertEquals("user3", itemKeys[0]); + assertEquals("user1", itemKeys[1]); + assertEquals("user2", itemKeys[2]); + + cache.save("user3", Arrays.asList("segment5", "segment6")); + + itemKeys = cache.linkedHashMap.keySet().toArray(new String[0]); + // save should move user3 to bottom of the list and push up others. + assertEquals("user1", itemKeys[0]); + assertEquals("user2", itemKeys[1]); + assertEquals("user3", itemKeys[2]); + } + + @Test + public void whenCacheIsDisabled() { + DefaultLRUCache> cache = new DefaultLRUCache<>(0,Cache.DEFAULT_TIMEOUT_SECONDS); + + cache.save("user1", Arrays.asList("segment1", "segment2")); + cache.save("user2", Arrays.asList("segment3", "segment4")); + cache.save("user3", Arrays.asList("segment5", "segment6")); + + assertNull(cache.lookup("user1")); + assertNull(cache.lookup("user2")); + assertNull(cache.lookup("user3")); + } + + @Test + public void whenItemsExpire() throws InterruptedException { + DefaultLRUCache> cache = new DefaultLRUCache<>(Cache.DEFAULT_MAX_SIZE, 1); + cache.save("user1", Arrays.asList("segment1", "segment2")); + assertEquals(Arrays.asList("segment1", "segment2"), cache.lookup("user1")); + assertEquals(1, cache.linkedHashMap.size()); + Thread.sleep(1000); + assertNull(cache.lookup("user1")); + assertEquals(0, cache.linkedHashMap.size()); + } + + @Test + public void whenCacheReachesMaxSize() { + DefaultLRUCache> cache = new DefaultLRUCache<>(2, Cache.DEFAULT_TIMEOUT_SECONDS); + + cache.save("user1", Arrays.asList("segment1", "segment2")); + cache.save("user2", Arrays.asList("segment3", "segment4")); + cache.save("user3", Arrays.asList("segment5", "segment6")); + + assertEquals(2, cache.linkedHashMap.size()); + + assertEquals(Arrays.asList("segment5", "segment6"), cache.lookup("user3")); + assertEquals(Arrays.asList("segment3", "segment4"), cache.lookup("user2")); + assertNull(cache.lookup("user1")); + } + + @Test + public void whenCacheIsReset() { + DefaultLRUCache> cache = new DefaultLRUCache<>(); + cache.save("user1", Arrays.asList("segment1", "segment2")); + cache.save("user2", Arrays.asList("segment3", "segment4")); + cache.save("user3", Arrays.asList("segment5", "segment6")); + + assertEquals(Arrays.asList("segment1", "segment2"), cache.lookup("user1")); + assertEquals(Arrays.asList("segment3", "segment4"), cache.lookup("user2")); + assertEquals(Arrays.asList("segment5", "segment6"), cache.lookup("user3")); + + assertEquals(3, cache.linkedHashMap.size()); + + cache.reset(); + + assertNull(cache.lookup("user1")); + assertNull(cache.lookup("user2")); + assertNull(cache.lookup("user3")); + + assertEquals(0, cache.linkedHashMap.size()); + } +} From 5866f7b1622b6b90f31c5f0fe8cab481d3cd7374 Mon Sep 17 00:00:00 2001 From: Zeeshan Ashraf <35262377+zashraf1985@users.noreply.github.com> Date: Wed, 10 Aug 2022 11:00:28 -0700 Subject: [PATCH 18/80] feat: Added support to get All segments used in the project (#483) ## Summary ODP Server needs a subset of segments to look for in the API call. This PR adds functionality to get all segments used in the project inside `DatafileProjectConfig`. ## Test plan - Manually tested thoroughly - Added Unit tests ## Jira [OASIS-8383](https://optimizely.atlassian.net/browse/OASIS-8383) --- .../ab/config/DatafileProjectConfig.java | 14 ++++++++ .../ab/config/audience/AndCondition.java | 1 + .../ab/config/audience/Audience.java | 28 ++++++++++++++- .../config/audience/AudienceIdCondition.java | 6 ++++ .../ab/config/audience/Condition.java | 3 ++ .../ab/config/audience/EmptyCondition.java | 2 +- .../ab/config/audience/LeafCondition.java | 26 ++++++++++++++ .../ab/config/audience/NotCondition.java | 7 ++++ .../ab/config/audience/NullCondition.java | 2 +- .../ab/config/audience/OrCondition.java | 1 + .../ab/config/audience/UserAttribute.java | 2 +- .../AudienceConditionEvaluationTest.java | 36 +++++++++++++++++++ 12 files changed, 124 insertions(+), 4 deletions(-) create mode 100644 core-api/src/main/java/com/optimizely/ab/config/audience/LeafCondition.java diff --git a/core-api/src/main/java/com/optimizely/ab/config/DatafileProjectConfig.java b/core-api/src/main/java/com/optimizely/ab/config/DatafileProjectConfig.java index 65edf5768..94341c717 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/DatafileProjectConfig.java +++ b/core-api/src/main/java/com/optimizely/ab/config/DatafileProjectConfig.java @@ -74,6 +74,7 @@ public class DatafileProjectConfig implements ProjectConfig { private final List groups; private final List rollouts; private final List integrations; + private final Set allSegments; // key to entity mappings private final Map attributeKeyMapping; @@ -204,6 +205,15 @@ public DatafileProjectConfig(String accountId, this.publicKeyForODP = publicKeyForODP; this.hostForODP = hostForODP; + Set allSegments = new HashSet<>(); + if (typedAudiences != null) { + for(Audience audience: typedAudiences) { + allSegments.addAll(audience.getSegments()); + } + } + + this.allSegments = allSegments; + Map variationIdToExperimentMap = new HashMap(); for (Experiment experiment : this.experiments) { for (Variation variation : experiment.getVariations()) { @@ -424,6 +434,10 @@ public List getExperiments() { return experiments; } + public Set getAllSegments() { + return this.allSegments; + } + @Override public List getExperimentsForEventKey(String eventKey) { EventType event = eventNameMapping.get(eventKey); diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/AndCondition.java b/core-api/src/main/java/com/optimizely/ab/config/audience/AndCondition.java index 8d855e3e9..7865eb2d2 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/AndCondition.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/AndCondition.java @@ -38,6 +38,7 @@ public AndCondition(@Nonnull List conditions) { this.conditions = conditions; } + @Override public List getConditions() { return conditions; } diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/Audience.java b/core-api/src/main/java/com/optimizely/ab/config/audience/Audience.java index 8db26844a..bfc1be85d 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/Audience.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/Audience.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2017, 2019, Optimizely and contributors + * Copyright 2016-2017, 2019, 2022, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,9 @@ import com.optimizely.ab.config.IdKeyMapped; import javax.annotation.concurrent.Immutable; +import java.util.HashSet; +import java.util.List; +import java.util.Set; /** * Represents the Optimizely Audience configuration. @@ -69,4 +72,27 @@ public String toString() { ", conditions=" + conditions + '}'; } + + public Set getSegments() { + return getSegments(conditions); + } + + private static Set getSegments(Condition conditions) { + List nestedConditions = conditions.getConditions(); + Set segments = new HashSet<>(); + if (nestedConditions != null) { + for (Condition nestedCondition : nestedConditions) { + Set nestedSegments = getSegments(nestedCondition); + segments.addAll(nestedSegments); + } + } else { + if (conditions.getClass() == UserAttribute.class) { + UserAttribute userAttributeCondition = (UserAttribute) conditions; + if (UserAttribute.QUALIFIED.equals(userAttributeCondition.getMatch())) { + segments.add((String)userAttributeCondition.getValue()); + } + } + } + return segments; + } } diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/AudienceIdCondition.java b/core-api/src/main/java/com/optimizely/ab/config/audience/AudienceIdCondition.java index 4b3341d4c..9fc248522 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/AudienceIdCondition.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/AudienceIdCondition.java @@ -27,6 +27,7 @@ import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; +import java.util.List; import java.util.Map; import java.util.Objects; @@ -97,6 +98,11 @@ public boolean equals(Object o) { (audienceId.equals(condition.audienceId))); } + @Override + public List getConditions() { + return null; + } + @Override public int hashCode() { diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/Condition.java b/core-api/src/main/java/com/optimizely/ab/config/audience/Condition.java index 105c9b8e0..ab3fe99af 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/Condition.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/Condition.java @@ -20,6 +20,7 @@ import com.optimizely.ab.config.ProjectConfig; import javax.annotation.Nullable; +import java.util.List; import java.util.Map; /** @@ -33,4 +34,6 @@ public interface Condition { String toJson(); String getOperandOrId(); + + List getConditions(); } diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/EmptyCondition.java b/core-api/src/main/java/com/optimizely/ab/config/audience/EmptyCondition.java index 61e010317..1f7a87b12 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/EmptyCondition.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/EmptyCondition.java @@ -21,7 +21,7 @@ import javax.annotation.Nullable; import java.util.Map; -public class EmptyCondition implements Condition { +public class EmptyCondition extends LeafCondition { @Nullable @Override public Boolean evaluate(ProjectConfig config, OptimizelyUserContext user) { diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/LeafCondition.java b/core-api/src/main/java/com/optimizely/ab/config/audience/LeafCondition.java new file mode 100644 index 000000000..a61c1650e --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/LeafCondition.java @@ -0,0 +1,26 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.config.audience; + +import java.util.List; + +public abstract class LeafCondition implements Condition { + + @Override + public List getConditions() { + return null; + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/NotCondition.java b/core-api/src/main/java/com/optimizely/ab/config/audience/NotCondition.java index 9e4b2fb86..45dec6637 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/NotCondition.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/NotCondition.java @@ -22,6 +22,8 @@ import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import javax.annotation.Nonnull; +import java.util.Arrays; +import java.util.List; /** @@ -41,6 +43,11 @@ public Condition getCondition() { return condition; } + @Override + public List getConditions() { + return Arrays.asList(condition); + } + @Nullable public Boolean evaluate(ProjectConfig config, OptimizelyUserContext user) { Boolean conditionEval = condition == null ? null : condition.evaluate(config, user); diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/NullCondition.java b/core-api/src/main/java/com/optimizely/ab/config/audience/NullCondition.java index 44ddee7ca..1e12b836e 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/NullCondition.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/NullCondition.java @@ -21,7 +21,7 @@ import javax.annotation.Nullable; import java.util.Map; -public class NullCondition implements Condition { +public class NullCondition extends LeafCondition { @Nullable @Override public Boolean evaluate(ProjectConfig config, OptimizelyUserContext user) { diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/OrCondition.java b/core-api/src/main/java/com/optimizely/ab/config/audience/OrCondition.java index 12fbbb3b2..c0f3603eb 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/OrCondition.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/OrCondition.java @@ -38,6 +38,7 @@ public OrCondition(@Nonnull List conditions) { this.conditions = conditions; } + @Override public List getConditions() { return conditions; } diff --git a/core-api/src/main/java/com/optimizely/ab/config/audience/UserAttribute.java b/core-api/src/main/java/com/optimizely/ab/config/audience/UserAttribute.java index e7ff16f31..c38b6c2a4 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/audience/UserAttribute.java +++ b/core-api/src/main/java/com/optimizely/ab/config/audience/UserAttribute.java @@ -38,7 +38,7 @@ */ @Immutable @JsonIgnoreProperties(ignoreUnknown = true) -public class UserAttribute implements Condition { +public class UserAttribute extends LeafCondition { public static final String QUALIFIED = "qualified"; private static final Logger logger = LoggerFactory.getLogger(UserAttribute.class); diff --git a/core-api/src/test/java/com/optimizely/ab/config/audience/AudienceConditionEvaluationTest.java b/core-api/src/test/java/com/optimizely/ab/config/audience/AudienceConditionEvaluationTest.java index 5a69b35ee..5a88e8ad9 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/audience/AudienceConditionEvaluationTest.java +++ b/core-api/src/test/java/com/optimizely/ab/config/audience/AudienceConditionEvaluationTest.java @@ -1840,4 +1840,40 @@ public void nullValueEvaluate() { assertNull(nullValueAttribute.evaluate(null, OTUtils.user(Collections.singletonMap(attributeName, attributeValue)))); assertNull(nullValueAttribute.evaluate(null, OTUtils.user((Collections.singletonMap(attributeName, ""))))); } + + @Test + public void getAllSegmentsFromAudience() { + Condition condition = createMultipleConditionAudienceAndOrODP(); + Audience audience = new Audience("1", "testAudience", condition); + assertEquals(new HashSet<>(Arrays.asList("odp-segment-1", "odp-segment-2", "odp-segment-3", "odp-segment-4")), audience.getSegments()); + + // ["and", "1", "2"] + List audience1And2 = new ArrayList<>(); + audience1And2.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-1")); + audience1And2.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-2")); + AndCondition audienceCondition1 = new AndCondition(audience1And2); + + // ["and", "3", "4"] + List audience3And4 = new ArrayList<>(); + audience3And4.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-3")); + audience3And4.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-4")); + AndCondition audienceCondition2 = new AndCondition(audience3And4); + + // ["or", "5", "6"] + List audience5And6 = new ArrayList<>(); + audience5And6.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-5")); + audience5And6.add(new UserAttribute("odp.audiences", "third_party_dimension", "qualified", "odp-segment-6")); + OrCondition audienceCondition3 = new OrCondition(audience5And6); + + + //['or', '1', '2', '3'] + List conditions = new ArrayList<>(); + conditions.add(audienceCondition1); + conditions.add(audienceCondition2); + conditions.add(audienceCondition3); + + OrCondition implicitOr = new OrCondition(conditions); + audience = new Audience("1", "testAudience", implicitOr); + assertEquals(new HashSet<>(Arrays.asList("odp-segment-1", "odp-segment-2", "odp-segment-3", "odp-segment-4", "odp-segment-5", "odp-segment-6")), audience.getSegments()); + } } From 1cf2d7214e7b6b54c929ee8b946c32ae40dfb01a Mon Sep 17 00:00:00 2001 From: Zeeshan Ashraf <35262377+zashraf1985@users.noreply.github.com> Date: Wed, 17 Aug 2022 17:08:03 -0700 Subject: [PATCH 19/80] feat: Added ODPSegmentManager (#484) ## Summary Added an ODPSegmentManager which provides functionality to fetch segments from ODP server and cache and re-use them. ## Test plan - Manually tested thoroughly - Added new unit tests - Existing unit tests pass - All Full stack compatibility suite tests pass ## JIRA [OASIS-8383](https://optimizely.atlassian.net/browse/OASIS-8383) --- .../java/com/optimizely/ab/odp/ODPConfig.java | 74 +++++++ .../optimizely/ab/odp/ODPSegmentManager.java | 108 +++++++++ .../optimizely/ab/odp/ODPSegmentOption.java | 25 +++ .../com/optimizely/ab/odp/ODPUserKey.java | 34 +++ .../ab/odp/ODPSegmentManagerTest.java | 207 ++++++++++++++++++ 5 files changed, 448 insertions(+) create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentOption.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/ODPUserKey.java create mode 100644 core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java new file mode 100644 index 000000000..ad8667eb4 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java @@ -0,0 +1,74 @@ +/** + * + * Copyright 2022, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp; + +import java.util.Collections; +import java.util.List; + +public class ODPConfig { + + private String apiKey; + + private String apiHost; + + private List allSegments; + + public ODPConfig(String apiKey, String apiHost, List allSegments) { + this.apiKey = apiKey; + this.apiHost = apiHost; + this.allSegments = allSegments; + } + + public ODPConfig(String apiKey, String apiHost) { + this(apiKey, apiHost, Collections.emptyList()); + } + + public synchronized Boolean isReady() { + return !( + this.apiKey == null || this.apiKey.isEmpty() + || this.apiHost == null || this.apiHost.isEmpty() + ); + } + + public synchronized Boolean hasSegments() { + return allSegments != null && !allSegments.isEmpty(); + } + + public synchronized void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public synchronized void setApiHost(String apiHost) { + this.apiHost = apiHost; + } + + public synchronized String getApiKey() { + return apiKey; + } + + public synchronized String getApiHost() { + return apiHost; + } + + public synchronized List getAllSegments() { + return allSegments; + } + + public synchronized void setAllSegments(List allSegments) { + this.allSegments = allSegments; + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java new file mode 100644 index 000000000..ffda9c19c --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java @@ -0,0 +1,108 @@ +/** + * + * Copyright 2022, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp; + +import com.optimizely.ab.internal.Cache; +import com.optimizely.ab.internal.DefaultLRUCache; +import com.optimizely.ab.odp.parser.ResponseJsonParser; +import com.optimizely.ab.odp.parser.ResponseJsonParserFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Collections; +import java.util.List; + +public class ODPSegmentManager { + + private static final Logger logger = LoggerFactory.getLogger(ODPSegmentManager.class); + + private static final String SEGMENT_URL_PATH = "/v3/graphql"; + + private final ODPApiManager apiManager; + + private final ODPConfig odpConfig; + + private final Cache> segmentsCache; + + public ODPSegmentManager(ODPConfig odpConfig, ODPApiManager apiManager) { + this(odpConfig, apiManager, Cache.DEFAULT_MAX_SIZE, Cache.DEFAULT_TIMEOUT_SECONDS); + } + + public ODPSegmentManager(ODPConfig odpConfig, ODPApiManager apiManager, Cache> cache) { + this.apiManager = apiManager; + this.odpConfig = odpConfig; + this.segmentsCache = cache; + } + + public ODPSegmentManager(ODPConfig odpConfig, ODPApiManager apiManager, Integer cacheSize, Integer cacheTimeoutSeconds) { + this.apiManager = apiManager; + this.odpConfig = odpConfig; + this.segmentsCache = new DefaultLRUCache<>(cacheSize, cacheTimeoutSeconds); + } + + public List getQualifiedSegments(String fsUserId) { + return getQualifiedSegments(ODPUserKey.FS_USER_ID, fsUserId, Collections.emptyList()); + } + public List getQualifiedSegments(String fsUserId, List options) { + return getQualifiedSegments(ODPUserKey.FS_USER_ID, fsUserId, options); + } + + public List getQualifiedSegments(ODPUserKey userKey, String userValue) { + return getQualifiedSegments(userKey, userValue, Collections.emptyList()); + } + + public List getQualifiedSegments(ODPUserKey userKey, String userValue, List options) { + if (!odpConfig.isReady()) { + logger.error("Audience segments fetch failed (ODP is not enabled)"); + return Collections.emptyList(); + } + + if (!odpConfig.hasSegments()) { + logger.debug("No Segments are used in the project, Not Fetching segments. Returning empty list"); + return Collections.emptyList(); + } + + List qualifiedSegments; + String cacheKey = getCacheKey(userKey.getKeyString(), userValue); + + if (options.contains(ODPSegmentOption.RESET_CACHE)) { + segmentsCache.reset(); + } else if (!options.contains(ODPSegmentOption.IGNORE_CACHE)) { + qualifiedSegments = segmentsCache.lookup(cacheKey); + if (qualifiedSegments != null) { + logger.debug("ODP Cache Hit. Returning segments from Cache."); + return qualifiedSegments; + } + } + + logger.debug("ODP Cache Miss. Making a call to ODP Server."); + + ResponseJsonParser parser = ResponseJsonParserFactory.getParser(); + String qualifiedSegmentsResponse = apiManager.fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + SEGMENT_URL_PATH, userKey.getKeyString(), userValue, odpConfig.getAllSegments()); + qualifiedSegments = parser.parseQualifiedSegments(qualifiedSegmentsResponse); + + if (qualifiedSegments != null && !options.contains(ODPSegmentOption.IGNORE_CACHE)) { + segmentsCache.save(cacheKey, qualifiedSegments); + } + + return qualifiedSegments; + } + + private String getCacheKey(String userKey, String userValue) { + return userKey + "-$-" + userValue; + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentOption.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentOption.java new file mode 100644 index 000000000..8e2eb901b --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentOption.java @@ -0,0 +1,25 @@ +/** + * + * Copyright 2022, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp; + +public enum ODPSegmentOption { + + IGNORE_CACHE, + + RESET_CACHE; + +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPUserKey.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPUserKey.java new file mode 100644 index 000000000..d7cdbb641 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPUserKey.java @@ -0,0 +1,34 @@ +/** + * + * Copyright 2022, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp; + +public enum ODPUserKey { + + VUID("vuid"), + + FS_USER_ID("fs_user_id"); + + private final String keyString; + + ODPUserKey(String keyString) { + this.keyString = keyString; + } + + public String getKeyString() { + return keyString; + } +} diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java new file mode 100644 index 000000000..f784d53d0 --- /dev/null +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java @@ -0,0 +1,207 @@ +/** + * + * Copyright 2022, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp; + +import ch.qos.logback.classic.Level; +import com.optimizely.ab.internal.Cache; +import com.optimizely.ab.internal.LogbackVerifier; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; + +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; +import static org.junit.Assert.*; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class ODPSegmentManagerTest { + + @Rule + public LogbackVerifier logbackVerifier = new LogbackVerifier(); + + @Mock + Cache> mockCache; + + @Mock + ODPApiManager mockApiManager; + + private static final String API_RESPONSE = "{\"data\":{\"customer\":{\"audiences\":{\"edges\":[{\"node\":{\"name\":\"segment1\",\"state\":\"qualified\"}},{\"node\":{\"name\":\"segment2\",\"state\":\"qualified\"}}]}}}}"; + + @Before + public void setup() { + mockCache = mock(Cache.class); + mockApiManager = mock(ODPApiManager.class); + } + + @Test + public void cacheHit() { + Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); + + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", Arrays.asList("segment1", "segment2")); + ODPSegmentManager segmentManager = new ODPSegmentManager(odpConfig, mockApiManager, mockCache); + List segments = segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId"); + + // Cache lookup called with correct key + verify(mockCache, times(1)).lookup("fs_user_id-$-testId"); + + // Cache hit! No api call was made to the server. + verify(mockApiManager, times(0)).fetchQualifiedSegments(any(), any(), any(), any(), any()); + verify(mockCache, times(0)).save(any(), any()); + verify(mockCache, times(0)).reset(); + + logbackVerifier.expectMessage(Level.DEBUG, "ODP Cache Hit. Returning segments from Cache."); + + assertEquals(Arrays.asList("segment1-cached", "segment2-cached"), segments); + } + + @Test + public void cacheMiss() { + Mockito.when(mockCache.lookup(any())).thenReturn(null); + Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anyList())) + .thenReturn(API_RESPONSE); + + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", Arrays.asList("segment1", "segment2")); + ODPSegmentManager segmentManager = new ODPSegmentManager(odpConfig, mockApiManager, mockCache); + List segments = segmentManager.getQualifiedSegments(ODPUserKey.VUID, "testId"); + + // Cache lookup called with correct key + verify(mockCache, times(1)).lookup("vuid-$-testId"); + + // Cache miss! Make api call and save to cache + verify(mockApiManager, times(1)) + .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "vuid", "testId", Arrays.asList("segment1", "segment2")); + verify(mockCache, times(1)).save("vuid-$-testId", Arrays.asList("segment1", "segment2")); + verify(mockCache, times(0)).reset(); + + logbackVerifier.expectMessage(Level.DEBUG, "ODP Cache Miss. Making a call to ODP Server."); + + assertEquals(Arrays.asList("segment1", "segment2"), segments); + } + + @Test + public void ignoreCache() { + Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); + Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anyList())) + .thenReturn(API_RESPONSE); + + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", Arrays.asList("segment1", "segment2")); + ODPSegmentManager segmentManager = new ODPSegmentManager(odpConfig, mockApiManager, mockCache); + List segments = segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId", Collections.singletonList(ODPSegmentOption.IGNORE_CACHE)); + + // Cache Ignored! lookup should not be called + verify(mockCache, times(0)).lookup(any()); + + // Cache Ignored! Make API Call but do NOT save because of cacheIgnore + verify(mockApiManager, times(1)) + .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "fs_user_id", "testId", Arrays.asList("segment1", "segment2")); + verify(mockCache, times(0)).save(any(), any()); + verify(mockCache, times(0)).reset(); + + assertEquals(Arrays.asList("segment1", "segment2"), segments); + } + + @Test + public void resetCache() { + Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); + Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anyList())) + .thenReturn(API_RESPONSE); + + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", Arrays.asList("segment1", "segment2")); + ODPSegmentManager segmentManager = new ODPSegmentManager(odpConfig, mockApiManager, mockCache); + List segments = segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId", Collections.singletonList(ODPSegmentOption.RESET_CACHE)); + + // Call reset + verify(mockCache, times(1)).reset(); + + // Cache Reset! lookup should not be called becaues cache would be empty. + verify(mockCache, times(0)).lookup(any()); + + // Cache reset but not Ignored! Make API Call and save to cache + verify(mockApiManager, times(1)) + .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "fs_user_id", "testId", Arrays.asList("segment1", "segment2")); + verify(mockCache, times(1)).save("fs_user_id-$-testId", Arrays.asList("segment1", "segment2")); + + assertEquals(Arrays.asList("segment1", "segment2"), segments); + } + + @Test + public void resetAndIgnoreCache() { + Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); + Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anyList())) + .thenReturn(API_RESPONSE); + + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", Arrays.asList("segment1", "segment2")); + ODPSegmentManager segmentManager = new ODPSegmentManager(odpConfig, mockApiManager, mockCache); + List segments = segmentManager + .getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId", Arrays.asList(ODPSegmentOption.RESET_CACHE, ODPSegmentOption.IGNORE_CACHE)); + + // Call reset + verify(mockCache, times(1)).reset(); + + verify(mockCache, times(0)).lookup(any()); + + // Cache is also Ignored! Make API Call but do not save + verify(mockApiManager, times(1)) + .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "fs_user_id", "testId", Arrays.asList("segment1", "segment2")); + verify(mockCache, times(0)).save(any(), any()); + + assertEquals(Arrays.asList("segment1", "segment2"), segments); + } + + @Test + public void odpConfigNotReady() { + Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); + + ODPConfig odpConfig = new ODPConfig(null, null, Arrays.asList("segment1", "segment2")); + ODPSegmentManager segmentManager = new ODPSegmentManager(odpConfig, mockApiManager, mockCache); + List segments = segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId"); + + // No further methods should be called. + verify(mockCache, times(0)).lookup("fs_user_id-$-testId"); + verify(mockApiManager, times(0)).fetchQualifiedSegments(any(), any(), any(), any(), any()); + verify(mockCache, times(0)).save(any(), any()); + verify(mockCache, times(0)).reset(); + + logbackVerifier.expectMessage(Level.ERROR, "Audience segments fetch failed (ODP is not enabled)"); + + assertEquals(Collections.emptyList(), segments); + } + + @Test + public void noSegmentsInProject() { + Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); + + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", null); + ODPSegmentManager segmentManager = new ODPSegmentManager(odpConfig, mockApiManager, mockCache); + List segments = segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId"); + + // No further methods should be called. + verify(mockCache, times(0)).lookup("fs_user_id-$-testId"); + verify(mockApiManager, times(0)).fetchQualifiedSegments(any(), any(), any(), any(), any()); + verify(mockCache, times(0)).save(any(), any()); + verify(mockCache, times(0)).reset(); + + logbackVerifier.expectMessage(Level.DEBUG, "No Segments are used in the project, Not Fetching segments. Returning empty list"); + + assertEquals(Collections.emptyList(), segments); + } +} From 8b8a9838cfd3824d13e5c472a7d578a4f4d4ed97 Mon Sep 17 00:00:00 2001 From: Zeeshan Ashraf <35262377+zashraf1985@users.noreply.github.com> Date: Mon, 29 Aug 2022 11:27:37 -0700 Subject: [PATCH 20/80] feat: Added ODP RestApi interface for sending Events to ODP (#485) ## Summary This module provides an internal service for ODP event REST api access. ## Test plan - Manually tested thoroughly. - Added new unit tests. - All Existing Unit tests pass. - All existing Full stack compatibility tests pass. ## Jira [OASIS-8387](https://optimizely.atlassian.net/browse/OASIS-8387) --- .../com/optimizely/ab/odp/ODPApiManager.java | 2 + .../java/com/optimizely/ab/odp/ODPEvent.java | 64 ++++++++++++++ .../ab/odp/serializer/ODPJsonSerializer.java | 24 ++++++ .../serializer/ODPJsonSerializerFactory.java | 49 +++++++++++ .../odp/serializer/impl/GsonSerializer.java | 31 +++++++ .../serializer/impl/JacksonSerializer.java | 36 ++++++++ .../odp/serializer/impl/JsonSerializer.java | 59 +++++++++++++ .../serializer/impl/JsonSimpleSerializer.java | 55 ++++++++++++ .../parser/ResponseJsonParserFactoryTest.java | 1 - .../ODPJsonSerializerFactoryTest.java | 64 ++++++++++++++ .../odp/serializer/ODPJsonSerializerTest.java | 85 +++++++++++++++++++ .../ab/odp/DefaultODPApiManager.java | 57 ++++++++++++- .../ab/odp/DefaultODPApiManagerTest.java | 17 +++- 13 files changed, 541 insertions(+), 3 deletions(-) create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/serializer/ODPJsonSerializer.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/serializer/ODPJsonSerializerFactory.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/GsonSerializer.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/JacksonSerializer.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/JsonSerializer.java create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/JsonSimpleSerializer.java create mode 100644 core-api/src/test/java/com/optimizely/ab/odp/serializer/ODPJsonSerializerFactoryTest.java create mode 100644 core-api/src/test/java/com/optimizely/ab/odp/serializer/ODPJsonSerializerTest.java diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java index ed40e37fd..dee9413dd 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java @@ -19,4 +19,6 @@ public interface ODPApiManager { String fetchQualifiedSegments(String apiKey, String apiEndpoint, String userKey, String userValue, List segmentsToCheck); + + Integer sendEvents(String apiKey, String apiEndpoint, String eventPayload); } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java new file mode 100644 index 000000000..34bd340b6 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java @@ -0,0 +1,64 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp; + +import java.util.Map; + +public class ODPEvent { + private String type; + private String action; + private Map identifiers; + private Map data; + + public ODPEvent(String type, String action, Map identifiers, Map data) { + this.type = type; + this.action = action; + this.identifiers = identifiers; + this.data = data; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public Map getIdentifiers() { + return identifiers; + } + + public void setIdentifiers(Map identifiers) { + this.identifiers = identifiers; + } + + public Map getData() { + return data; + } + + public void setData(Map data) { + this.data = data; + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/serializer/ODPJsonSerializer.java b/core-api/src/main/java/com/optimizely/ab/odp/serializer/ODPJsonSerializer.java new file mode 100644 index 000000000..4f3922340 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/serializer/ODPJsonSerializer.java @@ -0,0 +1,24 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.serializer; + +import com.optimizely.ab.odp.ODPEvent; + +import java.util.List; + +public interface ODPJsonSerializer { + public String serializeEvents(List events); +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/serializer/ODPJsonSerializerFactory.java b/core-api/src/main/java/com/optimizely/ab/odp/serializer/ODPJsonSerializerFactory.java new file mode 100644 index 000000000..ca47e3bf4 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/serializer/ODPJsonSerializerFactory.java @@ -0,0 +1,49 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.serializer; + +import com.optimizely.ab.internal.JsonParserProvider; +import com.optimizely.ab.odp.serializer.impl.GsonSerializer; +import com.optimizely.ab.odp.serializer.impl.JacksonSerializer; +import com.optimizely.ab.odp.serializer.impl.JsonSerializer; +import com.optimizely.ab.odp.serializer.impl.JsonSimpleSerializer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ODPJsonSerializerFactory { + private static final Logger logger = LoggerFactory.getLogger(ODPJsonSerializerFactory.class); + + public static ODPJsonSerializer getSerializer() { + JsonParserProvider parserProvider = JsonParserProvider.getDefaultParser(); + ODPJsonSerializer jsonSerializer = null; + switch (parserProvider) { + case GSON_CONFIG_PARSER: + jsonSerializer = new GsonSerializer(); + break; + case JACKSON_CONFIG_PARSER: + jsonSerializer = new JacksonSerializer(); + break; + case JSON_CONFIG_PARSER: + jsonSerializer = new JsonSerializer(); + break; + case JSON_SIMPLE_CONFIG_PARSER: + jsonSerializer = new JsonSimpleSerializer(); + break; + } + logger.info("Using " + parserProvider.toString() + " serializer"); + return jsonSerializer; + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/GsonSerializer.java b/core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/GsonSerializer.java new file mode 100644 index 000000000..d72963260 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/GsonSerializer.java @@ -0,0 +1,31 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.serializer.impl; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.optimizely.ab.odp.ODPEvent; +import com.optimizely.ab.odp.serializer.ODPJsonSerializer; + +import java.util.List; + +public class GsonSerializer implements ODPJsonSerializer { + @Override + public String serializeEvents(List events) { + Gson gson = new GsonBuilder().serializeNulls().create(); + return gson.toJson(events); + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/JacksonSerializer.java b/core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/JacksonSerializer.java new file mode 100644 index 000000000..80cffa7d0 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/JacksonSerializer.java @@ -0,0 +1,36 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.serializer.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.optimizely.ab.odp.ODPEvent; +import com.optimizely.ab.odp.serializer.ODPJsonSerializer; + +import java.util.List; + +public class JacksonSerializer implements ODPJsonSerializer { + @Override + public String serializeEvents(List events) { + ObjectMapper objectMapper = new ObjectMapper(); + try { + return objectMapper.writeValueAsString(events); + } catch (JsonProcessingException e) { + // log error here + } + return null; + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/JsonSerializer.java b/core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/JsonSerializer.java new file mode 100644 index 000000000..c65c1fda3 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/JsonSerializer.java @@ -0,0 +1,59 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.serializer.impl; + +import com.optimizely.ab.odp.ODPEvent; +import com.optimizely.ab.odp.serializer.ODPJsonSerializer; +import org.json.JSONArray; +import org.json.JSONObject; + +import java.util.List; +import java.util.Map; + +public class JsonSerializer implements ODPJsonSerializer { + @Override + public String serializeEvents(List events) { + JSONArray jsonArray = new JSONArray(); + for (ODPEvent event: events) { + JSONObject eventObject = new JSONObject(); + eventObject.put("type", event.getType()); + eventObject.put("action", event.getAction()); + + if (event.getIdentifiers() != null) { + JSONObject identifiers = new JSONObject(); + for (Map.Entry identifier : event.getIdentifiers().entrySet()) { + identifiers.put(identifier.getKey(), identifier.getValue()); + } + eventObject.put("identifiers", identifiers); + } + + if (event.getData() != null) { + JSONObject data = new JSONObject(); + for (Map.Entry dataEntry : event.getData().entrySet()) { + data.put(dataEntry.getKey(), getJSONObjectValue(dataEntry.getValue())); + } + eventObject.put("data", data); + } + + jsonArray.put(eventObject); + } + return jsonArray.toString(); + } + + private static Object getJSONObjectValue(Object value) { + return value == null ? JSONObject.NULL : value; + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/JsonSimpleSerializer.java b/core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/JsonSimpleSerializer.java new file mode 100644 index 000000000..96e5a7357 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/serializer/impl/JsonSimpleSerializer.java @@ -0,0 +1,55 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.serializer.impl; + +import com.optimizely.ab.odp.ODPEvent; +import com.optimizely.ab.odp.serializer.ODPJsonSerializer; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +import java.util.List; +import java.util.Map; + +public class JsonSimpleSerializer implements ODPJsonSerializer { + @Override + public String serializeEvents(List events) { + JSONArray jsonArray = new JSONArray(); + for (ODPEvent event: events) { + JSONObject eventObject = new JSONObject(); + eventObject.put("type", event.getType()); + eventObject.put("action", event.getAction()); + + if (event.getIdentifiers() != null) { + JSONObject identifiers = new JSONObject(); + for (Map.Entry identifier : event.getIdentifiers().entrySet()) { + identifiers.put(identifier.getKey(), identifier.getValue()); + } + eventObject.put("identifiers", identifiers); + } + + if (event.getData() != null) { + JSONObject data = new JSONObject(); + for (Map.Entry dataEntry : event.getData().entrySet()) { + data.put(dataEntry.getKey(), dataEntry.getValue()); + } + eventObject.put("data", data); + } + + jsonArray.add(eventObject); + } + return jsonArray.toJSONString(); + } +} diff --git a/core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactoryTest.java b/core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactoryTest.java index f5d8e8c89..a4f51a3a7 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactoryTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactoryTest.java @@ -15,7 +15,6 @@ */ package com.optimizely.ab.odp.parser; -import com.optimizely.ab.internal.JsonParserProvider; import com.optimizely.ab.internal.PropertyUtils; import com.optimizely.ab.odp.parser.impl.GsonParser; import com.optimizely.ab.odp.parser.impl.JsonParser; diff --git a/core-api/src/test/java/com/optimizely/ab/odp/serializer/ODPJsonSerializerFactoryTest.java b/core-api/src/test/java/com/optimizely/ab/odp/serializer/ODPJsonSerializerFactoryTest.java new file mode 100644 index 000000000..5c47a1f4f --- /dev/null +++ b/core-api/src/test/java/com/optimizely/ab/odp/serializer/ODPJsonSerializerFactoryTest.java @@ -0,0 +1,64 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.serializer; + +import com.optimizely.ab.internal.PropertyUtils; +import com.optimizely.ab.odp.serializer.impl.GsonSerializer; +import com.optimizely.ab.odp.serializer.impl.JacksonSerializer; +import com.optimizely.ab.odp.serializer.impl.JsonSerializer; +import com.optimizely.ab.odp.serializer.impl.JsonSimpleSerializer; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class ODPJsonSerializerFactoryTest { + @Before + @After + public void clearParserSystemProperty() { + PropertyUtils.clear("default_parser"); + } + + @Test + public void getGsonSerializerWhenNoDefaultIsSet() { + assertEquals(GsonSerializer.class, ODPJsonSerializerFactory.getSerializer().getClass()); + } + + @Test + public void getCorrectSerializerWhenValidDefaultIsProvidedIsJson() { + PropertyUtils.set("default_parser", "JSON_CONFIG_PARSER"); + assertEquals(JsonSerializer.class, ODPJsonSerializerFactory.getSerializer().getClass()); + } + + @Test + public void getCorrectSerializerWhenValidDefaultIsProvidedIsJsonSimple() { + PropertyUtils.set("default_parser", "JSON_SIMPLE_CONFIG_PARSER"); + assertEquals(JsonSimpleSerializer.class, ODPJsonSerializerFactory.getSerializer().getClass()); + } + + @Test + public void getCorrectSerializerWhenValidDefaultIsProvidedIsJackson() { + PropertyUtils.set("default_parser", "JACKSON_CONFIG_PARSER"); + assertEquals(JacksonSerializer.class, ODPJsonSerializerFactory.getSerializer().getClass()); + } + + @Test + public void getGsonSerializerWhenGivenDefaultSerializerDoesNotExist() { + PropertyUtils.set("default_parser", "GARBAGE_VALUE"); + assertEquals(GsonSerializer.class, ODPJsonSerializerFactory.getSerializer().getClass()); + } +} diff --git a/core-api/src/test/java/com/optimizely/ab/odp/serializer/ODPJsonSerializerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/serializer/ODPJsonSerializerTest.java new file mode 100644 index 000000000..7a9538a8f --- /dev/null +++ b/core-api/src/test/java/com/optimizely/ab/odp/serializer/ODPJsonSerializerTest.java @@ -0,0 +1,85 @@ +/** + * Copyright 2022, Optimizely Inc. and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp.serializer; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.optimizely.ab.odp.ODPEvent; +import com.optimizely.ab.odp.serializer.impl.*; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.util.*; + +import static junit.framework.TestCase.assertEquals; + +@RunWith(Parameterized.class) +public class ODPJsonSerializerTest { + private final ODPJsonSerializer jsonSerializer; + + public ODPJsonSerializerTest(ODPJsonSerializer jsonSerializer) { + super(); + this.jsonSerializer = jsonSerializer; + } + + @Parameterized.Parameters + public static List input() { + return Arrays.asList(new GsonSerializer(), new JsonSerializer(), new JsonSimpleSerializer(), new JacksonSerializer()); + } + + @Test + public void serializeMultipleEvents() throws JsonProcessingException { + List events = Arrays.asList( + createTestEvent("1"), + createTestEvent("2"), + createTestEvent("3") + ); + + ObjectMapper mapper = new ObjectMapper(); + + String expectedResult = "[{\"type\":\"type-1\",\"action\":\"action-1\",\"identifiers\":{\"vuid-1-3\":\"fs-1-3\",\"vuid-1-1\":\"fs-1-1\",\"vuid-1-2\":\"fs-1-2\"},\"data\":{\"source\":\"java-sdk\",\"data-1\":\"data-value-1\",\"data-num\":1,\"data-bool-true\":true,\"data-bool-false\":false,\"data-float\":2.33,\"data-null\":null}},{\"type\":\"type-2\",\"action\":\"action-2\",\"identifiers\":{\"vuid-2-3\":\"fs-2-3\",\"vuid-2-2\":\"fs-2-2\",\"vuid-2-1\":\"fs-2-1\"},\"data\":{\"source\":\"java-sdk\",\"data-1\":\"data-value-2\",\"data-num\":2,\"data-bool-true\":true,\"data-bool-false\":false,\"data-float\":2.33,\"data-null\":null}},{\"type\":\"type-3\",\"action\":\"action-3\",\"identifiers\":{\"vuid-3-3\":\"fs-3-3\",\"vuid-3-2\":\"fs-3-2\",\"vuid-3-1\":\"fs-3-1\"},\"data\":{\"source\":\"java-sdk\",\"data-1\":\"data-value-3\",\"data-num\":3,\"data-bool-true\":true,\"data-bool-false\":false,\"data-float\":2.33,\"data-null\":null}}]"; + String serializedString = jsonSerializer.serializeEvents(events); + assertEquals(mapper.readTree(expectedResult), mapper.readTree(serializedString)); + } + + @Test + public void serializeEmptyList() throws JsonProcessingException { + List events = Collections.emptyList(); + String expectedResult = "[]"; + String serializedString = jsonSerializer.serializeEvents(events); + assertEquals(expectedResult, serializedString); + } + + private static ODPEvent createTestEvent(String index) { + Map identifiers = new HashMap<>(); + identifiers.put("vuid-" + index + "-1", "fs-" + index + "-1"); + identifiers.put("vuid-" + index + "-2", "fs-" + index + "-2"); + identifiers.put("vuid-" + index + "-3", "fs-" + index + "-3"); + + Map data = new HashMap<>(); + data.put("source", "java-sdk"); + data.put("data-1", "data-value-" + index); + data.put("data-num", Integer.parseInt(index)); + data.put("data-float", 2.33); + data.put("data-bool-true", true); + data.put("data-bool-false", false); + data.put("data-null", null); + + + return new ODPEvent("type-" + index, "action-" + index, identifiers, data); + } +} diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java index f0703dcb0..07ee1b3eb 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java @@ -17,7 +17,6 @@ import com.optimizely.ab.OptimizelyHttpClient; import com.optimizely.ab.annotations.VisibleForTesting; -import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; @@ -167,6 +166,62 @@ public String fetchQualifiedSegments(String apiKey, String apiEndpoint, String u return null; } + /* + eventPayload Format + [ + { + "action": "identified", + "identifiers": {"vuid": , "fs_user_id": , ....}, + "data": {“source”: , ....}, + "type": " fullstack " + }, + { + "action": "client_initialized", + "identifiers": {"vuid": , ....}, + "data": {“source”: , ....}, + "type": "fullstack" + } + ] + + Returns: + 1. null, When there was a non-recoverable error and no retry is needed. + 2. 0 If an unexpected error occurred and retrying can be useful. + 3. HTTPStatus code if httpclient was able to make the request and was able to receive response. + It is recommended to retry if status code was 5xx. + */ + @Override + public Integer sendEvents(String apiKey, String apiEndpoint, String eventPayload) { + HttpPost request = new HttpPost(apiEndpoint); + + try { + request.setEntity(new StringEntity(eventPayload)); + } catch (UnsupportedEncodingException e) { + logger.error("ODP event send failed (Error encoding request payload)", e); + return null; + } + request.setHeader("x-api-key", apiKey); + request.setHeader("content-type", "application/json"); + + CloseableHttpResponse response = null; + try { + response = httpClient.execute(request); + } catch (IOException e) { + logger.error("Error retrieving response from event request", e); + return 0; + } + + int statusCode = response.getStatusLine().getStatusCode(); + if ( statusCode >= 400) { + StatusLine statusLine = response.getStatusLine(); + logger.error(String.format("ODP event send failed (Response code: %d, %s)", statusLine.getStatusCode(), statusLine.getReasonPhrase())); + } else { + logger.debug("ODP Event Dispatched successfully"); + } + + closeHttpResponse(response); + return statusCode; + } + private static void closeHttpResponse(CloseableHttpResponse response) { if (response != null) { try { diff --git a/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java b/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java index c81af2dce..77440f804 100644 --- a/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java +++ b/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java @@ -111,6 +111,21 @@ public void returnNullWhenStatusIsNot200AndLogError() throws Exception { String responseString = apiManager.fetchQualifiedSegments("key", "endPoint", "fs_user_id", "test_user", Arrays.asList("segment_1", "segment_2")); verify(mockHttpClient, times(1)).execute(any(HttpPost.class)); logbackVerifier.expectMessage(Level.ERROR, "Unexpected response from ODP server, Response code: 500, null"); - assertEquals(null, responseString); + assertNull(responseString); + } + + @Test + public void eventDispatchSuccess() { + ODPApiManager apiManager = new DefaultODPApiManager(mockHttpClient); + apiManager.sendEvents("testKey", "testEndpoint", "[]"); + logbackVerifier.expectMessage(Level.DEBUG, "ODP Event Dispatched successfully"); + } + + @Test + public void eventDispatchFailStatus() throws Exception { + setupHttpClient(400); + ODPApiManager apiManager = new DefaultODPApiManager(mockHttpClient); + apiManager.sendEvents("testKey", "testEndpoint", "[]]"); + logbackVerifier.expectMessage(Level.ERROR, "ODP event send failed (Response code: 400, null)"); } } From 2a38338dbe39283f86b8a5144ca519aab4dfceb9 Mon Sep 17 00:00:00 2001 From: Zeeshan Ashraf <35262377+zashraf1985@users.noreply.github.com> Date: Fri, 16 Sep 2022 10:24:47 -0700 Subject: [PATCH 21/80] feat: Added ODPEventManager implementation (#487) ## Summary Added `ODPEventManager` implementation. ## Test plan - Unit tests pending. ## Jira [OASIS-8386](https://optimizely.atlassian.net/browse/OASIS-8386) --- .../java/com/optimizely/ab/odp/ODPEvent.java | 9 +- .../optimizely/ab/odp/ODPEventManager.java | 199 +++++++++++++++ .../ab/odp/ODPEventManagerTest.java | 234 ++++++++++++++++++ 3 files changed, 439 insertions(+), 3 deletions(-) create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java create mode 100644 core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java index 34bd340b6..903bcf663 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java @@ -15,6 +15,9 @@ */ package com.optimizely.ab.odp; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Collections; import java.util.Map; public class ODPEvent { @@ -23,11 +26,11 @@ public class ODPEvent { private Map identifiers; private Map data; - public ODPEvent(String type, String action, Map identifiers, Map data) { + public ODPEvent(@Nonnull String type, @Nonnull String action, @Nullable Map identifiers, @Nullable Map data) { this.type = type; this.action = action; - this.identifiers = identifiers; - this.data = data; + this.identifiers = identifiers != null ? identifiers : Collections.emptyMap(); + this.data = data != null ? data : Collections.emptyMap(); } public String getType() { diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java new file mode 100644 index 000000000..7cc601f29 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java @@ -0,0 +1,199 @@ +/** + * + * Copyright 2022, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp; + +import com.optimizely.ab.event.internal.BuildVersionInfo; +import com.optimizely.ab.event.internal.ClientEngineInfo; +import com.optimizely.ab.odp.serializer.ODPJsonSerializerFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.*; +import java.util.concurrent.*; + +public class ODPEventManager { + private static final Logger logger = LoggerFactory.getLogger(ODPEventManager.class); + private static final int DEFAULT_BATCH_SIZE = 10; + private static final int DEFAULT_QUEUE_SIZE = 10000; + private static final int DEFAULT_FLUSH_INTERVAL = 1000; + private static final int MAX_RETRIES = 3; + private static final String EVENT_URL_PATH = "/v3/events"; + + private final int queueSize; + private final int batchSize; + private final int flushInterval; + + private Boolean isRunning = false; + + // This needs to be volatile because it will be updated in the main thread and the event dispatcher thread + // needs to see the change immediately. + private volatile ODPConfig odpConfig; + private EventDispatcherThread eventDispatcherThread; + + private final ODPApiManager apiManager; + + // The eventQueue needs to be thread safe. We are not doing anything extra for thread safety here + // because `LinkedBlockingQueue` itself is thread safe. + private final BlockingQueue eventQueue = new LinkedBlockingQueue<>(); + + public ODPEventManager(@Nonnull ODPConfig odpConfig, @Nonnull ODPApiManager apiManager) { + this(odpConfig, apiManager, null, null, null); + } + + public ODPEventManager(@Nonnull ODPConfig odpConfig, @Nonnull ODPApiManager apiManager, @Nullable Integer batchSize, @Nullable Integer queueSize, @Nullable Integer flushInterval) { + this.odpConfig = odpConfig; + this.apiManager = apiManager; + this.batchSize = (batchSize != null && batchSize > 1) ? batchSize : DEFAULT_BATCH_SIZE; + this.queueSize = queueSize != null ? queueSize : DEFAULT_QUEUE_SIZE; + this.flushInterval = (flushInterval != null && flushInterval > 0) ? flushInterval : DEFAULT_FLUSH_INTERVAL; + } + + public void start() { + isRunning = true; + eventDispatcherThread = new EventDispatcherThread(); + eventDispatcherThread.start(); + } + + public void updateSettings(ODPConfig odpConfig) { + this.odpConfig = odpConfig; + } + + public void identifyUser(@Nullable String vuid, String userId) { + Map identifiers = new HashMap<>(); + if (vuid != null) { + identifiers.put(ODPUserKey.VUID.getKeyString(), vuid); + } + identifiers.put(ODPUserKey.FS_USER_ID.getKeyString(), userId); + ODPEvent event = new ODPEvent("fullstack", "client_initialized", identifiers, null); + sendEvent(event); + } + + public void sendEvent(ODPEvent event) { + event.setData(augmentCommonData(event.getData())); + processEvent(event); + } + + private Map augmentCommonData(Map sourceData) { + Map data = new HashMap<>(); + data.put("idempotence_id", UUID.randomUUID().toString()); + data.put("data_source_type", "sdk"); + data.put("data_source", ClientEngineInfo.getClientEngine().getClientEngineValue()); + data.put("data_source_version", BuildVersionInfo.getClientVersion()); + data.putAll(sourceData); + return data; + } + + private void processEvent(ODPEvent event) { + if (!isRunning) { + logger.warn("Failed to Process ODP Event. ODPEventManager is not running"); + return; + } + + if (!odpConfig.isReady()) { + logger.debug("Unable to Process ODP Event. ODPConfig is not ready."); + return; + } + + if (eventQueue.size() >= queueSize) { + logger.warn("Failed to Process ODP Event. Event Queue full. queueSize = " + queueSize); + return; + } + + if (!eventQueue.offer(event)) { + logger.error("Failed to Process ODP Event. Event Queue is not accepting any more events"); + } + } + + public void stop() { + logger.debug("Sending stop signal to ODP Event Dispatcher Thread"); + eventDispatcherThread.signalStop(); + } + + private class EventDispatcherThread extends Thread { + + private volatile boolean shouldStop = false; + + private final List currentBatch = new ArrayList<>(); + + private long nextFlushTime = new Date().getTime(); + + @Override + public void run() { + while (true) { + try { + ODPEvent nextEvent; + + // If batch has events, set the timeout to remaining time for flush interval, + // otherwise wait for the new event indefinitely + if (currentBatch.size() > 0) { + nextEvent = eventQueue.poll(nextFlushTime - new Date().getTime(), TimeUnit.MILLISECONDS); + } else { + nextEvent = eventQueue.poll(); + } + + if (nextEvent == null) { + // null means no new events received and flush interval is over, dispatch whatever is in the batch. + if (!currentBatch.isEmpty()) { + flush(); + } + if (shouldStop) { + break; + } + continue; + } + + if (currentBatch.size() == 0) { + // Batch starting, create a new flush time + nextFlushTime = new Date().getTime() + flushInterval; + } + + currentBatch.add(nextEvent); + + if (currentBatch.size() >= batchSize) { + flush(); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + logger.debug("Exiting ODP Event Dispatcher Thread."); + } + + private void flush() { + if (odpConfig.isReady()) { + String payload = ODPJsonSerializerFactory.getSerializer().serializeEvents(currentBatch); + String endpoint = odpConfig.getApiHost() + EVENT_URL_PATH; + Integer statusCode; + int numAttempts = 0; + do { + statusCode = apiManager.sendEvents(odpConfig.getApiKey(), endpoint, payload); + numAttempts ++; + } while (numAttempts < MAX_RETRIES && statusCode != null && (statusCode == 0 || statusCode >= 500)); + } else { + logger.debug("ODPConfig not ready, discarding event batch"); + } + currentBatch.clear(); + } + + public void signalStop() { + shouldStop = true; + } + } +} diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java new file mode 100644 index 000000000..7be51e415 --- /dev/null +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java @@ -0,0 +1,234 @@ +/** + * + * Copyright 2022, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp; + +import ch.qos.logback.classic.Level; +import com.optimizely.ab.internal.LogbackVerifier; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; +import static org.junit.Assert.*; + +@RunWith(MockitoJUnitRunner.class) +public class ODPEventManagerTest { + + @Rule + public LogbackVerifier logbackVerifier = new LogbackVerifier(); + + @Mock + ODPApiManager mockApiManager; + + @Captor + ArgumentCaptor payloadCaptor; + + @Before + public void setup() { + mockApiManager = mock(ODPApiManager.class); + } + + @Test + public void logAndDiscardEventWhenEventManagerIsNotRunning() { + ODPConfig odpConfig = new ODPConfig("key", "host", null); + ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager); + ODPEvent event = new ODPEvent("test-type", "test-action", Collections.emptyMap(), Collections.emptyMap()); + eventManager.sendEvent(event); + logbackVerifier.expectMessage(Level.WARN, "Failed to Process ODP Event. ODPEventManager is not running"); + } + + @Test + public void logAndDiscardEventWhenODPConfigNotReady() { + ODPConfig odpConfig = new ODPConfig(null, null, null); + ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager); + eventManager.start(); + ODPEvent event = new ODPEvent("test-type", "test-action", Collections.emptyMap(), Collections.emptyMap()); + eventManager.sendEvent(event); + logbackVerifier.expectMessage(Level.DEBUG, "Unable to Process ODP Event. ODPConfig is not ready."); + } + + @Test + public void dispatchEventsInCorrectNumberOfBatches() throws InterruptedException { + Mockito.reset(mockApiManager); + Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); + ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); + ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager); + eventManager.start(); + for (int i = 0; i < 25; i++) { + eventManager.sendEvent(getEvent(i)); + } + Thread.sleep(1500); + Mockito.verify(mockApiManager, times(3)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), any()); + } + + @Test + public void dispatchEventsWithCorrectPayload() throws InterruptedException { + Mockito.reset(mockApiManager); + Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); + int batchSize = 2; + ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); + ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager, batchSize, null, null); + eventManager.start(); + for (int i = 0; i < 6; i++) { + eventManager.sendEvent(getEvent(i)); + } + Thread.sleep(500); + Mockito.verify(mockApiManager, times(3)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), payloadCaptor.capture()); + List payloads = payloadCaptor.getAllValues(); + + for (int i = 0; i < payloads.size(); i++) { + JSONArray events = new JSONArray(payloads.get(i)); + assertEquals(batchSize, events.length()); + for (int j = 0; j < events.length(); j++) { + int id = (batchSize * i) + j; + JSONObject event = events.getJSONObject(j); + assertEquals("test-type-" + id , event.getString("type")); + assertEquals("test-action-" + id , event.getString("action")); + assertEquals("value1-" + id, event.getJSONObject("identifiers").getString("identifier1")); + assertEquals("value2-" + id, event.getJSONObject("identifiers").getString("identifier2")); + assertEquals("data-value1-" + id, event.getJSONObject("data").getString("data1")); + assertEquals(id, event.getJSONObject("data").getInt("data2")); + assertEquals("sdk", event.getJSONObject("data").getString("data_source_type")); + } + } + } + + @Test + public void dispatchEventsWithCorrectFlushInterval() throws InterruptedException { + Mockito.reset(mockApiManager); + Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); + ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); + ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager); + eventManager.start(); + for (int i = 0; i < 25; i++) { + eventManager.sendEvent(getEvent(i)); + } + Thread.sleep(500); + Mockito.verify(mockApiManager, times(2)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), any()); + + // Last batch is incomplete so it needs almost a second to flush. + Thread.sleep(1500); + Mockito.verify(mockApiManager, times(3)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), any()); + } + + @Test + public void retryFailedEvents() throws InterruptedException { + Mockito.reset(mockApiManager); + Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(500); + ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); + ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager); + eventManager.start(); + for (int i = 0; i < 25; i++) { + eventManager.sendEvent(getEvent(i)); + } + Thread.sleep(500); + + // Should be called thrice for each batch + Mockito.verify(mockApiManager, times(6)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), any()); + + // Last batch is incomplete so it needs almost a second to flush. + Thread.sleep(1500); + Mockito.verify(mockApiManager, times(9)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), any()); + } + + @Test + public void shouldFlushAllScheduledEventsBeforeStopping() throws InterruptedException { + Mockito.reset(mockApiManager); + Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); + ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); + ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager); + eventManager.start(); + for (int i = 0; i < 25; i++) { + eventManager.sendEvent(getEvent(i)); + } + eventManager.stop(); + Thread.sleep(1500); + Mockito.verify(mockApiManager, times(3)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), any()); + logbackVerifier.expectMessage(Level.DEBUG, "Exiting ODP Event Dispatcher Thread."); + } + + @Test + public void prepareCorrectPayloadForIdentifyUser() throws InterruptedException { + Mockito.reset(mockApiManager); + Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); + int batchSize = 2; + ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); + ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager, batchSize, null, null); + eventManager.start(); + for (int i = 0; i < 2; i++) { + eventManager.identifyUser("the-vuid-" + i, "the-fs-user-id-" + i); + } + + Thread.sleep(1500); + Mockito.verify(mockApiManager, times(1)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), payloadCaptor.capture()); + + String payload = payloadCaptor.getValue(); + JSONArray events = new JSONArray(payload); + assertEquals(batchSize, events.length()); + for (int i = 0; i < events.length(); i++) { + JSONObject event = events.getJSONObject(i); + assertEquals("fullstack", event.getString("type")); + assertEquals("client_initialized", event.getString("action")); + assertEquals("the-vuid-" + i, event.getJSONObject("identifiers").getString("vuid")); + assertEquals("the-fs-user-id-" + i, event.getJSONObject("identifiers").getString("fs_user_id")); + assertEquals("sdk", event.getJSONObject("data").getString("data_source_type")); + } + } + + @Test + public void applyUpdatedODPConfigWhenAvailable() throws InterruptedException { + Mockito.reset(mockApiManager); + Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); + ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); + ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager); + eventManager.start(); + for (int i = 0; i < 25; i++) { + eventManager.sendEvent(getEvent(i)); + } + Thread.sleep(500); + Mockito.verify(mockApiManager, times(2)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), any()); + eventManager.updateSettings(new ODPConfig("new-key", "http://www.new-odp-host.com")); + Thread.sleep(1500); + Mockito.verify(mockApiManager, times(1)).sendEvents(eq("new-key"), eq("http://www.new-odp-host.com/v3/events"), any()); + } + + private ODPEvent getEvent(int id) { + Map identifiers = new HashMap<>(); + identifiers.put("identifier1", "value1-" + id); + identifiers.put("identifier2", "value2-" + id); + + Map data = new HashMap<>(); + data.put("data1", "data-value1-" + id); + data.put("data2", id); + + return new ODPEvent("test-type-" + id , "test-action-" + id, identifiers, data); + } +} From 913b8e428e01d6a58a4f09dac9d6092861bcbcbc Mon Sep 17 00:00:00 2001 From: Muhammad Shaharyar Date: Wed, 28 Sep 2022 22:18:37 +0500 Subject: [PATCH 22/80] chore : updated prefix of ticket-check action (#488) --- .github/workflows/ticket_reference_check.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ticket_reference_check.yml b/.github/workflows/ticket_reference_check.yml index d2829e0c4..b7d52780f 100644 --- a/.github/workflows/ticket_reference_check.yml +++ b/.github/workflows/ticket_reference_check.yml @@ -13,4 +13,4 @@ jobs: - name: Check for Jira ticket reference uses: optimizely/github-action-ticket-reference-checker-public@master with: - bodyRegex: 'OASIS-(?\d+)' + bodyRegex: 'FSSDK-(?\d+)' From 7428c4c91d25a415c4aa3637040d35a6e520e079 Mon Sep 17 00:00:00 2001 From: Zeeshan Ashraf <35262377+zashraf1985@users.noreply.github.com> Date: Thu, 20 Oct 2022 11:31:21 -0700 Subject: [PATCH 23/80] feat: Added ODPManager implementation (#489) ## Summary Added ODPManager Implementation which does the following. 1. Initializes and provides access to ODPEventManager and ODPSegmentManager 2. Provides updated ODPConfig settings to event manager and segment manager. 3. Stops Event Manager thread when closed. ## Test plan 1. Manually tested thoroughly 2. Added unit tests. ## Issues [FSSDK-8388](https://jira.sso.episerver.net/browse/FSSDK-8388) --- .../java/com/optimizely/ab/odp/ODPConfig.java | 8 ++ .../java/com/optimizely/ab/odp/ODPEvent.java | 18 +++ .../optimizely/ab/odp/ODPEventManager.java | 36 ++++- .../com/optimizely/ab/odp/ODPManager.java | 61 +++++++++ .../optimizely/ab/odp/ODPSegmentManager.java | 10 +- .../ab/odp/ODPEventManagerTest.java | 28 +++- .../com/optimizely/ab/odp/ODPManagerTest.java | 123 ++++++++++++++++++ 7 files changed, 277 insertions(+), 7 deletions(-) create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java create mode 100644 core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java index ad8667eb4..25402b172 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java @@ -71,4 +71,12 @@ public synchronized List getAllSegments() { public synchronized void setAllSegments(List allSegments) { this.allSegments = allSegments; } + + public Boolean equals(ODPConfig toCompare) { + return getApiHost().equals(toCompare.getApiHost()) && getApiKey().equals(toCompare.getApiKey()) && getAllSegments().equals(toCompare.allSegments); + } + + public synchronized ODPConfig getClone() { + return new ODPConfig(apiKey, apiHost, allSegments); + } } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java index 903bcf663..de7001ca8 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java @@ -17,6 +17,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; +import java.beans.Transient; import java.util.Collections; import java.util.Map; @@ -64,4 +65,21 @@ public Map getData() { public void setData(Map data) { this.data = data; } + + @Transient + public Boolean isDataValid() { + for (Object entry: this.data.values()) { + if ( + !( entry instanceof String + || entry instanceof Integer + || entry instanceof Long + || entry instanceof Boolean + || entry instanceof Float + || entry instanceof Double + || entry == null)) { + return false; + } + } + return true; + } } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java index 7cc601f29..ab4ce301e 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java @@ -50,7 +50,7 @@ public class ODPEventManager { // The eventQueue needs to be thread safe. We are not doing anything extra for thread safety here // because `LinkedBlockingQueue` itself is thread safe. - private final BlockingQueue eventQueue = new LinkedBlockingQueue<>(); + private final BlockingQueue eventQueue = new LinkedBlockingQueue<>(); public ODPEventManager(@Nonnull ODPConfig odpConfig, @Nonnull ODPApiManager apiManager) { this(odpConfig, apiManager, null, null, null); @@ -71,7 +71,9 @@ public void start() { } public void updateSettings(ODPConfig odpConfig) { - this.odpConfig = odpConfig; + if (!this.odpConfig.equals(odpConfig) && eventQueue.offer(new FlushEvent(this.odpConfig))) { + this.odpConfig = odpConfig; + } } public void identifyUser(@Nullable String vuid, String userId) { @@ -85,6 +87,10 @@ public void identifyUser(@Nullable String vuid, String userId) { } public void sendEvent(ODPEvent event) { + if (!event.isDataValid()) { + logger.error("ODP event send failed (ODP data is not valid)"); + return; + } event.setData(augmentCommonData(event.getData())); processEvent(event); } @@ -137,7 +143,7 @@ private class EventDispatcherThread extends Thread { public void run() { while (true) { try { - ODPEvent nextEvent; + Object nextEvent; // If batch has events, set the timeout to remaining time for flush interval, // otherwise wait for the new event indefinitely @@ -158,12 +164,17 @@ public void run() { continue; } + if (nextEvent instanceof FlushEvent) { + flush(((FlushEvent) nextEvent).getOdpConfig()); + continue; + } + if (currentBatch.size() == 0) { // Batch starting, create a new flush time nextFlushTime = new Date().getTime() + flushInterval; } - currentBatch.add(nextEvent); + currentBatch.add((ODPEvent) nextEvent); if (currentBatch.size() >= batchSize) { flush(); @@ -176,7 +187,7 @@ public void run() { logger.debug("Exiting ODP Event Dispatcher Thread."); } - private void flush() { + private void flush(ODPConfig odpConfig) { if (odpConfig.isReady()) { String payload = ODPJsonSerializerFactory.getSerializer().serializeEvents(currentBatch); String endpoint = odpConfig.getApiHost() + EVENT_URL_PATH; @@ -192,8 +203,23 @@ private void flush() { currentBatch.clear(); } + private void flush() { + flush(odpConfig); + } + public void signalStop() { shouldStop = true; } } + + private static class FlushEvent { + private final ODPConfig odpConfig; + public FlushEvent(ODPConfig odpConfig) { + this.odpConfig = odpConfig.getClone(); + } + + public ODPConfig getOdpConfig() { + return odpConfig; + } + } } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java new file mode 100644 index 000000000..cb7e04f99 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java @@ -0,0 +1,61 @@ +/** + * + * Copyright 2022, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp; + +import javax.annotation.Nonnull; +import java.util.List; + +public class ODPManager { + private volatile ODPConfig odpConfig; + private final ODPSegmentManager segmentManager; + private final ODPEventManager eventManager; + + public ODPManager(@Nonnull ODPConfig odpConfig, @Nonnull ODPApiManager apiManager) { + this(odpConfig, new ODPSegmentManager(odpConfig, apiManager), new ODPEventManager(odpConfig, apiManager)); + } + + public ODPManager(@Nonnull ODPConfig odpConfig, @Nonnull ODPSegmentManager segmentManager, @Nonnull ODPEventManager eventManager) { + this.odpConfig = odpConfig; + this.segmentManager = segmentManager; + this.eventManager = eventManager; + this.eventManager.start(); + } + + public ODPSegmentManager getSegmentManager() { + return segmentManager; + } + + public ODPEventManager getEventManager() { + return eventManager; + } + + public Boolean updateSettings(String apiHost, String apiKey, List allSegments) { + ODPConfig newConfig = new ODPConfig(apiKey, apiHost, allSegments); + if (!odpConfig.equals(newConfig)) { + odpConfig = newConfig; + eventManager.updateSettings(odpConfig); + segmentManager.resetCache(); + segmentManager.updateSettings(odpConfig); + return true; + } + return false; + } + + public void close() { + eventManager.stop(); + } +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java index ffda9c19c..352c4ec8f 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java @@ -34,7 +34,7 @@ public class ODPSegmentManager { private final ODPApiManager apiManager; - private final ODPConfig odpConfig; + private volatile ODPConfig odpConfig; private final Cache> segmentsCache; @@ -105,4 +105,12 @@ public List getQualifiedSegments(ODPUserKey userKey, String userValue, L private String getCacheKey(String userKey, String userValue) { return userKey + "-$-" + userValue; } + + public void updateSettings(ODPConfig odpConfig) { + this.odpConfig = odpConfig; + } + + public void resetCache() { + segmentsCache.reset(); + } } diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java index 7be51e415..fd4287e0f 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java @@ -216,10 +216,36 @@ public void applyUpdatedODPConfigWhenAvailable() throws InterruptedException { Thread.sleep(500); Mockito.verify(mockApiManager, times(2)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), any()); eventManager.updateSettings(new ODPConfig("new-key", "http://www.new-odp-host.com")); - Thread.sleep(1500); + + // Should immediately Flush current batch with old ODP config when settings are changed + Thread.sleep(100); + Mockito.verify(mockApiManager, times(3)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), any()); + + // New events should use new config + for (int i = 0; i < 10; i++) { + eventManager.sendEvent(getEvent(i)); + } + Thread.sleep(100); Mockito.verify(mockApiManager, times(1)).sendEvents(eq("new-key"), eq("http://www.new-odp-host.com/v3/events"), any()); } + @Test + public void validateEventData() { + ODPEvent event = new ODPEvent("type", "action", null, null); + Map data = new HashMap<>(); + + data.put("String", "string Value"); + data.put("Integer", 100); + data.put("Float", 33.89); + data.put("Boolean", true); + data.put("null", null); + event.setData(data); + assertTrue(event.isDataValid()); + + data.put("RandomObject", new Object()); + assertFalse(event.isDataValid()); + } + private ODPEvent getEvent(int id) { Map identifiers = new HashMap<>(); identifiers.put("identifier1", "value1-" + id); diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java new file mode 100644 index 000000000..924c88836 --- /dev/null +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java @@ -0,0 +1,123 @@ +/** + * + * Copyright 2022, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; + +import java.util.Arrays; + +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; +import static org.junit.Assert.*; + +public class ODPManagerTest { + private static final String API_RESPONSE = "{\"data\":{\"customer\":{\"audiences\":{\"edges\":[{\"node\":{\"name\":\"segment1\",\"state\":\"qualified\"}},{\"node\":{\"name\":\"segment2\",\"state\":\"qualified\"}}]}}}}"; + + @Mock + ODPApiManager mockApiManager; + + @Mock + ODPEventManager mockEventManager; + + @Mock + ODPSegmentManager mockSegmentManager; + + @Before + public void setup() { + mockApiManager = mock(ODPApiManager.class); + mockEventManager = mock(ODPEventManager.class); + mockSegmentManager = mock(ODPSegmentManager.class); + } + + @Test + public void shouldStartEventManagerWhenODPManagerIsInitialized() { + ODPConfig config = new ODPConfig("test-key", "test-host"); + new ODPManager(config, mockSegmentManager, mockEventManager); + verify(mockEventManager, times(1)).start(); + } + + @Test + public void shouldStopEventManagerWhenCloseIsCalled() { + ODPConfig config = new ODPConfig("test-key", "test-host"); + ODPManager odpManager = new ODPManager(config, mockSegmentManager, mockEventManager); + + // Stop is not called in the default flow. + verify(mockEventManager, times(0)).stop(); + + odpManager.close(); + // stop should be called when odpManager is closed. + verify(mockEventManager, times(1)).stop(); + } + + @Test + public void shouldUseNewSettingsInEventManagerWhenODPConfigIsUpdated() throws InterruptedException { + Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(200); + ODPConfig config = new ODPConfig("test-key", "test-host", Arrays.asList("segment1", "segment2")); + ODPManager odpManager = new ODPManager(config, mockApiManager); + + odpManager.getEventManager().identifyUser("vuid", "fsuid"); + Thread.sleep(2000); + verify(mockApiManager, times(1)) + .sendEvents(eq("test-key"), eq("test-host/v3/events"), any()); + + odpManager.updateSettings("test-host-updated", "test-key-updated", Arrays.asList("segment1")); + odpManager.getEventManager().identifyUser("vuid", "fsuid"); + Thread.sleep(1200); + verify(mockApiManager, times(1)) + .sendEvents(eq("test-key-updated"), eq("test-host-updated/v3/events"), any()); + } + + @Test + public void shouldUseNewSettingsInSegmentManagerWhenODPConfigIsUpdated() { + Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anyList())) + .thenReturn(API_RESPONSE); + ODPConfig config = new ODPConfig("test-key", "test-host", Arrays.asList("segment1", "segment2")); + ODPManager odpManager = new ODPManager(config, mockApiManager); + + odpManager.getSegmentManager().getQualifiedSegments("test-id"); + verify(mockApiManager, times(1)) + .fetchQualifiedSegments(eq("test-key"), eq("test-host/v3/graphql"), any(), any(), any()); + + odpManager.updateSettings("test-host-updated", "test-key-updated", Arrays.asList("segment1")); + odpManager.getSegmentManager().getQualifiedSegments("test-id"); + verify(mockApiManager, times(1)) + .fetchQualifiedSegments(eq("test-key-updated"), eq("test-host-updated/v3/graphql"), any(), any(), any()); + } + + @Test + public void shouldGetEventManager() { + ODPConfig config = new ODPConfig("test-key", "test-host"); + ODPManager odpManager = new ODPManager(config, mockSegmentManager, mockEventManager); + assertNotNull(odpManager.getEventManager()); + + odpManager = new ODPManager(config, mockApiManager); + assertNotNull(odpManager.getEventManager()); + } + + @Test + public void shouldGetSegmentManager() { + ODPConfig config = new ODPConfig("test-key", "test-host"); + ODPManager odpManager = new ODPManager(config, mockSegmentManager, mockEventManager); + assertNotNull(odpManager.getSegmentManager()); + + odpManager = new ODPManager(config, mockApiManager); + assertNotNull(odpManager.getSegmentManager()); + } +} From b16dff5f7d958ea36b94e1cfd8d0bdd0b2aae7f8 Mon Sep 17 00:00:00 2001 From: Zeeshan Ashraf <35262377+zashraf1985@users.noreply.github.com> Date: Mon, 21 Nov 2022 11:11:34 -0800 Subject: [PATCH 24/80] feat: Integrated ODPManager with UserContext and Optimizely client (#490) ## Summary This PR integrates ODP functionality with UserContext and Optimizely client to make it available for users. There are two ways to integrate ODPManager. 1. ODPManager.Builder. 2. Use default instance from OptimizelyFactory. ## Test plan 1. Manually tested thoroughly 2. Will add unit tests after the first review passes. ## Issues FSSDK-8389, FS-8683 --- .../java/com/optimizely/ab/Optimizely.java | 94 ++++++- .../optimizely/ab/OptimizelyUserContext.java | 74 +++++- .../ab/config/DatafileProjectConfig.java | 1 + .../optimizely/ab/config/ProjectConfig.java | 3 + .../com/optimizely/ab/odp/ODPApiManager.java | 4 +- .../java/com/optimizely/ab/odp/ODPConfig.java | 12 +- .../java/com/optimizely/ab/odp/ODPEvent.java | 6 +- .../optimizely/ab/odp/ODPEventManager.java | 38 ++- .../com/optimizely/ab/odp/ODPManager.java | 142 +++++++++- .../optimizely/ab/odp/ODPSegmentCallback.java | 22 ++ .../optimizely/ab/odp/ODPSegmentManager.java | 65 ++++- .../optimizely/ab/OptimizelyBuilderTest.java | 18 +- .../com/optimizely/ab/OptimizelyTest.java | 134 +++++++++- .../ab/OptimizelyUserContextTest.java | 130 ++++++++- .../ab/odp/ODPEventManagerTest.java | 27 +- .../ab/odp/ODPManagerBuilderTest.java | 76 ++++++ .../com/optimizely/ab/odp/ODPManagerTest.java | 34 +-- .../ab/odp/ODPSegmentManagerTest.java | 246 ++++++++++++++++-- .../com/optimizely/ab/OptimizelyFactory.java | 9 + .../ab/odp/DefaultODPApiManager.java | 17 +- .../ab/odp/DefaultODPApiManagerTest.java | 19 +- 21 files changed, 1045 insertions(+), 126 deletions(-) create mode 100644 core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentCallback.java create mode 100644 core-api/src/test/java/com/optimizely/ab/odp/ODPManagerBuilderTest.java diff --git a/core-api/src/main/java/com/optimizely/ab/Optimizely.java b/core-api/src/main/java/com/optimizely/ab/Optimizely.java index 51335ec4f..0fbacaa3b 100644 --- a/core-api/src/main/java/com/optimizely/ab/Optimizely.java +++ b/core-api/src/main/java/com/optimizely/ab/Optimizely.java @@ -28,6 +28,7 @@ import com.optimizely.ab.event.internal.*; import com.optimizely.ab.event.internal.payload.EventBatch; import com.optimizely.ab.notification.*; +import com.optimizely.ab.odp.*; import com.optimizely.ab.optimizelyconfig.OptimizelyConfig; import com.optimizely.ab.optimizelyconfig.OptimizelyConfigManager; import com.optimizely.ab.optimizelyconfig.OptimizelyConfigService; @@ -96,6 +97,9 @@ public class Optimizely implements AutoCloseable { @Nullable private final UserProfileService userProfileService; + @Nullable + private final ODPManager odpManager; + private Optimizely(@Nonnull EventHandler eventHandler, @Nonnull EventProcessor eventProcessor, @Nonnull ErrorHandler errorHandler, @@ -104,7 +108,8 @@ private Optimizely(@Nonnull EventHandler eventHandler, @Nonnull ProjectConfigManager projectConfigManager, @Nullable OptimizelyConfigManager optimizelyConfigManager, @Nonnull NotificationCenter notificationCenter, - @Nonnull List defaultDecideOptions + @Nonnull List defaultDecideOptions, + @Nullable ODPManager odpManager ) { this.eventHandler = eventHandler; this.eventProcessor = eventProcessor; @@ -115,6 +120,15 @@ private Optimizely(@Nonnull EventHandler eventHandler, this.optimizelyConfigManager = optimizelyConfigManager; this.notificationCenter = notificationCenter; this.defaultDecideOptions = defaultDecideOptions; + this.odpManager = odpManager; + + if (odpManager != null) { + odpManager.getEventManager().start(); + if (getProjectConfig() != null) { + updateODPSettings(); + } + addUpdateConfigNotificationHandler(configNotification -> { updateODPSettings(); }); + } } /** @@ -128,8 +142,6 @@ public boolean isValid() { return getProjectConfig() != null; } - - /** * Checks if eventHandler {@link EventHandler} and projectConfigManager {@link ProjectConfigManager} * are Closeable {@link Closeable} and calls close on them. @@ -141,6 +153,9 @@ public void close() { tryClose(eventProcessor); tryClose(eventHandler); tryClose(projectConfigManager); + if (odpManager != null) { + tryClose(odpManager); + } } //======== activate calls ========// @@ -674,9 +689,9 @@ public OptimizelyJSON getFeatureVariableJSON(@Nonnull String featureKey, */ @Nullable public OptimizelyJSON getFeatureVariableJSON(@Nonnull String featureKey, - @Nonnull String variableKey, - @Nonnull String userId, - @Nonnull Map attributes) { + @Nonnull String variableKey, + @Nonnull String userId, + @Nonnull Map attributes) { return getFeatureVariableValueForType( featureKey, @@ -688,10 +703,10 @@ public OptimizelyJSON getFeatureVariableJSON(@Nonnull String featureKey, @VisibleForTesting T getFeatureVariableValueForType(@Nonnull String featureKey, - @Nonnull String variableKey, - @Nonnull String userId, - @Nonnull Map attributes, - @Nonnull String variableType) { + @Nonnull String variableKey, + @Nonnull String userId, + @Nonnull Map attributes, + @Nonnull String variableType) { if (featureKey == null) { logger.warn("The featureKey parameter must be nonnull."); return null; @@ -878,7 +893,7 @@ public OptimizelyJSON getAllFeatureVariables(@Nonnull String featureKey, } } else { logger.info("User \"{}\" was not bucketed into any variation for feature flag \"{}\". " + - "The default values are being returned.", userId, featureKey); + "The default values are being returned.", userId, featureKey); } Map valuesMap = new HashMap(); @@ -1142,7 +1157,7 @@ public OptimizelyConfig getOptimizelyConfig() { * @param userId The user ID to be used for bucketing. * @param attributes: A map of attribute names to current user attribute values. * @return An OptimizelyUserContext associated with this OptimizelyClient. - */ + */ public OptimizelyUserContext createUserContext(@Nonnull String userId, @Nonnull Map attributes) { if (userId == null) { @@ -1413,6 +1428,53 @@ public int addNotificationHandler(Class clazz, NotificationHandler han return notificationCenter.addNotificationHandler(clazz, handler); } + public List fetchQualifiedSegments(String userId, @Nonnull List segmentOptions) { + if (odpManager != null) { + synchronized (odpManager) { + return odpManager.getSegmentManager().getQualifiedSegments(userId, segmentOptions); + } + } + logger.error("Audience segments fetch failed (ODP is not enabled)."); + return null; + } + + public void fetchQualifiedSegments(String userId, ODPSegmentManager.ODPSegmentFetchCallback callback, List segmentOptions) { + if (odpManager == null) { + logger.error("Audience segments fetch failed (ODP is not enabled)."); + callback.onCompleted(null); + } else { + odpManager.getSegmentManager().getQualifiedSegments(userId, callback, segmentOptions); + } + } + + @Nullable + public ODPManager getODPManager() { + return odpManager; + } + + public void sendODPEvent(@Nullable String type, @Nonnull String action, @Nullable Map identifiers, @Nullable Map data) { + if (odpManager != null) { + ODPEvent event = new ODPEvent(type, action, identifiers, data); + odpManager.getEventManager().sendEvent(event); + } else { + logger.error("ODP event send failed (ODP is not enabled)"); + } + } + + public void identifyUser(@Nonnull String userId) { + ODPManager odpManager = getODPManager(); + if (odpManager != null) { + odpManager.getEventManager().identifyUser(userId); + } + } + + private void updateODPSettings() { + if (odpManager != null && getProjectConfig() != null) { + ProjectConfig projectConfig = getProjectConfig(); + odpManager.updateSettings(projectConfig.getHostForODP(), projectConfig.getPublicKeyForODP(), projectConfig.getAllSegments()); + } + } + //======== Builder ========// /** @@ -1467,6 +1529,7 @@ public static class Builder { private UserProfileService userProfileService; private NotificationCenter notificationCenter; private List defaultDecideOptions; + private ODPManager odpManager; // For backwards compatibility private AtomicProjectConfigManager fallbackConfigManager = new AtomicProjectConfigManager(); @@ -1562,6 +1625,11 @@ public Builder withDefaultDecideOptions(List defaultDeci return this; } + public Builder withODPManager(ODPManager odpManager) { + this.odpManager = odpManager; + return this; + } + // Helper functions for making testing easier protected Builder withBucketing(Bucketer bucketer) { this.bucketer = bucketer; @@ -1636,7 +1704,7 @@ public Optimizely build() { defaultDecideOptions = Collections.emptyList(); } - return new Optimizely(eventHandler, eventProcessor, errorHandler, decisionService, userProfileService, projectConfigManager, optimizelyConfigManager, notificationCenter, defaultDecideOptions); + return new Optimizely(eventHandler, eventProcessor, errorHandler, decisionService, userProfileService, projectConfigManager, optimizelyConfigManager, notificationCenter, defaultDecideOptions, odpManager); } } } diff --git a/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java b/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java index e59c4f3aa..5ba15b5b4 100644 --- a/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java +++ b/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java @@ -16,7 +16,9 @@ */ package com.optimizely.ab; -import com.optimizely.ab.config.Variation; +import com.optimizely.ab.odp.ODPManager; +import com.optimizely.ab.odp.ODPSegmentCallback; +import com.optimizely.ab.odp.ODPSegmentOption; import com.optimizely.ab.optimizelydecision.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -54,6 +56,15 @@ public OptimizelyUserContext(@Nonnull Optimizely optimizely, @Nonnull Map attributes, @Nullable Map forcedDecisionsMap, @Nullable List qualifiedSegments) { + this(optimizely, userId, attributes, forcedDecisionsMap, qualifiedSegments, true); + } + + public OptimizelyUserContext(@Nonnull Optimizely optimizely, + @Nonnull String userId, + @Nonnull Map attributes, + @Nullable Map forcedDecisionsMap, + @Nullable List qualifiedSegments, + @Nullable Boolean shouldIdentifyUser) { this.optimizely = optimizely; this.userId = userId; if (attributes != null) { @@ -66,6 +77,10 @@ public OptimizelyUserContext(@Nonnull Optimizely optimizely, } this.qualifiedSegments = Collections.synchronizedList( qualifiedSegments == null ? new LinkedList<>(): qualifiedSegments); + + if (shouldIdentifyUser == null || shouldIdentifyUser) { + optimizely.identifyUser(userId); + } } public OptimizelyUserContext(@Nonnull Optimizely optimizely, @Nonnull String userId) { @@ -85,7 +100,7 @@ public Optimizely getOptimizely() { } public OptimizelyUserContext copy() { - return new OptimizelyUserContext(optimizely, userId, attributes, forcedDecisionsMap, qualifiedSegments); + return new OptimizelyUserContext(optimizely, userId, attributes, forcedDecisionsMap, qualifiedSegments, false); } /** @@ -282,6 +297,60 @@ public void setQualifiedSegments(List qualifiedSegments) { this.qualifiedSegments.addAll(qualifiedSegments); } + /** + * Fetch all qualified segments for the user context. + *

+ * The segments fetched will be saved and can be accessed at any time by calling {@link #getQualifiedSegments()}. + */ + public Boolean fetchQualifiedSegments() { + return fetchQualifiedSegments(Collections.emptyList()); + } + + /** + * Fetch all qualified segments for the user context. + *

+ * The segments fetched will be saved and can be accessed at any time by calling {@link #getQualifiedSegments()}. + * + * @param segmentOptions A set of options for fetching qualified segments. + */ + public Boolean fetchQualifiedSegments(@Nonnull List segmentOptions) { + List segments = optimizely.fetchQualifiedSegments(userId, segmentOptions); + if (segments != null) { + setQualifiedSegments(segments); + } + return segments != null; + } + + /** + * Fetch all qualified segments for the user context in a non-blocking manner. This method will fetch segments + * in a separate thread and invoke the provided callback when results are available. + *

+ * The segments fetched will be saved and can be accessed at any time by calling {@link #getQualifiedSegments()}. + * + * @param callback A callback to invoke when results are available. + * @param segmentOptions A set of options for fetching qualified segments. + */ + public void fetchQualifiedSegments(ODPSegmentCallback callback, List segmentOptions) { + optimizely.fetchQualifiedSegments(userId, segments -> { + if (segments != null) { + setQualifiedSegments(segments); + } + callback.onCompleted(segments != null); + }, segmentOptions); + } + + /** + * Fetch all qualified segments for the user context in a non-blocking manner. This method will fetch segments + * in a separate thread and invoke the provided callback when results are available. + *

+ * The segments fetched will be saved and can be accessed at any time by calling {@link #getQualifiedSegments()}. + * + * @param callback A callback to invoke when results are available. + */ + public void fetchQualifiedSegments(ODPSegmentCallback callback) { + fetchQualifiedSegments(callback, Collections.emptyList()); + } + // Utils @Override @@ -309,5 +378,4 @@ public String toString() { ", attributes='" + attributes + '\'' + '}'; } - } diff --git a/core-api/src/main/java/com/optimizely/ab/config/DatafileProjectConfig.java b/core-api/src/main/java/com/optimizely/ab/config/DatafileProjectConfig.java index 94341c717..28ad519a5 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/DatafileProjectConfig.java +++ b/core-api/src/main/java/com/optimizely/ab/config/DatafileProjectConfig.java @@ -434,6 +434,7 @@ public List getExperiments() { return experiments; } + @Override public Set getAllSegments() { return this.allSegments; } diff --git a/core-api/src/main/java/com/optimizely/ab/config/ProjectConfig.java b/core-api/src/main/java/com/optimizely/ab/config/ProjectConfig.java index be512bd04..2073be9ef 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/ProjectConfig.java +++ b/core-api/src/main/java/com/optimizely/ab/config/ProjectConfig.java @@ -24,6 +24,7 @@ import javax.annotation.Nullable; import java.util.List; import java.util.Map; +import java.util.Set; /** * ProjectConfig is an interface capturing the experiment, variation and feature definitions. @@ -69,6 +70,8 @@ Experiment getExperimentForKey(@Nonnull String experimentKey, List getExperiments(); + Set getAllSegments(); + List getExperimentsForEventKey(String eventKey); List getFeatureFlags(); diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java index dee9413dd..6385d2b7b 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java @@ -15,10 +15,10 @@ */ package com.optimizely.ab.odp; -import java.util.List; +import java.util.Set; public interface ODPApiManager { - String fetchQualifiedSegments(String apiKey, String apiEndpoint, String userKey, String userValue, List segmentsToCheck); + String fetchQualifiedSegments(String apiKey, String apiEndpoint, String userKey, String userValue, Set segmentsToCheck); Integer sendEvents(String apiKey, String apiEndpoint, String eventPayload); } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java index 25402b172..eb055e63f 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java @@ -17,7 +17,7 @@ package com.optimizely.ab.odp; import java.util.Collections; -import java.util.List; +import java.util.Set; public class ODPConfig { @@ -25,16 +25,16 @@ public class ODPConfig { private String apiHost; - private List allSegments; + private Set allSegments; - public ODPConfig(String apiKey, String apiHost, List allSegments) { + public ODPConfig(String apiKey, String apiHost, Set allSegments) { this.apiKey = apiKey; this.apiHost = apiHost; this.allSegments = allSegments; } public ODPConfig(String apiKey, String apiHost) { - this(apiKey, apiHost, Collections.emptyList()); + this(apiKey, apiHost, Collections.emptySet()); } public synchronized Boolean isReady() { @@ -64,11 +64,11 @@ public synchronized String getApiHost() { return apiHost; } - public synchronized List getAllSegments() { + public synchronized Set getAllSegments() { return allSegments; } - public synchronized void setAllSegments(List allSegments) { + public synchronized void setAllSegments(Set allSegments) { this.allSegments = allSegments; } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java index de7001ca8..a4dd37f2b 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java @@ -22,13 +22,15 @@ import java.util.Map; public class ODPEvent { + public static final String EVENT_TYPE_FULLSTACK = "fullstack"; + private String type; private String action; private Map identifiers; private Map data; - public ODPEvent(@Nonnull String type, @Nonnull String action, @Nullable Map identifiers, @Nullable Map data) { - this.type = type; + public ODPEvent(@Nullable String type, @Nonnull String action, @Nullable Map identifiers, @Nullable Map data) { + this.type = type == null ? EVENT_TYPE_FULLSTACK : type; this.action = action; this.identifiers = identifiers != null ? identifiers : Collections.emptyMap(); this.data = data != null ? data : Collections.emptyMap(); diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java index ab4ce301e..b2a9a658b 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java @@ -52,12 +52,11 @@ public class ODPEventManager { // because `LinkedBlockingQueue` itself is thread safe. private final BlockingQueue eventQueue = new LinkedBlockingQueue<>(); - public ODPEventManager(@Nonnull ODPConfig odpConfig, @Nonnull ODPApiManager apiManager) { - this(odpConfig, apiManager, null, null, null); + public ODPEventManager(@Nonnull ODPApiManager apiManager) { + this(apiManager, null, null, null); } - public ODPEventManager(@Nonnull ODPConfig odpConfig, @Nonnull ODPApiManager apiManager, @Nullable Integer batchSize, @Nullable Integer queueSize, @Nullable Integer flushInterval) { - this.odpConfig = odpConfig; + public ODPEventManager(@Nonnull ODPApiManager apiManager, @Nullable Integer batchSize, @Nullable Integer queueSize, @Nullable Integer flushInterval) { this.apiManager = apiManager; this.batchSize = (batchSize != null && batchSize > 1) ? batchSize : DEFAULT_BATCH_SIZE; this.queueSize = queueSize != null ? queueSize : DEFAULT_QUEUE_SIZE; @@ -65,23 +64,33 @@ public ODPEventManager(@Nonnull ODPConfig odpConfig, @Nonnull ODPApiManager apiM } public void start() { + if (eventDispatcherThread == null) { + eventDispatcherThread = new EventDispatcherThread(); + } + if (!isRunning) { + eventDispatcherThread.start(); + } isRunning = true; - eventDispatcherThread = new EventDispatcherThread(); - eventDispatcherThread.start(); } - public void updateSettings(ODPConfig odpConfig) { - if (!this.odpConfig.equals(odpConfig) && eventQueue.offer(new FlushEvent(this.odpConfig))) { - this.odpConfig = odpConfig; + public void updateSettings(ODPConfig newConfig) { + if (odpConfig == null || (!odpConfig.equals(newConfig) && eventQueue.offer(new FlushEvent(odpConfig)))) { + odpConfig = newConfig; } } - public void identifyUser(@Nullable String vuid, String userId) { + public void identifyUser(String userId) { + identifyUser(null, userId); + } + + public void identifyUser(@Nullable String vuid, @Nullable String userId) { Map identifiers = new HashMap<>(); if (vuid != null) { identifiers.put(ODPUserKey.VUID.getKeyString(), vuid); } - identifiers.put(ODPUserKey.FS_USER_ID.getKeyString(), userId); + if (userId != null) { + identifiers.put(ODPUserKey.FS_USER_ID.getKeyString(), userId); + } ODPEvent event = new ODPEvent("fullstack", "client_initialized", identifiers, null); sendEvent(event); } @@ -111,7 +120,7 @@ private void processEvent(ODPEvent event) { return; } - if (!odpConfig.isReady()) { + if (odpConfig == null || !odpConfig.isReady()) { logger.debug("Unable to Process ODP Event. ODPConfig is not ready."); return; } @@ -184,10 +193,15 @@ public void run() { } } + isRunning = false; logger.debug("Exiting ODP Event Dispatcher Thread."); } private void flush(ODPConfig odpConfig) { + if (currentBatch.size() == 0) { + return; + } + if (odpConfig.isReady()) { String payload = ODPJsonSerializerFactory.getSerializer().serializeEvents(currentBatch); String endpoint = odpConfig.getApiHost() + EVENT_URL_PATH; diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java index cb7e04f99..3e198a209 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java @@ -16,20 +16,26 @@ */ package com.optimizely.ab.odp; +import com.optimizely.ab.internal.Cache; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import javax.annotation.Nonnull; import java.util.List; +import java.util.Set; + +public class ODPManager implements AutoCloseable { + private static final Logger logger = LoggerFactory.getLogger(ODPManager.class); -public class ODPManager { private volatile ODPConfig odpConfig; private final ODPSegmentManager segmentManager; private final ODPEventManager eventManager; - public ODPManager(@Nonnull ODPConfig odpConfig, @Nonnull ODPApiManager apiManager) { - this(odpConfig, new ODPSegmentManager(odpConfig, apiManager), new ODPEventManager(odpConfig, apiManager)); + private ODPManager(@Nonnull ODPApiManager apiManager) { + this(new ODPSegmentManager(apiManager), new ODPEventManager(apiManager)); } - public ODPManager(@Nonnull ODPConfig odpConfig, @Nonnull ODPSegmentManager segmentManager, @Nonnull ODPEventManager eventManager) { - this.odpConfig = odpConfig; + private ODPManager(@Nonnull ODPSegmentManager segmentManager, @Nonnull ODPEventManager eventManager) { this.segmentManager = segmentManager; this.eventManager = eventManager; this.eventManager.start(); @@ -43,9 +49,10 @@ public ODPEventManager getEventManager() { return eventManager; } - public Boolean updateSettings(String apiHost, String apiKey, List allSegments) { + public Boolean updateSettings(String apiHost, String apiKey, Set allSegments) { ODPConfig newConfig = new ODPConfig(apiKey, apiHost, allSegments); - if (!odpConfig.equals(newConfig)) { + if (odpConfig == null || !odpConfig.equals(newConfig)) { + logger.debug("Updating ODP Config"); odpConfig = newConfig; eventManager.updateSettings(odpConfig); segmentManager.resetCache(); @@ -58,4 +65,125 @@ public Boolean updateSettings(String apiHost, String apiKey, List allSeg public void close() { eventManager.stop(); } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + private ODPSegmentManager segmentManager; + private ODPEventManager eventManager; + private ODPApiManager apiManager; + private Integer cacheSize; + private Integer cacheTimeoutSeconds; + private Cache> cacheImpl; + + /** + * Provide a custom {@link ODPManager} instance which makes http calls to fetch segments and send events. + * + * A Default ODPApiManager is available in `core-httpclient-impl` package. + * + * @param apiManager The implementation of {@link ODPManager} + * @return ODPManager builder + */ + public Builder withApiManager(ODPApiManager apiManager) { + this.apiManager = apiManager; + return this; + } + + /** + * Provide an optional custom {@link ODPSegmentManager} instance. + * + * A Default {@link ODPSegmentManager} implementation is automatically used if none provided. + * + * @param segmentManager The implementation of {@link ODPSegmentManager} + * @return ODPManager builder + */ + public Builder withSegmentManager(ODPSegmentManager segmentManager) { + this.segmentManager = segmentManager; + return this; + } + + /** + * Provide an optional custom {@link ODPEventManager} instance. + * + * A Default {@link ODPEventManager} implementation is automatically used if none provided. + * + * @param eventManager The implementation of {@link ODPEventManager} + * @return ODPManager builder + */ + public Builder withEventManager(ODPEventManager eventManager) { + this.eventManager = eventManager; + return this; + } + + /** + * Provide an optional custom cache size + * + * A Default cache size is automatically used if none provided. + * + * @param cacheSize Custom cache size to be used. + * @return ODPManager builder + */ + public Builder withSegmentCacheSize(Integer cacheSize) { + this.cacheSize = cacheSize; + return this; + } + + /** + * Provide an optional custom cache timeout. + * + * A Default cache timeout is automatically used if none provided. + * + * @param cacheTimeoutSeconds Custom cache timeout in seconds. + * @return ODPManager builder + */ + public Builder withSegmentCacheTimeout(Integer cacheTimeoutSeconds) { + this.cacheTimeoutSeconds = cacheTimeoutSeconds; + return this; + } + + /** + * Provide an optional custom Segment Cache implementation. + * + * A Default LRU Cache implementation is automatically used if none provided. + * + * @param cacheImpl Customer Cache Implementation. + * @return ODPManager builder + */ + public Builder withSegmentCache(Cache> cacheImpl) { + this.cacheImpl = cacheImpl; + return this; + } + + public ODPManager build() { + if ((segmentManager == null || eventManager == null) && apiManager == null) { + logger.warn("ApiManager instance is needed when using default EventManager or SegmentManager"); + return null; + } + + if (segmentManager == null) { + if (cacheImpl != null) { + segmentManager = new ODPSegmentManager(apiManager, cacheImpl); + } else if (cacheSize != null || cacheTimeoutSeconds != null) { + // Converting null to -1 so that DefaultCache uses the default values; + if (cacheSize == null) { + cacheSize = -1; + } + if (cacheTimeoutSeconds == null) { + cacheTimeoutSeconds = -1; + } + segmentManager = new ODPSegmentManager(apiManager, cacheSize, cacheTimeoutSeconds); + } else { + segmentManager = new ODPSegmentManager(apiManager); + } + } + + if (eventManager == null) { + eventManager = new ODPEventManager(apiManager); + } + + return new ODPManager(segmentManager, eventManager); + } + } } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentCallback.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentCallback.java new file mode 100644 index 000000000..57bc5097a --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentCallback.java @@ -0,0 +1,22 @@ +/** + * + * Copyright 2022, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp; + +@FunctionalInterface +public interface ODPSegmentCallback { + void onCompleted(Boolean isFetchSuccessful); +} diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java index 352c4ec8f..90a36fa5d 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java @@ -38,19 +38,17 @@ public class ODPSegmentManager { private final Cache> segmentsCache; - public ODPSegmentManager(ODPConfig odpConfig, ODPApiManager apiManager) { - this(odpConfig, apiManager, Cache.DEFAULT_MAX_SIZE, Cache.DEFAULT_TIMEOUT_SECONDS); + public ODPSegmentManager(ODPApiManager apiManager) { + this(apiManager, Cache.DEFAULT_MAX_SIZE, Cache.DEFAULT_TIMEOUT_SECONDS); } - public ODPSegmentManager(ODPConfig odpConfig, ODPApiManager apiManager, Cache> cache) { + public ODPSegmentManager(ODPApiManager apiManager, Cache> cache) { this.apiManager = apiManager; - this.odpConfig = odpConfig; this.segmentsCache = cache; } - public ODPSegmentManager(ODPConfig odpConfig, ODPApiManager apiManager, Integer cacheSize, Integer cacheTimeoutSeconds) { + public ODPSegmentManager(ODPApiManager apiManager, Integer cacheSize, Integer cacheTimeoutSeconds) { this.apiManager = apiManager; - this.odpConfig = odpConfig; this.segmentsCache = new DefaultLRUCache<>(cacheSize, cacheTimeoutSeconds); } @@ -66,9 +64,9 @@ public List getQualifiedSegments(ODPUserKey userKey, String userValue) { } public List getQualifiedSegments(ODPUserKey userKey, String userValue, List options) { - if (!odpConfig.isReady()) { + if (odpConfig == null || !odpConfig.isReady()) { logger.error("Audience segments fetch failed (ODP is not enabled)"); - return Collections.emptyList(); + return null; } if (!odpConfig.hasSegments()) { @@ -93,7 +91,13 @@ public List getQualifiedSegments(ODPUserKey userKey, String userValue, L ResponseJsonParser parser = ResponseJsonParserFactory.getParser(); String qualifiedSegmentsResponse = apiManager.fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + SEGMENT_URL_PATH, userKey.getKeyString(), userValue, odpConfig.getAllSegments()); - qualifiedSegments = parser.parseQualifiedSegments(qualifiedSegmentsResponse); + try { + qualifiedSegments = parser.parseQualifiedSegments(qualifiedSegmentsResponse); + } catch (Exception e) { + logger.error("Audience segments fetch failed (Error Parsing Response)"); + logger.debug(e.getMessage()); + qualifiedSegments = null; + } if (qualifiedSegments != null && !options.contains(ODPSegmentOption.IGNORE_CACHE)) { segmentsCache.save(cacheKey, qualifiedSegments); @@ -102,6 +106,23 @@ public List getQualifiedSegments(ODPUserKey userKey, String userValue, L return qualifiedSegments; } + public void getQualifiedSegments(ODPUserKey userKey, String userValue, ODPSegmentFetchCallback callback, List options) { + AsyncSegmentFetcher segmentFetcher = new AsyncSegmentFetcher(userKey, userValue, options, callback); + segmentFetcher.start(); + } + + public void getQualifiedSegments(ODPUserKey userKey, String userValue, ODPSegmentFetchCallback callback) { + getQualifiedSegments(userKey, userValue, callback, Collections.emptyList()); + } + + public void getQualifiedSegments(String fsUserId, ODPSegmentFetchCallback callback, List segmentOptions) { + getQualifiedSegments(ODPUserKey.FS_USER_ID, fsUserId, callback, segmentOptions); + } + + public void getQualifiedSegments(String fsUserId, ODPSegmentFetchCallback callback) { + getQualifiedSegments(ODPUserKey.FS_USER_ID, fsUserId, callback, Collections.emptyList()); + } + private String getCacheKey(String userKey, String userValue) { return userKey + "-$-" + userValue; } @@ -113,4 +134,30 @@ public void updateSettings(ODPConfig odpConfig) { public void resetCache() { segmentsCache.reset(); } + + @FunctionalInterface + public interface ODPSegmentFetchCallback { + void onCompleted(List segments); + } + + private class AsyncSegmentFetcher extends Thread { + + private final ODPUserKey userKey; + private final String userValue; + private final List segmentOptions; + private final ODPSegmentFetchCallback callback; + + public AsyncSegmentFetcher(ODPUserKey userKey, String userValue, List segmentOptions, ODPSegmentFetchCallback callback) { + this.userKey = userKey; + this.userValue = userValue; + this.segmentOptions = segmentOptions; + this.callback = callback; + } + + @Override + public void run() { + List segments = getQualifiedSegments(userKey, userValue, segmentOptions); + callback.onCompleted(segments); + } + } } diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java index 91bb19e18..79382a5b7 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java @@ -20,11 +20,12 @@ import com.optimizely.ab.config.*; import com.optimizely.ab.error.ErrorHandler; import com.optimizely.ab.error.NoOpErrorHandler; -import com.optimizely.ab.event.BatchEventProcessor; import com.optimizely.ab.event.EventHandler; import com.optimizely.ab.event.LogEvent; import com.optimizely.ab.event.internal.BuildVersionInfo; import com.optimizely.ab.event.internal.payload.EventBatch; +import com.optimizely.ab.odp.ODPEventManager; +import com.optimizely.ab.odp.ODPManager; import com.optimizely.ab.optimizelydecision.OptimizelyDecideOption; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.junit.Rule; @@ -32,6 +33,7 @@ import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; @@ -43,10 +45,7 @@ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; -import static org.mockito.Mockito.never; /** * Tests for {@link Optimizely#builder(String, EventHandler)}. @@ -244,4 +243,15 @@ public void withClientInfo() throws Exception { assertEquals(argument.getValue().getEventBatch().getClientVersion(), "1.2.3"); } + @Test + public void withODPManager() { + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Optimizely optimizely = Optimizely.builder() + .withODPManager(mockODPManager) + .build(); + assertEquals(mockODPManager, optimizely.getODPManager()); + } } diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java index 2cab4a01e..9fd3dd675 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java @@ -34,6 +34,9 @@ import com.optimizely.ab.internal.ControlAttribute; import com.optimizely.ab.internal.LogbackVerifier; import com.optimizely.ab.notification.*; +import com.optimizely.ab.odp.ODPEvent; +import com.optimizely.ab.odp.ODPEventManager; +import com.optimizely.ab.odp.ODPManager; import com.optimizely.ab.optimizelydecision.DecisionResponse; import com.optimizely.ab.optimizelyjson.OptimizelyJSON; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @@ -44,7 +47,9 @@ import org.junit.rules.RuleChain; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; @@ -179,10 +184,21 @@ public void testClose() throws Exception { withSettings().extraInterfaces(AutoCloseable.class) ); + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + Mockito.doNothing().when(mockODPEventManager).sendEvent(any()); + + ODPManager mockODPManager = mock( + ODPManager.class, + withSettings().extraInterfaces(AutoCloseable.class) + ); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Optimizely optimizely = Optimizely.builder() .withEventHandler(mockEventHandler) .withEventProcessor(mockEventProcessor) .withConfigManager(mockProjectConfigManager) + .withODPManager(mockODPManager) .build(); optimizely.close(); @@ -190,7 +206,7 @@ public void testClose() throws Exception { verify((AutoCloseable) mockEventHandler).close(); verify((AutoCloseable) mockProjectConfigManager).close(); verify((AutoCloseable) mockEventProcessor).close(); - + verify((AutoCloseable) mockODPManager).close(); } //======== activate tests ========// @@ -4666,4 +4682,120 @@ public void getFlagVariationByKey() throws IOException { assertEquals(variationKey, variation.getKey()); } + @Test + public void initODPManagerWithoutProjectConfig() { + ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Optimizely.builder() + .withConfigManager(mockProjectConfigManager) + .withODPManager(mockODPManager) + .build(); + + verify(mockODPEventManager).start(); + verify(mockODPManager, never()).updateSettings(any(), any(), any()); + } + + @Test + public void initODPManagerWithProjectConfig() throws IOException { + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Optimizely.builder() + .withDatafile(validConfigJsonV4()) + .withODPManager(mockODPManager) + .build(); + + verify(mockODPEventManager).start(); + verify(mockODPManager, times(1)).updateSettings(any(), any(), any()); + } + + @Test + public void updateODPManagerWhenConfigUpdates() throws IOException { + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + NotificationCenter mockNotificationCenter = mock(NotificationCenter.class); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Optimizely.builder() + .withDatafile(validConfigJsonV4()) + .withNotificationCenter(mockNotificationCenter) + .withODPManager(mockODPManager) + .build(); + + verify(mockODPManager, times(1)).updateSettings(any(), any(), any()); + + Mockito.verify(mockNotificationCenter, times(1)).addNotificationHandler(any(), any()); + } + + @Test + public void sendODPEvent() { + ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Optimizely optimizely = Optimizely.builder() + .withConfigManager(mockProjectConfigManager) + .withODPManager(mockODPManager) + .build(); + + verify(mockODPEventManager).start(); + + Map identifiers = new HashMap<>(); + identifiers.put("id1", "value1"); + identifiers.put("id2", "value2"); + + Map data = new HashMap<>(); + data.put("sdk", "java"); + data.put("revision", 52); + + optimizely.sendODPEvent("fullstack", "identify", identifiers, data); + ArgumentCaptor eventArgument = ArgumentCaptor.forClass(ODPEvent.class); + verify(mockODPEventManager).sendEvent(eventArgument.capture()); + + assertEquals("fullstack", eventArgument.getValue().getType()); + assertEquals("identify", eventArgument.getValue().getAction()); + assertEquals(identifiers, eventArgument.getValue().getIdentifiers()); + assertEquals(data, eventArgument.getValue().getData()); + } + + @Test + public void sendODPEventError() { + ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); + + Optimizely optimizely = Optimizely.builder() + .withConfigManager(mockProjectConfigManager) + .build(); + + Map identifiers = new HashMap<>(); + identifiers.put("id1", "value1"); + identifiers.put("id2", "value2"); + + Map data = new HashMap<>(); + data.put("sdk", "java"); + data.put("revision", 52); + + optimizely.sendODPEvent("fullstack", "identify", identifiers, data); + logbackVerifier.expectMessage(Level.ERROR, "ODP event send failed (ODP is not enabled)"); + } + + @Test + public void identifyUser() { + ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Optimizely optimizely = Optimizely.builder() + .withConfigManager(mockProjectConfigManager) + .withODPManager(mockODPManager) + .build(); + + optimizely.identifyUser("the-user"); + Mockito.verify(mockODPEventManager, times(1)).identifyUser("the-user"); + } } diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java index c196938c4..5dd47a8cf 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java @@ -16,6 +16,7 @@ */ package com.optimizely.ab; +import ch.qos.logback.classic.Level; import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.optimizely.ab.bucketing.FeatureDecision; @@ -24,9 +25,10 @@ import com.optimizely.ab.config.parser.ConfigParseException; import com.optimizely.ab.event.ForwardingEventProcessor; import com.optimizely.ab.event.internal.payload.DecisionMetadata; +import com.optimizely.ab.internal.LogbackVerifier; import com.optimizely.ab.notification.NotificationCenter; +import com.optimizely.ab.odp.*; import com.optimizely.ab.optimizelydecision.DecisionMessage; -import com.optimizely.ab.optimizelydecision.DecisionResponse; import com.optimizely.ab.optimizelydecision.OptimizelyDecideOption; import com.optimizely.ab.optimizelydecision.OptimizelyDecision; import com.optimizely.ab.optimizelyjson.OptimizelyJSON; @@ -35,8 +37,10 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.mockito.Mockito; import java.util.*; +import java.util.concurrent.CountDownLatch; import static com.optimizely.ab.config.ValidProjectConfigV4.ATTRIBUTE_HOUSE_KEY; import static com.optimizely.ab.config.ValidProjectConfigV4.AUDIENCE_GRYFFINDOR_VALUE; @@ -51,6 +55,9 @@ public class OptimizelyUserContextTest { @Rule public EventHandlerRule eventHandler = new EventHandlerRule(); + @Rule + public LogbackVerifier logbackVerifier = new LogbackVerifier(); + String userId = "tester"; boolean isListenerCalled = false; @@ -1610,6 +1617,127 @@ public void setForcedDecisionsAndCallDecideDeliveryRuleToDecision() { )); } /********************************************[END DECIDE TESTS WITH FDs]******************************************/ + + @Test + public void fetchQualifiedSegments() { + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPSegmentManager mockODPSegmentManager = mock(ODPSegmentManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Mockito.when(mockODPManager.getSegmentManager()).thenReturn(mockODPSegmentManager); + + Optimizely optimizely = Optimizely.builder() + .withODPManager(mockODPManager) + .build(); + + OptimizelyUserContext userContext = optimizely.createUserContext("test-user"); + + assertTrue(userContext.fetchQualifiedSegments()); + verify(mockODPSegmentManager).getQualifiedSegments("test-user", Collections.emptyList()); + + assertTrue(userContext.fetchQualifiedSegments(Collections.singletonList(ODPSegmentOption.RESET_CACHE))); + verify(mockODPSegmentManager).getQualifiedSegments("test-user", Collections.singletonList(ODPSegmentOption.RESET_CACHE)); + } + + @Test + public void fetchQualifiedSegmentsError() { + Optimizely optimizely = Optimizely.builder() + .build(); + OptimizelyUserContext userContext = optimizely.createUserContext("test-user"); + + assertFalse(userContext.fetchQualifiedSegments()); + logbackVerifier.expectMessage(Level.ERROR, "Audience segments fetch failed (ODP is not enabled)."); + } + + @Test + public void fetchQualifiedSegmentsAsync() throws InterruptedException { + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPSegmentManager mockODPSegmentManager = mock(ODPSegmentManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + + doAnswer( + invocation -> { + ODPSegmentManager.ODPSegmentFetchCallback callback = invocation.getArgumentAt(1, ODPSegmentManager.ODPSegmentFetchCallback.class); + callback.onCompleted(Arrays.asList("segment1", "segment2")); + return null; + } + ).when(mockODPSegmentManager).getQualifiedSegments(any(), (ODPSegmentManager.ODPSegmentFetchCallback) any(), any()); + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Mockito.when(mockODPManager.getSegmentManager()).thenReturn(mockODPSegmentManager); + + Optimizely optimizely = Optimizely.builder() + .withODPManager(mockODPManager) + .build(); + + OptimizelyUserContext userContext = optimizely.createUserContext("test-user"); + + CountDownLatch countDownLatch = new CountDownLatch(1); + userContext.fetchQualifiedSegments((Boolean isFetchSuccessful) -> { + assertTrue(isFetchSuccessful); + countDownLatch.countDown(); + }); + + countDownLatch.await(); + verify(mockODPSegmentManager).getQualifiedSegments(eq("test-user"), any(ODPSegmentManager.ODPSegmentFetchCallback.class), eq(Collections.emptyList())); + assertEquals(Arrays.asList("segment1", "segment2"), userContext.getQualifiedSegments()); + + // reset qualified segments + userContext.setQualifiedSegments(Collections.emptyList()); + CountDownLatch countDownLatch2 = new CountDownLatch(1); + userContext.fetchQualifiedSegments((Boolean isFetchSuccessful) -> { + assertTrue(isFetchSuccessful); + countDownLatch2.countDown(); + }, Collections.singletonList(ODPSegmentOption.RESET_CACHE)); + + countDownLatch2.await(); + verify(mockODPSegmentManager).getQualifiedSegments(eq("test-user"), any(ODPSegmentManager.ODPSegmentFetchCallback.class), eq(Collections.singletonList(ODPSegmentOption.RESET_CACHE))); + assertEquals(Arrays.asList("segment1", "segment2"), userContext.getQualifiedSegments()); + } + + @Test + public void fetchQualifiedSegmentsAsyncError() throws InterruptedException { + Optimizely optimizely = Optimizely.builder() + .build(); + + OptimizelyUserContext userContext = optimizely.createUserContext("test-user"); + + CountDownLatch countDownLatch = new CountDownLatch(1); + userContext.fetchQualifiedSegments((Boolean isFetchSuccessful) -> { + assertFalse(isFetchSuccessful); + countDownLatch.countDown(); + }); + + countDownLatch.await(); + assertEquals(Collections.emptyList(), userContext.getQualifiedSegments()); + logbackVerifier.expectMessage(Level.ERROR, "Audience segments fetch failed (ODP is not enabled)."); + } + + @Test + public void identifyUser() { + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPSegmentManager mockODPSegmentManager = mock(ODPSegmentManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Mockito.when(mockODPManager.getSegmentManager()).thenReturn(mockODPSegmentManager); + + Optimizely optimizely = Optimizely.builder() + .withODPManager(mockODPManager) + .build(); + + OptimizelyUserContext userContext = optimizely.createUserContext("test-user"); + verify(mockODPEventManager).identifyUser("test-user"); + + Mockito.reset(mockODPEventManager); + OptimizelyUserContext userContextClone = userContext.copy(); + + // identifyUser should not be called the new userContext is created through copy + verify(mockODPEventManager, never()).identifyUser("test-user"); + + assertNotSame(userContextClone, userContext); + } + // utils Map createUserProfileMap(String experimentId, String variationId) { diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java index fd4287e0f..d6941671f 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java @@ -59,7 +59,8 @@ public void setup() { @Test public void logAndDiscardEventWhenEventManagerIsNotRunning() { ODPConfig odpConfig = new ODPConfig("key", "host", null); - ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager); + ODPEventManager eventManager = new ODPEventManager(mockApiManager); + eventManager.updateSettings(odpConfig); ODPEvent event = new ODPEvent("test-type", "test-action", Collections.emptyMap(), Collections.emptyMap()); eventManager.sendEvent(event); logbackVerifier.expectMessage(Level.WARN, "Failed to Process ODP Event. ODPEventManager is not running"); @@ -68,7 +69,8 @@ public void logAndDiscardEventWhenEventManagerIsNotRunning() { @Test public void logAndDiscardEventWhenODPConfigNotReady() { ODPConfig odpConfig = new ODPConfig(null, null, null); - ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager); + ODPEventManager eventManager = new ODPEventManager(mockApiManager); + eventManager.updateSettings(odpConfig); eventManager.start(); ODPEvent event = new ODPEvent("test-type", "test-action", Collections.emptyMap(), Collections.emptyMap()); eventManager.sendEvent(event); @@ -80,7 +82,8 @@ public void dispatchEventsInCorrectNumberOfBatches() throws InterruptedException Mockito.reset(mockApiManager); Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); - ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager); + ODPEventManager eventManager = new ODPEventManager(mockApiManager); + eventManager.updateSettings(odpConfig); eventManager.start(); for (int i = 0; i < 25; i++) { eventManager.sendEvent(getEvent(i)); @@ -95,7 +98,8 @@ public void dispatchEventsWithCorrectPayload() throws InterruptedException { Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); int batchSize = 2; ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); - ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager, batchSize, null, null); + ODPEventManager eventManager = new ODPEventManager(mockApiManager, batchSize, null, null); + eventManager.updateSettings(odpConfig); eventManager.start(); for (int i = 0; i < 6; i++) { eventManager.sendEvent(getEvent(i)); @@ -126,7 +130,8 @@ public void dispatchEventsWithCorrectFlushInterval() throws InterruptedException Mockito.reset(mockApiManager); Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); - ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager); + ODPEventManager eventManager = new ODPEventManager(mockApiManager); + eventManager.updateSettings(odpConfig); eventManager.start(); for (int i = 0; i < 25; i++) { eventManager.sendEvent(getEvent(i)); @@ -144,7 +149,8 @@ public void retryFailedEvents() throws InterruptedException { Mockito.reset(mockApiManager); Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(500); ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); - ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager); + ODPEventManager eventManager = new ODPEventManager(mockApiManager); + eventManager.updateSettings(odpConfig); eventManager.start(); for (int i = 0; i < 25; i++) { eventManager.sendEvent(getEvent(i)); @@ -164,7 +170,8 @@ public void shouldFlushAllScheduledEventsBeforeStopping() throws InterruptedExce Mockito.reset(mockApiManager); Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); - ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager); + ODPEventManager eventManager = new ODPEventManager(mockApiManager); + eventManager.updateSettings(odpConfig); eventManager.start(); for (int i = 0; i < 25; i++) { eventManager.sendEvent(getEvent(i)); @@ -181,7 +188,8 @@ public void prepareCorrectPayloadForIdentifyUser() throws InterruptedException { Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); int batchSize = 2; ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); - ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager, batchSize, null, null); + ODPEventManager eventManager = new ODPEventManager(mockApiManager, batchSize, null, null); + eventManager.updateSettings(odpConfig); eventManager.start(); for (int i = 0; i < 2; i++) { eventManager.identifyUser("the-vuid-" + i, "the-fs-user-id-" + i); @@ -208,7 +216,8 @@ public void applyUpdatedODPConfigWhenAvailable() throws InterruptedException { Mockito.reset(mockApiManager); Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); - ODPEventManager eventManager = new ODPEventManager(odpConfig, mockApiManager); + ODPEventManager eventManager = new ODPEventManager(mockApiManager); + eventManager.updateSettings(odpConfig); eventManager.start(); for (int i = 0; i < 25; i++) { eventManager.sendEvent(getEvent(i)); diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerBuilderTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerBuilderTest.java new file mode 100644 index 000000000..0f7f59ae9 --- /dev/null +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerBuilderTest.java @@ -0,0 +1,76 @@ +/** + * + * Copyright 2022, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.odp; + +import com.optimizely.ab.internal.Cache; +import org.junit.Test; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; + +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; +import static org.junit.Assert.*; + +public class ODPManagerBuilderTest { + + @Test + public void withApiManager() { + ODPApiManager mockApiManager = mock(ODPApiManager.class); + ODPManager odpManager = ODPManager.builder().withApiManager(mockApiManager).build(); + odpManager.updateSettings("test-host", "test-key", new HashSet<>(Arrays.asList("Segment-1", "Segment-2"))); + odpManager.getSegmentManager().getQualifiedSegments("test-user"); + verify(mockApiManager).fetchQualifiedSegments(any(), any(), any(), any(), any()); + } + + @Test + public void withSegmentManager() { + ODPSegmentManager mockSegmentManager = mock(ODPSegmentManager.class); + ODPEventManager mockEventManager = mock(ODPEventManager.class); + ODPManager odpManager = ODPManager.builder() + .withSegmentManager(mockSegmentManager) + .withEventManager(mockEventManager) + .build(); + assertSame(mockSegmentManager, odpManager.getSegmentManager()); + } + + @Test + public void withEventManager() { + ODPSegmentManager mockSegmentManager = mock(ODPSegmentManager.class); + ODPEventManager mockEventManager = mock(ODPEventManager.class); + ODPManager odpManager = ODPManager.builder() + .withSegmentManager(mockSegmentManager) + .withEventManager(mockEventManager) + .build(); + assertSame(mockEventManager, odpManager.getEventManager()); + } + + @Test + public void withSegmentCache() { + Cache> mockCache = mock(Cache.class); + ODPApiManager mockApiManager = mock(ODPApiManager.class); + ODPManager odpManager = ODPManager.builder() + .withApiManager(mockApiManager) + .withSegmentCache(mockCache) + .build(); + + odpManager.updateSettings("test-host", "test-key", new HashSet<>(Arrays.asList("Segment-1", "Segment-2"))); + odpManager.getSegmentManager().getQualifiedSegments("test-user"); + verify(mockCache).lookup("fs_user_id-$-test-user"); + } +} diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java index 924c88836..02abe88a1 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java @@ -22,6 +22,8 @@ import org.mockito.Mockito; import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; @@ -48,15 +50,15 @@ public void setup() { @Test public void shouldStartEventManagerWhenODPManagerIsInitialized() { - ODPConfig config = new ODPConfig("test-key", "test-host"); - new ODPManager(config, mockSegmentManager, mockEventManager); + ODPManager.builder().withSegmentManager(mockSegmentManager).withEventManager(mockEventManager).build(); + verify(mockEventManager, times(1)).start(); } @Test public void shouldStopEventManagerWhenCloseIsCalled() { - ODPConfig config = new ODPConfig("test-key", "test-host"); - ODPManager odpManager = new ODPManager(config, mockSegmentManager, mockEventManager); + ODPManager odpManager = ODPManager.builder().withSegmentManager(mockSegmentManager).withEventManager(mockEventManager).build(); + odpManager.updateSettings("test-key", "test-host", Collections.emptySet()); // Stop is not called in the default flow. verify(mockEventManager, times(0)).stop(); @@ -69,15 +71,15 @@ public void shouldStopEventManagerWhenCloseIsCalled() { @Test public void shouldUseNewSettingsInEventManagerWhenODPConfigIsUpdated() throws InterruptedException { Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(200); - ODPConfig config = new ODPConfig("test-key", "test-host", Arrays.asList("segment1", "segment2")); - ODPManager odpManager = new ODPManager(config, mockApiManager); + ODPManager odpManager = ODPManager.builder().withApiManager(mockApiManager).build(); + odpManager.updateSettings("test-host", "test-key", new HashSet<>(Arrays.asList("segment1", "segment2"))); odpManager.getEventManager().identifyUser("vuid", "fsuid"); Thread.sleep(2000); verify(mockApiManager, times(1)) .sendEvents(eq("test-key"), eq("test-host/v3/events"), any()); - odpManager.updateSettings("test-host-updated", "test-key-updated", Arrays.asList("segment1")); + odpManager.updateSettings("test-host-updated", "test-key-updated", new HashSet<>(Arrays.asList("segment1"))); odpManager.getEventManager().identifyUser("vuid", "fsuid"); Thread.sleep(1200); verify(mockApiManager, times(1)) @@ -86,16 +88,16 @@ public void shouldUseNewSettingsInEventManagerWhenODPConfigIsUpdated() throws In @Test public void shouldUseNewSettingsInSegmentManagerWhenODPConfigIsUpdated() { - Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anyList())) + Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anySet())) .thenReturn(API_RESPONSE); - ODPConfig config = new ODPConfig("test-key", "test-host", Arrays.asList("segment1", "segment2")); - ODPManager odpManager = new ODPManager(config, mockApiManager); + ODPManager odpManager = ODPManager.builder().withApiManager(mockApiManager).build(); + odpManager.updateSettings("test-host", "test-key", new HashSet<>(Arrays.asList("segment1", "segment2"))); odpManager.getSegmentManager().getQualifiedSegments("test-id"); verify(mockApiManager, times(1)) .fetchQualifiedSegments(eq("test-key"), eq("test-host/v3/graphql"), any(), any(), any()); - odpManager.updateSettings("test-host-updated", "test-key-updated", Arrays.asList("segment1")); + odpManager.updateSettings("test-host-updated", "test-key-updated", new HashSet<>(Arrays.asList("segment1"))); odpManager.getSegmentManager().getQualifiedSegments("test-id"); verify(mockApiManager, times(1)) .fetchQualifiedSegments(eq("test-key-updated"), eq("test-host-updated/v3/graphql"), any(), any(), any()); @@ -103,21 +105,19 @@ public void shouldUseNewSettingsInSegmentManagerWhenODPConfigIsUpdated() { @Test public void shouldGetEventManager() { - ODPConfig config = new ODPConfig("test-key", "test-host"); - ODPManager odpManager = new ODPManager(config, mockSegmentManager, mockEventManager); + ODPManager odpManager = ODPManager.builder().withSegmentManager(mockSegmentManager).withEventManager(mockEventManager).build(); assertNotNull(odpManager.getEventManager()); - odpManager = new ODPManager(config, mockApiManager); + odpManager = ODPManager.builder().withApiManager(mockApiManager).build(); assertNotNull(odpManager.getEventManager()); } @Test public void shouldGetSegmentManager() { - ODPConfig config = new ODPConfig("test-key", "test-host"); - ODPManager odpManager = new ODPManager(config, mockSegmentManager, mockEventManager); + ODPManager odpManager = ODPManager.builder().withSegmentManager(mockSegmentManager).withEventManager(mockEventManager).build(); assertNotNull(odpManager.getSegmentManager()); - odpManager = new ODPManager(config, mockApiManager); + odpManager = ODPManager.builder().withApiManager(mockApiManager).build(); assertNotNull(odpManager.getSegmentManager()); } } diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java index f784d53d0..4d34d49b9 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java @@ -29,9 +29,8 @@ import static org.mockito.Mockito.*; import static org.junit.Assert.*; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; +import java.util.*; +import java.util.concurrent.CountDownLatch; public class ODPSegmentManagerTest { @@ -56,8 +55,9 @@ public void setup() { public void cacheHit() { Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); - ODPConfig odpConfig = new ODPConfig("testKey", "testHost", Arrays.asList("segment1", "segment2")); - ODPSegmentManager segmentManager = new ODPSegmentManager(odpConfig, mockApiManager, mockCache); + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", new HashSet<>(Arrays.asList("segment1", "segment2"))); + ODPSegmentManager segmentManager = new ODPSegmentManager(mockApiManager, mockCache); + segmentManager.updateSettings(odpConfig); List segments = segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId"); // Cache lookup called with correct key @@ -76,11 +76,12 @@ public void cacheHit() { @Test public void cacheMiss() { Mockito.when(mockCache.lookup(any())).thenReturn(null); - Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anyList())) + Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anySet())) .thenReturn(API_RESPONSE); - ODPConfig odpConfig = new ODPConfig("testKey", "testHost", Arrays.asList("segment1", "segment2")); - ODPSegmentManager segmentManager = new ODPSegmentManager(odpConfig, mockApiManager, mockCache); + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", new HashSet<>(Arrays.asList("segment1", "segment2"))); + ODPSegmentManager segmentManager = new ODPSegmentManager(mockApiManager, mockCache); + segmentManager.updateSettings(odpConfig); List segments = segmentManager.getQualifiedSegments(ODPUserKey.VUID, "testId"); // Cache lookup called with correct key @@ -88,7 +89,7 @@ public void cacheMiss() { // Cache miss! Make api call and save to cache verify(mockApiManager, times(1)) - .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "vuid", "testId", Arrays.asList("segment1", "segment2")); + .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "vuid", "testId", new HashSet<>(Arrays.asList("segment1", "segment2"))); verify(mockCache, times(1)).save("vuid-$-testId", Arrays.asList("segment1", "segment2")); verify(mockCache, times(0)).reset(); @@ -100,11 +101,12 @@ public void cacheMiss() { @Test public void ignoreCache() { Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); - Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anyList())) + Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anySet())) .thenReturn(API_RESPONSE); - ODPConfig odpConfig = new ODPConfig("testKey", "testHost", Arrays.asList("segment1", "segment2")); - ODPSegmentManager segmentManager = new ODPSegmentManager(odpConfig, mockApiManager, mockCache); + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", new HashSet<>(Arrays.asList("segment1", "segment2"))); + ODPSegmentManager segmentManager = new ODPSegmentManager(mockApiManager, mockCache); + segmentManager.updateSettings(odpConfig); List segments = segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId", Collections.singletonList(ODPSegmentOption.IGNORE_CACHE)); // Cache Ignored! lookup should not be called @@ -112,7 +114,7 @@ public void ignoreCache() { // Cache Ignored! Make API Call but do NOT save because of cacheIgnore verify(mockApiManager, times(1)) - .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "fs_user_id", "testId", Arrays.asList("segment1", "segment2")); + .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "fs_user_id", "testId", new HashSet<>(Arrays.asList("segment1", "segment2"))); verify(mockCache, times(0)).save(any(), any()); verify(mockCache, times(0)).reset(); @@ -122,22 +124,23 @@ public void ignoreCache() { @Test public void resetCache() { Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); - Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anyList())) + Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anySet())) .thenReturn(API_RESPONSE); - ODPConfig odpConfig = new ODPConfig("testKey", "testHost", Arrays.asList("segment1", "segment2")); - ODPSegmentManager segmentManager = new ODPSegmentManager(odpConfig, mockApiManager, mockCache); + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", new HashSet<>(Arrays.asList("segment1", "segment2"))); + ODPSegmentManager segmentManager = new ODPSegmentManager(mockApiManager, mockCache); + segmentManager.updateSettings(odpConfig); List segments = segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId", Collections.singletonList(ODPSegmentOption.RESET_CACHE)); // Call reset verify(mockCache, times(1)).reset(); - // Cache Reset! lookup should not be called becaues cache would be empty. + // Cache Reset! lookup should not be called because cache would be empty. verify(mockCache, times(0)).lookup(any()); // Cache reset but not Ignored! Make API Call and save to cache verify(mockApiManager, times(1)) - .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "fs_user_id", "testId", Arrays.asList("segment1", "segment2")); + .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "fs_user_id", "testId", new HashSet<>(Arrays.asList("segment1", "segment2"))); verify(mockCache, times(1)).save("fs_user_id-$-testId", Arrays.asList("segment1", "segment2")); assertEquals(Arrays.asList("segment1", "segment2"), segments); @@ -146,11 +149,12 @@ public void resetCache() { @Test public void resetAndIgnoreCache() { Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); - Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anyList())) + Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anySet())) .thenReturn(API_RESPONSE); - ODPConfig odpConfig = new ODPConfig("testKey", "testHost", Arrays.asList("segment1", "segment2")); - ODPSegmentManager segmentManager = new ODPSegmentManager(odpConfig, mockApiManager, mockCache); + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", new HashSet<>(Arrays.asList("segment1", "segment2"))); + ODPSegmentManager segmentManager = new ODPSegmentManager(mockApiManager, mockCache); + segmentManager.updateSettings(odpConfig); List segments = segmentManager .getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId", Arrays.asList(ODPSegmentOption.RESET_CACHE, ODPSegmentOption.IGNORE_CACHE)); @@ -161,7 +165,7 @@ public void resetAndIgnoreCache() { // Cache is also Ignored! Make API Call but do not save verify(mockApiManager, times(1)) - .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "fs_user_id", "testId", Arrays.asList("segment1", "segment2")); + .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "fs_user_id", "testId", new HashSet<>(Arrays.asList("segment1", "segment2"))); verify(mockCache, times(0)).save(any(), any()); assertEquals(Arrays.asList("segment1", "segment2"), segments); @@ -171,8 +175,9 @@ public void resetAndIgnoreCache() { public void odpConfigNotReady() { Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); - ODPConfig odpConfig = new ODPConfig(null, null, Arrays.asList("segment1", "segment2")); - ODPSegmentManager segmentManager = new ODPSegmentManager(odpConfig, mockApiManager, mockCache); + ODPConfig odpConfig = new ODPConfig(null, null, new HashSet<>(Arrays.asList("segment1", "segment2"))); + ODPSegmentManager segmentManager = new ODPSegmentManager(mockApiManager, mockCache); + segmentManager.updateSettings(odpConfig); List segments = segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId"); // No further methods should be called. @@ -183,7 +188,7 @@ public void odpConfigNotReady() { logbackVerifier.expectMessage(Level.ERROR, "Audience segments fetch failed (ODP is not enabled)"); - assertEquals(Collections.emptyList(), segments); + assertNull(segments); } @Test @@ -191,7 +196,8 @@ public void noSegmentsInProject() { Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); ODPConfig odpConfig = new ODPConfig("testKey", "testHost", null); - ODPSegmentManager segmentManager = new ODPSegmentManager(odpConfig, mockApiManager, mockCache); + ODPSegmentManager segmentManager = new ODPSegmentManager(mockApiManager, mockCache); + segmentManager.updateSettings(odpConfig); List segments = segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId"); // No further methods should be called. @@ -204,4 +210,192 @@ public void noSegmentsInProject() { assertEquals(Collections.emptyList(), segments); } + + // Tests for Async version + + @Test + public void cacheHitAsync() throws InterruptedException { + CountDownLatch countDownLatch = new CountDownLatch(1); + Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); + + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", new HashSet<>(Arrays.asList("segment1", "segment2"))); + ODPSegmentManager segmentManager = new ODPSegmentManager(mockApiManager, mockCache); + segmentManager.updateSettings(odpConfig); + segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId", (segments) -> { + assertEquals(Arrays.asList("segment1-cached", "segment2-cached"), segments); + countDownLatch.countDown(); + }); + + countDownLatch.await(); + + // Cache lookup called with correct key + verify(mockCache, times(1)).lookup("fs_user_id-$-testId"); + + // Cache hit! No api call was made to the server. + verify(mockApiManager, times(0)).fetchQualifiedSegments(any(), any(), any(), any(), any()); + verify(mockCache, times(0)).save(any(), any()); + verify(mockCache, times(0)).reset(); + + logbackVerifier.expectMessage(Level.DEBUG, "ODP Cache Hit. Returning segments from Cache."); + } + + @Test + public void cacheMissAsync() throws InterruptedException { + CountDownLatch countDownLatch = new CountDownLatch(1); + Mockito.when(mockCache.lookup(any())).thenReturn(null); + Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anySet())) + .thenReturn(API_RESPONSE); + + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", new HashSet<>(Arrays.asList("segment1", "segment2"))); + ODPSegmentManager segmentManager = new ODPSegmentManager(mockApiManager, mockCache); + segmentManager.updateSettings(odpConfig); + segmentManager.getQualifiedSegments(ODPUserKey.VUID, "testId", (segments) -> { + assertEquals(Arrays.asList("segment1", "segment2"), segments); + countDownLatch.countDown(); + }); + + countDownLatch.await(); + + // Cache lookup called with correct key + verify(mockCache, times(1)).lookup("vuid-$-testId"); + + // Cache miss! Make api call and save to cache + verify(mockApiManager, times(1)) + .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "vuid", "testId", new HashSet<>(Arrays.asList("segment1", "segment2"))); + verify(mockCache, times(1)).save("vuid-$-testId", Arrays.asList("segment1", "segment2")); + verify(mockCache, times(0)).reset(); + + logbackVerifier.expectMessage(Level.DEBUG, "ODP Cache Miss. Making a call to ODP Server."); + } + + @Test + public void ignoreCacheAsync() throws InterruptedException { + CountDownLatch countDownLatch = new CountDownLatch(1); + Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); + Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anySet())) + .thenReturn(API_RESPONSE); + + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", new HashSet<>(Arrays.asList("segment1", "segment2"))); + ODPSegmentManager segmentManager = new ODPSegmentManager(mockApiManager, mockCache); + segmentManager.updateSettings(odpConfig); + segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId", segments -> { + assertEquals(Arrays.asList("segment1", "segment2"), segments); + countDownLatch.countDown(); + }, Collections.singletonList(ODPSegmentOption.IGNORE_CACHE)); + + countDownLatch.await(); + + // Cache Ignored! lookup should not be called + verify(mockCache, times(0)).lookup(any()); + + // Cache Ignored! Make API Call but do NOT save because of cacheIgnore + verify(mockApiManager, times(1)) + .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "fs_user_id", "testId", new HashSet<>(Arrays.asList("segment1", "segment2"))); + verify(mockCache, times(0)).save(any(), any()); + verify(mockCache, times(0)).reset(); + } + + @Test + public void resetCacheAsync() throws InterruptedException { + CountDownLatch countDownLatch = new CountDownLatch(1); + Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); + Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anySet())) + .thenReturn(API_RESPONSE); + + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", new HashSet<>(Arrays.asList("segment1", "segment2"))); + ODPSegmentManager segmentManager = new ODPSegmentManager(mockApiManager, mockCache); + segmentManager.updateSettings(odpConfig); + segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId", segments -> { + assertEquals(Arrays.asList("segment1", "segment2"), segments); + countDownLatch.countDown(); + }, Collections.singletonList(ODPSegmentOption.RESET_CACHE)); + + countDownLatch.await(); + + // Call reset + verify(mockCache, times(1)).reset(); + + // Cache Reset! lookup should not be called because cache would be empty. + verify(mockCache, times(0)).lookup(any()); + + // Cache reset but not Ignored! Make API Call and save to cache + verify(mockApiManager, times(1)) + .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "fs_user_id", "testId", new HashSet<>(Arrays.asList("segment1", "segment2"))); + verify(mockCache, times(1)).save("fs_user_id-$-testId", Arrays.asList("segment1", "segment2")); + } + + @Test + public void resetAndIgnoreCacheAsync() throws InterruptedException { + CountDownLatch countDownLatch = new CountDownLatch(1); + Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); + Mockito.when(mockApiManager.fetchQualifiedSegments(anyString(), anyString(), anyString(), anyString(), anySet())) + .thenReturn(API_RESPONSE); + + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", new HashSet<>(Arrays.asList("segment1", "segment2"))); + ODPSegmentManager segmentManager = new ODPSegmentManager(mockApiManager, mockCache); + segmentManager.updateSettings(odpConfig); + segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId", segments -> { + assertEquals(Arrays.asList("segment1", "segment2"), segments); + countDownLatch.countDown(); + }, Arrays.asList(ODPSegmentOption.RESET_CACHE, ODPSegmentOption.IGNORE_CACHE)); + + countDownLatch.await(); + + // Call reset + verify(mockCache, times(1)).reset(); + + verify(mockCache, times(0)).lookup(any()); + + // Cache is also Ignored! Make API Call but do not save + verify(mockApiManager, times(1)) + .fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + "/v3/graphql", "fs_user_id", "testId", new HashSet<>(Arrays.asList("segment1", "segment2"))); + verify(mockCache, times(0)).save(any(), any()); + } + + @Test + public void odpConfigNotReadyAsync() throws InterruptedException { + CountDownLatch countDownLatch = new CountDownLatch(1); + Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); + + ODPConfig odpConfig = new ODPConfig(null, null, new HashSet<>(Arrays.asList("segment1", "segment2"))); + ODPSegmentManager segmentManager = new ODPSegmentManager(mockApiManager, mockCache); + segmentManager.updateSettings(odpConfig); + segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId", segments -> { + assertNull(segments); + countDownLatch.countDown(); + }); + + countDownLatch.await(); + // No further methods should be called. + verify(mockCache, times(0)).lookup("fs_user_id-$-testId"); + verify(mockApiManager, times(0)).fetchQualifiedSegments(any(), any(), any(), any(), any()); + verify(mockCache, times(0)).save(any(), any()); + verify(mockCache, times(0)).reset(); + + logbackVerifier.expectMessage(Level.ERROR, "Audience segments fetch failed (ODP is not enabled)"); + } + + @Test + public void noSegmentsInProjectAsync() throws InterruptedException { + CountDownLatch countDownLatch = new CountDownLatch(1); + Mockito.when(mockCache.lookup(any())).thenReturn(Arrays.asList("segment1-cached", "segment2-cached")); + + ODPConfig odpConfig = new ODPConfig("testKey", "testHost", null); + ODPSegmentManager segmentManager = new ODPSegmentManager(mockApiManager, mockCache); + segmentManager.updateSettings(odpConfig); + segmentManager.getQualifiedSegments(ODPUserKey.FS_USER_ID, "testId", segments -> { + assertEquals(Collections.emptyList(), segments); + countDownLatch.countDown(); + }); + + countDownLatch.await(); + + // No further methods should be called. + verify(mockCache, times(0)).lookup("fs_user_id-$-testId"); + verify(mockApiManager, times(0)).fetchQualifiedSegments(any(), any(), any(), any(), any()); + verify(mockCache, times(0)).save(any(), any()); + verify(mockCache, times(0)).reset(); + + logbackVerifier.expectMessage(Level.DEBUG, "No Segments are used in the project, Not Fetching segments. Returning empty list"); + } } diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyFactory.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyFactory.java index 2e888e9bb..37d56da03 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyFactory.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyFactory.java @@ -23,6 +23,9 @@ import com.optimizely.ab.event.EventHandler; import com.optimizely.ab.internal.PropertyUtils; import com.optimizely.ab.notification.NotificationCenter; +import com.optimizely.ab.odp.DefaultODPApiManager; +import com.optimizely.ab.odp.ODPApiManager; +import com.optimizely.ab.odp.ODPManager; import org.apache.http.impl.client.CloseableHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -319,10 +322,16 @@ public static Optimizely newDefaultInstance(ProjectConfigManager configManager, .withNotificationCenter(notificationCenter) .build(); + ODPApiManager defaultODPApiManager = new DefaultODPApiManager(); + ODPManager odpManager = ODPManager.builder() + .withApiManager(defaultODPApiManager) + .build(); + return Optimizely.builder() .withEventProcessor(eventProcessor) .withConfigManager(configManager) .withNotificationCenter(notificationCenter) + .withODPManager(odpManager) .build(); } } diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java index 07ee1b3eb..576701066 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java @@ -27,7 +27,8 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; -import java.util.List; +import java.util.Iterator; +import java.util.Set; public class DefaultODPApiManager implements ODPApiManager { private static final Logger logger = LoggerFactory.getLogger(DefaultODPApiManager.class); @@ -44,13 +45,15 @@ public DefaultODPApiManager() { } @VisibleForTesting - String getSegmentsStringForRequest(List segmentsList) { + String getSegmentsStringForRequest(Set segmentsList) { + StringBuilder segmentsString = new StringBuilder(); + Iterator segmentsListIterator = segmentsList.iterator(); for (int i = 0; i < segmentsList.size(); i++) { if (i > 0) { segmentsString.append(", "); } - segmentsString.append("\\\"").append(segmentsList.get(i)).append("\\\""); + segmentsString.append("\"").append(segmentsListIterator.next()).append("\""); } return segmentsString.toString(); } @@ -129,10 +132,14 @@ String getSegmentsStringForRequest(List segmentsList) { } */ @Override - public String fetchQualifiedSegments(String apiKey, String apiEndpoint, String userKey, String userValue, List segmentsToCheck) { + public String fetchQualifiedSegments(String apiKey, String apiEndpoint, String userKey, String userValue, Set segmentsToCheck) { HttpPost request = new HttpPost(apiEndpoint); String segmentsString = getSegmentsStringForRequest(segmentsToCheck); - String requestPayload = String.format("{\"query\": \"query {customer(%s: \\\"%s\\\") {audiences(subset: [%s]) {edges {node {name state}}}}}\"}", userKey, userValue, segmentsString); + + String query = String.format("query($userId: String, $audiences: [String]) {customer(%s: $userId) {audiences(subset: $audiences) {edges {node {name state}}}}}", userKey); + String variables = String.format("{\"userId\": \"%s\", \"audiences\": [%s]}", userValue, segmentsString); + String requestPayload = String.format("{\"query\": \"%s\", \"variables\": %s}", query, variables); + try { request.setEntity(new StringEntity(requestPayload)); } catch (UnsupportedEncodingException e) { diff --git a/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java b/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java index 77440f804..638a3e1ee 100644 --- a/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java +++ b/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java @@ -30,6 +30,7 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.HashSet; import static org.junit.Assert.*; import static org.mockito.Matchers.any; @@ -64,33 +65,33 @@ private void setupHttpClient(int statusCode) throws Exception { @Test public void generateCorrectSegmentsStringWhenListHasOneItem() { DefaultODPApiManager apiManager = new DefaultODPApiManager(); - String expected = "\\\"only_segment\\\""; - String actual = apiManager.getSegmentsStringForRequest(Arrays.asList("only_segment")); + String expected = "\"only_segment\""; + String actual = apiManager.getSegmentsStringForRequest(new HashSet<>(Arrays.asList("only_segment"))); assertEquals(expected, actual); } @Test public void generateCorrectSegmentsStringWhenListHasMultipleItems() { DefaultODPApiManager apiManager = new DefaultODPApiManager(); - String expected = "\\\"segment_1\\\", \\\"segment_2\\\", \\\"segment_3\\\""; - String actual = apiManager.getSegmentsStringForRequest(Arrays.asList("segment_1", "segment_2", "segment_3")); + String expected = "\"segment_1\", \"segment_3\", \"segment_2\""; + String actual = apiManager.getSegmentsStringForRequest(new HashSet<>(Arrays.asList("segment_1", "segment_2", "segment_3"))); assertEquals(expected, actual); } @Test public void generateEmptyStringWhenGivenListIsEmpty() { DefaultODPApiManager apiManager = new DefaultODPApiManager(); - String actual = apiManager.getSegmentsStringForRequest(new ArrayList<>()); + String actual = apiManager.getSegmentsStringForRequest(new HashSet<>()); assertEquals("", actual); } @Test public void generateCorrectRequestBody() throws Exception { ODPApiManager apiManager = new DefaultODPApiManager(mockHttpClient); - apiManager.fetchQualifiedSegments("key", "endPoint", "fs_user_id", "test_user", Arrays.asList("segment_1", "segment_2")); + apiManager.fetchQualifiedSegments("key", "endPoint", "fs_user_id", "test_user", new HashSet<>(Arrays.asList("segment_1", "segment_2"))); verify(mockHttpClient, times(1)).execute(any(HttpPost.class)); - String expectedResponse = "{\"query\": \"query {customer(fs_user_id: \\\"test_user\\\") {audiences(subset: [\\\"segment_1\\\", \\\"segment_2\\\"]) {edges {node {name state}}}}}\"}"; + String expectedResponse = "{\"query\": \"query($userId: String, $audiences: [String]) {customer(fs_user_id: $userId) {audiences(subset: $audiences) {edges {node {name state}}}}}\", \"variables\": {\"userId\": \"test_user\", \"audiences\": [\"segment_1\", \"segment_2\"]}}"; ArgumentCaptor request = ArgumentCaptor.forClass(HttpPost.class); verify(mockHttpClient).execute(request.capture()); assertEquals(expectedResponse, EntityUtils.toString(request.getValue().getEntity())); @@ -99,7 +100,7 @@ public void generateCorrectRequestBody() throws Exception { @Test public void returnResponseStringWhenStatusIs200() throws Exception { ODPApiManager apiManager = new DefaultODPApiManager(mockHttpClient); - String responseString = apiManager.fetchQualifiedSegments("key", "endPoint", "fs_user_id", "test_user", Arrays.asList("segment_1", "segment_2")); + String responseString = apiManager.fetchQualifiedSegments("key", "endPoint", "fs_user_id", "test_user", new HashSet<>(Arrays.asList("segment_1", "segment_2"))); verify(mockHttpClient, times(1)).execute(any(HttpPost.class)); assertEquals(validResponse, responseString); } @@ -108,7 +109,7 @@ public void returnResponseStringWhenStatusIs200() throws Exception { public void returnNullWhenStatusIsNot200AndLogError() throws Exception { setupHttpClient(500); ODPApiManager apiManager = new DefaultODPApiManager(mockHttpClient); - String responseString = apiManager.fetchQualifiedSegments("key", "endPoint", "fs_user_id", "test_user", Arrays.asList("segment_1", "segment_2")); + String responseString = apiManager.fetchQualifiedSegments("key", "endPoint", "fs_user_id", "test_user", new HashSet<>(Arrays.asList("segment_1", "segment_2"))); verify(mockHttpClient, times(1)).execute(any(HttpPost.class)); logbackVerifier.expectMessage(Level.ERROR, "Unexpected response from ODP server, Response code: 500, null"); assertNull(responseString); From 42039e22f8ce497afb1f483ad90109c976443e9a Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Tue, 29 Nov 2022 16:12:00 -0800 Subject: [PATCH 25/80] skip unit and fsc tests for snapshot and publish (#493) --- .github/workflows/java.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml index af0dccf0a..1c6c57a02 100644 --- a/.github/workflows/java.yml +++ b/.github/workflows/java.yml @@ -30,12 +30,14 @@ jobs: run: find . -type f -name '*.md' -exec awesome_bot {} \; integration_tests: + if: ${{ startsWith(github.ref, 'refs/tags/') != true && github.event.inputs.SNAPSHOT != 'true' }} uses: optimizely/java-sdk/.github/workflows/integration_test.yml@mnoman/fsc-gitaction-test secrets: CI_USER_TOKEN: ${{ secrets.CI_USER_TOKEN }} TRAVIS_COM_TOKEN: ${{ secrets.TRAVIS_COM_TOKEN }} fullstack_production_suite: + if: ${{ startsWith(github.ref, 'refs/tags/') != true && github.event.inputs.SNAPSHOT != 'true' }} uses: optimizely/java-sdk/.github/workflows/integration_test.yml@master with: FULLSTACK_TEST_REPO: ProdTesting @@ -44,7 +46,7 @@ jobs: TRAVIS_COM_TOKEN: ${{ secrets.TRAVIS_COM_TOKEN }} test: - if: startsWith(github.ref, 'refs/tags/') != true + if: ${{ startsWith(github.ref, 'refs/tags/') != true && github.event.inputs.SNAPSHOT != 'true' }} runs-on: macos-latest strategy: fail-fast: false From c68a55420331e6e1cc66319631551c03d9df243d Mon Sep 17 00:00:00 2001 From: Zeeshan Ashraf <35262377+zashraf1985@users.noreply.github.com> Date: Wed, 14 Dec 2022 19:59:27 -0800 Subject: [PATCH 26/80] feat: Added configurable timeouts for fetchSegments and dispatch events ODP calls (#494) ## Summary Added configurable timeouts for fetchSegments and dispatch events ODP calls. The default timeout is 10s. ## Test plan - Manually tested thoroughly - All test pass ## Issues [FSSDK-8689](https://jira.sso.episerver.net/browse/FSSDK-8689) --- .../com/optimizely/ab/HttpClientUtils.java | 19 +++++++++++++++--- .../optimizely/ab/OptimizelyHttpClient.java | 16 +++++++++++++-- .../ab/odp/DefaultODPApiManager.java | 20 +++++++++++++++---- .../ab/odp/DefaultODPApiManagerTest.java | 17 +++++++++++++++- 4 files changed, 62 insertions(+), 10 deletions(-) diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/HttpClientUtils.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/HttpClientUtils.java index 8a4d104d5..c35bb4b3f 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/HttpClientUtils.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/HttpClientUtils.java @@ -23,9 +23,11 @@ */ public final class HttpClientUtils { - private static final int CONNECTION_TIMEOUT_MS = 10000; - private static final int CONNECTION_REQUEST_TIMEOUT_MS = 5000; - private static final int SOCKET_TIMEOUT_MS = 10000; + public static final int CONNECTION_TIMEOUT_MS = 10000; + public static final int CONNECTION_REQUEST_TIMEOUT_MS = 5000; + public static final int SOCKET_TIMEOUT_MS = 10000; + + private static RequestConfig requestConfigWithTimeout; private HttpClientUtils() { } @@ -36,6 +38,17 @@ private HttpClientUtils() { .setSocketTimeout(SOCKET_TIMEOUT_MS) .build(); + public static RequestConfig getDefaultRequestConfigWithTimeout(int timeoutMillis) { + if (requestConfigWithTimeout == null) { + requestConfigWithTimeout = RequestConfig.custom() + .setConnectTimeout(timeoutMillis) + .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT_MS) + .setSocketTimeout(SOCKET_TIMEOUT_MS) + .build(); + } + return requestConfigWithTimeout; + } + public static OptimizelyHttpClient getDefaultHttpClient() { return OptimizelyHttpClient.builder().build(); } diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyHttpClient.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyHttpClient.java index 37c2163ac..f4040276f 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyHttpClient.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyHttpClient.java @@ -1,6 +1,6 @@ /** * - * Copyright 2019, Optimizely + * Copyright 2019, 2022 Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,8 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; @@ -38,6 +40,8 @@ */ public class OptimizelyHttpClient implements Closeable { + private static final Logger logger = LoggerFactory.getLogger(OptimizelyHttpClient.class); + private final CloseableHttpClient httpClient; OptimizelyHttpClient(CloseableHttpClient httpClient) { @@ -78,6 +82,7 @@ public static class Builder { // force-close the connection after this idle time (with 0, eviction is disabled by default) long evictConnectionIdleTimePeriod = 0; TimeUnit evictConnectionIdleTimeUnit = TimeUnit.MILLISECONDS; + private int timeoutMillis = HttpClientUtils.CONNECTION_TIMEOUT_MS; private Builder() { @@ -103,6 +108,11 @@ public Builder withEvictIdleConnections(long maxIdleTime, TimeUnit maxIdleTimeUn this.evictConnectionIdleTimeUnit = maxIdleTimeUnit; return this; } + + public Builder setTimeoutMillis(int timeoutMillis) { + this.timeoutMillis = timeoutMillis; + return this; + } public OptimizelyHttpClient build() { PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(); @@ -111,11 +121,13 @@ public OptimizelyHttpClient build() { poolingHttpClientConnectionManager.setValidateAfterInactivity(validateAfterInactivity); HttpClientBuilder builder = HttpClients.custom() - .setDefaultRequestConfig(HttpClientUtils.DEFAULT_REQUEST_CONFIG) + .setDefaultRequestConfig(HttpClientUtils.getDefaultRequestConfigWithTimeout(timeoutMillis)) .setConnectionManager(poolingHttpClientConnectionManager) .disableCookieManagement() .useSystemProperties(); + logger.debug("Creating HttpClient with timeout: " + timeoutMillis); + if (evictConnectionIdleTimePeriod > 0) { builder.evictIdleConnections(evictConnectionIdleTimePeriod, evictConnectionIdleTimeUnit); } diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java index 576701066..636ed8eec 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java @@ -33,15 +33,27 @@ public class DefaultODPApiManager implements ODPApiManager { private static final Logger logger = LoggerFactory.getLogger(DefaultODPApiManager.class); - private final OptimizelyHttpClient httpClient; + private final OptimizelyHttpClient httpClientSegments; + private final OptimizelyHttpClient httpClientEvents; public DefaultODPApiManager() { this(OptimizelyHttpClient.builder().build()); } + public DefaultODPApiManager(int segmentFetchTimeoutMillis, int eventDispatchTimeoutMillis) { + httpClientSegments = OptimizelyHttpClient.builder().setTimeoutMillis(segmentFetchTimeoutMillis).build(); + if (segmentFetchTimeoutMillis == eventDispatchTimeoutMillis) { + // If the timeouts are same, single httpClient can be used for both. + httpClientEvents = httpClientSegments; + } else { + httpClientEvents = OptimizelyHttpClient.builder().setTimeoutMillis(eventDispatchTimeoutMillis).build(); + } + } + @VisibleForTesting DefaultODPApiManager(OptimizelyHttpClient httpClient) { - this.httpClient = httpClient; + this.httpClientSegments = httpClient; + this.httpClientEvents = httpClient; } @VisibleForTesting @@ -150,7 +162,7 @@ public String fetchQualifiedSegments(String apiKey, String apiEndpoint, String u CloseableHttpResponse response = null; try { - response = httpClient.execute(request); + response = httpClientSegments.execute(request); } catch (IOException e) { logger.error("Error retrieving response from ODP service", e); return null; @@ -211,7 +223,7 @@ public Integer sendEvents(String apiKey, String apiEndpoint, String eventPayload CloseableHttpResponse response = null; try { - response = httpClient.execute(request); + response = httpClientEvents.execute(request); } catch (IOException e) { logger.error("Error retrieving response from event request", e); return 0; diff --git a/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java b/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java index 638a3e1ee..93b728fba 100644 --- a/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java +++ b/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java @@ -28,7 +28,6 @@ import org.junit.Test; import org.mockito.ArgumentCaptor; -import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; @@ -129,4 +128,20 @@ public void eventDispatchFailStatus() throws Exception { apiManager.sendEvents("testKey", "testEndpoint", "[]]"); logbackVerifier.expectMessage(Level.ERROR, "ODP event send failed (Response code: 400, null)"); } + + @Test + public void apiTimeouts() { + // Default timeout is 10 seconds + new DefaultODPApiManager(); + logbackVerifier.expectMessage(Level.DEBUG, "Creating HttpClient with timeout: 10000", 1); + + // Same timeouts result in single httpclient + new DefaultODPApiManager(2222, 2222); + logbackVerifier.expectMessage(Level.DEBUG, "Creating HttpClient with timeout: 2222", 1); + + // Different timeouts result in different HttpClients + new DefaultODPApiManager(3333, 4444); + logbackVerifier.expectMessage(Level.DEBUG, "Creating HttpClient with timeout: 3333", 1); + logbackVerifier.expectMessage(Level.DEBUG, "Creating HttpClient with timeout: 4444", 1); + } } From 3c14dde2d728a0a6b7f5bb89b429305d7a5e75e4 Mon Sep 17 00:00:00 2001 From: Zeeshan Ashraf <35262377+zashraf1985@users.noreply.github.com> Date: Tue, 20 Dec 2022 18:54:50 -0800 Subject: [PATCH 27/80] fix: Fixed ODP Event type and Json Parser log levels (#495) ## Summary 1. Changed default event type from `client_initialized` to `identified`. 2. Changed Parser log levels from `info` to `debug`. ## Test plan - Manually tested thoroughly. - All existing unit tests and FSC test pass. ## Issues https://jira.sso.episerver.net/browse/FSSDK-8725 https://jira.sso.episerver.net/browse/FSSDK-8726 --- .../java/com/optimizely/ab/internal/JsonParserProvider.java | 2 +- .../src/main/java/com/optimizely/ab/odp/ODPEventManager.java | 2 +- .../com/optimizely/ab/odp/parser/ResponseJsonParserFactory.java | 2 +- .../test/java/com/optimizely/ab/odp/ODPEventManagerTest.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/internal/JsonParserProvider.java b/core-api/src/main/java/com/optimizely/ab/internal/JsonParserProvider.java index 6f6de6516..8bde2ac66 100644 --- a/core-api/src/main/java/com/optimizely/ab/internal/JsonParserProvider.java +++ b/core-api/src/main/java/com/optimizely/ab/internal/JsonParserProvider.java @@ -64,7 +64,7 @@ public static JsonParserProvider getDefaultParser() { continue; } - logger.info("using json parser: {}", parser.className); + logger.debug("using json parser: {}", parser.className); return parser; } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java index b2a9a658b..0ae441c44 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java @@ -91,7 +91,7 @@ public void identifyUser(@Nullable String vuid, @Nullable String userId) { if (userId != null) { identifiers.put(ODPUserKey.FS_USER_ID.getKeyString(), userId); } - ODPEvent event = new ODPEvent("fullstack", "client_initialized", identifiers, null); + ODPEvent event = new ODPEvent("fullstack", "identified", identifiers, null); sendEvent(event); } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactory.java b/core-api/src/main/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactory.java index 7762cef0e..111c7ae85 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactory.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/parser/ResponseJsonParserFactory.java @@ -43,7 +43,7 @@ public static ResponseJsonParser getParser() { jsonParser = new JsonSimpleParser(); break; } - logger.info("Using " + parserProvider.toString() + " parser"); + logger.debug("Using " + parserProvider.toString() + " parser"); return jsonParser; } } diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java index d6941671f..17c489dd4 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java @@ -204,7 +204,7 @@ public void prepareCorrectPayloadForIdentifyUser() throws InterruptedException { for (int i = 0; i < events.length(); i++) { JSONObject event = events.getJSONObject(i); assertEquals("fullstack", event.getString("type")); - assertEquals("client_initialized", event.getString("action")); + assertEquals("identified", event.getString("action")); assertEquals("the-vuid-" + i, event.getJSONObject("identifiers").getString("vuid")); assertEquals("the-fs-user-id-" + i, event.getJSONObject("identifiers").getString("fs_user_id")); assertEquals("sdk", event.getJSONObject("data").getString("data_source_type")); From f63cff509fe2049b8256d71935d5fc43e2aa69d3 Mon Sep 17 00:00:00 2001 From: Zeeshan Ashraf <35262377+zashraf1985@users.noreply.github.com> Date: Fri, 6 Jan 2023 11:34:12 -0800 Subject: [PATCH 28/80] fix: ODP - getQualifiedSegments should return null when fetch fails (#496) --- .../java/com/optimizely/ab/Optimizely.java | 18 ++++++++---- .../optimizely/ab/OptimizelyUserContext.java | 28 ++++++++++++------- .../ab/OptimizelyUserContextTest.java | 4 +-- 3 files changed, 33 insertions(+), 17 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/Optimizely.java b/core-api/src/main/java/com/optimizely/ab/Optimizely.java index 0fbacaa3b..12b9f33d1 100644 --- a/core-api/src/main/java/com/optimizely/ab/Optimizely.java +++ b/core-api/src/main/java/com/optimizely/ab/Optimizely.java @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright 2016-2022, Optimizely, Inc. and contributors * + * Copyright 2016-2023, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * @@ -436,7 +436,7 @@ private Boolean isFeatureEnabled(@Nonnull ProjectConfig projectConfig, Map copiedAttributes = copyAttributes(attributes); FeatureDecision.DecisionSource decisionSource = FeatureDecision.DecisionSource.ROLLOUT; - FeatureDecision featureDecision = decisionService.getVariationForFeature(featureFlag, createUserContext(userId, copiedAttributes), projectConfig).getResult(); + FeatureDecision featureDecision = decisionService.getVariationForFeature(featureFlag, createUserContextCopy(userId, copiedAttributes), projectConfig).getResult(); Boolean featureEnabled = false; SourceInfo sourceInfo = new RolloutSourceInfo(); if (featureDecision.decisionSource != null) { @@ -745,7 +745,7 @@ T getFeatureVariableValueForType(@Nonnull String featureKey, String variableValue = variable.getDefaultValue(); Map copiedAttributes = copyAttributes(attributes); - FeatureDecision featureDecision = decisionService.getVariationForFeature(featureFlag, createUserContext(userId, copiedAttributes), projectConfig).getResult(); + FeatureDecision featureDecision = decisionService.getVariationForFeature(featureFlag, createUserContextCopy(userId, copiedAttributes), projectConfig).getResult(); Boolean featureEnabled = false; if (featureDecision.variation != null) { if (featureDecision.variation.getFeatureEnabled()) { @@ -880,7 +880,7 @@ public OptimizelyJSON getAllFeatureVariables(@Nonnull String featureKey, } Map copiedAttributes = copyAttributes(attributes); - FeatureDecision featureDecision = decisionService.getVariationForFeature(featureFlag, createUserContext(userId, copiedAttributes), projectConfig, Collections.emptyList()).getResult(); + FeatureDecision featureDecision = decisionService.getVariationForFeature(featureFlag, createUserContextCopy(userId, copiedAttributes), projectConfig, Collections.emptyList()).getResult(); Boolean featureEnabled = false; Variation variation = featureDecision.variation; @@ -982,7 +982,7 @@ private Variation getVariation(@Nonnull ProjectConfig projectConfig, @Nonnull String userId, @Nonnull Map attributes) throws UnknownExperimentException { Map copiedAttributes = copyAttributes(attributes); - Variation variation = decisionService.getVariation(experiment, createUserContext(userId, copiedAttributes), projectConfig).getResult(); + Variation variation = decisionService.getVariation(experiment, createUserContextCopy(userId, copiedAttributes), projectConfig).getResult(); String notificationType = NotificationCenter.DecisionNotificationType.AB_TEST.toString(); if (projectConfig.getExperimentFeatureKeyMapping().get(experiment.getId()) != null) { @@ -1172,6 +1172,14 @@ public OptimizelyUserContext createUserContext(@Nonnull String userId) { return new OptimizelyUserContext(this, userId); } + private OptimizelyUserContext createUserContextCopy(@Nonnull String userId, @Nonnull Map attributes) { + if (userId == null) { + logger.warn("The userId parameter must be nonnull."); + return null; + } + return new OptimizelyUserContext(this, userId, attributes, Collections.EMPTY_MAP, null, false); + } + OptimizelyDecision decide(@Nonnull OptimizelyUserContext user, @Nonnull String key, @Nonnull List options) { diff --git a/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java b/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java index 5ba15b5b4..7cb8753f4 100644 --- a/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java +++ b/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java @@ -1,6 +1,6 @@ /** * - * Copyright 2020-2022, Optimizely and contributors + * Copyright 2020-2023, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,7 +76,9 @@ public OptimizelyUserContext(@Nonnull Optimizely optimizely, this.forcedDecisionsMap = new ConcurrentHashMap<>(forcedDecisionsMap); } - this.qualifiedSegments = Collections.synchronizedList( qualifiedSegments == null ? new LinkedList<>(): qualifiedSegments); + if (qualifiedSegments != null) { + this.qualifiedSegments = Collections.synchronizedList(new LinkedList<>(qualifiedSegments)); + } if (shouldIdentifyUser == null || shouldIdentifyUser) { optimizely.identifyUser(userId); @@ -109,6 +111,10 @@ public OptimizelyUserContext copy() { * @return boolean Is user qualified for a segment. */ public boolean isQualifiedFor(@Nonnull String segment) { + if (qualifiedSegments == null) { + return false; + } + return qualifiedSegments.contains(segment); } @@ -293,8 +299,14 @@ public List getQualifiedSegments() { } public void setQualifiedSegments(List qualifiedSegments) { - this.qualifiedSegments.clear(); - this.qualifiedSegments.addAll(qualifiedSegments); + if (qualifiedSegments == null) { + this.qualifiedSegments = null; + } else if (this.qualifiedSegments == null) { + this.qualifiedSegments = Collections.synchronizedList(new LinkedList<>(qualifiedSegments)); + } else { + this.qualifiedSegments.clear(); + this.qualifiedSegments.addAll(qualifiedSegments); + } } /** @@ -315,9 +327,7 @@ public Boolean fetchQualifiedSegments() { */ public Boolean fetchQualifiedSegments(@Nonnull List segmentOptions) { List segments = optimizely.fetchQualifiedSegments(userId, segmentOptions); - if (segments != null) { - setQualifiedSegments(segments); - } + setQualifiedSegments(segments); return segments != null; } @@ -332,9 +342,7 @@ public Boolean fetchQualifiedSegments(@Nonnull List segmentOpt */ public void fetchQualifiedSegments(ODPSegmentCallback callback, List segmentOptions) { optimizely.fetchQualifiedSegments(userId, segments -> { - if (segments != null) { - setQualifiedSegments(segments); - } + setQualifiedSegments(segments); callback.onCompleted(segments != null); }, segmentOptions); } diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java index 5dd47a8cf..8f8bae834 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java @@ -1,6 +1,6 @@ /** * - * Copyright 2021-2022, Optimizely and contributors + * Copyright 2021-2023, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -1709,7 +1709,7 @@ public void fetchQualifiedSegmentsAsyncError() throws InterruptedException { }); countDownLatch.await(); - assertEquals(Collections.emptyList(), userContext.getQualifiedSegments()); + assertEquals(null, userContext.getQualifiedSegments()); logbackVerifier.expectMessage(Level.ERROR, "Audience segments fetch failed (ODP is not enabled)."); } From 395e8c9a71dfdfea3f77e6ca13c9737e1ed2910b Mon Sep 17 00:00:00 2001 From: Zeeshan Ashraf <35262377+zashraf1985@users.noreply.github.com> Date: Fri, 6 Jan 2023 11:58:17 -0800 Subject: [PATCH 29/80] Made ODP Event Dispatcher a daemon thread (#497) --- .../java/com/optimizely/ab/odp/ODPEventManager.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java index 0ae441c44..ae034fd68 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java @@ -68,7 +68,13 @@ public void start() { eventDispatcherThread = new EventDispatcherThread(); } if (!isRunning) { - eventDispatcherThread.start(); + final ThreadFactory threadFactory = Executors.defaultThreadFactory(); + ExecutorService executor = Executors.newSingleThreadExecutor(runnable -> { + Thread thread = threadFactory.newThread(runnable); + thread.setDaemon(true); + return thread; + }); + executor.submit(eventDispatcherThread); } isRunning = true; } @@ -159,7 +165,7 @@ public void run() { if (currentBatch.size() > 0) { nextEvent = eventQueue.poll(nextFlushTime - new Date().getTime(), TimeUnit.MILLISECONDS); } else { - nextEvent = eventQueue.poll(); + nextEvent = eventQueue.take(); } if (nextEvent == null) { From 3f7c53c223a3cd38e4db7242a2b3ab02c90cd046 Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Sat, 7 Jan 2023 02:18:20 +0500 Subject: [PATCH 30/80] Fix: Removed null check from getDefaultRequestConfigWithTimeout to create separate request configs (#498) --- .../java/com/optimizely/ab/HttpClientUtils.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/HttpClientUtils.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/HttpClientUtils.java index c35bb4b3f..dc786c4f6 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/HttpClientUtils.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/HttpClientUtils.java @@ -1,6 +1,6 @@ /** * - * Copyright 2016-2017, 2019, Optimizely and contributors + * Copyright 2016-2017, 2019, 2022-2023, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,13 +39,11 @@ private HttpClientUtils() { .build(); public static RequestConfig getDefaultRequestConfigWithTimeout(int timeoutMillis) { - if (requestConfigWithTimeout == null) { - requestConfigWithTimeout = RequestConfig.custom() - .setConnectTimeout(timeoutMillis) - .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT_MS) - .setSocketTimeout(SOCKET_TIMEOUT_MS) - .build(); - } + requestConfigWithTimeout = RequestConfig.custom() + .setConnectTimeout(timeoutMillis) + .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT_MS) + .setSocketTimeout(timeoutMillis) + .build(); return requestConfigWithTimeout; } From ac27ae795ca4f6fc028270270af9d593b10c9c79 Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Tue, 17 Jan 2023 22:15:35 +0500 Subject: [PATCH 31/80] removed setting up batchSize and it will set it to 1 when you set flushInterval to 0 (#500) --- .../optimizely/ab/odp/ODPEventManager.java | 8 +++---- .../ab/odp/ODPEventManagerTest.java | 22 +++++++++---------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java index ae034fd68..a0129f925 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java @@ -1,6 +1,6 @@ /** * - * Copyright 2022, Optimizely + * Copyright 2022-2023, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,14 +53,14 @@ public class ODPEventManager { private final BlockingQueue eventQueue = new LinkedBlockingQueue<>(); public ODPEventManager(@Nonnull ODPApiManager apiManager) { - this(apiManager, null, null, null); + this(apiManager, null, null); } - public ODPEventManager(@Nonnull ODPApiManager apiManager, @Nullable Integer batchSize, @Nullable Integer queueSize, @Nullable Integer flushInterval) { + public ODPEventManager(@Nonnull ODPApiManager apiManager, @Nullable Integer queueSize, @Nullable Integer flushInterval) { this.apiManager = apiManager; - this.batchSize = (batchSize != null && batchSize > 1) ? batchSize : DEFAULT_BATCH_SIZE; this.queueSize = queueSize != null ? queueSize : DEFAULT_QUEUE_SIZE; this.flushInterval = (flushInterval != null && flushInterval > 0) ? flushInterval : DEFAULT_FLUSH_INTERVAL; + this.batchSize = (flushInterval != null && flushInterval == 0) ? 1 : DEFAULT_BATCH_SIZE; } public void start() { diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java index 17c489dd4..ff970c846 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java @@ -96,23 +96,23 @@ public void dispatchEventsInCorrectNumberOfBatches() throws InterruptedException public void dispatchEventsWithCorrectPayload() throws InterruptedException { Mockito.reset(mockApiManager); Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); - int batchSize = 2; + int flushInterval = 0; ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); - ODPEventManager eventManager = new ODPEventManager(mockApiManager, batchSize, null, null); + ODPEventManager eventManager = new ODPEventManager(mockApiManager, null, flushInterval); eventManager.updateSettings(odpConfig); eventManager.start(); for (int i = 0; i < 6; i++) { eventManager.sendEvent(getEvent(i)); } Thread.sleep(500); - Mockito.verify(mockApiManager, times(3)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), payloadCaptor.capture()); + Mockito.verify(mockApiManager, times(6)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), payloadCaptor.capture()); List payloads = payloadCaptor.getAllValues(); for (int i = 0; i < payloads.size(); i++) { JSONArray events = new JSONArray(payloads.get(i)); - assertEquals(batchSize, events.length()); + assertEquals(1, events.length()); for (int j = 0; j < events.length(); j++) { - int id = (batchSize * i) + j; + int id = (1 * i) + j; JSONObject event = events.getJSONObject(j); assertEquals("test-type-" + id , event.getString("type")); assertEquals("test-action-" + id , event.getString("action")); @@ -186,9 +186,9 @@ public void shouldFlushAllScheduledEventsBeforeStopping() throws InterruptedExce public void prepareCorrectPayloadForIdentifyUser() throws InterruptedException { Mockito.reset(mockApiManager); Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); - int batchSize = 2; + int flushInterval = 0; ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); - ODPEventManager eventManager = new ODPEventManager(mockApiManager, batchSize, null, null); + ODPEventManager eventManager = new ODPEventManager(mockApiManager, null, flushInterval); eventManager.updateSettings(odpConfig); eventManager.start(); for (int i = 0; i < 2; i++) { @@ -196,17 +196,17 @@ public void prepareCorrectPayloadForIdentifyUser() throws InterruptedException { } Thread.sleep(1500); - Mockito.verify(mockApiManager, times(1)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), payloadCaptor.capture()); + Mockito.verify(mockApiManager, times(2)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), payloadCaptor.capture()); String payload = payloadCaptor.getValue(); JSONArray events = new JSONArray(payload); - assertEquals(batchSize, events.length()); + assertEquals(1, events.length()); for (int i = 0; i < events.length(); i++) { JSONObject event = events.getJSONObject(i); assertEquals("fullstack", event.getString("type")); assertEquals("identified", event.getString("action")); - assertEquals("the-vuid-" + i, event.getJSONObject("identifiers").getString("vuid")); - assertEquals("the-fs-user-id-" + i, event.getJSONObject("identifiers").getString("fs_user_id")); + assertEquals("the-vuid-" + (i + 1), event.getJSONObject("identifiers").getString("vuid")); + assertEquals("the-fs-user-id-" + (i + 1), event.getJSONObject("identifiers").getString("fs_user_id")); assertEquals("sdk", event.getJSONObject("data").getString("data_source_type")); } } From cbe85de051193c0d02539fad08962778233b9592 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Tue, 17 Jan 2023 10:50:28 -0800 Subject: [PATCH 32/80] feat(ats): add support for android ODP events (#502) Add support for Android-SDK ODP integration, which may not be implemented in the Android-SDK. 1. ODPManager.Builder.withExtraCommonData(commonData) - clients (android-sdk) will pass common data (client os, device type,...) which should be added into all ODPEvents. 2. ODPManager.Builder.withExtraCommonIdentifiers(commonIdentifiers) - clients (android-sdk) will pass common identifiers (vuid,...) which should be added into all ODPEvents. --- .../optimizely/ab/OptimizelyUserContext.java | 4 + .../java/com/optimizely/ab/odp/ODPEvent.java | 4 +- .../optimizely/ab/odp/ODPEventManager.java | 31 ++- .../com/optimizely/ab/odp/ODPManager.java | 32 +++ .../optimizelyconfig/OptimizelyFeature.java | 4 +- .../optimizely/ab/OptimizelyBuilderTest.java | 6 + .../ab/odp/ODPEventManagerTest.java | 195 +++++++++++++++++- .../ab/odp/ODPManagerBuilderTest.java | 27 ++- 8 files changed, 290 insertions(+), 13 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java b/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java index 7cb8753f4..e2c03b147 100644 --- a/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java +++ b/core-api/src/main/java/com/optimizely/ab/OptimizelyUserContext.java @@ -16,6 +16,7 @@ */ package com.optimizely.ab; +import com.optimizely.ab.config.ProjectConfig; import com.optimizely.ab.odp.ODPManager; import com.optimizely.ab.odp.ODPSegmentCallback; import com.optimizely.ab.odp.ODPSegmentOption; @@ -313,6 +314,8 @@ public void setQualifiedSegments(List qualifiedSegments) { * Fetch all qualified segments for the user context. *

* The segments fetched will be saved and can be accessed at any time by calling {@link #getQualifiedSegments()}. + * + * @return a boolean value for fetch success or failure. */ public Boolean fetchQualifiedSegments() { return fetchQualifiedSegments(Collections.emptyList()); @@ -324,6 +327,7 @@ public Boolean fetchQualifiedSegments() { * The segments fetched will be saved and can be accessed at any time by calling {@link #getQualifiedSegments()}. * * @param segmentOptions A set of options for fetching qualified segments. + * @return a boolean value for fetch success or failure. */ public Boolean fetchQualifiedSegments(@Nonnull List segmentOptions) { List segments = optimizely.fetchQualifiedSegments(userId, segmentOptions); diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java index a4dd37f2b..2ed2c1e76 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java @@ -1,5 +1,5 @@ /** - * Copyright 2022, Optimizely Inc. and contributors + * Copyright 2022-2023, Optimizely Inc. and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ public class ODPEvent { private String type; private String action; - private Map identifiers; + private Map identifiers; private Map data; public ODPEvent(@Nullable String type, @Nonnull String action, @Nullable Map identifiers, @Nullable Map data) { diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java index a0129f925..fbd39ffaf 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java @@ -16,6 +16,7 @@ */ package com.optimizely.ab.odp; +import com.optimizely.ab.annotations.VisibleForTesting; import com.optimizely.ab.event.internal.BuildVersionInfo; import com.optimizely.ab.event.internal.ClientEngineInfo; import com.optimizely.ab.odp.serializer.ODPJsonSerializerFactory; @@ -38,6 +39,8 @@ public class ODPEventManager { private final int queueSize; private final int batchSize; private final int flushInterval; + @Nonnull private Map userCommonData = Collections.emptyMap(); + @Nonnull private Map userCommonIdentifiers = Collections.emptyMap(); private Boolean isRunning = false; @@ -63,6 +66,16 @@ public ODPEventManager(@Nonnull ODPApiManager apiManager, @Nullable Integer queu this.batchSize = (flushInterval != null && flushInterval == 0) ? 1 : DEFAULT_BATCH_SIZE; } + // these user-provided common data are included in all ODP events in addition to the SDK-generated common data. + public void setUserCommonData(@Nullable Map commonData) { + if (commonData != null) this.userCommonData = commonData; + } + + // these user-provided common identifiers are included in all ODP events in addition to the SDK-generated identifiers. + public void setUserCommonIdentifiers(@Nullable Map commonIdentifiers) { + if (commonIdentifiers != null) this.userCommonIdentifiers = commonIdentifiers; + } + public void start() { if (eventDispatcherThread == null) { eventDispatcherThread = new EventDispatcherThread(); @@ -107,19 +120,35 @@ public void sendEvent(ODPEvent event) { return; } event.setData(augmentCommonData(event.getData())); + event.setIdentifiers(augmentCommonIdentifiers(event.getIdentifiers())); processEvent(event); } - private Map augmentCommonData(Map sourceData) { + @VisibleForTesting + Map augmentCommonData(Map sourceData) { + // priority: sourceData > userCommonData > sdkCommonData + Map data = new HashMap<>(); data.put("idempotence_id", UUID.randomUUID().toString()); data.put("data_source_type", "sdk"); data.put("data_source", ClientEngineInfo.getClientEngine().getClientEngineValue()); data.put("data_source_version", BuildVersionInfo.getClientVersion()); + + data.putAll(userCommonData); data.putAll(sourceData); return data; } + @VisibleForTesting + Map augmentCommonIdentifiers(Map sourceIdentifiers) { + // priority: sourceIdentifiers > userCommonIdentifiers + + Map identifiers = new HashMap<>(); + identifiers.putAll(userCommonIdentifiers); + identifiers.putAll(sourceIdentifiers); + return identifiers; + } + private void processEvent(ODPEvent event) { if (!isRunning) { logger.warn("Failed to Process ODP Event. ODPEventManager is not running"); diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java index 3e198a209..cacbcad0d 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java @@ -21,7 +21,9 @@ import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; +import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Set; public class ODPManager implements AutoCloseable { @@ -77,6 +79,8 @@ public static class Builder { private Integer cacheSize; private Integer cacheTimeoutSeconds; private Cache> cacheImpl; + private Map userCommonData; + private Map userCommonIdentifiers; /** * Provide a custom {@link ODPManager} instance which makes http calls to fetch segments and send events. @@ -156,6 +160,32 @@ public Builder withSegmentCache(Cache> cacheImpl) { return this; } + /** + * Provide an optional group of user data that should be included in all ODP events. + * + * Note that this is in addition to the default data that is automatically included in all ODP events by this SDK (sdk-name, sdk-version, etc). + * + * @param commonData A key-value map of common user data. + * @return ODPManager builder + */ + public Builder withUserCommonData(@Nonnull Map commonData) { + this.userCommonData = commonData; + return this; + } + + /** + * Provide an optional group of identifiers that should be included in all ODP events. + * + * Note that this is in addition to the identifiers that is automatically included in all ODP events by this SDK. + * + * @param commonIdentifiers A key-value map of common identifiers. + * @return ODPManager builder + */ + public Builder withUserCommonIdentifiers(@Nonnull Map commonIdentifiers) { + this.userCommonIdentifiers = commonIdentifiers; + return this; + } + public ODPManager build() { if ((segmentManager == null || eventManager == null) && apiManager == null) { logger.warn("ApiManager instance is needed when using default EventManager or SegmentManager"); @@ -182,6 +212,8 @@ public ODPManager build() { if (eventManager == null) { eventManager = new ODPEventManager(apiManager); } + eventManager.setUserCommonData(userCommonData); + eventManager.setUserCommonIdentifiers(userCommonIdentifiers); return new ODPManager(segmentManager, eventManager); } diff --git a/core-api/src/main/java/com/optimizely/ab/optimizelyconfig/OptimizelyFeature.java b/core-api/src/main/java/com/optimizely/ab/optimizelyconfig/OptimizelyFeature.java index 77a1f67fd..7dec828a6 100644 --- a/core-api/src/main/java/com/optimizely/ab/optimizelyconfig/OptimizelyFeature.java +++ b/core-api/src/main/java/com/optimizely/ab/optimizelyconfig/OptimizelyFeature.java @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright 2020-2021, Optimizely, Inc. and contributors * + * Copyright 2020-2021, 2023, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * @@ -63,6 +63,8 @@ public String getKey() { /** * @deprecated use {@link #getExperimentRules()} and {@link #getDeliveryRules()} instead + * + * @return a map of ExperimentKey to OptimizelyExperiment */ @Deprecated public Map getExperimentsMap() { diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java index 79382a5b7..566eec635 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java @@ -23,6 +23,8 @@ import com.optimizely.ab.event.EventHandler; import com.optimizely.ab.event.LogEvent; import com.optimizely.ab.event.internal.BuildVersionInfo; +import com.optimizely.ab.event.internal.ClientEngineInfo; +import com.optimizely.ab.event.internal.payload.Event; import com.optimizely.ab.event.internal.payload.EventBatch; import com.optimizely.ab.odp.ODPEventManager; import com.optimizely.ab.odp.ODPManager; @@ -241,6 +243,10 @@ public void withClientInfo() throws Exception { verify(eventHandler, timeout(5000)).dispatchEvent(argument.capture()); assertEquals(argument.getValue().getEventBatch().getClientName(), "android-sdk"); assertEquals(argument.getValue().getEventBatch().getClientVersion(), "1.2.3"); + + // restore the default values for other tests + ClientEngineInfo.setClientEngine(ClientEngineInfo.DEFAULT); + BuildVersionInfo.setClientVersion(BuildVersionInfo.VERSION); } @Test diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java index ff970c846..27de838f3 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java @@ -1,6 +1,6 @@ /** * - * Copyright 2022, Optimizely + * Copyright 2022-2023, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,9 @@ package com.optimizely.ab.odp; import ch.qos.logback.classic.Level; +import com.optimizely.ab.event.internal.BuildVersionInfo; +import com.optimizely.ab.event.internal.ClientEngineInfo; +import com.optimizely.ab.event.internal.payload.EventBatch; import com.optimizely.ab.internal.LogbackVerifier; import org.json.JSONArray; import org.json.JSONObject; @@ -30,10 +33,7 @@ import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; @@ -255,6 +255,191 @@ public void validateEventData() { assertFalse(event.isDataValid()); } + @Test + public void validateEventCommonData() { + Map sourceData = new HashMap<>(); + sourceData.put("k1", "v1"); + + Mockito.reset(mockApiManager); + ODPEventManager eventManager = new ODPEventManager(mockApiManager); + Map merged = eventManager.augmentCommonData(sourceData); + + assertEquals(merged.get("k1"), "v1"); + assertTrue(merged.get("idempotence_id").toString().length() > 16); + assertEquals(merged.get("data_source_type"), "sdk"); + assertEquals(merged.get("data_source"), "java-sdk"); + assertTrue(merged.get("data_source_version").toString().length() > 0); + assertEquals(merged.size(), 5); + + // when clientInfo is overridden (android-sdk): + + ClientEngineInfo.setClientEngine(EventBatch.ClientEngine.ANDROID_SDK); + BuildVersionInfo.setClientVersion("1.2.3"); + merged = eventManager.augmentCommonData(sourceData); + + assertEquals(merged.get("k1"), "v1"); + assertTrue(merged.get("idempotence_id").toString().length() > 16); + assertEquals(merged.get("data_source_type"), "sdk"); + assertEquals(merged.get("data_source"), "android-sdk"); + assertEquals(merged.get("data_source_version"), "1.2.3"); + assertEquals(merged.size(), 5); + + // restore the default values for other tests + ClientEngineInfo.setClientEngine(ClientEngineInfo.DEFAULT); + BuildVersionInfo.setClientVersion(BuildVersionInfo.VERSION); + } + + @Test + public void validateAugmentCommonData() { + Map sourceData = new HashMap<>(); + sourceData.put("k1", "source-1"); + sourceData.put("k2", "source-2"); + Map userCommonData = new HashMap<>(); + userCommonData.put("k3", "common-1"); + userCommonData.put("k4", "common-2"); + + Mockito.reset(mockApiManager); + ODPEventManager eventManager = new ODPEventManager(mockApiManager); + eventManager.setUserCommonData(userCommonData); + + Map merged = eventManager.augmentCommonData(sourceData); + + // event-sourceData + assertEquals(merged.get("k1"), "source-1"); + assertEquals(merged.get("k2"), "source-2"); + // userCommonData + assertEquals(merged.get("k3"), "common-1"); + assertEquals(merged.get("k4"), "common-2"); + // sdk-generated common data + assertNotNull(merged.get("idempotence_id")); + assertEquals(merged.get("data_source_type"), "sdk"); + assertNotNull(merged.get("data_source")); + assertNotNull(merged.get("data_source_version")); + + assertEquals(merged.size(), 8); + } + + @Test + public void validateAugmentCommonData_keyConflicts1() { + Map sourceData = new HashMap<>(); + sourceData.put("k1", "source-1"); + sourceData.put("k2", "source-2"); + Map userCommonData = new HashMap<>(); + userCommonData.put("k1", "common-1"); + userCommonData.put("k2", "common-2"); + + Mockito.reset(mockApiManager); + ODPEventManager eventManager = new ODPEventManager(mockApiManager); + eventManager.setUserCommonData(userCommonData); + + Map merged = eventManager.augmentCommonData(sourceData); + + // event-sourceData overrides userCommonData + assertEquals(merged.get("k1"), "source-1"); + assertEquals(merged.get("k2"), "source-2"); + // sdk-generated common data + assertNotNull(merged.get("idempotence_id")); + assertEquals(merged.get("data_source_type"), "sdk"); + assertNotNull(merged.get("data_source")); + assertNotNull(merged.get("data_source_version")); + + assertEquals(merged.size(), 6); + } + + @Test + public void validateAugmentCommonData_keyConflicts2() { + Map sourceData = new HashMap<>(); + sourceData.put("data_source_type", "source-1"); + Map userCommonData = new HashMap<>(); + userCommonData.put("data_source_type", "common-1"); + + Mockito.reset(mockApiManager); + ODPEventManager eventManager = new ODPEventManager(mockApiManager); + eventManager.setUserCommonData(userCommonData); + + Map merged = eventManager.augmentCommonData(sourceData); + + // event-sourceData overrides userCommonData and sdk-generated common data + assertEquals(merged.get("data_source_type"), "source-1"); + // sdk-generated common data + assertNotNull(merged.get("idempotence_id")); + assertNotNull(merged.get("data_source")); + assertNotNull(merged.get("data_source_version")); + + assertEquals(merged.size(), 4); + } + + @Test + public void validateAugmentCommonData_keyConflicts3() { + Map sourceData = new HashMap<>(); + sourceData.put("k1", "source-1"); + Map userCommonData = new HashMap<>(); + userCommonData.put("data_source_type", "common-1"); + + Mockito.reset(mockApiManager); + ODPEventManager eventManager = new ODPEventManager(mockApiManager); + eventManager.setUserCommonData(userCommonData); + + Map merged = eventManager.augmentCommonData(sourceData); + + // userCommonData overrides sdk-generated common data + assertEquals(merged.get("data_source_type"), "common-1"); + assertEquals(merged.get("k1"), "source-1"); + // sdk-generated common data + assertNotNull(merged.get("idempotence_id")); + assertNotNull(merged.get("data_source")); + assertNotNull(merged.get("data_source_version")); + + assertEquals(merged.size(), 5); + } + + @Test + public void validateAugmentCommonIdentifiers() { + Map sourceIdentifiers = new HashMap<>(); + sourceIdentifiers.put("k1", "source-1"); + sourceIdentifiers.put("k2", "source-2"); + Map userCommonIdentifiers = new HashMap<>(); + userCommonIdentifiers.put("k3", "common-1"); + userCommonIdentifiers.put("k4", "common-2"); + + Mockito.reset(mockApiManager); + ODPEventManager eventManager = new ODPEventManager(mockApiManager); + eventManager.setUserCommonIdentifiers(userCommonIdentifiers); + + Map merged = eventManager.augmentCommonIdentifiers(sourceIdentifiers); + + // event-sourceIdentifiers + assertEquals(merged.get("k1"), "source-1"); + assertEquals(merged.get("k2"), "source-2"); + // userCommonIdentifiers + assertEquals(merged.get("k3"), "common-1"); + assertEquals(merged.get("k4"), "common-2"); + + assertEquals(merged.size(), 4); + } + + @Test + public void validateAugmentCommonIdentifiers_keyConflicts() { + Map sourceIdentifiers = new HashMap<>(); + sourceIdentifiers.put("k1", "source-1"); + sourceIdentifiers.put("k2", "source-2"); + Map userCommonIdentifiers = new HashMap<>(); + userCommonIdentifiers.put("k1", "common-1"); + userCommonIdentifiers.put("k2", "common-2"); + + Mockito.reset(mockApiManager); + ODPEventManager eventManager = new ODPEventManager(mockApiManager); + eventManager.setUserCommonIdentifiers(userCommonIdentifiers); + + Map merged = eventManager.augmentCommonIdentifiers(sourceIdentifiers); + + // event-sourceIdentifiers overrides userCommonIdentifiers + assertEquals(merged.get("k1"), "source-1"); + assertEquals(merged.get("k2"), "source-2"); + + assertEquals(merged.size(), 2); + } + private ODPEvent getEvent(int id) { Map identifiers = new HashMap<>(); identifiers.put("identifier1", "value1-" + id); diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerBuilderTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerBuilderTest.java index 0f7f59ae9..0dcc9104a 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerBuilderTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerBuilderTest.java @@ -1,6 +1,6 @@ /** * - * Copyright 2022, Optimizely + * Copyright 2022-2023, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,9 +19,7 @@ import com.optimizely.ab.internal.Cache; import org.junit.Test; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; +import java.util.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; @@ -73,4 +71,25 @@ public void withSegmentCache() { odpManager.getSegmentManager().getQualifiedSegments("test-user"); verify(mockCache).lookup("fs_user_id-$-test-user"); } + + @Test + public void withUserCommonDataAndCommonIdentifiers() { + Map data = new HashMap<>(); + data.put("k1", "v1"); + Map identifiers = new HashMap<>(); + identifiers.put("k2", "v2"); + + ODPEventManager mockEventManager = mock(ODPEventManager.class); + ODPSegmentManager mockSegmentManager = mock(ODPSegmentManager.class); + ODPManager.builder() + .withUserCommonData(data) + .withUserCommonIdentifiers(identifiers) + .withEventManager(mockEventManager) + .withSegmentManager(mockSegmentManager) + .build(); + + verify(mockEventManager).setUserCommonData(eq(data)); + verify(mockEventManager).setUserCommonIdentifiers(eq(identifiers)); + } + } From cbaeb85aabe1f07add9cdf5d806d2706556fcc88 Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Fri, 27 Jan 2023 03:17:06 +0500 Subject: [PATCH 33/80] Fix: Added notificationRegistry to make sure that odpSettings updates (#501) * Added notificationRegistry to make sure that odpSettings update will call upon UpdateConfig * Updated headers and added additional checks in unittests * Added suppress warning * renamed NoficationRegistry function. Added default implementation of getSDKKey in ProjectConfigManager * reverting header change * reverting extra changes * reverting extra changes * nit fix * nit * Resolved comments * Added getCachedconfig Function to return ProjectConfig without wait, but the default implementation of it will return null. * ProjectConfig getCachedConfig(); without default implementation * Removed default implementation of getSDKkey to enforce user to make their own choice. * Resolved comments * setting Sdk key inside pollingConfigManager to make sure that the sdkKey for a particular config is always same. * setting sdkKey in parent class * fix * making sure that if the SDKKey is set by the user then it should be picked from projectConfig * Refactored and moved getSdkKey to pollingConfigManager to make sure that to trigger the notification always user provided sdkKey will be prioritized Co-authored-by: mnoman09 --- .../java/com/optimizely/ab/Optimizely.java | 16 +++- .../ab/config/AtomicProjectConfigManager.java | 17 +++- .../config/PollingProjectConfigManager.java | 30 ++++++- .../ab/config/ProjectConfigManager.java | 23 ++++- .../ab/internal/NotificationRegistry.java | 52 ++++++++++++ .../com/optimizely/ab/OptimizelyTest.java | 47 +++++------ .../PollingProjectConfigManagerTest.java | 24 +++++- .../ab/internal/NotificationRegistryTest.java | 84 +++++++++++++++++++ .../com/optimizely/ab/OptimizelyFactory.java | 20 ++++- .../ab/config/HttpProjectConfigManager.java | 9 +- .../optimizely/ab/OptimizelyFactoryTest.java | 26 +++++- .../config/HttpProjectConfigManagerTest.java | 4 +- 12 files changed, 306 insertions(+), 46 deletions(-) create mode 100644 core-api/src/main/java/com/optimizely/ab/internal/NotificationRegistry.java create mode 100644 core-api/src/test/java/com/optimizely/ab/internal/NotificationRegistryTest.java diff --git a/core-api/src/main/java/com/optimizely/ab/Optimizely.java b/core-api/src/main/java/com/optimizely/ab/Optimizely.java index 12b9f33d1..5f41bcd6e 100644 --- a/core-api/src/main/java/com/optimizely/ab/Optimizely.java +++ b/core-api/src/main/java/com/optimizely/ab/Optimizely.java @@ -27,6 +27,7 @@ import com.optimizely.ab.event.*; import com.optimizely.ab.event.internal.*; import com.optimizely.ab.event.internal.payload.EventBatch; +import com.optimizely.ab.internal.NotificationRegistry; import com.optimizely.ab.notification.*; import com.optimizely.ab.odp.*; import com.optimizely.ab.optimizelyconfig.OptimizelyConfig; @@ -124,10 +125,15 @@ private Optimizely(@Nonnull EventHandler eventHandler, if (odpManager != null) { odpManager.getEventManager().start(); - if (getProjectConfig() != null) { + if (projectConfigManager.getCachedConfig() != null) { updateODPSettings(); } - addUpdateConfigNotificationHandler(configNotification -> { updateODPSettings(); }); + if (projectConfigManager.getSDKKey() != null) { + NotificationRegistry.getInternalNotificationCenter(projectConfigManager.getSDKKey()). + addNotificationHandler(UpdateConfigNotification.class, + configNotification -> { updateODPSettings(); }); + } + } } @@ -153,6 +159,8 @@ public void close() { tryClose(eventProcessor); tryClose(eventHandler); tryClose(projectConfigManager); + notificationCenter.clearAllNotificationListeners(); + NotificationRegistry.clearNotificationCenterRegistry(projectConfigManager.getSDKKey()); if (odpManager != null) { tryClose(odpManager); } @@ -1477,8 +1485,8 @@ public void identifyUser(@Nonnull String userId) { } private void updateODPSettings() { - if (odpManager != null && getProjectConfig() != null) { - ProjectConfig projectConfig = getProjectConfig(); + ProjectConfig projectConfig = projectConfigManager.getCachedConfig(); + if (odpManager != null && projectConfig != null) { odpManager.updateSettings(projectConfig.getHostForODP(), projectConfig.getPublicKeyForODP(), projectConfig.getAllSegments()); } } diff --git a/core-api/src/main/java/com/optimizely/ab/config/AtomicProjectConfigManager.java b/core-api/src/main/java/com/optimizely/ab/config/AtomicProjectConfigManager.java index fa1f4bd62..336d33c0e 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/AtomicProjectConfigManager.java +++ b/core-api/src/main/java/com/optimizely/ab/config/AtomicProjectConfigManager.java @@ -1,6 +1,6 @@ /** * - * Copyright 2019, Optimizely and contributors + * Copyright 2019, 2023, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,21 @@ public ProjectConfig getConfig() { return projectConfigReference.get(); } + /** + * Access to current cached project configuration. + * + * @return {@link ProjectConfig} + */ + @Override + public ProjectConfig getCachedConfig() { + return projectConfigReference.get(); + } + + @Override + public String getSDKKey() { + return null; + } + public void setConfig(ProjectConfig projectConfig) { projectConfigReference.set(projectConfig); } diff --git a/core-api/src/main/java/com/optimizely/ab/config/PollingProjectConfigManager.java b/core-api/src/main/java/com/optimizely/ab/config/PollingProjectConfigManager.java index b03aeabc0..4ad34e7a8 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/PollingProjectConfigManager.java +++ b/core-api/src/main/java/com/optimizely/ab/config/PollingProjectConfigManager.java @@ -1,6 +1,6 @@ /** * - * Copyright 2019-2020, Optimizely and contributors + * Copyright 2019-2020, 2023, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ */ package com.optimizely.ab.config; +import com.optimizely.ab.internal.NotificationRegistry; import com.optimizely.ab.notification.NotificationCenter; import com.optimizely.ab.notification.UpdateConfigNotification; import com.optimizely.ab.optimizelyconfig.OptimizelyConfig; @@ -56,6 +57,7 @@ public abstract class PollingProjectConfigManager implements ProjectConfigManage private final CountDownLatch countDownLatch = new CountDownLatch(1); + private volatile String sdkKey; private volatile boolean started; private ScheduledFuture scheduledFuture; @@ -84,6 +86,16 @@ public PollingProjectConfigManager(long period, TimeUnit timeUnit, long blocking protected abstract ProjectConfig poll(); + /** + * Access to current cached project configuration, This is to make sure that config returns without any wait, even if it is null. + * + * @return {@link ProjectConfig} + */ + @Override + public ProjectConfig getCachedConfig() { + return currentProjectConfig.get(); + } + /** * Only allow the ProjectConfig to be set to a non-null value, if and only if the value has not already been set. * @param projectConfig @@ -109,6 +121,13 @@ void setConfig(ProjectConfig projectConfig) { currentProjectConfig.set(projectConfig); currentOptimizelyConfig.set(new OptimizelyConfigService(projectConfig).getConfig()); countDownLatch.countDown(); + + if (sdkKey == null) { + sdkKey = projectConfig.getSdkKey(); + } + if (sdkKey != null) { + NotificationRegistry.getInternalNotificationCenter(sdkKey).send(SIGNAL); + } notificationCenter.send(SIGNAL); } @@ -150,6 +169,11 @@ public OptimizelyConfig getOptimizelyConfig() { return currentOptimizelyConfig.get(); } + @Override + public String getSDKKey() { + return this.sdkKey; + } + public synchronized void start() { if (started) { logger.warn("Manager already started."); @@ -189,6 +213,10 @@ public synchronized void close() { started = false; } + protected void setSdkKey(String sdkKey) { + this.sdkKey = sdkKey; + } + public boolean isRunning() { return started; } diff --git a/core-api/src/main/java/com/optimizely/ab/config/ProjectConfigManager.java b/core-api/src/main/java/com/optimizely/ab/config/ProjectConfigManager.java index 1a1b2f4bc..002acae55 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/ProjectConfigManager.java +++ b/core-api/src/main/java/com/optimizely/ab/config/ProjectConfigManager.java @@ -1,6 +1,6 @@ /** * - * Copyright 2019, Optimizely and contributors + * Copyright 2019, 2023, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ */ package com.optimizely.ab.config; +import javax.annotation.Nullable; + public interface ProjectConfigManager { /** * Implementations of this method should block until a datafile is available. @@ -23,5 +25,24 @@ public interface ProjectConfigManager { * @return ProjectConfig */ ProjectConfig getConfig(); + + /** + * Implementations of this method should not block until a datafile is available, instead return current cached project configuration. + * return null if ProjectConfig is not ready at the moment. + * + * NOTE: To use ODP segments, implementation of this function is required to return current project configuration. + * @return ProjectConfig + */ + @Nullable + ProjectConfig getCachedConfig(); + + /** + * Implementations of this method should return SDK key. If there is no SDKKey then it should return null. + * + * NOTE: To update ODP segments configuration via polling, it is required to return sdkKey. + * @return String + */ + @Nullable + String getSDKKey(); } diff --git a/core-api/src/main/java/com/optimizely/ab/internal/NotificationRegistry.java b/core-api/src/main/java/com/optimizely/ab/internal/NotificationRegistry.java new file mode 100644 index 000000000..92d0c6d38 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/internal/NotificationRegistry.java @@ -0,0 +1,52 @@ +/** + * + * Copyright 2023, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.internal; + +import com.optimizely.ab.notification.NotificationCenter; + +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +public class NotificationRegistry { + private final static Map _notificationCenters = new ConcurrentHashMap<>(); + + private NotificationRegistry() + { + } + + public static NotificationCenter getInternalNotificationCenter(@Nonnull String sdkKey) + { + NotificationCenter notificationCenter = null; + if (sdkKey != null) { + if (_notificationCenters.containsKey(sdkKey)) { + notificationCenter = _notificationCenters.get(sdkKey); + } else { + notificationCenter = new NotificationCenter(); + _notificationCenters.put(sdkKey, notificationCenter); + } + } + return notificationCenter; + } + + public static void clearNotificationCenterRegistry(@Nonnull String sdkKey) { + if (sdkKey != null) { + _notificationCenters.remove(sdkKey); + } + } + +} diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java index 9fd3dd675..705ce1cb6 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright 2016-2022, Optimizely, Inc. and contributors * + * Copyright 2016-2023, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * @@ -119,6 +119,23 @@ public static Collection data() throws IOException { public OptimizelyRule optimizelyBuilder = new OptimizelyRule(); public EventHandlerRule eventHandler = new EventHandlerRule(); + public ProjectConfigManager projectConfigManagerReturningNull = new ProjectConfigManager() { + @Override + public ProjectConfig getConfig() { + return null; + } + + @Override + public ProjectConfig getCachedConfig() { + return null; + } + + @Override + public String getSDKKey() { + return null; + } + }; + @Rule @SuppressFBWarnings("URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD") public RuleChain ruleChain = RuleChain.outerRule(thrown) @@ -4505,13 +4522,13 @@ public void isValidReturnsTrueWhenClientIsValid() throws Exception { @Test public void testGetNotificationCenter() { - Optimizely optimizely = optimizelyBuilder.withConfigManager(() -> null).build(); + Optimizely optimizely = optimizelyBuilder.withConfigManager(projectConfigManagerReturningNull).build(); assertEquals(optimizely.notificationCenter, optimizely.getNotificationCenter()); } @Test public void testAddTrackNotificationHandler() { - Optimizely optimizely = optimizelyBuilder.withConfigManager(() -> null).build(); + Optimizely optimizely = optimizelyBuilder.withConfigManager(projectConfigManagerReturningNull).build(); NotificationManager manager = optimizely.getNotificationCenter() .getNotificationManager(TrackNotification.class); @@ -4521,7 +4538,7 @@ public void testAddTrackNotificationHandler() { @Test public void testAddDecisionNotificationHandler() { - Optimizely optimizely = optimizelyBuilder.withConfigManager(() -> null).build(); + Optimizely optimizely = optimizelyBuilder.withConfigManager(projectConfigManagerReturningNull).build(); NotificationManager manager = optimizely.getNotificationCenter() .getNotificationManager(DecisionNotification.class); @@ -4531,7 +4548,7 @@ public void testAddDecisionNotificationHandler() { @Test public void testAddUpdateConfigNotificationHandler() { - Optimizely optimizely = optimizelyBuilder.withConfigManager(() -> null).build(); + Optimizely optimizely = optimizelyBuilder.withConfigManager(projectConfigManagerReturningNull).build(); NotificationManager manager = optimizely.getNotificationCenter() .getNotificationManager(UpdateConfigNotification.class); @@ -4541,7 +4558,7 @@ public void testAddUpdateConfigNotificationHandler() { @Test public void testAddLogEventNotificationHandler() { - Optimizely optimizely = optimizelyBuilder.withConfigManager(() -> null).build(); + Optimizely optimizely = optimizelyBuilder.withConfigManager(projectConfigManagerReturningNull).build(); NotificationManager manager = optimizely.getNotificationCenter() .getNotificationManager(LogEvent.class); @@ -4713,24 +4730,6 @@ public void initODPManagerWithProjectConfig() throws IOException { verify(mockODPManager, times(1)).updateSettings(any(), any(), any()); } - @Test - public void updateODPManagerWhenConfigUpdates() throws IOException { - ODPEventManager mockODPEventManager = mock(ODPEventManager.class); - ODPManager mockODPManager = mock(ODPManager.class); - NotificationCenter mockNotificationCenter = mock(NotificationCenter.class); - - Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); - Optimizely.builder() - .withDatafile(validConfigJsonV4()) - .withNotificationCenter(mockNotificationCenter) - .withODPManager(mockODPManager) - .build(); - - verify(mockODPManager, times(1)).updateSettings(any(), any(), any()); - - Mockito.verify(mockNotificationCenter, times(1)).addNotificationHandler(any(), any()); - } - @Test public void sendODPEvent() { ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); diff --git a/core-api/src/test/java/com/optimizely/ab/config/PollingProjectConfigManagerTest.java b/core-api/src/test/java/com/optimizely/ab/config/PollingProjectConfigManagerTest.java index 390c9b874..130f8844a 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/PollingProjectConfigManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/config/PollingProjectConfigManagerTest.java @@ -1,6 +1,6 @@ /** * - * Copyright 2019-2021, Optimizely and contributors + * Copyright 2019-2021, 2023, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ */ package com.optimizely.ab.config; +import com.optimizely.ab.internal.NotificationRegistry; import com.optimizely.ab.notification.NotificationCenter; import com.optimizely.ab.notification.UpdateConfigNotification; import org.junit.After; @@ -95,12 +96,14 @@ public void testBlockingGetConfig() throws Exception { testProjectConfigManager.release(); TimeUnit.MILLISECONDS.sleep(PROJECT_CONFIG_DELAY); assertEquals(projectConfig, testProjectConfigManager.getConfig()); + assertEquals(projectConfig.getSdkKey(), testProjectConfigManager.getSDKKey()); } @Test public void testBlockingGetConfigWithDefault() throws Exception { testProjectConfigManager.setConfig(projectConfig); assertEquals(projectConfig, testProjectConfigManager.getConfig()); + assertEquals(projectConfig.getSdkKey(), testProjectConfigManager.getSDKKey()); } @Test @@ -124,6 +127,7 @@ public void testGetConfigNotStartedDefault() throws Exception { testProjectConfigManager.close(); assertFalse(testProjectConfigManager.isRunning()); assertEquals(projectConfig, testProjectConfigManager.getConfig()); + assertEquals(projectConfig.getSdkKey(), testProjectConfigManager.getSDKKey()); } @Test @@ -210,11 +214,17 @@ public ProjectConfig poll() { @Test public void testUpdateConfigNotificationGetsTriggered() throws InterruptedException { - CountDownLatch countDownLatch = new CountDownLatch(1); + CountDownLatch countDownLatch = new CountDownLatch(2); + NotificationCenter registryDefaultNotificationCenter = NotificationRegistry.getInternalNotificationCenter("ValidProjectConfigV4"); + NotificationCenter userNotificationCenter = testProjectConfigManager.getNotificationCenter(); + assertNotEquals(registryDefaultNotificationCenter, userNotificationCenter); + testProjectConfigManager.getNotificationCenter() .getNotificationManager(UpdateConfigNotification.class) .addHandler(message -> {countDownLatch.countDown();}); - + NotificationRegistry.getInternalNotificationCenter("ValidProjectConfigV4") + .getNotificationManager(UpdateConfigNotification.class) + .addHandler(message -> {countDownLatch.countDown();}); assertTrue(countDownLatch.await(500, TimeUnit.MILLISECONDS)); } @@ -271,5 +281,13 @@ public int getCount() { public void release() { countDownLatch.countDown(); } + + @Override + public String getSDKKey() { + if (projectConfig == null) { + return null; + } + return projectConfig.getSdkKey(); + } } } diff --git a/core-api/src/test/java/com/optimizely/ab/internal/NotificationRegistryTest.java b/core-api/src/test/java/com/optimizely/ab/internal/NotificationRegistryTest.java new file mode 100644 index 000000000..4f130a848 --- /dev/null +++ b/core-api/src/test/java/com/optimizely/ab/internal/NotificationRegistryTest.java @@ -0,0 +1,84 @@ +/** + * + * Copyright 2023, Optimizely + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.optimizely.ab.internal; + +import com.optimizely.ab.notification.NotificationCenter; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import org.junit.Assert; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + + +public class NotificationRegistryTest { + + @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") + @Test + public void getNullNotificationCenterWhenSDKeyIsNull() { + String sdkKey = null; + NotificationCenter notificationCenter = NotificationRegistry.getInternalNotificationCenter(sdkKey); + assertNull(notificationCenter); + } + + @Test + public void getSameNotificationCenterWhenSDKKeyIsSameButNotNull() { + String sdkKey = "testSDkKey"; + NotificationCenter notificationCenter1 = NotificationRegistry.getInternalNotificationCenter(sdkKey); + NotificationCenter notificationCenter2 = NotificationRegistry.getInternalNotificationCenter(sdkKey); + assertEquals(notificationCenter1, notificationCenter2); + } + + @Test + public void getSameNotificationCenterWhenSDKKeyIsEmpty() { + String sdkKey1 = ""; + String sdkKey2 = ""; + NotificationCenter notificationCenter1 = NotificationRegistry.getInternalNotificationCenter(sdkKey1); + NotificationCenter notificationCenter2 = NotificationRegistry.getInternalNotificationCenter(sdkKey2); + assertEquals(notificationCenter1, notificationCenter2); + } + + @Test + public void getDifferentNotificationCenterWhenSDKKeyIsNotSame() { + String sdkKey1 = "testSDkKey1"; + String sdkKey2 = "testSDkKey2"; + NotificationCenter notificationCenter1 = NotificationRegistry.getInternalNotificationCenter(sdkKey1); + NotificationCenter notificationCenter2 = NotificationRegistry.getInternalNotificationCenter(sdkKey2); + Assert.assertNotEquals(notificationCenter1, notificationCenter2); + } + + @Test + public void clearRegistryNotificationCenterClearsOldNotificationCenter() { + String sdkKey1 = "testSDkKey1"; + NotificationCenter notificationCenter1 = NotificationRegistry.getInternalNotificationCenter(sdkKey1); + NotificationRegistry.clearNotificationCenterRegistry(sdkKey1); + NotificationCenter notificationCenter2 = NotificationRegistry.getInternalNotificationCenter(sdkKey1); + + Assert.assertNotEquals(notificationCenter1, notificationCenter2); + } + + @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") + @Test + public void clearRegistryNotificationCenterWillNotCauseExceptionIfPassedNullSDkKey() { + String sdkKey1 = "testSDkKey1"; + NotificationCenter notificationCenter1 = NotificationRegistry.getInternalNotificationCenter(sdkKey1); + NotificationRegistry.clearNotificationCenterRegistry(null); + NotificationCenter notificationCenter2 = NotificationRegistry.getInternalNotificationCenter(sdkKey1); + + Assert.assertEquals(notificationCenter1, notificationCenter2); + } +} diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyFactory.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyFactory.java index 37d56da03..1c6ee2820 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyFactory.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyFactory.java @@ -1,6 +1,6 @@ /** * - * Copyright 2019-2021, Optimizely + * Copyright 2019-2021, 2023, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package com.optimizely.ab; import com.optimizely.ab.config.HttpProjectConfigManager; +import com.optimizely.ab.config.ProjectConfig; import com.optimizely.ab.config.ProjectConfigManager; import com.optimizely.ab.event.AsyncEventHandler; import com.optimizely.ab.event.BatchEventProcessor; @@ -222,7 +223,22 @@ public static Optimizely newDefaultInstance() { public static Optimizely newDefaultInstance(String sdkKey) { if (sdkKey == null) { logger.error("Must provide an sdkKey, returning non-op Optimizely client"); - return newDefaultInstance(() -> null); + return newDefaultInstance(new ProjectConfigManager() { + @Override + public ProjectConfig getConfig() { + return null; + } + + @Override + public ProjectConfig getCachedConfig() { + return null; + } + + @Override + public String getSDKKey() { + return null; + } + }); } return newDefaultInstance(sdkKey, null); diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java index cef13fdcd..4be1715d2 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java @@ -332,11 +332,10 @@ public HttpProjectConfigManager build(boolean defer) { .withEvictIdleConnections(evictConnectionIdleTimePeriod, evictConnectionIdleTimeUnit) .build(); } - + if (sdkKey == null) { + throw new NullPointerException("sdkKey cannot be null"); + } if (url == null) { - if (sdkKey == null) { - throw new NullPointerException("sdkKey cannot be null"); - } if (datafileAccessToken == null) { url = String.format(format, sdkKey); @@ -358,7 +357,7 @@ public HttpProjectConfigManager build(boolean defer) { blockingTimeoutPeriod, blockingTimeoutUnit, notificationCenter); - + httpProjectManager.setSdkKey(sdkKey); if (datafile != null) { try { ProjectConfig projectConfig = HttpProjectConfigManager.parseProjectConfig(datafile); diff --git a/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyFactoryTest.java b/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyFactoryTest.java index 07c2c0634..aaa3a67fa 100644 --- a/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyFactoryTest.java +++ b/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyFactoryTest.java @@ -1,6 +1,6 @@ /** * - * Copyright 2019-2020, Optimizely + * Copyright 2019-2020, 2023, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,8 @@ import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.optimizely.ab.config.HttpProjectConfigManager; +import com.optimizely.ab.config.ProjectConfig; +import com.optimizely.ab.config.ProjectConfigManager; import com.optimizely.ab.event.AsyncEventHandler; import com.optimizely.ab.event.BatchEventProcessor; import com.optimizely.ab.internal.PropertyUtils; @@ -260,17 +262,33 @@ public void newDefaultInstanceWithDatafileAccessTokenAndCustomHttpClient() throw optimizely = OptimizelyFactory.newDefaultInstance("sdk-key", datafileString, "auth-token", httpClient); assertTrue(optimizely.isValid()); } + public ProjectConfigManager projectConfigManagerReturningNull = new ProjectConfigManager() { + @Override + public ProjectConfig getConfig() { + return null; + } + + @Override + public ProjectConfig getCachedConfig() { + return null; + } + + @Override + public String getSDKKey() { + return null; + } + }; @Test public void newDefaultInstanceWithProjectConfig() throws Exception { - optimizely = OptimizelyFactory.newDefaultInstance(() -> null); + optimizely = OptimizelyFactory.newDefaultInstance(projectConfigManagerReturningNull); assertFalse(optimizely.isValid()); } @Test public void newDefaultInstanceWithProjectConfigAndNotificationCenter() throws Exception { NotificationCenter notificationCenter = new NotificationCenter(); - optimizely = OptimizelyFactory.newDefaultInstance(() -> null, notificationCenter); + optimizely = OptimizelyFactory.newDefaultInstance(projectConfigManagerReturningNull, notificationCenter); assertFalse(optimizely.isValid()); assertEquals(notificationCenter, optimizely.getNotificationCenter()); } @@ -278,7 +296,7 @@ public void newDefaultInstanceWithProjectConfigAndNotificationCenter() throws Ex @Test public void newDefaultInstanceWithProjectConfigAndNotificationCenterAndEventHandler() { NotificationCenter notificationCenter = new NotificationCenter(); - optimizely = OptimizelyFactory.newDefaultInstance(() -> null, notificationCenter, logEvent -> {}); + optimizely = OptimizelyFactory.newDefaultInstance(projectConfigManagerReturningNull, notificationCenter, logEvent -> {}); assertFalse(optimizely.isValid()); assertEquals(notificationCenter, optimizely.getNotificationCenter()); } diff --git a/core-httpclient-impl/src/test/java/com/optimizely/ab/config/HttpProjectConfigManagerTest.java b/core-httpclient-impl/src/test/java/com/optimizely/ab/config/HttpProjectConfigManagerTest.java index c61a1f01a..9cbc0bb01 100644 --- a/core-httpclient-impl/src/test/java/com/optimizely/ab/config/HttpProjectConfigManagerTest.java +++ b/core-httpclient-impl/src/test/java/com/optimizely/ab/config/HttpProjectConfigManagerTest.java @@ -1,6 +1,6 @@ /** * - * Copyright 2019, Optimizely + * Copyright 2019, 2023, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -129,6 +129,7 @@ public void testHttpGetByCustomUrl() throws Exception { projectConfigManager = builder() .withOptimizelyHttpClient(mockHttpClient) + .withSdkKey("custom-sdkKey") .withUrl(expected) .build(); @@ -207,6 +208,7 @@ public void testBuildDefer() throws Exception { .withOptimizelyHttpClient(mockHttpClient) .withSdkKey("sdk-key") .build(true); + assertEquals("sdk-key", projectConfigManager.getSDKKey()); } @Test From 42f88992952eaeea6da52080cd1d748fcac3bc35 Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Wed, 8 Feb 2023 21:59:01 +0500 Subject: [PATCH 34/80] Refact: ODPAPIManager now returns fetchQualifiedSegments list instead of string (#503) --- .../com/optimizely/ab/odp/ODPApiManager.java | 5 +++-- .../com/optimizely/ab/odp/ODPEventManager.java | 14 +++++++++++--- .../com/optimizely/ab/odp/ODPSegmentManager.java | 13 ++----------- .../com/optimizely/ab/odp/ODPManagerTest.java | 5 +++-- .../optimizely/ab/odp/ODPSegmentManagerTest.java | 4 ++-- .../optimizely/ab/odp/DefaultODPApiManager.java | 15 ++++++++++----- .../ab/odp/DefaultODPApiManagerTest.java | 16 +++++++++------- 7 files changed, 40 insertions(+), 32 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java index 6385d2b7b..b45bd937f 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPApiManager.java @@ -1,5 +1,5 @@ /** - * Copyright 2022, Optimizely Inc. and contributors + * Copyright 2022-2023, Optimizely Inc. and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,10 +15,11 @@ */ package com.optimizely.ab.odp; +import java.util.List; import java.util.Set; public interface ODPApiManager { - String fetchQualifiedSegments(String apiKey, String apiEndpoint, String userKey, String userValue, Set segmentsToCheck); + List fetchQualifiedSegments(String apiKey, String apiEndpoint, String userKey, String userValue, Set segmentsToCheck); Integer sendEvents(String apiKey, String apiEndpoint, String eventPayload); } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java index fbd39ffaf..ce218ed9d 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java @@ -108,7 +108,11 @@ public void identifyUser(@Nullable String vuid, @Nullable String userId) { identifiers.put(ODPUserKey.VUID.getKeyString(), vuid); } if (userId != null) { - identifiers.put(ODPUserKey.FS_USER_ID.getKeyString(), userId); + if (isVuid(userId)) { + identifiers.put(ODPUserKey.VUID.getKeyString(), userId); + } else { + identifiers.put(ODPUserKey.FS_USER_ID.getKeyString(), userId); + } } ODPEvent event = new ODPEvent("fullstack", "identified", identifiers, null); sendEvent(event); @@ -125,7 +129,7 @@ public void sendEvent(ODPEvent event) { } @VisibleForTesting - Map augmentCommonData(Map sourceData) { + protected Map augmentCommonData(Map sourceData) { // priority: sourceData > userCommonData > sdkCommonData Map data = new HashMap<>(); @@ -140,7 +144,7 @@ Map augmentCommonData(Map sourceData) { } @VisibleForTesting - Map augmentCommonIdentifiers(Map sourceIdentifiers) { + protected Map augmentCommonIdentifiers(Map sourceIdentifiers) { // priority: sourceIdentifiers > userCommonIdentifiers Map identifiers = new HashMap<>(); @@ -149,6 +153,10 @@ Map augmentCommonIdentifiers(Map sourceIdentifie return identifiers; } + private boolean isVuid(String userId) { + return userId.startsWith("vuid_"); + } + private void processEvent(ODPEvent event) { if (!isRunning) { logger.warn("Failed to Process ODP Event. ODPEventManager is not running"); diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java index 90a36fa5d..275c45ee1 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java @@ -1,6 +1,6 @@ /** * - * Copyright 2022, Optimizely + * Copyright 2022-2023, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,16 +89,7 @@ public List getQualifiedSegments(ODPUserKey userKey, String userValue, L logger.debug("ODP Cache Miss. Making a call to ODP Server."); - ResponseJsonParser parser = ResponseJsonParserFactory.getParser(); - String qualifiedSegmentsResponse = apiManager.fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + SEGMENT_URL_PATH, userKey.getKeyString(), userValue, odpConfig.getAllSegments()); - try { - qualifiedSegments = parser.parseQualifiedSegments(qualifiedSegmentsResponse); - } catch (Exception e) { - logger.error("Audience segments fetch failed (Error Parsing Response)"); - logger.debug(e.getMessage()); - qualifiedSegments = null; - } - + qualifiedSegments = apiManager.fetchQualifiedSegments(odpConfig.getApiKey(), odpConfig.getApiHost() + SEGMENT_URL_PATH, userKey.getKeyString(), userValue, odpConfig.getAllSegments()); if (qualifiedSegments != null && !options.contains(ODPSegmentOption.IGNORE_CACHE)) { segmentsCache.save(cacheKey, qualifiedSegments); } diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java index 02abe88a1..9673bfa69 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java @@ -1,6 +1,6 @@ /** * - * Copyright 2022, Optimizely + * Copyright 2022-2023, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,13 +24,14 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashSet; +import java.util.List; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; import static org.junit.Assert.*; public class ODPManagerTest { - private static final String API_RESPONSE = "{\"data\":{\"customer\":{\"audiences\":{\"edges\":[{\"node\":{\"name\":\"segment1\",\"state\":\"qualified\"}},{\"node\":{\"name\":\"segment2\",\"state\":\"qualified\"}}]}}}}"; + private static final List API_RESPONSE = Arrays.asList(new String[]{"segment1", "segment2"}); @Mock ODPApiManager mockApiManager; diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java index 4d34d49b9..2e6aa611e 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java @@ -1,6 +1,6 @@ /** * - * Copyright 2022, Optimizely + * Copyright 2022-2023, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,7 +43,7 @@ public class ODPSegmentManagerTest { @Mock ODPApiManager mockApiManager; - private static final String API_RESPONSE = "{\"data\":{\"customer\":{\"audiences\":{\"edges\":[{\"node\":{\"name\":\"segment1\",\"state\":\"qualified\"}},{\"node\":{\"name\":\"segment2\",\"state\":\"qualified\"}}]}}}}"; + private static final List API_RESPONSE = Arrays.asList(new String[]{"segment1", "segment2"}); @Before public void setup() { diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java index 636ed8eec..040709d39 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java @@ -1,5 +1,5 @@ /** - * Copyright 2022, Optimizely Inc. and contributors + * Copyright 2022-2023, Optimizely Inc. and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,8 @@ import com.optimizely.ab.OptimizelyHttpClient; import com.optimizely.ab.annotations.VisibleForTesting; +import com.optimizely.ab.odp.parser.ResponseJsonParser; +import com.optimizely.ab.odp.parser.ResponseJsonParserFactory; import org.apache.http.StatusLine; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; @@ -28,6 +30,7 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Iterator; +import java.util.List; import java.util.Set; public class DefaultODPApiManager implements ODPApiManager { @@ -144,7 +147,7 @@ String getSegmentsStringForRequest(Set segmentsList) { } */ @Override - public String fetchQualifiedSegments(String apiKey, String apiEndpoint, String userKey, String userValue, Set segmentsToCheck) { + public List fetchQualifiedSegments(String apiKey, String apiEndpoint, String userKey, String userValue, Set segmentsToCheck) { HttpPost request = new HttpPost(apiEndpoint); String segmentsString = getSegmentsStringForRequest(segmentsToCheck); @@ -174,11 +177,14 @@ public String fetchQualifiedSegments(String apiKey, String apiEndpoint, String u closeHttpResponse(response); return null; } - + ResponseJsonParser parser = ResponseJsonParserFactory.getParser(); try { - return EntityUtils.toString(response.getEntity()); + return parser.parseQualifiedSegments(EntityUtils.toString(response.getEntity())); } catch (IOException e) { logger.error("Error converting ODP segments response to string", e); + } catch (Exception e) { + logger.error("Audience segments fetch failed (Error Parsing Response)"); + logger.debug(e.getMessage()); } finally { closeHttpResponse(response); } @@ -201,7 +207,6 @@ public String fetchQualifiedSegments(String apiKey, String apiEndpoint, String u "type": "fullstack" } ] - Returns: 1. null, When there was a non-recoverable error and no retry is needed. 2. 0 If an unexpected error occurred and retrying can be useful. diff --git a/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java b/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java index 93b728fba..a268cacc7 100644 --- a/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java +++ b/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2022, Optimizely Inc. and contributors + * Copyright 2022-2023, Optimizely Inc. and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,13 +30,15 @@ import java.util.Arrays; import java.util.HashSet; +import java.util.List; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; public class DefaultODPApiManagerTest { - private static final String validResponse = "{\"data\":{\"customer\":{\"audiences\":{\"edges\":[{\"node\":{\"name\":\"has_email\",\"state\":\"qualified\"}},{\"node\":{\"name\":\"has_email_opted_in\",\"state\":\"qualified\"}}]}}}}"; + private static final List validResponse = Arrays.asList(new String[] {"has_email", "has_email_opted_in"}); + private static final String validRequestResponse = "{\"data\":{\"customer\":{\"audiences\":{\"edges\":[{\"node\":{\"name\":\"has_email\",\"state\":\"qualified\"}},{\"node\":{\"name\":\"has_email_opted_in\",\"state\":\"qualified\"}}]}}}}"; @Rule public LogbackVerifier logbackVerifier = new LogbackVerifier(); @@ -55,7 +57,7 @@ private void setupHttpClient(int statusCode) throws Exception { when(statusLine.getStatusCode()).thenReturn(statusCode); when(httpResponse.getStatusLine()).thenReturn(statusLine); - when(httpResponse.getEntity()).thenReturn(new StringEntity(validResponse)); + when(httpResponse.getEntity()).thenReturn(new StringEntity(validRequestResponse)); when(mockHttpClient.execute(any(HttpPost.class))) .thenReturn(httpResponse); @@ -99,19 +101,19 @@ public void generateCorrectRequestBody() throws Exception { @Test public void returnResponseStringWhenStatusIs200() throws Exception { ODPApiManager apiManager = new DefaultODPApiManager(mockHttpClient); - String responseString = apiManager.fetchQualifiedSegments("key", "endPoint", "fs_user_id", "test_user", new HashSet<>(Arrays.asList("segment_1", "segment_2"))); + List response = apiManager.fetchQualifiedSegments("key", "endPoint", "fs_user_id", "test_user", new HashSet<>(Arrays.asList("segment_1", "segment_2"))); verify(mockHttpClient, times(1)).execute(any(HttpPost.class)); - assertEquals(validResponse, responseString); + assertEquals(validResponse, response); } @Test public void returnNullWhenStatusIsNot200AndLogError() throws Exception { setupHttpClient(500); ODPApiManager apiManager = new DefaultODPApiManager(mockHttpClient); - String responseString = apiManager.fetchQualifiedSegments("key", "endPoint", "fs_user_id", "test_user", new HashSet<>(Arrays.asList("segment_1", "segment_2"))); + List response = apiManager.fetchQualifiedSegments("key", "endPoint", "fs_user_id", "test_user", new HashSet<>(Arrays.asList("segment_1", "segment_2"))); verify(mockHttpClient, times(1)).execute(any(HttpPost.class)); logbackVerifier.expectMessage(Level.ERROR, "Unexpected response from ODP server, Response code: 500, null"); - assertNull(responseString); + assertNull(response); } @Test From c7f9099108b285f3f10d380d7e693e476d3f166e Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Fri, 10 Feb 2023 08:40:27 -0800 Subject: [PATCH 35/80] fix vuid support for fetchQualifiedSegments (#504) --- .../optimizely/ab/odp/ODPEventManager.java | 10 +--- .../com/optimizely/ab/odp/ODPManager.java | 4 ++ .../optimizely/ab/odp/ODPSegmentManager.java | 14 +++-- .../ab/odp/ODPEventManagerTest.java | 58 +++++++++++++++++++ .../com/optimizely/ab/odp/ODPManagerTest.java | 8 +++ .../ab/odp/ODPSegmentManagerTest.java | 16 +++++ 6 files changed, 98 insertions(+), 12 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java index ce218ed9d..8edb135aa 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java @@ -108,10 +108,10 @@ public void identifyUser(@Nullable String vuid, @Nullable String userId) { identifiers.put(ODPUserKey.VUID.getKeyString(), vuid); } if (userId != null) { - if (isVuid(userId)) { - identifiers.put(ODPUserKey.VUID.getKeyString(), userId); + if (ODPManager.isVuid(userId)) { + identifiers.put(ODPUserKey.VUID.getKeyString(), userId); } else { - identifiers.put(ODPUserKey.FS_USER_ID.getKeyString(), userId); + identifiers.put(ODPUserKey.FS_USER_ID.getKeyString(), userId); } } ODPEvent event = new ODPEvent("fullstack", "identified", identifiers, null); @@ -153,10 +153,6 @@ protected Map augmentCommonIdentifiers(Map sourc return identifiers; } - private boolean isVuid(String userId) { - return userId.startsWith("vuid_"); - } - private void processEvent(ODPEvent event) { if (!isRunning) { logger.warn("Failed to Process ODP Event. ODPEventManager is not running"); diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java index cacbcad0d..4f1ddc52d 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java @@ -68,6 +68,10 @@ public void close() { eventManager.stop(); } + public static boolean isVuid(String userId) { + return userId.startsWith("vuid_"); + } + public static Builder builder() { return new Builder(); } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java index 275c45ee1..ce1aaffd3 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java @@ -52,11 +52,15 @@ public ODPSegmentManager(ODPApiManager apiManager, Integer cacheSize, Integer ca this.segmentsCache = new DefaultLRUCache<>(cacheSize, cacheTimeoutSeconds); } - public List getQualifiedSegments(String fsUserId) { - return getQualifiedSegments(ODPUserKey.FS_USER_ID, fsUserId, Collections.emptyList()); - } - public List getQualifiedSegments(String fsUserId, List options) { - return getQualifiedSegments(ODPUserKey.FS_USER_ID, fsUserId, options); + public List getQualifiedSegments(String userId) { + return getQualifiedSegments(userId, Collections.emptyList()); + } + public List getQualifiedSegments(String userId, List options) { + if (ODPManager.isVuid(userId)) { + return getQualifiedSegments(ODPUserKey.VUID, userId, options); + } else { + return getQualifiedSegments(ODPUserKey.FS_USER_ID, userId, options); + } } public List getQualifiedSegments(ODPUserKey userKey, String userValue) { diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java index 27de838f3..0c1c01a2c 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java @@ -211,6 +211,64 @@ public void prepareCorrectPayloadForIdentifyUser() throws InterruptedException { } } + @Test + public void identifyUserWithVuidAndUserId() throws InterruptedException { + ODPEventManager eventManager = spy(new ODPEventManager(mockApiManager)); + ArgumentCaptor captor = ArgumentCaptor.forClass(ODPEvent.class); + + eventManager.identifyUser("vuid_123", "test-user"); + verify(eventManager, times(1)).sendEvent(captor.capture()); + + ODPEvent event = captor.getValue(); + Map identifiers = event.getIdentifiers(); + assertEquals(identifiers.size(), 2); + assertEquals(identifiers.get("vuid"), "vuid_123"); + assertEquals(identifiers.get("fs_user_id"), "test-user"); + } + + @Test + public void identifyUserWithVuidOnly() throws InterruptedException { + ODPEventManager eventManager = spy(new ODPEventManager(mockApiManager)); + ArgumentCaptor captor = ArgumentCaptor.forClass(ODPEvent.class); + + eventManager.identifyUser("vuid_123", null); + verify(eventManager, times(1)).sendEvent(captor.capture()); + + ODPEvent event = captor.getValue(); + Map identifiers = event.getIdentifiers(); + assertEquals(identifiers.size(), 1); + assertEquals(identifiers.get("vuid"), "vuid_123"); + } + + @Test + public void identifyUserWithUserIdOnly() throws InterruptedException { + ODPEventManager eventManager = spy(new ODPEventManager(mockApiManager)); + ArgumentCaptor captor = ArgumentCaptor.forClass(ODPEvent.class); + + eventManager.identifyUser(null, "test-user"); + verify(eventManager, times(1)).sendEvent(captor.capture()); + + ODPEvent event = captor.getValue(); + Map identifiers = event.getIdentifiers(); + assertEquals(identifiers.size(), 1); + assertEquals(identifiers.get("fs_user_id"), "test-user"); + } + + @Test + public void identifyUserWithVuidAsUserId() throws InterruptedException { + ODPEventManager eventManager = spy(new ODPEventManager(mockApiManager)); + ArgumentCaptor captor = ArgumentCaptor.forClass(ODPEvent.class); + + eventManager.identifyUser(null, "vuid_123"); + verify(eventManager, times(1)).sendEvent(captor.capture()); + + ODPEvent event = captor.getValue(); + Map identifiers = event.getIdentifiers(); + assertEquals(identifiers.size(), 1); + // SDK will convert userId to vuid when userId has a valid vuid format. + assertEquals(identifiers.get("vuid"), "vuid_123"); + } + @Test public void applyUpdatedODPConfigWhenAvailable() throws InterruptedException { Mockito.reset(mockApiManager); diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java index 9673bfa69..1e1f59f29 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPManagerTest.java @@ -121,4 +121,12 @@ public void shouldGetSegmentManager() { odpManager = ODPManager.builder().withApiManager(mockApiManager).build(); assertNotNull(odpManager.getSegmentManager()); } + + @Test + public void isVuid() { + assertTrue(ODPManager.isVuid("vuid_123")); + assertFalse(ODPManager.isVuid("vuid123")); + assertFalse(ODPManager.isVuid("any_123")); + assertFalse(ODPManager.isVuid("")); + } } diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java index 2e6aa611e..3d71f0d2c 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPSegmentManagerTest.java @@ -398,4 +398,20 @@ public void noSegmentsInProjectAsync() throws InterruptedException { logbackVerifier.expectMessage(Level.DEBUG, "No Segments are used in the project, Not Fetching segments. Returning empty list"); } + + @Test + public void getQualifiedSegmentsWithUserId() { + ODPSegmentManager segmentManager = spy(new ODPSegmentManager(mockApiManager, mockCache)); + segmentManager.getQualifiedSegments("test-user"); + verify(segmentManager).getQualifiedSegments(ODPUserKey.FS_USER_ID, "test-user", Collections.emptyList()); + } + + @Test + public void getQualifiedSegmentsWithVuid() { + ODPSegmentManager segmentManager = spy(new ODPSegmentManager(mockApiManager, mockCache)); + segmentManager.getQualifiedSegments("vuid_123"); + // SDK will convert userId to vuid when userId has a valid vuid format. + verify(segmentManager).getQualifiedSegments(ODPUserKey.VUID, "vuid_123", Collections.emptyList()); + } + } From 989cf3fbc3bf14367e51ba86ec5c4c031f03412f Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Fri, 10 Mar 2023 13:40:39 -0800 Subject: [PATCH 36/80] [FSSDK-8953] update non-code-path resources for FX (#506) --- README.md | 129 ++++++++++++++++++++++++++++----------------- build.gradle | 2 +- core-api/README.md | 6 +-- 3 files changed, 85 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 376a8ec59..33e55928d 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,40 @@ -Optimizely Java SDK -=================== +# Optimizely Java SDK + [![Build Status](https://travis-ci.org/optimizely/java-sdk.svg?branch=master)](https://travis-ci.org/optimizely/java-sdk) [![Apache 2.0](https://img.shields.io/badge/license-APACHE%202.0-blue.svg)](http://www.apache.org/licenses/LICENSE-2.0) -This repository houses the Java SDK for use with Optimizely Full Stack and Optimizely Rollouts. +This repository houses the Java SDK for use with Optimizely Feature Experimentation and Optimizely Full Stack (legacy). + +Optimizely Feature Experimentation is an A/B testing and feature management tool for product development teams that enables you to experiment at every step. Using Optimizely Feature Experimentation allows for every feature on your roadmap to be an opportunity to discover hidden insights. Learn more at [Optimizely.com](https://www.optimizely.com/products/experiment/feature-experimentation/), or see the [developer documentation](https://docs.developers.optimizely.com/experimentation/v4.0.0-full-stack/docs/welcome). + +Optimizely Rollouts is [free feature flags](https://www.optimizely.com/free-feature-flagging/) for development teams. You can easily roll out and roll back features in any application without code deploys, mitigating risk for every feature on your roadmap. + +## Get started -Optimizely Full Stack is A/B testing and feature flag management for product development teams. Experiment in any application. Make every feature on your roadmap an opportunity to learn. Learn more at https://www.optimizely.com/platform/full-stack/, or see the [documentation](https://docs.developers.optimizely.com/experimentation/v4.0-full-stack/docs). +Refer to the [Java SDK's developer documentation](https://docs.developers.optimizely.com/experimentation/v4.0.0-full-stack/docs/java-sdk) for detailed instructions on getting started with using the SDK. -Optimizely Rollouts is free feature flags for development teams. Easily roll out and roll back features in any application without code deploys. Mitigate risk for every feature on your roadmap. Learn more at https://www.optimizely.com/rollouts/, or see the [documentation](https://docs.developers.optimizely.com/experimentation/v3.1.0-full-stack/docs/introduction-to-rollouts). +### Requirements +Java 8 or higher versions. -## Getting Started +### Install the SDK -### Installing the SDK +The Java SDK is distributed through Maven Central and is created with source and target compatibility of Java 1.8. The `core-api` and `httpclient` packages are [optimizely-sdk-core-api](https://mvnrepository.com/artifact/com.optimizely.ab/core-api) and [optimizely-sdk-httpclient](https://mvnrepository.com/artifact/com.optimizely.ab/core-httpclient-impl), respectively. -#### Gradle -The Java SDK is distributed through Maven Central and is created with source and target compatibility of Java 1.8. The `core-api` and `httpclient` packages are [optimizely-sdk-core-api](https://mvnrepository.com/artifact/com.optimizely.ab/core-api) and [optimizely-sdk-httpclient](https://mvnrepository.com/artifact/com.optimizely.ab/core-httpclient-impl), respectively. +`core-api` requires [org.slf4j:slf4j-api:1.7.16](https://mvnrepository.com/artifact/org.slf4j/slf4j-api/1.7.16) and a supported JSON parser. +We currently integrate with [Jackson](https://github.com/FasterXML/jackson), [GSON](https://github.com/google/gson), [json.org](http://www.json.org), and [json-simple](https://code.google.com/archive/p/json-simple); if any of those packages are available at runtime, they will be used by `core-api`. If none of those packages are already provided in your project's classpath, one will need to be added. + +`core-httpclient-impl` is an optional dependency that implements the event dispatcher and requires [org.apache.httpcomponents:httpclient:4.5.2](https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/4.5.2). --- + **NOTE** Optimizely previously distributed the Java SDK through Bintray/JCenter. But, as of April 27, 2021, [Bintray/JCenter will become a read-only repository indefinitely](https://jfrog.com/blog/into-the-sunset-bintray-jcenter-gocenter-and-chartcenter/). The publish repository has been migrated to [MavenCentral](https://mvnrepository.com/artifact/com.optimizely.ab) for the SDK version 3.8.1 or later. --- - ``` repositories { mavenCentral() @@ -35,49 +44,29 @@ repositories { dependencies { compile 'com.optimizely.ab:core-api:{VERSION}' compile 'com.optimizely.ab:core-httpclient-impl:{VERSION}' - // The SDK integrates with multiple JSON parsers, here we use - // Jackson. + // The SDK integrates with multiple JSON parsers, here we use Jackson. compile 'com.fasterxml.jackson.core:jackson-core:2.7.1' compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.1' compile 'com.fasterxml.jackson.core:jackson-databind:2.7.1' } -``` - -#### Dependencies - -`core-api` requires [org.slf4j:slf4j-api:1.7.16](https://mvnrepository.com/artifact/org.slf4j/slf4j-api/1.7.16) and a supported JSON parser. -We currently integrate with [Jackson](https://github.com/FasterXML/jackson), [GSON](https://github.com/google/gson), [json.org](http://www.json.org), -and [json-simple](https://code.google.com/archive/p/json-simple); if any of those packages are available at runtime, they will be used by `core-api`. -If none of those packages are already provided in your project's classpath, one will need to be added. `core-httpclient-impl` is an optional -dependency that implements the event dispatcher and requires [org.apache.httpcomponents:httpclient:4.5.2](https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/4.5.2). -The supplied `pom` files on Bintray define module dependencies. - -### Feature Management Access -To access the Feature Management configuration in the Optimizely dashboard, please contact your Optimizely account executive. +``` -### Using the SDK -See the Optimizely Full Stack [developer documentation](https://docs.developers.optimizely.com/experimentation/v4.0-full-stack/docs/java-sdk) to learn how to set -up your first Java project and use the SDK. +## Use the Java SDK -## Development +See the Optimizely Feature Experimentation [developer documentation](https://docs.developers.optimizely.com/experimentation/v4.0-full-stack/docs/java-sdk) to learn how to set up your first Java project and use the SDK. -### Building the SDK -To build local jars which are outputted into the respective modules' `build/lib` directories: - -``` -./gradlew build -``` +## SDK Development ### Unit tests -#### Running all tests - You can run all unit tests with: ``` + ./gradlew test + ``` ### Checking for bugs @@ -85,7 +74,9 @@ You can run all unit tests with: We utilize [FindBugs](http://findbugs.sourceforge.net/) to identify possible bugs in the SDK. To run the check: ``` + ./gradlew check + ``` ### Benchmarking @@ -93,7 +84,9 @@ We utilize [FindBugs](http://findbugs.sourceforge.net/) to identify possible bug [JMH](http://openjdk.java.net/projects/code-tools/jmh/) benchmarks can be run through gradle: ``` + ./gradlew core-api:jmh + ``` Results are generated in `$buildDir/reports/jmh`. @@ -112,34 +105,74 @@ This software incorporates code from the following open source projects: #### core-api module -**SLF4J** [https://www.slf4j.org ](https://www.slf4j.org) -Copyright © 2004-2017 QOS.ch +**SLF4J** [https://www.slf4j.org ](https://www.slf4j.org) + +Copyright © 2004-2017 QOS.ch + License (MIT): [https://www.slf4j.org/license.html](https://www.slf4j.org/license.html) -**Jackson Annotations** [https://github.com/FasterXML/jackson-annotations](https://github.com/FasterXML/jackson-annotations) +**Jackson Annotations** [https://github.com/FasterXML/jackson-annotations](https://github.com/FasterXML/jackson-annotations) + License (Apache 2.0): [https://github.com/FasterXML/jackson-annotations/blob/master/src/main/resources/META-INF/LICENSE](https://github.com/FasterXML/jackson-annotations/blob/master/src/main/resources/META-INF/LICENSE) -**Gson** [https://github.com/google/gson ](https://github.com/google/gson) +**Gson** [https://github.com/google/gson ](https://github.com/google/gson) + Copyright © 2008 Google Inc. + License (Apache 2.0): [https://github.com/google/gson/blob/master/LICENSE](https://github.com/google/gson/blob/master/LICENSE) -**JSON-java** [https://github.com/stleary/JSON-java](https://github.com/stleary/JSON-java) -Copyright © 2002 JSON.org +**JSON-java** [https://github.com/stleary/JSON-java](https://github.com/stleary/JSON-java) + +Copyright © 2002 JSON.org + License (The JSON License): [https://github.com/stleary/JSON-java/blob/master/LICENSE](https://github.com/stleary/JSON-java/blob/master/LICENSE) -**JSON.simple** [https://code.google.com/archive/p/json-simple/](https://code.google.com/archive/p/json-simple/) -Copyright © January 2004 +**JSON.simple** [https://code.google.com/archive/p/json-simple/](https://code.google.com/archive/p/json-simple/) + +Copyright © January 2004 + License (Apache 2.0): [https://github.com/fangyidong/json-simple/blob/master/LICENSE.txt](https://github.com/fangyidong/json-simple/blob/master/LICENSE.txt) -**Jackson Databind** [https://github.com/FasterXML/jackson-databind](https://github.com/FasterXML/jackson-databind) +**Jackson Databind** [https://github.com/FasterXML/jackson-databind](https://github.com/FasterXML/jackson-databind) + License (Apache 2.0): [https://github.com/FasterXML/jackson-databind/blob/master/src/main/resources/META-INF/LICENSE](https://github.com/FasterXML/jackson-databind/blob/master/src/main/resources/META-INF/LICENSE) #### core-httpclient-impl module -**Gson** [https://github.com/google/gson ](https://github.com/google/gson) +**Gson** [https://github.com/google/gson ](https://github.com/google/gson) + Copyright © 2008 Google Inc. + License (Apache 2.0): [https://github.com/google/gson/blob/master/LICENSE](https://github.com/google/gson/blob/master/LICENSE) -**Apache HttpClient** [https://hc.apache.org/httpcomponents-client-ga/index.html ](https://hc.apache.org/httpcomponents-client-ga/index.html) +**Apache HttpClient** [https://hc.apache.org/httpcomponents-client-ga/index.html ](https://hc.apache.org/httpcomponents-client-ga/index.html) + Copyright © January 2004 + License (Apache 2.0): [https://github.com/apache/httpcomponents-client/blob/master/LICENSE.txt](https://github.com/apache/httpcomponents-client/blob/master/LICENSE.txt) + +### Other Optimzely SDKs + +- Agent - https://github.com/optimizely/agent + +- Android - https://github.com/optimizely/android-sdk + +- C# - https://github.com/optimizely/csharp-sdk + +- Flutter - https://github.com/optimizely/optimizely-flutter-sdk + +- Go - https://github.com/optimizely/go-sdk + +- Java - https://github.com/optimizely/java-sdk + +- JavaScript - https://github.com/optimizely/javascript-sdk + +- PHP - https://github.com/optimizely/php-sdk + +- Python - https://github.com/optimizely/python-sdk + +- React - https://github.com/optimizely/react-sdk + +- Ruby - https://github.com/optimizely/ruby-sdk + +- Swift - https://github.com/optimizely/swift-sdk diff --git a/build.gradle b/build.gradle index 4c167014f..b8405e39b 100644 --- a/build.gradle +++ b/build.gradle @@ -223,7 +223,7 @@ def customizePom(pom, title) { name title url 'https://github.com/optimizely/java-sdk' - description 'The Java SDK for Optimizely Full Stack (feature flag management for product development teams)' + description 'The Java SDK for Optimizely Feature Experimentation, Optimizely Full Stack (legacy), and Optimizely Rollouts' licenses { license { name 'The Apache Software License, Version 2.0' diff --git a/core-api/README.md b/core-api/README.md index 13504566f..91d439ec7 100644 --- a/core-api/README.md +++ b/core-api/README.md @@ -1,7 +1,7 @@ # Java SDK Core API -This package contains the core APIs and interfaces for the Optimizely Full Stack API in Java. +This package contains the core APIs and interfaces for the Optimizely Feature Experimentation API in Java. -Full product documentation is in the [Optimizely developers documentation](https://docs.developers.optimizely.com/full-stack/docs/welcome). +Full product documentation is in the [Optimizely developers documentation](https://docs.developers.optimizely.com/experimentation/v4.0.0-full-stack/docs/welcome). ## Installation @@ -22,7 +22,7 @@ compile 'com.optimizely.ab:core-api:{VERSION}' ## Optimizely [`Optimizely`](https://github.com/optimizely/java-sdk/blob/master/core-api/src/main/java/com/optimizely/ab/Optimizely.java) -provides top level API access to the Full Stack project. +provides top level API access to the Feature Experimentation project. ### Usage ```Java From 2de31040b71d59605848600a38588542a481153b Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Fri, 10 Mar 2023 14:52:38 -0800 Subject: [PATCH 37/80] chore: prepare for release 3.10.3 (#507) --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50b9c6cf0..2fab5c6e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Optimizely Java X SDK Changelog +## [3.10.3] +March 10th, 2023 + +### Fixes +We updated our README.md and other non-functional code to reflect that this SDK supports both Optimizely Feature Experimentation and Optimizely Full Stack ([#506](https://github.com/optimizely/java-sdk/pull/506)). + ## [3.10.2] March 17th, 2022 From d9f19b35edba56824ebef40f4f1ff227dd2d4809 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Mon, 13 Mar 2023 10:30:51 -0700 Subject: [PATCH 38/80] fix release date (#508) --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fab5c6e7..ac028c780 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,7 @@ # Optimizely Java X SDK Changelog ## [3.10.3] -March 10th, 2023 +March 13th, 2023 ### Fixes We updated our README.md and other non-functional code to reflect that this SDK supports both Optimizely Feature Experimentation and Optimizely Full Stack ([#506](https://github.com/optimizely/java-sdk/pull/506)). From 9e02c7e24d09fedf058203c56617bcf6546f2f37 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Tue, 21 Mar 2023 08:45:05 -0700 Subject: [PATCH 39/80] fix(odp): check odp identifiers not empty before sending (#509) --- .../java/com/optimizely/ab/Optimizely.java | 9 +++++++++ .../java/com/optimizely/ab/odp/ODPEvent.java | 14 ++++++++++---- .../optimizely/ab/odp/ODPEventManager.java | 13 ++++++++++--- .../ab/odp/ODPEventManagerTest.java | 19 +++++++++++++++++-- 4 files changed, 46 insertions(+), 9 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/Optimizely.java b/core-api/src/main/java/com/optimizely/ab/Optimizely.java index 5f41bcd6e..fe28a8bb4 100644 --- a/core-api/src/main/java/com/optimizely/ab/Optimizely.java +++ b/core-api/src/main/java/com/optimizely/ab/Optimizely.java @@ -1468,6 +1468,15 @@ public ODPManager getODPManager() { return odpManager; } + + /** + * Send an event to the ODP server. + * + * @param type the event type (default = "fullstack"). + * @param action the event action name. + * @param identifiers a dictionary for identifiers. The caller must provide at least one key-value pair unless non-empty common identifiers have been set already with {@link ODPManager.Builder#withUserCommonIdentifiers(Map) }. + * @param data a dictionary for associated data. The default event data will be added to this data before sending to the ODP server. + */ public void sendODPEvent(@Nullable String type, @Nonnull String action, @Nullable Map identifiers, @Nullable Map data) { if (odpManager != null) { ODPEvent event = new ODPEvent(type, action, identifiers, data); diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java index 2ed2c1e76..71e054df0 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java @@ -24,10 +24,10 @@ public class ODPEvent { public static final String EVENT_TYPE_FULLSTACK = "fullstack"; - private String type; - private String action; - private Map identifiers; - private Map data; + @Nonnull private String type; + @Nonnull private String action; + @Nonnull private Map identifiers; + @Nonnull private Map data; public ODPEvent(@Nullable String type, @Nonnull String action, @Nullable Map identifiers, @Nullable Map data) { this.type = type == null ? EVENT_TYPE_FULLSTACK : type; @@ -84,4 +84,10 @@ public Boolean isDataValid() { } return true; } + + @Transient + public Boolean isIdentifiersValid() { + return !identifiers.isEmpty(); + } + } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java index 8edb135aa..352c47eac 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java @@ -119,12 +119,19 @@ public void identifyUser(@Nullable String vuid, @Nullable String userId) { } public void sendEvent(ODPEvent event) { + event.setData(augmentCommonData(event.getData())); + event.setIdentifiers(augmentCommonIdentifiers(event.getIdentifiers())); + + if (!event.isIdentifiersValid()) { + logger.error("ODP event send failed (event identifiers must have at least one key-value pair)"); + return; + } + if (!event.isDataValid()) { - logger.error("ODP event send failed (ODP data is not valid)"); + logger.error("ODP event send failed (event data is not valid)"); return; } - event.setData(augmentCommonData(event.getData())); - event.setIdentifiers(augmentCommonIdentifiers(event.getIdentifiers())); + processEvent(event); } diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java index 0c1c01a2c..d2163a6b6 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java @@ -61,7 +61,7 @@ public void logAndDiscardEventWhenEventManagerIsNotRunning() { ODPConfig odpConfig = new ODPConfig("key", "host", null); ODPEventManager eventManager = new ODPEventManager(mockApiManager); eventManager.updateSettings(odpConfig); - ODPEvent event = new ODPEvent("test-type", "test-action", Collections.emptyMap(), Collections.emptyMap()); + ODPEvent event = new ODPEvent("test-type", "test-action", Collections.singletonMap("any-key", "any-value"), Collections.emptyMap()); eventManager.sendEvent(event); logbackVerifier.expectMessage(Level.WARN, "Failed to Process ODP Event. ODPEventManager is not running"); } @@ -72,7 +72,7 @@ public void logAndDiscardEventWhenODPConfigNotReady() { ODPEventManager eventManager = new ODPEventManager(mockApiManager); eventManager.updateSettings(odpConfig); eventManager.start(); - ODPEvent event = new ODPEvent("test-type", "test-action", Collections.emptyMap(), Collections.emptyMap()); + ODPEvent event = new ODPEvent("test-type", "test-action", Collections.singletonMap("any-key", "any-value"), Collections.emptyMap()); eventManager.sendEvent(event); logbackVerifier.expectMessage(Level.DEBUG, "Unable to Process ODP Event. ODPConfig is not ready."); } @@ -92,6 +92,21 @@ public void dispatchEventsInCorrectNumberOfBatches() throws InterruptedException Mockito.verify(mockApiManager, times(3)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), any()); } + @Test + public void logAndDiscardEventWhenIdentifiersEmpty() throws InterruptedException { + int flushInterval = 0; + ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); + ODPEventManager eventManager = new ODPEventManager(mockApiManager, null, flushInterval); + eventManager.updateSettings(odpConfig); + eventManager.start(); + + ODPEvent event = new ODPEvent("test-type", "test-action", Collections.emptyMap(), Collections.emptyMap()); + eventManager.sendEvent(event); + Thread.sleep(500); + Mockito.verify(mockApiManager, never()).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), any()); + logbackVerifier.expectMessage(Level.ERROR, "ODP event send failed (event identifiers must have at least one key-value pair)"); + } + @Test public void dispatchEventsWithCorrectPayload() throws InterruptedException { Mockito.reset(mockApiManager); From 2022b49a0a2b4d5046a32aa6e62f53f3b9b158a1 Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Tue, 25 Apr 2023 22:54:06 +0500 Subject: [PATCH 40/80] [FSSDK-9054] fix(odp): flush odp events instantly upon calling close (#511) * corrected flush all test and added shutdown event instead of shutdown boolean. * Added check --------- Co-authored-by: NomanShoaib --- .../com/optimizely/ab/odp/ODPEventManager.java | 18 ++++++++++-------- .../optimizely/ab/odp/ODPEventManagerTest.java | 7 ++++--- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java index 352c47eac..0a93627b7 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java @@ -35,6 +35,7 @@ public class ODPEventManager { private static final int DEFAULT_FLUSH_INTERVAL = 1000; private static final int MAX_RETRIES = 3; private static final String EVENT_URL_PATH = "/v3/events"; + private static final Object SHUTDOWN_SIGNAL = new Object(); private final int queueSize; private final int batchSize; @@ -188,8 +189,6 @@ public void stop() { private class EventDispatcherThread extends Thread { - private volatile boolean shouldStop = false; - private final List currentBatch = new ArrayList<>(); private long nextFlushTime = new Date().getTime(); @@ -198,7 +197,7 @@ private class EventDispatcherThread extends Thread { public void run() { while (true) { try { - Object nextEvent; + Object nextEvent = null; // If batch has events, set the timeout to remaining time for flush interval, // otherwise wait for the new event indefinitely @@ -213,9 +212,6 @@ public void run() { if (!currentBatch.isEmpty()) { flush(); } - if (shouldStop) { - break; - } continue; } @@ -228,7 +224,11 @@ public void run() { // Batch starting, create a new flush time nextFlushTime = new Date().getTime() + flushInterval; } - + if (nextEvent == SHUTDOWN_SIGNAL) { + flush(); + logger.info("Received shutdown signal."); + break; + } currentBatch.add((ODPEvent) nextEvent); if (currentBatch.size() >= batchSize) { @@ -268,7 +268,9 @@ private void flush() { } public void signalStop() { - shouldStop = true; + if (!eventQueue.offer(SHUTDOWN_SIGNAL)) { + logger.error("Failed to Process Shutdown odp Event. Event Queue is not accepting any more events"); + } } } diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java index d2163a6b6..eb005f832 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java @@ -182,18 +182,19 @@ public void retryFailedEvents() throws InterruptedException { @Test public void shouldFlushAllScheduledEventsBeforeStopping() throws InterruptedException { + int flushInterval = 20000; Mockito.reset(mockApiManager); Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); - ODPEventManager eventManager = new ODPEventManager(mockApiManager); + ODPEventManager eventManager = new ODPEventManager(mockApiManager, null, flushInterval); eventManager.updateSettings(odpConfig); eventManager.start(); - for (int i = 0; i < 25; i++) { + for (int i = 0; i < 8; i++) { eventManager.sendEvent(getEvent(i)); } eventManager.stop(); Thread.sleep(1500); - Mockito.verify(mockApiManager, times(3)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), any()); + Mockito.verify(mockApiManager, times(1)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), any()); logbackVerifier.expectMessage(Level.DEBUG, "Exiting ODP Event Dispatcher Thread."); } From 8dc9a74bcc662c9f8a7e0220d084b527fb36dc98 Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Tue, 25 Apr 2023 23:45:33 +0500 Subject: [PATCH 41/80] [FSSDK-9076] fix: send odp event empty values (#513) * [FSSDK-9076] fix: send odp event empty values * nit fix --------- Co-authored-by: NomanShoaib --- .../java/com/optimizely/ab/Optimizely.java | 5 + .../java/com/optimizely/ab/odp/ODPEvent.java | 2 +- .../optimizely/ab/odp/ODPEventManager.java | 28 +++- .../com/optimizely/ab/odp/ODPUserKey.java | 6 +- .../com/optimizely/ab/OptimizelyTest.java | 122 ++++++++++++++++++ .../ab/odp/ODPEventManagerTest.java | 67 ++++++++++ 6 files changed, 226 insertions(+), 4 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/Optimizely.java b/core-api/src/main/java/com/optimizely/ab/Optimizely.java index fe28a8bb4..c8ca3d55b 100644 --- a/core-api/src/main/java/com/optimizely/ab/Optimizely.java +++ b/core-api/src/main/java/com/optimizely/ab/Optimizely.java @@ -1479,6 +1479,11 @@ public ODPManager getODPManager() { */ public void sendODPEvent(@Nullable String type, @Nonnull String action, @Nullable Map identifiers, @Nullable Map data) { if (odpManager != null) { + if (action == null || action.trim().isEmpty()) { + logger.error("ODP action is not valid (cannot be empty)."); + return; + } + ODPEvent event = new ODPEvent(type, action, identifiers, data); odpManager.getEventManager().sendEvent(event); } else { diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java index 71e054df0..a505bf6d1 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEvent.java @@ -30,7 +30,7 @@ public class ODPEvent { @Nonnull private Map data; public ODPEvent(@Nullable String type, @Nonnull String action, @Nullable Map identifiers, @Nullable Map data) { - this.type = type == null ? EVENT_TYPE_FULLSTACK : type; + this.type = type == null || type.trim().isEmpty() ? EVENT_TYPE_FULLSTACK : type; this.action = action; this.identifiers = identifiers != null ? identifiers : Collections.emptyMap(); this.data = data != null ? data : Collections.emptyMap(); diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java index 0a93627b7..ba668a138 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java @@ -35,6 +35,10 @@ public class ODPEventManager { private static final int DEFAULT_FLUSH_INTERVAL = 1000; private static final int MAX_RETRIES = 3; private static final String EVENT_URL_PATH = "/v3/events"; + private static final List FS_USER_ID_MATCHES = new ArrayList<>(Arrays.asList( + ODPUserKey.FS_USER_ID.getKeyString(), + ODPUserKey.FS_USER_ID_ALIAS.getKeyString() + )); private static final Object SHUTDOWN_SIGNAL = new Object(); private final int queueSize; @@ -121,7 +125,7 @@ public void identifyUser(@Nullable String vuid, @Nullable String userId) { public void sendEvent(ODPEvent event) { event.setData(augmentCommonData(event.getData())); - event.setIdentifiers(augmentCommonIdentifiers(event.getIdentifiers())); + event.setIdentifiers(convertCriticalIdentifiers(augmentCommonIdentifiers(event.getIdentifiers()))); if (!event.isIdentifiersValid()) { logger.error("ODP event send failed (event identifiers must have at least one key-value pair)"); @@ -133,6 +137,7 @@ public void sendEvent(ODPEvent event) { return; } + processEvent(event); } @@ -158,6 +163,27 @@ protected Map augmentCommonIdentifiers(Map sourc Map identifiers = new HashMap<>(); identifiers.putAll(userCommonIdentifiers); identifiers.putAll(sourceIdentifiers); + + return identifiers; + } + + private static Map convertCriticalIdentifiers(Map identifiers) { + + if (identifiers.containsKey(ODPUserKey.FS_USER_ID.getKeyString())) { + return identifiers; + } + + List> identifiersList = new ArrayList<>(identifiers.entrySet()); + + for (Map.Entry kvp : identifiersList) { + + if (FS_USER_ID_MATCHES.contains(kvp.getKey().toLowerCase())) { + identifiers.remove(kvp.getKey()); + identifiers.put(ODPUserKey.FS_USER_ID.getKeyString(), kvp.getValue()); + break; + } + } + return identifiers; } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPUserKey.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPUserKey.java index d7cdbb641..ef0bce3ff 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPUserKey.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPUserKey.java @@ -1,6 +1,6 @@ /** * - * Copyright 2022, Optimizely + * Copyright 2022-2023, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,9 @@ public enum ODPUserKey { VUID("vuid"), - FS_USER_ID("fs_user_id"); + FS_USER_ID("fs_user_id"), + + FS_USER_ID_ALIAS("fs-user-id"); private final String keyString; diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java index 705ce1cb6..700780f75 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java @@ -4762,6 +4762,128 @@ public void sendODPEvent() { assertEquals(data, eventArgument.getValue().getData()); } + @Test + @SuppressFBWarnings(value = "NP_NONNULL_PARAM_VIOLATION", justification = "Testing nullness contract violation") + public void sendODPEventErrorNullAction() { + ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); + Mockito.when(mockProjectConfigManager.getConfig()).thenReturn(validProjectConfig); + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Optimizely optimizely = Optimizely.builder() + .withConfigManager(mockProjectConfigManager) + .withODPManager(mockODPManager) + .build(); + + verify(mockODPEventManager).start(); + + Map identifiers = new HashMap<>(); + identifiers.put("id1", "value1"); + identifiers.put("id2", "value2"); + + Map data = new HashMap<>(); + data.put("sdk", "java"); + data.put("revision", 52); + + optimizely.sendODPEvent("fullstack", null, identifiers, data); + logbackVerifier.expectMessage(Level.ERROR, "ODP action is not valid (cannot be empty)."); + } + + @Test + public void sendODPEventErrorEmptyAction() { + ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); + Mockito.when(mockProjectConfigManager.getConfig()).thenReturn(validProjectConfig); + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Optimizely optimizely = Optimizely.builder() + .withConfigManager(mockProjectConfigManager) + .withODPManager(mockODPManager) + .build(); + + verify(mockODPEventManager).start(); + + Map identifiers = new HashMap<>(); + identifiers.put("id1", "value1"); + identifiers.put("id2", "value2"); + + Map data = new HashMap<>(); + data.put("sdk", "java"); + data.put("revision", 52); + + optimizely.sendODPEvent("fullstack", "", identifiers, data); + logbackVerifier.expectMessage(Level.ERROR, "ODP action is not valid (cannot be empty)."); + } + + @Test + @SuppressFBWarnings(value = "NP_NONNULL_PARAM_VIOLATION", justification = "Testing nullness contract violation") + public void sendODPEventNullType() { + ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); + Mockito.when(mockProjectConfigManager.getConfig()).thenReturn(validProjectConfig); + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Optimizely optimizely = Optimizely.builder() + .withConfigManager(mockProjectConfigManager) + .withODPManager(mockODPManager) + .build(); + + verify(mockODPEventManager).start(); + + Map identifiers = new HashMap<>(); + identifiers.put("id1", "value1"); + identifiers.put("id2", "value2"); + + Map data = new HashMap<>(); + data.put("sdk", "java"); + data.put("revision", 52); + + optimizely.sendODPEvent(null, "identify", identifiers, data); + ArgumentCaptor eventArgument = ArgumentCaptor.forClass(ODPEvent.class); + verify(mockODPEventManager).sendEvent(eventArgument.capture()); + + assertEquals("fullstack", eventArgument.getValue().getType()); + assertEquals("identify", eventArgument.getValue().getAction()); + assertEquals(identifiers, eventArgument.getValue().getIdentifiers()); + assertEquals(data, eventArgument.getValue().getData()); + } + + @Test + public void sendODPEventEmptyType() { + ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); + Mockito.when(mockProjectConfigManager.getConfig()).thenReturn(validProjectConfig); + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Optimizely optimizely = Optimizely.builder() + .withConfigManager(mockProjectConfigManager) + .withODPManager(mockODPManager) + .build(); + + verify(mockODPEventManager).start(); + + Map identifiers = new HashMap<>(); + identifiers.put("id1", "value1"); + identifiers.put("id2", "value2"); + + Map data = new HashMap<>(); + data.put("sdk", "java"); + data.put("revision", 52); + + optimizely.sendODPEvent("", "identify", identifiers, data); + ArgumentCaptor eventArgument = ArgumentCaptor.forClass(ODPEvent.class); + verify(mockODPEventManager).sendEvent(eventArgument.capture()); + + assertEquals("fullstack", eventArgument.getValue().getType()); + assertEquals("identify", eventArgument.getValue().getAction()); + assertEquals(identifiers, eventArgument.getValue().getIdentifiers()); + assertEquals(data, eventArgument.getValue().getData()); + } + @Test public void sendODPEventError() { ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java index eb005f832..8a7546300 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java @@ -227,6 +227,73 @@ public void prepareCorrectPayloadForIdentifyUser() throws InterruptedException { } } + @Test + public void preparePayloadForIdentifyUserWithVariationsOfFsUserId() throws InterruptedException { + Mockito.reset(mockApiManager); + Mockito.when(mockApiManager.sendEvents(any(), any(), any())).thenReturn(202); + int flushInterval = 1; + ODPConfig odpConfig = new ODPConfig("key", "http://www.odp-host.com", null); + ODPEventManager eventManager = new ODPEventManager(mockApiManager, null, flushInterval); + eventManager.updateSettings(odpConfig); + eventManager.start(); + ODPEvent event1 = new ODPEvent("fullstack", + "identified", + new HashMap() {{ + put("fs-user-id", "123"); + }}, null); + + ODPEvent event2 = new ODPEvent("fullstack", + "identified", + new HashMap() {{ + put("FS-user-ID", "123"); + }}, null); + + ODPEvent event3 = new ODPEvent("fullstack", + "identified", + new HashMap() {{ + put("FS_USER_ID", "123"); + put("fs.user.id", "456"); + }}, null); + + ODPEvent event4 = new ODPEvent("fullstack", + "identified", + new HashMap() {{ + put("fs_user_id", "123"); + put("fsuserid", "456"); + }}, null); + List> expectedIdentifiers = new ArrayList>() {{ + add(new HashMap() {{ + put("fs_user_id", "123"); + }}); + add(new HashMap() {{ + put("fs_user_id", "123"); + }}); + add(new HashMap() {{ + put("fs_user_id", "123"); + put("fs.user.id", "456"); + }}); + add(new HashMap() {{ + put("fs_user_id", "123"); + put("fsuserid", "456"); + }}); + }}; + eventManager.sendEvent(event1); + eventManager.sendEvent(event2); + eventManager.sendEvent(event3); + eventManager.sendEvent(event4); + + Thread.sleep(1500); + Mockito.verify(mockApiManager, times(1)).sendEvents(eq("key"), eq("http://www.odp-host.com/v3/events"), payloadCaptor.capture()); + + String payload = payloadCaptor.getValue(); + JSONArray events = new JSONArray(payload); + assertEquals(4, events.length()); + for (int i = 0; i < events.length(); i++) { + JSONObject event = events.getJSONObject(i); + assertEquals(event.getJSONObject("identifiers").toMap(), expectedIdentifiers.get(i)); + } + } + @Test public void identifyUserWithVuidAndUserId() throws InterruptedException { ODPEventManager eventManager = spy(new ODPEventManager(mockApiManager)); From 791ae41785e403f840301ec4f5d79a6b0de34772 Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Wed, 26 Apr 2023 00:35:44 +0500 Subject: [PATCH 42/80] [FSSDK-9056] fix: add config check in odp methods (#512) * [FSSDK-9056] fix: add config check in odp methods * Fixed tests by passing valid config * spotbug fix --------- Co-authored-by: NomanShoaib --- .../java/com/optimizely/ab/Optimizely.java | 21 +++++ .../com/optimizely/ab/OptimizelyTest.java | 31 ++++++- .../ab/OptimizelyUserContextTest.java | 83 +++++++++++++++++++ 3 files changed, 134 insertions(+), 1 deletion(-) diff --git a/core-api/src/main/java/com/optimizely/ab/Optimizely.java b/core-api/src/main/java/com/optimizely/ab/Optimizely.java index c8ca3d55b..acd9d05fd 100644 --- a/core-api/src/main/java/com/optimizely/ab/Optimizely.java +++ b/core-api/src/main/java/com/optimizely/ab/Optimizely.java @@ -1445,6 +1445,11 @@ public int addNotificationHandler(Class clazz, NotificationHandler han } public List fetchQualifiedSegments(String userId, @Nonnull List segmentOptions) { + ProjectConfig projectConfig = getProjectConfig(); + if (projectConfig == null) { + logger.error("Optimizely instance is not valid, failing fetchQualifiedSegments call."); + return null; + } if (odpManager != null) { synchronized (odpManager) { return odpManager.getSegmentManager().getQualifiedSegments(userId, segmentOptions); @@ -1455,6 +1460,12 @@ public List fetchQualifiedSegments(String userId, @Nonnull List segmentOptions) { + ProjectConfig projectConfig = getProjectConfig(); + if (projectConfig == null) { + logger.error("Optimizely instance is not valid, failing fetchQualifiedSegments call."); + callback.onCompleted(null); + return; + } if (odpManager == null) { logger.error("Audience segments fetch failed (ODP is not enabled)."); callback.onCompleted(null); @@ -1478,6 +1489,11 @@ public ODPManager getODPManager() { * @param data a dictionary for associated data. The default event data will be added to this data before sending to the ODP server. */ public void sendODPEvent(@Nullable String type, @Nonnull String action, @Nullable Map identifiers, @Nullable Map data) { + ProjectConfig projectConfig = getProjectConfig(); + if (projectConfig == null) { + logger.error("Optimizely instance is not valid, failing sendODPEvent call."); + return; + } if (odpManager != null) { if (action == null || action.trim().isEmpty()) { logger.error("ODP action is not valid (cannot be empty)."); @@ -1492,6 +1508,11 @@ public void sendODPEvent(@Nullable String type, @Nonnull String action, @Nullabl } public void identifyUser(@Nonnull String userId) { + ProjectConfig projectConfig = getProjectConfig(); + if (projectConfig == null) { + logger.error("Optimizely instance is not valid, failing identifyUser call."); + return; + } ODPManager odpManager = getODPManager(); if (odpManager != null) { odpManager.getEventManager().identifyUser(userId); diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java index 700780f75..260de9945 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java @@ -4733,6 +4733,7 @@ public void initODPManagerWithProjectConfig() throws IOException { @Test public void sendODPEvent() { ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); + Mockito.when(mockProjectConfigManager.getConfig()).thenReturn(validProjectConfig); ODPEventManager mockODPEventManager = mock(ODPEventManager.class); ODPManager mockODPManager = mock(ODPManager.class); @@ -4762,6 +4763,33 @@ public void sendODPEvent() { assertEquals(data, eventArgument.getValue().getData()); } + @Test + public void sendODPEventInvalidConfig() { + ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); + Mockito.when(mockProjectConfigManager.getConfig()).thenReturn(null); + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Optimizely optimizely = Optimizely.builder() + .withConfigManager(mockProjectConfigManager) + .withODPManager(mockODPManager) + .build(); + + verify(mockODPEventManager).start(); + + Map identifiers = new HashMap<>(); + identifiers.put("id1", "value1"); + identifiers.put("id2", "value2"); + + Map data = new HashMap<>(); + data.put("sdk", "java"); + data.put("revision", 52); + + optimizely.sendODPEvent("fullstack", "identify", identifiers, data); + logbackVerifier.expectMessage(Level.ERROR, "Optimizely instance is not valid, failing sendODPEvent call."); + } + @Test @SuppressFBWarnings(value = "NP_NONNULL_PARAM_VIOLATION", justification = "Testing nullness contract violation") public void sendODPEventErrorNullAction() { @@ -4887,7 +4915,7 @@ public void sendODPEventEmptyType() { @Test public void sendODPEventError() { ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); - + Mockito.when(mockProjectConfigManager.getConfig()).thenReturn(validProjectConfig); Optimizely optimizely = Optimizely.builder() .withConfigManager(mockProjectConfigManager) .build(); @@ -4907,6 +4935,7 @@ public void sendODPEventError() { @Test public void identifyUser() { ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); + Mockito.when(mockProjectConfigManager.getConfig()).thenReturn(validProjectConfig); ODPEventManager mockODPEventManager = mock(ODPEventManager.class); ODPManager mockODPManager = mock(ODPManager.class); diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java index 8f8bae834..7c479f147 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java @@ -1628,6 +1628,8 @@ public void fetchQualifiedSegments() { Mockito.when(mockODPManager.getSegmentManager()).thenReturn(mockODPSegmentManager); Optimizely optimizely = Optimizely.builder() + .withDatafile(datafile) + .withEventProcessor(new ForwardingEventProcessor(eventHandler, null)) .withODPManager(mockODPManager) .build(); @@ -1640,9 +1642,33 @@ public void fetchQualifiedSegments() { verify(mockODPSegmentManager).getQualifiedSegments("test-user", Collections.singletonList(ODPSegmentOption.RESET_CACHE)); } + @Test + public void fetchQualifiedSegmentsErrorWhenConfigIsInvalid() { + ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); + Mockito.when(mockProjectConfigManager.getConfig()).thenReturn(null); + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPSegmentManager mockODPSegmentManager = mock(ODPSegmentManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Mockito.when(mockODPManager.getSegmentManager()).thenReturn(mockODPSegmentManager); + + Optimizely optimizely = Optimizely.builder() + .withConfigManager(mockProjectConfigManager) + .withODPManager(mockODPManager) + .build(); + + OptimizelyUserContext userContext = optimizely.createUserContext("test-user"); + + assertFalse(userContext.fetchQualifiedSegments()); + logbackVerifier.expectMessage(Level.ERROR, "Optimizely instance is not valid, failing fetchQualifiedSegments call."); + } + @Test public void fetchQualifiedSegmentsError() { Optimizely optimizely = Optimizely.builder() + .withDatafile(datafile) + .withEventProcessor(new ForwardingEventProcessor(eventHandler, null)) .build(); OptimizelyUserContext userContext = optimizely.createUserContext("test-user"); @@ -1667,6 +1693,8 @@ public void fetchQualifiedSegmentsAsync() throws InterruptedException { Mockito.when(mockODPManager.getSegmentManager()).thenReturn(mockODPSegmentManager); Optimizely optimizely = Optimizely.builder() + .withDatafile(datafile) + .withEventProcessor(new ForwardingEventProcessor(eventHandler, null)) .withODPManager(mockODPManager) .build(); @@ -1698,6 +1726,8 @@ public void fetchQualifiedSegmentsAsync() throws InterruptedException { @Test public void fetchQualifiedSegmentsAsyncError() throws InterruptedException { Optimizely optimizely = Optimizely.builder() + .withDatafile(datafile) + .withEventProcessor(new ForwardingEventProcessor(eventHandler, null)) .build(); OptimizelyUserContext userContext = optimizely.createUserContext("test-user"); @@ -1713,6 +1743,57 @@ public void fetchQualifiedSegmentsAsyncError() throws InterruptedException { logbackVerifier.expectMessage(Level.ERROR, "Audience segments fetch failed (ODP is not enabled)."); } + @Test + public void fetchQualifiedSegmentsAsyncErrorWhenConfigIsInvalid() throws InterruptedException { + ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); + Mockito.when(mockProjectConfigManager.getConfig()).thenReturn(null); + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPSegmentManager mockODPSegmentManager = mock(ODPSegmentManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Mockito.when(mockODPManager.getSegmentManager()).thenReturn(mockODPSegmentManager); + + Optimizely optimizely = Optimizely.builder() + .withConfigManager(mockProjectConfigManager) + .withODPManager(mockODPManager) + .build(); + + OptimizelyUserContext userContext = optimizely.createUserContext("test-user"); + + CountDownLatch countDownLatch = new CountDownLatch(1); + userContext.fetchQualifiedSegments((Boolean isFetchSuccessful) -> { + assertFalse(isFetchSuccessful); + countDownLatch.countDown(); + }); + + countDownLatch.await(); + assertEquals(null, userContext.getQualifiedSegments()); + logbackVerifier.expectMessage(Level.ERROR, "Optimizely instance is not valid, failing fetchQualifiedSegments call."); + } + + @Test + public void identifyUserErrorWhenConfigIsInvalid() { + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPSegmentManager mockODPSegmentManager = mock(ODPSegmentManager.class); + ODPManager mockODPManager = mock(ODPManager.class); + ProjectConfigManager mockProjectConfigManager = mock(ProjectConfigManager.class); + Mockito.when(mockProjectConfigManager.getConfig()).thenReturn(null); + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Mockito.when(mockODPManager.getSegmentManager()).thenReturn(mockODPSegmentManager); + + Optimizely optimizely = Optimizely.builder() + .withConfigManager(mockProjectConfigManager) + .withODPManager(mockODPManager) + .build(); + + optimizely.createUserContext("test-user"); + verify(mockODPEventManager, never()).identifyUser("test-user"); + Mockito.reset(mockODPEventManager); + + logbackVerifier.expectMessage(Level.ERROR, "Optimizely instance is not valid, failing identifyUser call."); + } + @Test public void identifyUser() { ODPEventManager mockODPEventManager = mock(ODPEventManager.class); @@ -1723,6 +1804,8 @@ public void identifyUser() { Mockito.when(mockODPManager.getSegmentManager()).thenReturn(mockODPSegmentManager); Optimizely optimizely = Optimizely.builder() + .withDatafile(datafile) + .withEventProcessor(new ForwardingEventProcessor(eventHandler, null)) .withODPManager(mockODPManager) .build(); From 562310f29a7ac2b569f11337c9e9a687ebefa062 Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Thu, 4 May 2023 04:49:47 +0500 Subject: [PATCH 43/80] [FSSDK-9127] fix: Handle ODP INVALID_IDENTIFIER_EXCEPTION code (#514) * [FSSDK-9127] Fix: Verifiying that ODP INVALID_IDENTIFIER_EXCEPTION code is handled gracefully. * Parsed errors as per new odp update * support case when code key is missing and classification key exist. --------- Co-authored-by: NomanShoaib --- .../ab/odp/parser/impl/GsonParser.java | 17 +++++----- .../ab/odp/parser/impl/JacksonParser.java | 15 ++++----- .../ab/odp/parser/impl/JsonParser.java | 18 ++++++----- .../ab/odp/parser/impl/JsonSimpleParser.java | 16 +++++----- .../ab/odp/parser/ResponseJsonParserTest.java | 31 +++++++++++++++++-- .../ab/odp/DefaultODPApiManager.java | 3 +- 6 files changed, 65 insertions(+), 35 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/GsonParser.java b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/GsonParser.java index b27d65078..70136536f 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/GsonParser.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/GsonParser.java @@ -1,5 +1,5 @@ /** - * Copyright 2022, Optimizely Inc. and contributors + * Copyright 2022-2023, Optimizely Inc. and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,15 +34,16 @@ public List parseQualifiedSegments(String responseJson) { JsonObject root = JsonParser.parseString(responseJson).getAsJsonObject(); if (root.has("errors")) { - JsonArray errors = root.getAsJsonArray("errors"); - StringBuilder logMessage = new StringBuilder(); - for (int i = 0; i < errors.size(); i++) { - if (i > 0) { - logMessage.append(", "); + JsonArray errors = root.getAsJsonArray("errors"); + JsonObject extensions = errors.get(0).getAsJsonObject().get("extensions").getAsJsonObject(); + if (extensions != null) { + if (extensions.has("code") && extensions.get("code").getAsString().equals("INVALID_IDENTIFIER_EXCEPTION")) { + logger.warn("Audience segments fetch failed (invalid identifier)"); + } else { + String errorMessage = extensions.get("classification") == null ? "decode error" : extensions.get("classification").getAsString(); + logger.error("Audience segments fetch failed (" + errorMessage + ")"); } - logMessage.append(errors.get(i).getAsJsonObject().get("message").getAsString()); } - logger.error(logMessage.toString()); return null; } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JacksonParser.java b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JacksonParser.java index f1a38eca7..b9a2b668f 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JacksonParser.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JacksonParser.java @@ -1,5 +1,5 @@ /** - * Copyright 2022, Optimizely Inc. and contributors + * Copyright 2022-2023, Optimizely Inc. and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,14 +39,15 @@ public List parseQualifiedSegments(String responseJson) { if (root.has("errors")) { JsonNode errors = root.path("errors"); - StringBuilder logMessage = new StringBuilder(); - for (int i = 0; i < errors.size(); i++) { - if (i > 0) { - logMessage.append(", "); + JsonNode extensions = errors.get(0).path("extensions"); + if (extensions != null) { + if (extensions.has("code") && extensions.path("code").asText().equals("INVALID_IDENTIFIER_EXCEPTION")) { + logger.warn("Audience segments fetch failed (invalid identifier)"); + } else { + String errorMessage = extensions.has("classification") ? extensions.path("classification").asText() : "decode error"; + logger.error("Audience segments fetch failed (" + errorMessage + ")"); } - logMessage.append(errors.get(i).path("message")); } - logger.error(logMessage.toString()); return null; } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonParser.java b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonParser.java index fcae748a4..e0e23c366 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonParser.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonParser.java @@ -1,5 +1,5 @@ /** - * Copyright 2022, Optimizely Inc. and contributors + * Copyright 2022-2023, Optimizely Inc. and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,15 +35,17 @@ public List parseQualifiedSegments(String responseJson) { JSONObject root = new JSONObject(responseJson); if (root.has("errors")) { - JSONArray errors = root.getJSONArray("errors"); - StringBuilder logMessage = new StringBuilder(); - for (int i = 0; i < errors.length(); i++) { - if (i > 0) { - logMessage.append(", "); + JSONArray errors = root.getJSONArray("errors"); + JSONObject extensions = errors.getJSONObject(0).getJSONObject("extensions"); + if (extensions != null) { + if (extensions.has("code") && extensions.getString("code").equals("INVALID_IDENTIFIER_EXCEPTION")) { + logger.warn("Audience segments fetch failed (invalid identifier)"); + } else { + String errorMessage = extensions.has("classification") ? + extensions.getString("classification") : "decode error"; + logger.error("Audience segments fetch failed (" + errorMessage + ")"); } - logMessage.append(errors.getJSONObject(i).getString("message")); } - logger.error(logMessage.toString()); return null; } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonSimpleParser.java b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonSimpleParser.java index 1bee81b0a..de444e3c2 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonSimpleParser.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/parser/impl/JsonSimpleParser.java @@ -1,5 +1,5 @@ /** - * Copyright 2022, Optimizely Inc. and contributors + * Copyright 2022-2023, Optimizely Inc. and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,17 +36,17 @@ public List parseQualifiedSegments(String responseJson) { JSONObject root = null; try { root = (JSONObject) parser.parse(responseJson); - if (root.containsKey("errors")) { JSONArray errors = (JSONArray) root.get("errors"); - StringBuilder logMessage = new StringBuilder(); - for (int i = 0; i < errors.size(); i++) { - if (i > 0) { - logMessage.append(", "); + JSONObject extensions = (JSONObject) ((JSONObject) errors.get(0)).get("extensions"); + if (extensions != null) { + if (extensions.containsKey("code") && extensions.get("code").equals("INVALID_IDENTIFIER_EXCEPTION")) { + logger.warn("Audience segments fetch failed (invalid identifier)"); + } else { + String errorMessage = extensions.get("classification") == null ? "decode error" : (String) extensions.get("classification"); + logger.error("Audience segments fetch failed (" + errorMessage + ")"); } - logMessage.append((String)((JSONObject) errors.get(i)).get("message")); } - logger.error(logMessage.toString()); return null; } diff --git a/core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserTest.java b/core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserTest.java index 1acd5cf15..454ab1718 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/parser/ResponseJsonParserTest.java @@ -1,5 +1,5 @@ /** - * Copyright 2022, Optimizely Inc. and contributors + * Copyright 2022-2023, Optimizely Inc. and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -84,9 +84,34 @@ public void returnNullWhenJsonIsMalformed() { @Test public void returnNullAndLogCorrectErrorWhenErrorResponseIsReturned() { - String responseToParse = "{\"errors\":[{\"message\":\"Exception while fetching data (/customer) : java.lang.RuntimeException: could not resolve _fs_user_id = wrong_id\",\"locations\":[{\"line\":2,\"column\":3}],\"path\":[\"customer\"],\"extensions\":{\"classification\":\"InvalidIdentifierException\"}}],\"data\":{\"customer\":null}}"; + String responseToParse = "{\"errors\":[{\"message\":\"Exception while fetching data (/customer) : java.lang.RuntimeException: could not resolve _fs_user_id = wrong_id\",\"locations\":[{\"line\":2,\"column\":3}],\"path\":[\"customer\"],\"extensions\":{\"code\":\"INVALID_IDENTIFIER_EXCEPTION\", \"classification\":\"DataFetchingException\"}}],\"data\":{\"customer\":null}}"; List parsedSegments = jsonParser.parseQualifiedSegments(responseToParse); - logbackVerifier.expectMessage(Level.ERROR, "Exception while fetching data (/customer) : java.lang.RuntimeException: could not resolve _fs_user_id = wrong_id"); + logbackVerifier.expectMessage(Level.WARN, "Audience segments fetch failed (invalid identifier)"); assertEquals(null, parsedSegments); } + + @Test + public void returnNullAndLogNoErrorWhenErrorResponseIsReturnedButCodeKeyIsNotPresent() { + String responseToParse = "{\"errors\":[{\"message\":\"Exception while fetching data (/customer) : java.lang.RuntimeException: could not resolve _fs_user_id = wrong_id\",\"locations\":[{\"line\":2,\"column\":3}],\"path\":[\"customer\"],\"extensions\":{\"classification\":\"DataFetchingException\"}}],\"data\":{\"customer\":null}}"; + List parsedSegments = jsonParser.parseQualifiedSegments(responseToParse); + logbackVerifier.expectMessage(Level.ERROR, "Audience segments fetch failed (DataFetchingException)"); + assertEquals(null, parsedSegments); + } + + @Test + public void returnNullAndLogCorrectErrorWhenErrorResponseIsReturnedButCodeValueIsNotInvalidIdentifierException() { + String responseToParse = "{\"errors\":[{\"message\":\"Exception while fetching data (/customer) : java.lang.RuntimeException: could not resolve _fs_user_id = wrong_id\",\"locations\":[{\"line\":2,\"column\":3}],\"path\":[\"customer\"],\"extensions\":{\"code\":\"OTHER_EXCEPTIONS\", \"classification\":\"DataFetchingException\"}}],\"data\":{\"customer\":null}}"; + List parsedSegments = jsonParser.parseQualifiedSegments(responseToParse); + logbackVerifier.expectMessage(Level.ERROR, "Audience segments fetch failed (DataFetchingException)"); + assertEquals(null, parsedSegments); + } + + @Test + public void returnNullAndLogCorrectErrorWhenErrorResponseIsReturnedButCodeValueIsNotInvalidIdentifierExceptionNullClassification() { + String responseToParse = "{\"errors\":[{\"message\":\"Exception while fetching data (/customer) : java.lang.RuntimeException: could not resolve _fs_user_id = wrong_id\",\"locations\":[{\"line\":2,\"column\":3}],\"path\":[\"customer\"],\"extensions\":{\"code\":\"OTHER_EXCEPTIONS\"}}],\"data\":{\"customer\":null}}"; + List parsedSegments = jsonParser.parseQualifiedSegments(responseToParse); + logbackVerifier.expectMessage(Level.ERROR, "Audience segments fetch failed (decode error)"); + assertEquals(null, parsedSegments); + } + } diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java index 040709d39..3a7ae3291 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java @@ -137,7 +137,8 @@ String getSegmentsStringForRequest(Set segmentsList) { "customer" ], "extensions": { - "classification": "InvalidIdentifierException" + "code": "INVALID_IDENTIFIER_EXCEPTION", + "classification": "DataFetchingException" } } ], From b7c8f3cc148e5a704fbae4b45d8ac057e40c9240 Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Fri, 5 May 2023 04:32:03 +0500 Subject: [PATCH 44/80] [FSSDK-8795]chore: prepare for pre release 4.0.0-beta (#515) --- CHANGELOG.md | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac028c780..9512cb740 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,50 @@ # Optimizely Java X SDK Changelog +## [4.0.0-beta] +May 5th, 2023 + +### New Features +The 4.0.0-beta release introduces a new primary feature, [Advanced Audience Targeting]( https://docs.developers.optimizely.com/feature-experimentation/docs/optimizely-data-platform-advanced-audience-targeting) +enabled through integration with [Optimizely Data Platform (ODP)](https://docs.developers.optimizely.com/optimizely-data-platform/docs) ( +[#474](https://github.com/optimizely/java-sdk/pull/474), +[#481](https://github.com/optimizely/java-sdk/pull/481), +[#482](https://github.com/optimizely/java-sdk/pull/482), +[#483](https://github.com/optimizely/java-sdk/pull/483), +[#484](https://github.com/optimizely/java-sdk/pull/484), +[#485](https://github.com/optimizely/java-sdk/pull/485), +[#487](https://github.com/optimizely/java-sdk/pull/487), +[#489](https://github.com/optimizely/java-sdk/pull/489), +[#490](https://github.com/optimizely/java-sdk/pull/490), +[#494](https://github.com/optimizely/java-sdk/pull/494) +). + +You can use ODP, a high-performance [Customer Data Platform (CDP)]( https://www.optimizely.com/optimization-glossary/customer-data-platform/), to easily create complex +real-time segments (RTS) using first-party and 50+ third-party data sources out of the box. You can create custom schemas that support the user attributes important +for your business, and stitch together user behavior done on different devices to better understand and target your customers for personalized user experiences. ODP can +be used as a single source of truth for these segments in any Optimizely or 3rd party tool. + +With ODP accounts integrated into Optimizely projects, you can build audiences using segments pre-defined in ODP. The SDK will fetch the segments for given users and +make decisions using the segments. For access to ODP audience targeting in your Feature Experimentation account, please contact your Optimizely Customer Success Manager. + +This version includes the following changes: +- New API added to `OptimizelyUserContext`: + - `fetchQualifiedSegments()`: this API will retrieve user segments from the ODP server. The fetched segments will be used for audience evaluation. The fetched data will be stored in the local cache to avoid repeated network delays. + - When an `OptimizelyUserContext` is created, the SDK will automatically send an identify request to the ODP server to facilitate observing user activities. +- New APIs added to `OptimizelyClient`: + - `sendOdpEvent()`: customers can build/send arbitrary ODP events that will bind user identifiers and data to user profiles in ODP. + +For details, refer to our documentation pages: +- [Advanced Audience Targeting](https://docs.developers.optimizely.com/feature-experimentation/docs/optimizely-data-platform-advanced-audience-targeting) +- [Server SDK Support](https://docs.developers.optimizely.com/feature-experimentation/v1.0/docs/advanced-audience-targeting-for-server-side-sdks) +- [Initialize Java SDK](https://docs.developers.optimizely.com/feature-experimentation/docs/initialize-sdk-java) +- [OptimizelyUserContext Java SDK](https://docs.developers.optimizely.com/feature-experimentation/docs/optimizelyusercontext-java) +- [Advanced Audience Targeting segment qualification methods](https://docs.developers.optimizely.com/feature-experimentation/docs/advanced-audience-targeting-segment-qualification-methods-java) +- [Send Optimizely Data Platform data using Advanced Audience Targeting](https://docs.developers.optimizely.com/feature-experimentation/docs/send-odp-data-using-advanced-audience-targeting-java) + +### Breaking Changes +- `OdpManager` in the SDK is enabled by default, if initialized using OptimizelyFactory. Unless an ODP account is integrated into the Optimizely projects, most `OdpManager` functions will be ignored. If needed, `OdpManager` to be disabled initialize `OptimizelyClient` without passing `OdpManager`. +- `ProjectConfigManager` interface has been changed to add 2 more methods `getCachedConfig()` and `getSDKKey()`. Custom ProjectConfigManager should implement these new methods. See `PollingProjectConfigManager` for reference. This change is required to support ODPManager updated on datafile download ([#501](https://github.com/optimizely/java-sdk/pull/501)). + ## [3.10.3] March 13th, 2023 From e67974b27e3157dc43862f81bf2b96da2a637134 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Thu, 4 May 2023 17:16:21 -0700 Subject: [PATCH 45/80] fix ubuntu for action (#516) --- .github/workflows/build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0cd965aad..e7ba7782e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -20,7 +20,7 @@ on: required: true jobs: run_build: - runs-on: ubuntu-18.04 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: set up JDK 8 From c60c9e63b453ebf535e855d71bebde486936e618 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Mon, 5 Jun 2023 15:34:50 -0700 Subject: [PATCH 46/80] upgrade dependency versions for source clear (#517) --- core-httpclient-impl/gradle.properties | 1 - gradle.properties | 5 +++-- java-quickstart/build.gradle | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) delete mode 100644 core-httpclient-impl/gradle.properties diff --git a/core-httpclient-impl/gradle.properties b/core-httpclient-impl/gradle.properties deleted file mode 100644 index 72bc00d4c..000000000 --- a/core-httpclient-impl/gradle.properties +++ /dev/null @@ -1 +0,0 @@ -httpClientVersion = 4.5.13 diff --git a/gradle.properties b/gradle.properties index c67b677d9..71d3f3310 100644 --- a/gradle.properties +++ b/gradle.properties @@ -10,14 +10,15 @@ org.gradle.daemon = true org.gradle.parallel = true # Application Packages -gsonVersion = 2.8.6 +gsonVersion = 2.10.1 guavaVersion = 22.0 hamcrestVersion = 1.3 -jacksonVersion = 2.11.2 +jacksonVersion = 2.15.2 jsonVersion = 20190722 jsonSimpleVersion = 1.1.1 logbackVersion = 1.2.3 slf4jVersion = 1.7.30 +httpClientVersion = 4.5.14 # Style Packages findbugsAnnotationVersion = 3.0.1 diff --git a/java-quickstart/build.gradle b/java-quickstart/build.gradle index db68cef27..3e6a978f8 100644 --- a/java-quickstart/build.gradle +++ b/java-quickstart/build.gradle @@ -4,9 +4,9 @@ dependencies { compile project(':core-api') compile project(':core-httpclient-impl') - compile group: 'com.google.code.gson', name: 'gson', version: '2.8.6' - compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.12' - compile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.30' + compile group: 'com.google.code.gson', name: 'gson', version: gsonVersion + compile group: 'org.apache.httpcomponents', name: 'httpclient', version: httpClientVersion + compile group: 'org.slf4j', name: 'slf4j-simple', version: slf4jVersion testCompile group: 'junit', name: 'junit', version: '4.12' } From 7ca4df3f01d8c871183d77647844b7dcfa76a7c4 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Tue, 6 Jun 2023 13:30:59 -0700 Subject: [PATCH 47/80] add evict timeout to logx connections (#518) --- .../main/java/com/optimizely/ab/event/AsyncEventHandler.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java index 3d32f3971..391f89b57 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java @@ -119,6 +119,8 @@ public AsyncEventHandler(int queueCapacity, .withMaxTotalConnections(maxConnections) .withMaxPerRoute(connectionsPerRoute) .withValidateAfterInactivity(validateAfter) + // infrequent event discards observed. staled connections force-closed after a long idle time. + .withEvictIdleConnections(1L, TimeUnit.MINUTES) .build(); this.workerExecutor = new ThreadPoolExecutor(numWorkers, numWorkers, From 3ca11a9d7a92aac43d5495ae0017444675846bc1 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Thu, 8 Jun 2023 13:40:39 -0700 Subject: [PATCH 48/80] fix changelog (#521) --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9512cb740..386c8eeb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Optimizely Java X SDK Changelog +## [3.10.4] +June 8th, 2023 + +### Fixes +- Fix intermittent logx event dispatch failures possibly caused by reusing stale connections. Add `evictIdleConnections` (1min) to `OptimizelyHttpClient` in `AsyncEventHandler` to force close persistent connections after 1min idle time ([#518](https://github.com/optimizely/java-sdk/pull/518)). + + ## [4.0.0-beta] May 5th, 2023 From c507649832f605fa6dd3419caf2284da0c1436c8 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Mon, 26 Jun 2023 15:37:46 -0700 Subject: [PATCH 49/80] [FSSDK-9432] fix: fix to support arbitrary client names to be included in logx and odp events. (#524) Fix to support arbitrary client names to be included in logx and odp events. - The previous implementation allows only a fixed set of values (java-sdk, android-sdk, and android-tv-sdk) with enum. - We need to make it more flexible to support other sdks too (flutter, react-native, etc) wrapping the android-sdk and java-sdk cores. - Old methods for enum access are all deprecated. Downgrade jackson library version down to 2.13.5 (2.14+ uses Java8 langs not supported in Android) --- .../java/com/optimizely/ab/Optimizely.java | 12 ++++++- .../ab/event/internal/BuildVersionInfo.java | 4 +-- .../ab/event/internal/ClientEngineInfo.java | 36 +++++++++++++++++-- .../ab/event/internal/EventFactory.java | 2 +- .../ab/event/internal/payload/EventBatch.java | 2 ++ .../optimizely/ab/odp/ODPEventManager.java | 2 +- .../optimizely/ab/OptimizelyBuilderTest.java | 5 ++- .../event/internal/ClientEngineInfoTest.java | 20 ++++++----- .../ab/event/internal/EventFactoryTest.java | 18 +++++----- gradle.properties | 3 +- 10 files changed, 75 insertions(+), 29 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/Optimizely.java b/core-api/src/main/java/com/optimizely/ab/Optimizely.java index acd9d05fd..3524cb24a 100644 --- a/core-api/src/main/java/com/optimizely/ab/Optimizely.java +++ b/core-api/src/main/java/com/optimizely/ab/Optimizely.java @@ -1633,10 +1633,20 @@ public Builder withUserProfileService(UserProfileService userProfileService) { /** * Override the SDK name and version (for client SDKs like android-sdk wrapping the core java-sdk) to be included in events. * - * @param clientEngine the client engine type. + * @param clientEngineName the client engine name ("java-sdk", "android-sdk", "flutter-sdk", etc.). * @param clientVersion the client SDK version. * @return An Optimizely builder */ + public Builder withClientInfo(String clientEngineName, String clientVersion) { + ClientEngineInfo.setClientEngineName(clientEngineName); + BuildVersionInfo.setClientVersion(clientVersion); + return this; + } + + /** + * @deprecated in favor of {@link withClientInfo(String, String)} which can set with arbitrary client names. + */ + @Deprecated public Builder withClientInfo(EventBatch.ClientEngine clientEngine, String clientVersion) { ClientEngineInfo.setClientEngine(clientEngine); BuildVersionInfo.setClientVersion(clientVersion); diff --git a/core-api/src/main/java/com/optimizely/ab/event/internal/BuildVersionInfo.java b/core-api/src/main/java/com/optimizely/ab/event/internal/BuildVersionInfo.java index d5620b4e9..f69be7cb5 100644 --- a/core-api/src/main/java/com/optimizely/ab/event/internal/BuildVersionInfo.java +++ b/core-api/src/main/java/com/optimizely/ab/event/internal/BuildVersionInfo.java @@ -37,9 +37,9 @@ public final class BuildVersionInfo { @Deprecated public final static String VERSION = readVersionNumber(); + public final static String DEFAULT_VERSION = readVersionNumber(); // can be overridden by other wrapper client (android-sdk, etc) - - private static String clientVersion = readVersionNumber(); + private static String clientVersion = DEFAULT_VERSION; public static void setClientVersion(String version) { if (version == null || version.isEmpty()) { diff --git a/core-api/src/main/java/com/optimizely/ab/event/internal/ClientEngineInfo.java b/core-api/src/main/java/com/optimizely/ab/event/internal/ClientEngineInfo.java index beb64be3d..85573d7fc 100644 --- a/core-api/src/main/java/com/optimizely/ab/event/internal/ClientEngineInfo.java +++ b/core-api/src/main/java/com/optimizely/ab/event/internal/ClientEngineInfo.java @@ -17,9 +17,13 @@ package com.optimizely.ab.event.internal; import com.optimizely.ab.event.internal.payload.EventBatch; +import com.optimizely.ab.notification.DecisionNotification; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + /** * ClientEngineInfo is a utility to globally get and set the ClientEngine used in * event tracking. The ClientEngine defaults to JAVA_SDK but can be overridden at @@ -28,9 +32,34 @@ public class ClientEngineInfo { private static final Logger logger = LoggerFactory.getLogger(ClientEngineInfo.class); + public static final String DEFAULT_NAME = "java-sdk"; + private static String clientEngineName = DEFAULT_NAME; + + public static void setClientEngineName(@Nullable String name) { + if (name == null || name.isEmpty()) { + logger.warn("ClientEngineName cannot be empty, defaulting to {}", ClientEngineInfo.clientEngineName); + return; + } + ClientEngineInfo.clientEngineName = name; + } + + @Nonnull + public static String getClientEngineName() { + return clientEngineName; + } + + private ClientEngineInfo() { + } + + @Deprecated public static final EventBatch.ClientEngine DEFAULT = EventBatch.ClientEngine.JAVA_SDK; + @Deprecated private static EventBatch.ClientEngine clientEngine = DEFAULT; + /** + * @deprecated in favor of {@link #setClientEngineName(String)} which can set with arbitrary client names. + */ + @Deprecated public static void setClientEngine(EventBatch.ClientEngine clientEngine) { if (clientEngine == null) { logger.warn("ClientEngine cannot be null, defaulting to {}", ClientEngineInfo.clientEngine.getClientEngineValue()); @@ -39,12 +68,15 @@ public static void setClientEngine(EventBatch.ClientEngine clientEngine) { logger.info("Setting Optimizely client engine to {}", clientEngine.getClientEngineValue()); ClientEngineInfo.clientEngine = clientEngine; + ClientEngineInfo.clientEngineName = clientEngine.getClientEngineValue(); } + /** + * @deprecated in favor of {@link #getClientEngineName()}. + */ + @Deprecated public static EventBatch.ClientEngine getClientEngine() { return clientEngine; } - private ClientEngineInfo() { - } } diff --git a/core-api/src/main/java/com/optimizely/ab/event/internal/EventFactory.java b/core-api/src/main/java/com/optimizely/ab/event/internal/EventFactory.java index f651be851..47839810d 100644 --- a/core-api/src/main/java/com/optimizely/ab/event/internal/EventFactory.java +++ b/core-api/src/main/java/com/optimizely/ab/event/internal/EventFactory.java @@ -72,7 +72,7 @@ public static LogEvent createLogEvent(List userEvents) { ProjectConfig projectConfig = userContext.getProjectConfig(); builder - .setClientName(ClientEngineInfo.getClientEngine().getClientEngineValue()) + .setClientName(ClientEngineInfo.getClientEngineName()) .setClientVersion(BuildVersionInfo.getClientVersion()) .setAccountId(projectConfig.getAccountId()) .setAnonymizeIp(projectConfig.getAnonymizeIP()) diff --git a/core-api/src/main/java/com/optimizely/ab/event/internal/payload/EventBatch.java b/core-api/src/main/java/com/optimizely/ab/event/internal/payload/EventBatch.java index c50ee6288..43965dafa 100644 --- a/core-api/src/main/java/com/optimizely/ab/event/internal/payload/EventBatch.java +++ b/core-api/src/main/java/com/optimizely/ab/event/internal/payload/EventBatch.java @@ -24,6 +24,8 @@ import java.util.List; public class EventBatch { + + @Deprecated public enum ClientEngine { JAVA_SDK("java-sdk"), ANDROID_SDK("android-sdk"), diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java index ba668a138..efcdd6cda 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java @@ -148,7 +148,7 @@ protected Map augmentCommonData(Map sourceData) Map data = new HashMap<>(); data.put("idempotence_id", UUID.randomUUID().toString()); data.put("data_source_type", "sdk"); - data.put("data_source", ClientEngineInfo.getClientEngine().getClientEngineValue()); + data.put("data_source", ClientEngineInfo.getClientEngineName()); data.put("data_source_version", BuildVersionInfo.getClientVersion()); data.putAll(userCommonData); diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java index 566eec635..6f091fdf8 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyBuilderTest.java @@ -224,7 +224,6 @@ public void withClientInfo() throws Exception { reset(eventHandler); optimizely = Optimizely.builder(validConfigJsonV4(), eventHandler) - .withClientInfo(null, null) .build(); optimizely.track("basic_event", "tester"); @@ -245,8 +244,8 @@ public void withClientInfo() throws Exception { assertEquals(argument.getValue().getEventBatch().getClientVersion(), "1.2.3"); // restore the default values for other tests - ClientEngineInfo.setClientEngine(ClientEngineInfo.DEFAULT); - BuildVersionInfo.setClientVersion(BuildVersionInfo.VERSION); + ClientEngineInfo.setClientEngineName(ClientEngineInfo.DEFAULT_NAME); + BuildVersionInfo.setClientVersion(BuildVersionInfo.DEFAULT_VERSION); } @Test diff --git a/core-api/src/test/java/com/optimizely/ab/event/internal/ClientEngineInfoTest.java b/core-api/src/test/java/com/optimizely/ab/event/internal/ClientEngineInfoTest.java index 33be48517..55b04296a 100644 --- a/core-api/src/test/java/com/optimizely/ab/event/internal/ClientEngineInfoTest.java +++ b/core-api/src/test/java/com/optimizely/ab/event/internal/ClientEngineInfoTest.java @@ -26,19 +26,21 @@ public class ClientEngineInfoTest { @After public void tearDown() throws Exception { - ClientEngineInfo.setClientEngine(ClientEngineInfo.DEFAULT); + ClientEngineInfo.setClientEngineName(ClientEngineInfo.DEFAULT_NAME); } @Test public void testSetAndGetClientEngine() { - for (EventBatch.ClientEngine expected: EventBatch.ClientEngine.values()) { - ClientEngineInfo.setClientEngine(expected); - assertEquals(expected, ClientEngineInfo.getClientEngine()); - } - } + // default "java-sdk" name + assertEquals("java-sdk", ClientEngineInfo.getClientEngineName()); - @Test - public void testDefaultValue() { - assertEquals(ClientEngineInfo.DEFAULT, ClientEngineInfo.getClientEngine()); + ClientEngineInfo.setClientEngineName(null); + assertEquals("java-sdk", ClientEngineInfo.getClientEngineName()); + + ClientEngineInfo.setClientEngineName(""); + assertEquals("java-sdk", ClientEngineInfo.getClientEngineName()); + + ClientEngineInfo.setClientEngineName("test-name"); + assertEquals("test-name", ClientEngineInfo.getClientEngineName()); } } diff --git a/core-api/src/test/java/com/optimizely/ab/event/internal/EventFactoryTest.java b/core-api/src/test/java/com/optimizely/ab/event/internal/EventFactoryTest.java index 657bc4fbf..e347074a8 100644 --- a/core-api/src/test/java/com/optimizely/ab/event/internal/EventFactoryTest.java +++ b/core-api/src/test/java/com/optimizely/ab/event/internal/EventFactoryTest.java @@ -87,7 +87,7 @@ public EventFactoryTest(int datafileVersion, @After public void tearDown() { - ClientEngineInfo.setClientEngine(EventBatch.ClientEngine.JAVA_SDK); + ClientEngineInfo.setClientEngineName(ClientEngineInfo.DEFAULT_NAME); } /** @@ -554,7 +554,7 @@ public void createImpressionEventIgnoresNullAttributes() { */ @Test public void createImpressionEventAndroidClientEngineClientVersion() throws Exception { - ClientEngineInfo.setClientEngine(EventBatch.ClientEngine.ANDROID_SDK); + ClientEngineInfo.setClientEngineName("android-sdk"); ProjectConfig projectConfig = validProjectConfigV2(); Experiment activatedExperiment = projectConfig.getExperiments().get(0); Variation bucketedVariation = activatedExperiment.getVariations().get(0); @@ -566,7 +566,7 @@ public void createImpressionEventAndroidClientEngineClientVersion() throws Excep userId, attributeMap); EventBatch impression = gson.fromJson(impressionEvent.getBody(), EventBatch.class); - assertThat(impression.getClientName(), is(EventBatch.ClientEngine.ANDROID_SDK.getClientEngineValue())); + assertThat(impression.getClientName(), is("android-sdk")); // assertThat(impression.getClientVersion(), is("0.0.0")); } @@ -577,7 +577,7 @@ public void createImpressionEventAndroidClientEngineClientVersion() throws Excep @Test public void createImpressionEventAndroidTVClientEngineClientVersion() throws Exception { String clientVersion = "0.0.0"; - ClientEngineInfo.setClientEngine(EventBatch.ClientEngine.ANDROID_TV_SDK); + ClientEngineInfo.setClientEngineName("android-tv-sdk"); ProjectConfig projectConfig = validProjectConfigV2(); Experiment activatedExperiment = projectConfig.getExperiments().get(0); Variation bucketedVariation = activatedExperiment.getVariations().get(0); @@ -589,7 +589,7 @@ public void createImpressionEventAndroidTVClientEngineClientVersion() throws Exc userId, attributeMap); EventBatch impression = gson.fromJson(impressionEvent.getBody(), EventBatch.class); - assertThat(impression.getClientName(), is(EventBatch.ClientEngine.ANDROID_TV_SDK.getClientEngineValue())); + assertThat(impression.getClientName(), is("android-tv-sdk")); // assertThat(impression.getClientVersion(), is(clientVersion)); } @@ -816,7 +816,7 @@ public void createConversionEventExperimentStatusPrecedesForcedVariation() { */ @Test public void createConversionEventAndroidClientEngineClientVersion() throws Exception { - ClientEngineInfo.setClientEngine(EventBatch.ClientEngine.ANDROID_SDK); + ClientEngineInfo.setClientEngineName("android-sdk"); Attribute attribute = validProjectConfig.getAttributes().get(0); EventType eventType = validProjectConfig.getEventTypes().get(0); @@ -838,7 +838,7 @@ public void createConversionEventAndroidClientEngineClientVersion() throws Excep EventBatch conversion = gson.fromJson(conversionEvent.getBody(), EventBatch.class); - assertThat(conversion.getClientName(), is(EventBatch.ClientEngine.ANDROID_SDK.getClientEngineValue())); + assertThat(conversion.getClientName(), is("android-sdk")); // assertThat(conversion.getClientVersion(), is("0.0.0")); } @@ -849,7 +849,7 @@ public void createConversionEventAndroidClientEngineClientVersion() throws Excep @Test public void createConversionEventAndroidTVClientEngineClientVersion() throws Exception { String clientVersion = "0.0.0"; - ClientEngineInfo.setClientEngine(EventBatch.ClientEngine.ANDROID_TV_SDK); + ClientEngineInfo.setClientEngineName("android-tv-sdk"); ProjectConfig projectConfig = validProjectConfigV2(); Attribute attribute = projectConfig.getAttributes().get(0); EventType eventType = projectConfig.getEventTypes().get(0); @@ -873,7 +873,7 @@ public void createConversionEventAndroidTVClientEngineClientVersion() throws Exc EventBatch conversion = gson.fromJson(conversionEvent.getBody(), EventBatch.class); - assertThat(conversion.getClientName(), is(EventBatch.ClientEngine.ANDROID_TV_SDK.getClientEngineValue())); + assertThat(conversion.getClientName(), is("android-tv-sdk")); // assertThat(conversion.getClientVersion(), is(clientVersion)); } diff --git a/gradle.properties b/gradle.properties index 71d3f3310..f8816af24 100644 --- a/gradle.properties +++ b/gradle.properties @@ -13,7 +13,8 @@ org.gradle.parallel = true gsonVersion = 2.10.1 guavaVersion = 22.0 hamcrestVersion = 1.3 -jacksonVersion = 2.15.2 +# NOTE: jackson 2.14+ uses Java8 stream apis not supported in android +jacksonVersion = 2.13.5 jsonVersion = 20190722 jsonSimpleVersion = 1.1.1 logbackVersion = 1.2.3 From f5528d5332d675063e4abdc68a0cabdc3a0e87b0 Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Fri, 28 Jul 2023 21:10:30 +0500 Subject: [PATCH 50/80] [FSSDK-9493] fix: Added check in AsyncGetQualifiedSegments to check if userID is fsuserid or vuid (#527) * Added check in AsyncGetQualifiedSegments to check if userID is fsuserid or vuid * Update unit test and added additional test to verify that proper userKey is getting passed given vuid and userid --------- Co-authored-by: NomanShoaib --- .../optimizely/ab/odp/ODPSegmentManager.java | 12 ++- .../ab/OptimizelyUserContextTest.java | 97 +++++++++++++++++++ 2 files changed, 105 insertions(+), 4 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java index ce1aaffd3..8cd917269 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java @@ -110,12 +110,16 @@ public void getQualifiedSegments(ODPUserKey userKey, String userValue, ODPSegmen getQualifiedSegments(userKey, userValue, callback, Collections.emptyList()); } - public void getQualifiedSegments(String fsUserId, ODPSegmentFetchCallback callback, List segmentOptions) { - getQualifiedSegments(ODPUserKey.FS_USER_ID, fsUserId, callback, segmentOptions); + public void getQualifiedSegments(String userId, ODPSegmentFetchCallback callback, List options) { + if (ODPManager.isVuid(userId)) { + getQualifiedSegments(ODPUserKey.VUID, userId, callback, options); + } else { + getQualifiedSegments(ODPUserKey.FS_USER_ID, userId, callback, options); + } } - public void getQualifiedSegments(String fsUserId, ODPSegmentFetchCallback callback) { - getQualifiedSegments(ODPUserKey.FS_USER_ID, fsUserId, callback, Collections.emptyList()); + public void getQualifiedSegments(String userId, ODPSegmentFetchCallback callback) { + getQualifiedSegments(userId, callback, Collections.emptyList()); } private String getCacheKey(String userKey, String userValue) { diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java index 7c479f147..0c07ef56a 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java @@ -1723,6 +1723,103 @@ public void fetchQualifiedSegmentsAsync() throws InterruptedException { assertEquals(Arrays.asList("segment1", "segment2"), userContext.getQualifiedSegments()); } + @Test + public void fetchQualifiedSegmentsAsyncWithVUID() throws InterruptedException { + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPApiManager mockAPIManager = mock(ODPApiManager.class); + ODPSegmentManager mockODPSegmentManager = spy(new ODPSegmentManager(mockAPIManager)); + ODPManager mockODPManager = mock(ODPManager.class); + + doAnswer( + invocation -> { + ODPSegmentManager.ODPSegmentFetchCallback callback = invocation.getArgumentAt(2, ODPSegmentManager.ODPSegmentFetchCallback.class); + callback.onCompleted(Arrays.asList("segment1", "segment2")); + return null; + } + ).when(mockODPSegmentManager).getQualifiedSegments(any(), eq("vuid_f6db3d60ba3a493d8e41bc995bb"), (ODPSegmentManager.ODPSegmentFetchCallback) any(), any()); + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Mockito.when(mockODPManager.getSegmentManager()).thenReturn(mockODPSegmentManager); + + Optimizely optimizely = Optimizely.builder() + .withDatafile(datafile) + .withEventProcessor(new ForwardingEventProcessor(eventHandler, null)) + .withODPManager(mockODPManager) + .build(); + + OptimizelyUserContext userContext = optimizely.createUserContext("vuid_f6db3d60ba3a493d8e41bc995bb"); + + CountDownLatch countDownLatch = new CountDownLatch(1); + userContext.fetchQualifiedSegments((Boolean isFetchSuccessful) -> { + assertTrue(isFetchSuccessful); + countDownLatch.countDown(); + }); + + countDownLatch.await(); + verify(mockODPSegmentManager).getQualifiedSegments(eq(ODPUserKey.VUID), eq("vuid_f6db3d60ba3a493d8e41bc995bb"), any(ODPSegmentManager.ODPSegmentFetchCallback.class), eq(Collections.emptyList())); + assertEquals(Arrays.asList("segment1", "segment2"), userContext.getQualifiedSegments()); + + // reset qualified segments + userContext.setQualifiedSegments(Collections.emptyList()); + CountDownLatch countDownLatch2 = new CountDownLatch(1); + userContext.fetchQualifiedSegments((Boolean isFetchSuccessful) -> { + assertTrue(isFetchSuccessful); + countDownLatch2.countDown(); + }, Collections.singletonList(ODPSegmentOption.RESET_CACHE)); + + countDownLatch2.await(); + verify(mockODPSegmentManager).getQualifiedSegments(eq(ODPUserKey.VUID) ,eq("vuid_f6db3d60ba3a493d8e41bc995bb"), any(ODPSegmentManager.ODPSegmentFetchCallback.class), eq(Collections.singletonList(ODPSegmentOption.RESET_CACHE))); + assertEquals(Arrays.asList("segment1", "segment2"), userContext.getQualifiedSegments()); + } + + + @Test + public void fetchQualifiedSegmentsAsyncWithUserID() throws InterruptedException { + ODPEventManager mockODPEventManager = mock(ODPEventManager.class); + ODPApiManager mockAPIManager = mock(ODPApiManager.class); + ODPSegmentManager mockODPSegmentManager = spy(new ODPSegmentManager(mockAPIManager)); + ODPManager mockODPManager = mock(ODPManager.class); + + doAnswer( + invocation -> { + ODPSegmentManager.ODPSegmentFetchCallback callback = invocation.getArgumentAt(2, ODPSegmentManager.ODPSegmentFetchCallback.class); + callback.onCompleted(Arrays.asList("segment1", "segment2")); + return null; + } + ).when(mockODPSegmentManager).getQualifiedSegments(any(), eq("f6db3d60ba3a493d8e41bc995bb"), (ODPSegmentManager.ODPSegmentFetchCallback) any(), any()); + Mockito.when(mockODPManager.getEventManager()).thenReturn(mockODPEventManager); + Mockito.when(mockODPManager.getSegmentManager()).thenReturn(mockODPSegmentManager); + + Optimizely optimizely = Optimizely.builder() + .withDatafile(datafile) + .withEventProcessor(new ForwardingEventProcessor(eventHandler, null)) + .withODPManager(mockODPManager) + .build(); + + OptimizelyUserContext userContext = optimizely.createUserContext("f6db3d60ba3a493d8e41bc995bb"); + + CountDownLatch countDownLatch = new CountDownLatch(1); + userContext.fetchQualifiedSegments((Boolean isFetchSuccessful) -> { + assertTrue(isFetchSuccessful); + countDownLatch.countDown(); + }); + + countDownLatch.await(); + verify(mockODPSegmentManager).getQualifiedSegments(eq(ODPUserKey.FS_USER_ID), eq("f6db3d60ba3a493d8e41bc995bb"), any(ODPSegmentManager.ODPSegmentFetchCallback.class), eq(Collections.emptyList())); + assertEquals(Arrays.asList("segment1", "segment2"), userContext.getQualifiedSegments()); + + // reset qualified segments + userContext.setQualifiedSegments(Collections.emptyList()); + CountDownLatch countDownLatch2 = new CountDownLatch(1); + userContext.fetchQualifiedSegments((Boolean isFetchSuccessful) -> { + assertTrue(isFetchSuccessful); + countDownLatch2.countDown(); + }, Collections.singletonList(ODPSegmentOption.RESET_CACHE)); + + countDownLatch2.await(); + verify(mockODPSegmentManager).getQualifiedSegments(eq(ODPUserKey.FS_USER_ID) ,eq("f6db3d60ba3a493d8e41bc995bb"), any(ODPSegmentManager.ODPSegmentFetchCallback.class), eq(Collections.singletonList(ODPSegmentOption.RESET_CACHE))); + assertEquals(Arrays.asList("segment1", "segment2"), userContext.getQualifiedSegments()); + } + @Test public void fetchQualifiedSegmentsAsyncError() throws InterruptedException { Optimizely optimizely = Optimizely.builder() From 65b3f43f239edb7faa165f007caaa277eeaa088a Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Thu, 3 Aug 2023 17:32:47 +0500 Subject: [PATCH 51/80] [FSSDK-8739] refact: Implements a warning log for polling interval less than 30s (#528) * Added warning upon setting polling time period below 30 ms * Updated test and changed expecting time to lower than 30 seconds --- .../config/PollingProjectConfigManager.java | 4 ++- .../PollingProjectConfigManagerTest.java | 30 +++++++++++++++---- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/config/PollingProjectConfigManager.java b/core-api/src/main/java/com/optimizely/ab/config/PollingProjectConfigManager.java index 4ad34e7a8..5f0c44e74 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/PollingProjectConfigManager.java +++ b/core-api/src/main/java/com/optimizely/ab/config/PollingProjectConfigManager.java @@ -75,7 +75,9 @@ public PollingProjectConfigManager(long period, TimeUnit timeUnit, long blocking this.blockingTimeoutPeriod = blockingTimeoutPeriod; this.blockingTimeoutUnit = blockingTimeoutUnit; this.notificationCenter = notificationCenter; - + if (TimeUnit.SECONDS.convert(period, this.timeUnit) < 30) { + logger.warn("Polling intervals below 30 seconds are not recommended."); + } final ThreadFactory threadFactory = Executors.defaultThreadFactory(); this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(runnable -> { Thread thread = threadFactory.newThread(runnable); diff --git a/core-api/src/test/java/com/optimizely/ab/config/PollingProjectConfigManagerTest.java b/core-api/src/test/java/com/optimizely/ab/config/PollingProjectConfigManagerTest.java index 130f8844a..91a9b8715 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/PollingProjectConfigManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/config/PollingProjectConfigManagerTest.java @@ -16,13 +16,15 @@ */ package com.optimizely.ab.config; +import ch.qos.logback.classic.Level; +import com.optimizely.ab.internal.LogbackVerifier; import com.optimizely.ab.internal.NotificationRegistry; import com.optimizely.ab.notification.NotificationCenter; import com.optimizely.ab.notification.UpdateConfigNotification; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import org.junit.*; +import org.junit.rules.ExpectedException; +import org.junit.rules.RuleChain; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; @@ -41,6 +43,13 @@ public class PollingProjectConfigManagerTest { private static final TimeUnit POLLING_UNIT = TimeUnit.MILLISECONDS; private static final int PROJECT_CONFIG_DELAY = 100; + public ExpectedException thrown = ExpectedException.none(); + public LogbackVerifier logbackVerifier = new LogbackVerifier(); + + @Rule + @SuppressFBWarnings("URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD") + public RuleChain ruleChain = RuleChain.outerRule(thrown) + .around(logbackVerifier); private TestProjectConfigManager testProjectConfigManager; private ProjectConfig projectConfig; @@ -228,6 +237,13 @@ public void testUpdateConfigNotificationGetsTriggered() throws InterruptedExcept assertTrue(countDownLatch.await(500, TimeUnit.MILLISECONDS)); } + @Test + public void testSettingUpLowerPollingPeriodResultsInWarning() throws InterruptedException { + long pollingPeriod = 29; + new TestProjectConfigManager(projectConfig, pollingPeriod, TimeUnit.SECONDS, pollingPeriod / 2, TimeUnit.SECONDS, new NotificationCenter()); + logbackVerifier.expectMessage(Level.WARN, "Polling intervals below 30 seconds are not recommended."); + } + @Test public void testUpdateConfigNotificationDoesNotResultInDeadlock() throws Exception { NotificationCenter notificationCenter = new NotificationCenter(); @@ -257,7 +273,11 @@ private TestProjectConfigManager(ProjectConfig projectConfig) { } private TestProjectConfigManager(ProjectConfig projectConfig, long blockPeriod, NotificationCenter notificationCenter) { - super(POLLING_PERIOD, POLLING_UNIT, blockPeriod, POLLING_UNIT, notificationCenter); + this(projectConfig, POLLING_PERIOD, POLLING_UNIT, blockPeriod, POLLING_UNIT, notificationCenter); + } + + private TestProjectConfigManager(ProjectConfig projectConfig, long pollingPeriod, TimeUnit pollingUnit, long blockPeriod, TimeUnit blockingUnit, NotificationCenter notificationCenter) { + super(pollingPeriod, pollingUnit, blockPeriod, blockingUnit, notificationCenter); this.projectConfig = projectConfig; } From 9374090585fdfa14b25fe1a5bbf0542cac55a61c Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Mon, 7 Aug 2023 19:23:17 +0500 Subject: [PATCH 52/80] added override close method in httpProjectConfigManager to avoid memory leak (#530) Co-authored-by: NomanShoaib --- .../ab/config/HttpProjectConfigManager.java | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java index 4be1715d2..15325350f 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java @@ -1,6 +1,6 @@ /** * - * Copyright 2019,2021, Optimizely + * Copyright 2019, 2021, 2023, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +16,15 @@ */ package com.optimizely.ab.config; -import com.optimizely.ab.HttpClientUtils; import com.optimizely.ab.OptimizelyHttpClient; import com.optimizely.ab.annotations.VisibleForTesting; import com.optimizely.ab.config.parser.ConfigParseException; import com.optimizely.ab.internal.PropertyUtils; import com.optimizely.ab.notification.NotificationCenter; -import com.optimizely.ab.optimizelyconfig.OptimizelyConfig; import org.apache.http.*; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -148,6 +145,16 @@ protected ProjectConfig poll() { return null; } + @Override + public synchronized void close() { + super.close(); + try { + httpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + @VisibleForTesting HttpGet createHttpRequest() { HttpGet httpGet = new HttpGet(uri); From 36d493bcbd08a2ec80982142a4530a92e353971a Mon Sep 17 00:00:00 2001 From: Muhammad Noman Date: Tue, 15 Aug 2023 18:00:53 +0500 Subject: [PATCH 53/80] [FSSDK-9549] chore: add github issue template (#531) * [FSSDK-9549] chore: add github issue template * Update config.yml --- .github/ISSUE_TEMPLATE/BUG-REPORT.yml | 88 +++++++++++++++++++++++ .github/ISSUE_TEMPLATE/ENHANCEMENT.yml | 45 ++++++++++++ .github/ISSUE_TEMPLATE/FEATURE-REQUEST.md | 4 ++ .github/ISSUE_TEMPLATE/config.yml | 5 ++ 4 files changed, 142 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/BUG-REPORT.yml create mode 100644 .github/ISSUE_TEMPLATE/ENHANCEMENT.yml create mode 100644 .github/ISSUE_TEMPLATE/FEATURE-REQUEST.md create mode 100644 .github/ISSUE_TEMPLATE/config.yml diff --git a/.github/ISSUE_TEMPLATE/BUG-REPORT.yml b/.github/ISSUE_TEMPLATE/BUG-REPORT.yml new file mode 100644 index 000000000..9295c6a34 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/BUG-REPORT.yml @@ -0,0 +1,88 @@ +name: 🐞 Bug +description: File a bug/issue +title: "[BUG] " +labels: ["bug", "needs-triage"] +body: +- type: checkboxes + attributes: + label: Is there an existing issue for this? + description: Please search to see if an issue already exists for the bug you encountered. + options: + - label: I have searched the existing issues + required: true +- type: textarea + attributes: + label: SDK Version + description: Version of the SDK in use? + validations: + required: true +- type: textarea + attributes: + label: Current Behavior + description: A concise description of what you're experiencing. + validations: + required: true +- type: textarea + attributes: + label: Expected Behavior + description: A concise description of what you expected to happen. + validations: + required: true +- type: textarea + attributes: + label: Steps To Reproduce + description: Steps to reproduce the behavior. + placeholder: | + 1. In this environment... + 1. With this config... + 1. Run '...' + 1. See error... + validations: + required: true +- type: textarea + attributes: + label: Java Version + description: What version of Java are you using? + validations: + required: false +- type: textarea + attributes: + label: Link + description: Link to code demonstrating the problem. + validations: + required: false +- type: textarea + attributes: + label: Logs + description: Logs/stack traces related to the problem (⚠️do not include sensitive information). + validations: + required: false +- type: dropdown + attributes: + label: Severity + description: What is the severity of the problem? + multiple: true + options: + - Blocking development + - Affecting users + - Minor issue + validations: + required: false +- type: textarea + attributes: + label: Workaround/Solution + description: Do you have any workaround or solution in mind for the problem? + validations: + required: false +- type: textarea + attributes: + label: "Recent Change" + description: Has this issue started happening after an update or experiment change? + validations: + required: false +- type: textarea + attributes: + label: Conflicts + description: Are there other libraries/dependencies potentially in conflict? + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/ENHANCEMENT.yml b/.github/ISSUE_TEMPLATE/ENHANCEMENT.yml new file mode 100644 index 000000000..2b315c010 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/ENHANCEMENT.yml @@ -0,0 +1,45 @@ +name: ✨Enhancement +description: Create a new ticket for a Enhancement/Tech-initiative for the benefit of the SDK which would be considered for a minor version update. +title: "[ENHANCEMENT] <title>" +labels: ["enhancement"] +body: + - type: textarea + id: description + attributes: + label: "Description" + description: Briefly describe the enhancement in a few sentences. + placeholder: Short description... + validations: + required: true + - type: textarea + id: benefits + attributes: + label: "Benefits" + description: How would the enhancement benefit to your product or usage? + placeholder: Benefits... + validations: + required: true + - type: textarea + id: detail + attributes: + label: "Detail" + description: How would you like the enhancement to work? Please provide as much detail as possible + placeholder: Detailed description... + validations: + required: false + - type: textarea + id: examples + attributes: + label: "Examples" + description: Are there any examples of this enhancement in other products/services? If so, please provide links or references. + placeholder: Links/References... + validations: + required: false + - type: textarea + id: risks + attributes: + label: "Risks/Downsides" + description: Do you think this enhancement could have any potential downsides or risks? + placeholder: Risks/Downsides... + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/FEATURE-REQUEST.md b/.github/ISSUE_TEMPLATE/FEATURE-REQUEST.md new file mode 100644 index 000000000..5aa42ce83 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/FEATURE-REQUEST.md @@ -0,0 +1,4 @@ +<!-- + Thanks for filing in issue! Are you requesting a new feature? If so, please share your feedback with us on the following link. +--> +## Feedback requesting a new feature can be shared [here.](https://feedback.optimizely.com/) diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..dc7735bc9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: 💡Feature Requests + url: https://feedback.optimizely.com/ + about: Feedback requesting a new feature can be shared here. From e9be5d0d4ef946be733088c560e3c08b9b50b333 Mon Sep 17 00:00:00 2001 From: Muzahidul Islam <129880873+muzahidul-opti@users.noreply.github.com> Date: Mon, 28 Aug 2023 23:14:43 +0600 Subject: [PATCH 54/80] [FSSDK-9617] chore: release 4.0.0-beta2 (#533) Prepare for release 4.0.0-beta2 --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 386c8eeb6..aef012ffd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Optimizely Java X SDK Changelog +## [4.0.0-beta2] +August 28th, 2023 + +### Fixes +- Fix thread leak from httpClient in HttpProjectConfigManager ([#530](https://github.com/optimizely/java-sdk/pull/530)). +- Fix issue when vuid is passed as userid for `AsyncGetQualifiedSegments` ([#527](https://github.com/optimizely/java-sdk/pull/527)). +- Fix to support arbitrary client names to be included in logx and odp events ([#524](https://github.com/optimizely/java-sdk/pull/524)). +- Add evict timeout to logx connections ([#518](https://github.com/optimizely/java-sdk/pull/518)). + + ## [3.10.4] June 8th, 2023 From 6c5e5b2cbdd62650e1604c08064263bc3e8538fc Mon Sep 17 00:00:00 2001 From: Muzahidul Islam <129880873+muzahidul-opti@users.noreply.github.com> Date: Tue, 29 Aug 2023 20:54:29 +0600 Subject: [PATCH 55/80] [FSSDK-9617] chore: release 4.0.0-beta2 (#534) Release 4.0.0-beta2 --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index aef012ffd..7ec53d038 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ August 28th, 2023 - Fix to support arbitrary client names to be included in logx and odp events ([#524](https://github.com/optimizely/java-sdk/pull/524)). - Add evict timeout to logx connections ([#518](https://github.com/optimizely/java-sdk/pull/518)). +### Functionality Enhancements +- Update Github Issue Templates ([#531](https://github.com/optimizely/java-sdk/pull/531)) + ## [3.10.4] June 8th, 2023 From ca2a8942920cfb34e2de44ba11ddaad33a219513 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Tue, 12 Sep 2023 03:20:26 -0700 Subject: [PATCH 56/80] add sample log4j config to demo app (#523) Co-authored-by: Muhammad Noman <Muhammadnoman@folio3.com> Co-authored-by: Muzahidul Islam <129880873+muzahidul-opti@users.noreply.github.com> --- gradle.properties | 1 + java-quickstart/build.gradle | 14 ++++++++------ .../src/main/resources/log4j2.properties | 10 ++++++++++ 3 files changed, 19 insertions(+), 6 deletions(-) create mode 100644 java-quickstart/src/main/resources/log4j2.properties diff --git a/gradle.properties b/gradle.properties index f8816af24..ef1dd8bfd 100644 --- a/gradle.properties +++ b/gradle.properties @@ -20,6 +20,7 @@ jsonSimpleVersion = 1.1.1 logbackVersion = 1.2.3 slf4jVersion = 1.7.30 httpClientVersion = 4.5.14 +log4jVersion = 2.20.0 # Style Packages findbugsAnnotationVersion = 3.0.1 diff --git a/java-quickstart/build.gradle b/java-quickstart/build.gradle index 3e6a978f8..a58fb090e 100644 --- a/java-quickstart/build.gradle +++ b/java-quickstart/build.gradle @@ -1,14 +1,16 @@ apply plugin: 'java' dependencies { - compile project(':core-api') - compile project(':core-httpclient-impl') + implementation project(':core-api') + implementation project(':core-httpclient-impl') - compile group: 'com.google.code.gson', name: 'gson', version: gsonVersion - compile group: 'org.apache.httpcomponents', name: 'httpclient', version: httpClientVersion - compile group: 'org.slf4j', name: 'slf4j-simple', version: slf4jVersion + implementation group: 'com.google.code.gson', name: 'gson', version: gsonVersion + implementation group: 'org.apache.httpcomponents', name: 'httpclient', version: httpClientVersion + implementation group: 'org.apache.logging.log4j', name: 'log4j-api', version: log4jVersion + implementation group: 'org.apache.logging.log4j', name: 'log4j-core', version: log4jVersion + implementation group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: log4jVersion - testCompile group: 'junit', name: 'junit', version: '4.12' + testImplementation group: 'junit', name: 'junit', version: junitVersion } task runExample(type: JavaExec) { diff --git a/java-quickstart/src/main/resources/log4j2.properties b/java-quickstart/src/main/resources/log4j2.properties new file mode 100644 index 000000000..d67078d5a --- /dev/null +++ b/java-quickstart/src/main/resources/log4j2.properties @@ -0,0 +1,10 @@ +# Set the root logger level to INFO and its appender to the console + +appender.console.type = Console +appender.console.name = STDOUT +appender.console.layout.type = PatternLayout +appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n + +# Specify the loggers +rootLogger.level = debug +rootLogger.appenderRef.stdout.ref = STDOUT From e59c5953f03bff3a3bcce1cd1e9716464d0f395b Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Mon, 27 Nov 2023 09:38:14 -0800 Subject: [PATCH 57/80] [FSSDK-9785] handle duplicate experiment keys with a warning (#535) When duplicate experiment keys are found in a datafile, SDK returns a correct experimentMap in OptimizelyConfig: - the experimentMap will contain the experiment later in the datafile experiments list. - add a warning log about "Duplicate experiment keys found in datafile: {key-name}" --- .../OptimizelyConfigService.java | 11 +++++- .../OptimizelyConfigServiceTest.java | 39 +++++++++++++++++-- .../src/main/java/com/optimizely/Example.java | 2 +- 3 files changed, 47 insertions(+), 5 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/optimizelyconfig/OptimizelyConfigService.java b/core-api/src/main/java/com/optimizely/ab/optimizelyconfig/OptimizelyConfigService.java index 8937d8572..c1ec93c01 100644 --- a/core-api/src/main/java/com/optimizely/ab/optimizelyconfig/OptimizelyConfigService.java +++ b/core-api/src/main/java/com/optimizely/ab/optimizelyconfig/OptimizelyConfigService.java @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright 2020-2021, Optimizely, Inc. and contributors * + * Copyright 2020-2021, 2023, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * @@ -18,6 +18,8 @@ import com.optimizely.ab.annotations.VisibleForTesting; import com.optimizely.ab.config.*; import com.optimizely.ab.config.audience.Audience; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.*; @@ -31,6 +33,8 @@ public class OptimizelyConfigService { private Map<String, List<FeatureVariable>> featureIdToVariablesMap = new HashMap<>(); private Map<String, OptimizelyExperiment> experimentMapByExperimentId = new HashMap<>(); + private static final Logger logger = LoggerFactory.getLogger(OptimizelyConfigService.class); + public OptimizelyConfigService(ProjectConfig projectConfig) { this.projectConfig = projectConfig; this.audiences = getAudiencesList(projectConfig.getTypedAudiences(), projectConfig.getAudiences()); @@ -125,6 +129,11 @@ Map<String, OptimizelyExperiment> getExperimentsMap() { experiment.serializeConditions(this.audiencesMap) ); + if (featureExperimentMap.containsKey(experiment.getKey())) { + // continue with this warning, so the later experiment will be used. + logger.warn("Duplicate experiment keys found in datafile: {}", experiment.getKey()); + } + featureExperimentMap.put(experiment.getKey(), optimizelyExperiment); experimentMapByExperimentId.put(experiment.getId(), optimizelyExperiment); } diff --git a/core-api/src/test/java/com/optimizely/ab/optimizelyconfig/OptimizelyConfigServiceTest.java b/core-api/src/test/java/com/optimizely/ab/optimizelyconfig/OptimizelyConfigServiceTest.java index 29cbe3695..418cb2494 100644 --- a/core-api/src/test/java/com/optimizely/ab/optimizelyconfig/OptimizelyConfigServiceTest.java +++ b/core-api/src/test/java/com/optimizely/ab/optimizelyconfig/OptimizelyConfigServiceTest.java @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright 2020-2021, Optimizely, Inc. and contributors * + * Copyright 2020-2021, 2023, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * @@ -15,16 +15,19 @@ ***************************************************************************/ package com.optimizely.ab.optimizelyconfig; +import ch.qos.logback.classic.Level; import com.optimizely.ab.config.*; import com.optimizely.ab.config.audience.Audience; +import com.optimizely.ab.internal.LogbackVerifier; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; import java.util.*; import static java.util.Arrays.asList; import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class OptimizelyConfigServiceTest { @@ -32,6 +35,9 @@ public class OptimizelyConfigServiceTest { private OptimizelyConfigService optimizelyConfigService; private OptimizelyConfig expectedConfig; + @Rule + public LogbackVerifier logbackVerifier = new LogbackVerifier(); + @Before public void initialize() { projectConfig = generateOptimizelyConfig(); @@ -46,6 +52,33 @@ public void testGetExperimentsMap() { assertEquals(expectedConfig.getExperimentsMap(), optimizelyExperimentMap); } + @Test + public void testGetExperimentsMapWithDuplicateKeys() { + List<Experiment> experiments = Arrays.asList( + new Experiment( + "first", + "duplicate_key", + null, null, Collections.<String>emptyList(), null, + Collections.<Variation>emptyList(), Collections.<String, String>emptyMap(), Collections.<TrafficAllocation>emptyList() + ), + new Experiment( + "second", + "duplicate_key", + null, null, Collections.<String>emptyList(), null, + Collections.<Variation>emptyList(), Collections.<String, String>emptyMap(), Collections.<TrafficAllocation>emptyList() + ) + ); + + ProjectConfig projectConfig = mock(ProjectConfig.class); + OptimizelyConfigService optimizelyConfigService = new OptimizelyConfigService(projectConfig); + when(projectConfig.getExperiments()).thenReturn(experiments); + + Map<String, OptimizelyExperiment> optimizelyExperimentMap = optimizelyConfigService.getExperimentsMap(); + assertEquals("Duplicate keys should be overwritten", optimizelyExperimentMap.size(), 1); + assertEquals("Duplicate keys should be overwritten", optimizelyExperimentMap.get("duplicate_key").getId(), "second"); + logbackVerifier.expectMessage(Level.WARN, "Duplicate experiment keys found in datafile: duplicate_key"); + } + @Test public void testRevision() { String revision = optimizelyConfigService.getConfig().getRevision(); diff --git a/java-quickstart/src/main/java/com/optimizely/Example.java b/java-quickstart/src/main/java/com/optimizely/Example.java index 04d7f78da..e3bccd483 100644 --- a/java-quickstart/src/main/java/com/optimizely/Example.java +++ b/java-quickstart/src/main/java/com/optimizely/Example.java @@ -56,7 +56,7 @@ private void processVisitor(String userId, Map<String, Object> attributes) { public static void main(String[] args) throws InterruptedException { Optimizely optimizely = OptimizelyFactory.newDefaultInstance("BX9Y3bTa4YErpHZEMpAwHm"); - + Example example = new Example(optimizely); Random random = new Random(); From 3afa432b04f199e3375d047917793e64ccb8205d Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Tue, 16 Jan 2024 13:29:33 -0800 Subject: [PATCH 58/80] [FSSDK-8579] chore: prepare for release 4.0.0 (#536) --- CHANGELOG.md | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++- LICENSE | 2 +- 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ec53d038..764c83982 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,61 @@ # Optimizely Java X SDK Changelog +## [4.0.0] +January 16th, 2024 + +### New Features +The 4.0.0 release introduces a new primary feature, [Advanced Audience Targeting]( https://docs.developers.optimizely.com/feature-experimentation/docs/optimizely-data-platform-advanced-audience-targeting) +enabled through integration with [Optimizely Data Platform (ODP)](https://docs.developers.optimizely.com/optimizely-data-platform/docs) ( +[#474](https://github.com/optimizely/java-sdk/pull/474), +[#481](https://github.com/optimizely/java-sdk/pull/481), +[#482](https://github.com/optimizely/java-sdk/pull/482), +[#483](https://github.com/optimizely/java-sdk/pull/483), +[#484](https://github.com/optimizely/java-sdk/pull/484), +[#485](https://github.com/optimizely/java-sdk/pull/485), +[#487](https://github.com/optimizely/java-sdk/pull/487), +[#489](https://github.com/optimizely/java-sdk/pull/489), +[#490](https://github.com/optimizely/java-sdk/pull/490), +[#494](https://github.com/optimizely/java-sdk/pull/494) +). + +You can use ODP, a high-performance [Customer Data Platform (CDP)]( https://www.optimizely.com/optimization-glossary/customer-data-platform/), to easily create complex +real-time segments (RTS) using first-party and 50+ third-party data sources out of the box. You can create custom schemas that support the user attributes important +for your business, and stitch together user behavior done on different devices to better understand and target your customers for personalized user experiences. ODP can +be used as a single source of truth for these segments in any Optimizely or 3rd party tool. + +With ODP accounts integrated into Optimizely projects, you can build audiences using segments pre-defined in ODP. The SDK will fetch the segments for given users and +make decisions using the segments. For access to ODP audience targeting in your Feature Experimentation account, please contact your Optimizely Customer Success Manager. + +This version includes the following changes: +- New API added to `OptimizelyUserContext`: + - `fetchQualifiedSegments()`: this API will retrieve user segments from the ODP server. The fetched segments will be used for audience evaluation. The fetched data will be stored in the local cache to avoid repeated network delays. + - When an `OptimizelyUserContext` is created, the SDK will automatically send an identify request to the ODP server to facilitate observing user activities. +- New APIs added to `OptimizelyClient`: + - `sendOdpEvent()`: customers can build/send arbitrary ODP events that will bind user identifiers and data to user profiles in ODP. + +For details, refer to our documentation pages: +- [Advanced Audience Targeting](https://docs.developers.optimizely.com/feature-experimentation/docs/optimizely-data-platform-advanced-audience-targeting) +- [Server SDK Support](https://docs.developers.optimizely.com/feature-experimentation/v1.0/docs/advanced-audience-targeting-for-server-side-sdks) +- [Initialize Java SDK](https://docs.developers.optimizely.com/feature-experimentation/docs/initialize-sdk-java) +- [OptimizelyUserContext Java SDK](https://docs.developers.optimizely.com/feature-experimentation/docs/optimizelyusercontext-java) +- [Advanced Audience Targeting segment qualification methods](https://docs.developers.optimizely.com/feature-experimentation/docs/advanced-audience-targeting-segment-qualification-methods-java) +- [Send Optimizely Data Platform data using Advanced Audience Targeting](https://docs.developers.optimizely.com/feature-experimentation/docs/send-odp-data-using-advanced-audience-targeting-java) + +### Breaking Changes +- `OdpManager` in the SDK is enabled by default, if initialized using OptimizelyFactory. Unless an ODP account is integrated into the Optimizely projects, most `OdpManager` functions will be ignored. If needed, ODP features can be disabled by initializing `OptimizelyClient` without passing `OdpManager`. +- `ProjectConfigManager` interface has been changed to add 2 more methods `getCachedConfig()` and `getSDKKey()`. Custom ProjectConfigManager should implement these new methods. See `PollingProjectConfigManager` for reference. This change is required to support ODPManager updated on datafile download ([#501](https://github.com/optimizely/java-sdk/pull/501)). + +### Fixes +- Fix thread leak from httpClient in HttpProjectConfigManager ([#530](https://github.com/optimizely/java-sdk/pull/530)). +- Fix issue when vuid is passed as userid for `AsyncGetQualifiedSegments` ([#527](https://github.com/optimizely/java-sdk/pull/527)). +- Fix to support arbitrary client names to be included in logx and odp events ([#524](https://github.com/optimizely/java-sdk/pull/524)). +- Add evict timeout to logx connections ([#518](https://github.com/optimizely/java-sdk/pull/518)). + +### Functionality Enhancements +- Update Github Issue Templates ([#531](https://github.com/optimizely/java-sdk/pull/531)) + + + ## [4.0.0-beta2] August 28th, 2023 @@ -7,7 +63,6 @@ August 28th, 2023 - Fix thread leak from httpClient in HttpProjectConfigManager ([#530](https://github.com/optimizely/java-sdk/pull/530)). - Fix issue when vuid is passed as userid for `AsyncGetQualifiedSegments` ([#527](https://github.com/optimizely/java-sdk/pull/527)). - Fix to support arbitrary client names to be included in logx and odp events ([#524](https://github.com/optimizely/java-sdk/pull/524)). -- Add evict timeout to logx connections ([#518](https://github.com/optimizely/java-sdk/pull/518)). ### Functionality Enhancements - Update Github Issue Templates ([#531](https://github.com/optimizely/java-sdk/pull/531)) diff --git a/LICENSE b/LICENSE index afc550977..c9f7279d1 100644 --- a/LICENSE +++ b/LICENSE @@ -187,7 +187,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2016, Optimizely + Copyright 2016-2024, Optimizely, Inc. and contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. From a77eaa857197967774d3f89239f30ab2675b267e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Rowicki?= <mirowicki@gmail.com> Date: Wed, 3 Apr 2024 23:07:42 +0200 Subject: [PATCH 59/80] Align to use virtual threads (#540) Align to use virtual threads - In scope of this ticket I removed synchronized blocks as they pin virtual thread to carrier thread. - Expose user way to inject ThreadFactory for creating virtual threads --- .../java/com/optimizely/ab/Optimizely.java | 8 +- .../config/PollingProjectConfigManager.java | 85 ++++++++++++------ .../ab/event/BatchEventProcessor.java | 23 +++-- .../ab/internal/DefaultLRUCache.java | 18 +++- .../ab/notification/NotificationManager.java | 12 ++- .../java/com/optimizely/ab/odp/ODPConfig.java | 90 ++++++++++++++----- .../optimizely/ab/odp/ODPEventManager.java | 10 ++- .../com/optimizely/ab/NamedThreadFactory.java | 12 ++- .../ab/config/HttpProjectConfigManager.java | 33 +++++-- .../ab/event/AsyncEventHandler.java | 21 ++++- 10 files changed, 234 insertions(+), 78 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/Optimizely.java b/core-api/src/main/java/com/optimizely/ab/Optimizely.java index 3524cb24a..e64882ed6 100644 --- a/core-api/src/main/java/com/optimizely/ab/Optimizely.java +++ b/core-api/src/main/java/com/optimizely/ab/Optimizely.java @@ -35,6 +35,7 @@ import com.optimizely.ab.optimizelyconfig.OptimizelyConfigService; import com.optimizely.ab.optimizelydecision.*; import com.optimizely.ab.optimizelyjson.OptimizelyJSON; +import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -101,6 +102,8 @@ public class Optimizely implements AutoCloseable { @Nullable private final ODPManager odpManager; + private final ReentrantLock lock = new ReentrantLock(); + private Optimizely(@Nonnull EventHandler eventHandler, @Nonnull EventProcessor eventProcessor, @Nonnull ErrorHandler errorHandler, @@ -1451,8 +1454,11 @@ public List<String> fetchQualifiedSegments(String userId, @Nonnull List<ODPSegme return null; } if (odpManager != null) { - synchronized (odpManager) { + lock.lock(); + try { return odpManager.getSegmentManager().getQualifiedSegments(userId, segmentOptions); + } finally { + lock.unlock(); } } logger.error("Audience segments fetch failed (ODP is not enabled)."); diff --git a/core-api/src/main/java/com/optimizely/ab/config/PollingProjectConfigManager.java b/core-api/src/main/java/com/optimizely/ab/config/PollingProjectConfigManager.java index 5f0c44e74..6dd84470e 100644 --- a/core-api/src/main/java/com/optimizely/ab/config/PollingProjectConfigManager.java +++ b/core-api/src/main/java/com/optimizely/ab/config/PollingProjectConfigManager.java @@ -22,6 +22,8 @@ import com.optimizely.ab.optimizelyconfig.OptimizelyConfig; import com.optimizely.ab.optimizelyconfig.OptimizelyConfigManager; import com.optimizely.ab.optimizelyconfig.OptimizelyConfigService; +import java.util.concurrent.locks.ReentrantLock; +import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -60,6 +62,7 @@ public abstract class PollingProjectConfigManager implements ProjectConfigManage private volatile String sdkKey; private volatile boolean started; private ScheduledFuture<?> scheduledFuture; + private ReentrantLock lock = new ReentrantLock(); public PollingProjectConfigManager(long period, TimeUnit timeUnit) { this(period, timeUnit, Long.MAX_VALUE, TimeUnit.MILLISECONDS, new NotificationCenter()); @@ -70,6 +73,15 @@ public PollingProjectConfigManager(long period, TimeUnit timeUnit, NotificationC } public PollingProjectConfigManager(long period, TimeUnit timeUnit, long blockingTimeoutPeriod, TimeUnit blockingTimeoutUnit, NotificationCenter notificationCenter) { + this(period, timeUnit, blockingTimeoutPeriod, blockingTimeoutUnit, notificationCenter, null); + } + + public PollingProjectConfigManager(long period, + TimeUnit timeUnit, + long blockingTimeoutPeriod, + TimeUnit blockingTimeoutUnit, + NotificationCenter notificationCenter, + @Nullable ThreadFactory customThreadFactory) { this.period = period; this.timeUnit = timeUnit; this.blockingTimeoutPeriod = blockingTimeoutPeriod; @@ -78,7 +90,7 @@ public PollingProjectConfigManager(long period, TimeUnit timeUnit, long blocking if (TimeUnit.SECONDS.convert(period, this.timeUnit) < 30) { logger.warn("Polling intervals below 30 seconds are not recommended."); } - final ThreadFactory threadFactory = Executors.defaultThreadFactory(); + final ThreadFactory threadFactory = customThreadFactory != null ? customThreadFactory : Executors.defaultThreadFactory(); this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(runnable -> { Thread thread = threadFactory.newThread(runnable); thread.setDaemon(true); @@ -176,43 +188,58 @@ public String getSDKKey() { return this.sdkKey; } - public synchronized void start() { - if (started) { - logger.warn("Manager already started."); - return; - } + public void start() { + lock.lock(); + try { + if (started) { + logger.warn("Manager already started."); + return; + } - if (scheduledExecutorService.isShutdown()) { - logger.warn("Not starting. Already in shutdown."); - return; - } + if (scheduledExecutorService.isShutdown()) { + logger.warn("Not starting. Already in shutdown."); + return; + } - Runnable runnable = new ProjectConfigFetcher(); - scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(runnable, 0, period, timeUnit); - started = true; + Runnable runnable = new ProjectConfigFetcher(); + scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(runnable, 0, period, timeUnit); + started = true; + } finally { + lock.unlock(); + } } - public synchronized void stop() { - if (!started) { - logger.warn("Not pausing. Manager has not been started."); - return; - } + public void stop() { + lock.lock(); + try { + if (!started) { + logger.warn("Not pausing. Manager has not been started."); + return; + } - if (scheduledExecutorService.isShutdown()) { - logger.warn("Not pausing. Already in shutdown."); - return; - } + if (scheduledExecutorService.isShutdown()) { + logger.warn("Not pausing. Already in shutdown."); + return; + } - logger.info("pausing project watcher"); - scheduledFuture.cancel(true); - started = false; + logger.info("pausing project watcher"); + scheduledFuture.cancel(true); + started = false; + } finally { + lock.unlock(); + } } @Override - public synchronized void close() { - stop(); - scheduledExecutorService.shutdownNow(); - started = false; + public void close() { + lock.lock(); + try { + stop(); + scheduledExecutorService.shutdownNow(); + started = false; + } finally { + lock.unlock(); + } } protected void setSdkKey(String sdkKey) { diff --git a/core-api/src/main/java/com/optimizely/ab/event/BatchEventProcessor.java b/core-api/src/main/java/com/optimizely/ab/event/BatchEventProcessor.java index daf81d71a..740cfb8c3 100644 --- a/core-api/src/main/java/com/optimizely/ab/event/BatchEventProcessor.java +++ b/core-api/src/main/java/com/optimizely/ab/event/BatchEventProcessor.java @@ -21,6 +21,7 @@ import com.optimizely.ab.event.internal.UserEvent; import com.optimizely.ab.internal.PropertyUtils; import com.optimizely.ab.notification.NotificationCenter; +import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -67,6 +68,7 @@ public class BatchEventProcessor implements EventProcessor, AutoCloseable { private Future<?> future; private boolean isStarted = false; + private final ReentrantLock lock = new ReentrantLock(); private BatchEventProcessor(BlockingQueue<Object> eventQueue, EventHandler eventHandler, Integer batchSize, Long flushInterval, Long timeoutMillis, ExecutorService executor, NotificationCenter notificationCenter) { this.eventHandler = eventHandler; @@ -78,15 +80,20 @@ private BatchEventProcessor(BlockingQueue<Object> eventQueue, EventHandler event this.executor = executor; } - public synchronized void start() { - if (isStarted) { - logger.info("Executor already started."); - return; - } + public void start() { + lock.lock(); + try { + if (isStarted) { + logger.info("Executor already started."); + return; + } - isStarted = true; - EventConsumer runnable = new EventConsumer(); - future = executor.submit(runnable); + isStarted = true; + EventConsumer runnable = new EventConsumer(); + future = executor.submit(runnable); + } finally { + lock.unlock(); + } } @Override diff --git a/core-api/src/main/java/com/optimizely/ab/internal/DefaultLRUCache.java b/core-api/src/main/java/com/optimizely/ab/internal/DefaultLRUCache.java index a531c5c83..b946a65ea 100644 --- a/core-api/src/main/java/com/optimizely/ab/internal/DefaultLRUCache.java +++ b/core-api/src/main/java/com/optimizely/ab/internal/DefaultLRUCache.java @@ -19,10 +19,11 @@ import com.optimizely.ab.annotations.VisibleForTesting; import java.util.*; +import java.util.concurrent.locks.ReentrantLock; public class DefaultLRUCache<T> implements Cache<T> { - private final Object lock = new Object(); + private final ReentrantLock lock = new ReentrantLock(); private final Integer maxSize; @@ -51,8 +52,11 @@ public void save(String key, T value) { return; } - synchronized (lock) { + lock.lock(); + try { linkedHashMap.put(key, new CacheEntity(value)); + } finally { + lock.unlock(); } } @@ -62,7 +66,8 @@ public T lookup(String key) { return null; } - synchronized (lock) { + lock.lock(); + try { if (linkedHashMap.containsKey(key)) { CacheEntity entity = linkedHashMap.get(key); Long nowMs = new Date().getTime(); @@ -75,12 +80,17 @@ public T lookup(String key) { linkedHashMap.remove(key); } return null; + } finally { + lock.unlock(); } } public void reset() { - synchronized (lock) { + lock.lock(); + try { linkedHashMap.clear(); + } finally { + lock.unlock(); } } diff --git a/core-api/src/main/java/com/optimizely/ab/notification/NotificationManager.java b/core-api/src/main/java/com/optimizely/ab/notification/NotificationManager.java index 7415e6b23..986a142a8 100644 --- a/core-api/src/main/java/com/optimizely/ab/notification/NotificationManager.java +++ b/core-api/src/main/java/com/optimizely/ab/notification/NotificationManager.java @@ -16,6 +16,7 @@ */ package com.optimizely.ab.notification; +import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,6 +37,7 @@ public class NotificationManager<T> { private final Map<Integer, NotificationHandler<T>> handlers = Collections.synchronizedMap(new LinkedHashMap<>()); private final AtomicInteger counter; + private final ReentrantLock lock = new ReentrantLock(); public NotificationManager() { this(new AtomicInteger()); @@ -48,13 +50,16 @@ public NotificationManager(AtomicInteger counter) { public int addHandler(NotificationHandler<T> newHandler) { // Prevent registering a duplicate listener. - synchronized (handlers) { + lock.lock(); + try { for (NotificationHandler<T> handler : handlers.values()) { if (handler.equals(newHandler)) { logger.warn("Notification listener was already added"); return -1; } } + } finally { + lock.unlock(); } int notificationId = counter.incrementAndGet(); @@ -64,7 +69,8 @@ public int addHandler(NotificationHandler<T> newHandler) { } public void send(final T message) { - synchronized (handlers) { + lock.lock(); + try { for (Map.Entry<Integer, NotificationHandler<T>> handler: handlers.entrySet()) { try { handler.getValue().handle(message); @@ -72,6 +78,8 @@ public void send(final T message) { logger.warn("Catching exception sending notification for class: {}, handler: {}", message.getClass(), handler.getKey()); } } + } finally { + lock.unlock(); } } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java index eb055e63f..8ffaaeada 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPConfig.java @@ -18,6 +18,7 @@ import java.util.Collections; import java.util.Set; +import java.util.concurrent.locks.ReentrantLock; public class ODPConfig { @@ -27,6 +28,8 @@ public class ODPConfig { private Set<String> allSegments; + private final ReentrantLock lock = new ReentrantLock(); + public ODPConfig(String apiKey, String apiHost, Set<String> allSegments) { this.apiKey = apiKey; this.apiHost = apiHost; @@ -37,46 +40,91 @@ public ODPConfig(String apiKey, String apiHost) { this(apiKey, apiHost, Collections.emptySet()); } - public synchronized Boolean isReady() { - return !( - this.apiKey == null || this.apiKey.isEmpty() - || this.apiHost == null || this.apiHost.isEmpty() - ); + public Boolean isReady() { + lock.lock(); + try { + return !( + this.apiKey == null || this.apiKey.isEmpty() + || this.apiHost == null || this.apiHost.isEmpty() + ); + } finally { + lock.unlock(); + } } - public synchronized Boolean hasSegments() { - return allSegments != null && !allSegments.isEmpty(); + public Boolean hasSegments() { + lock.lock(); + try { + return allSegments != null && !allSegments.isEmpty(); + } finally { + lock.unlock(); + } } - public synchronized void setApiKey(String apiKey) { - this.apiKey = apiKey; + public void setApiKey(String apiKey) { + lock.lock(); + try { + this.apiKey = apiKey; + } finally { + lock.unlock(); + } } - public synchronized void setApiHost(String apiHost) { - this.apiHost = apiHost; + public void setApiHost(String apiHost) { + lock.lock(); + try { + this.apiHost = apiHost; + } finally { + lock.unlock(); + } } - public synchronized String getApiKey() { - return apiKey; + public String getApiKey() { + lock.lock(); + try { + return apiKey; + } finally { + lock.unlock(); + } } - public synchronized String getApiHost() { - return apiHost; + public String getApiHost() { + lock.lock(); + try { + return apiHost; + } finally { + lock.unlock(); + } } - public synchronized Set<String> getAllSegments() { - return allSegments; + public Set<String> getAllSegments() { + lock.lock(); + try { + return allSegments; + } finally { + lock.unlock(); + } } - public synchronized void setAllSegments(Set<String> allSegments) { - this.allSegments = allSegments; + public void setAllSegments(Set<String> allSegments) { + lock.lock(); + try { + this.allSegments = allSegments; + } finally { + lock.unlock(); + } } public Boolean equals(ODPConfig toCompare) { return getApiHost().equals(toCompare.getApiHost()) && getApiKey().equals(toCompare.getApiKey()) && getAllSegments().equals(toCompare.allSegments); } - public synchronized ODPConfig getClone() { - return new ODPConfig(apiKey, apiHost, allSegments); + public ODPConfig getClone() { + lock.lock(); + try { + return new ODPConfig(apiKey, apiHost, allSegments); + } finally { + lock.unlock(); + } } } diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java index efcdd6cda..b50c16045 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java @@ -59,16 +59,25 @@ public class ODPEventManager { // The eventQueue needs to be thread safe. We are not doing anything extra for thread safety here // because `LinkedBlockingQueue` itself is thread safe. private final BlockingQueue<Object> eventQueue = new LinkedBlockingQueue<>(); + private ThreadFactory threadFactory; public ODPEventManager(@Nonnull ODPApiManager apiManager) { this(apiManager, null, null); } public ODPEventManager(@Nonnull ODPApiManager apiManager, @Nullable Integer queueSize, @Nullable Integer flushInterval) { + this(apiManager, queueSize, flushInterval, null); + } + + public ODPEventManager(@Nonnull ODPApiManager apiManager, + @Nullable Integer queueSize, + @Nullable Integer flushInterval, + @Nullable ThreadFactory threadFactory) { this.apiManager = apiManager; this.queueSize = queueSize != null ? queueSize : DEFAULT_QUEUE_SIZE; this.flushInterval = (flushInterval != null && flushInterval > 0) ? flushInterval : DEFAULT_FLUSH_INTERVAL; this.batchSize = (flushInterval != null && flushInterval == 0) ? 1 : DEFAULT_BATCH_SIZE; + this.threadFactory = threadFactory != null ? threadFactory : Executors.defaultThreadFactory(); } // these user-provided common data are included in all ODP events in addition to the SDK-generated common data. @@ -86,7 +95,6 @@ public void start() { eventDispatcherThread = new EventDispatcherThread(); } if (!isRunning) { - final ThreadFactory threadFactory = Executors.defaultThreadFactory(); ExecutorService executor = Executors.newSingleThreadExecutor(runnable -> { Thread thread = threadFactory.newThread(runnable); thread.setDaemon(true); diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/NamedThreadFactory.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/NamedThreadFactory.java index 5b3cb2fbb..594ce0e20 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/NamedThreadFactory.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/NamedThreadFactory.java @@ -28,7 +28,7 @@ public class NamedThreadFactory implements ThreadFactory { private final String nameFormat; private final boolean daemon; - private final ThreadFactory backingThreadFactory = Executors.defaultThreadFactory(); + private final ThreadFactory backingThreadFactory; private final AtomicLong threadCount = new AtomicLong(0); /** @@ -36,8 +36,18 @@ public class NamedThreadFactory implements ThreadFactory { * @param daemon whether the threads created should be {@link Thread#daemon}s or not */ public NamedThreadFactory(String nameFormat, boolean daemon) { + this(nameFormat, daemon, null); + } + + /** + * @param nameFormat the thread name format which should include a string placeholder for the thread number + * @param daemon whether the threads created should be {@link Thread#daemon}s or not + * @param backingThreadFactory the backing {@link ThreadFactory} to use for creating threads + */ + public NamedThreadFactory(String nameFormat, boolean daemon, ThreadFactory backingThreadFactory) { this.nameFormat = nameFormat; this.daemon = daemon; + this.backingThreadFactory = backingThreadFactory != null ? backingThreadFactory : Executors.defaultThreadFactory(); } @Override diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java index 15325350f..a583eae98 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java @@ -21,6 +21,9 @@ import com.optimizely.ab.config.parser.ConfigParseException; import com.optimizely.ab.internal.PropertyUtils; import com.optimizely.ab.notification.NotificationCenter; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.locks.ReentrantLock; +import javax.annotation.Nullable; import org.apache.http.*; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; @@ -62,6 +65,7 @@ public class HttpProjectConfigManager extends PollingProjectConfigManager { private final URI uri; private final String datafileAccessToken; private String datafileLastModified; + private final ReentrantLock lock = new ReentrantLock(); private HttpProjectConfigManager(long period, TimeUnit timeUnit, @@ -70,8 +74,9 @@ private HttpProjectConfigManager(long period, String datafileAccessToken, long blockingTimeoutPeriod, TimeUnit blockingTimeoutUnit, - NotificationCenter notificationCenter) { - super(period, timeUnit, blockingTimeoutPeriod, blockingTimeoutUnit, notificationCenter); + NotificationCenter notificationCenter, + @Nullable ThreadFactory threadFactory) { + super(period, timeUnit, blockingTimeoutPeriod, blockingTimeoutUnit, notificationCenter, threadFactory); this.httpClient = httpClient; this.uri = URI.create(url); this.datafileAccessToken = datafileAccessToken; @@ -146,12 +151,17 @@ protected ProjectConfig poll() { } @Override - public synchronized void close() { - super.close(); + public void close() { + lock.lock(); try { - httpClient.close(); - } catch (IOException e) { - e.printStackTrace(); + super.close(); + try { + httpClient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } finally { + lock.unlock(); } } @@ -193,6 +203,7 @@ public static class Builder { // force-close the persistent connection after this idle time long evictConnectionIdleTimePeriod = PropertyUtils.getLong(CONFIG_EVICT_DURATION, DEFAULT_EVICT_DURATION); TimeUnit evictConnectionIdleTimeUnit = PropertyUtils.getEnum(CONFIG_EVICT_UNIT, TimeUnit.class, DEFAULT_EVICT_UNIT); + ThreadFactory threadFactory = null; public Builder withDatafile(String datafile) { this.datafile = datafile; @@ -302,6 +313,11 @@ public Builder withNotificationCenter(NotificationCenter notificationCenter) { return this; } + public Builder withThreadFactory(ThreadFactory threadFactory) { + this.threadFactory = threadFactory; + return this; + } + /** * HttpProjectConfigManager.Builder that builds and starts a HttpProjectConfigManager. * This is the default builder which will block until a config is available. @@ -363,7 +379,8 @@ public HttpProjectConfigManager build(boolean defer) { datafileAccessToken, blockingTimeoutPeriod, blockingTimeoutUnit, - notificationCenter); + notificationCenter, + threadFactory); httpProjectManager.setSdkKey(sdkKey); if (datafile != null) { try { diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java index 391f89b57..539b8b642 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java @@ -21,6 +21,8 @@ import com.optimizely.ab.annotations.VisibleForTesting; import com.optimizely.ab.internal.PropertyUtils; +import java.util.concurrent.ThreadFactory; +import javax.annotation.Nullable; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; @@ -108,6 +110,17 @@ public AsyncEventHandler(int queueCapacity, int validateAfter, long closeTimeout, TimeUnit closeTimeoutUnit) { + this(queueCapacity, numWorkers, maxConnections, connectionsPerRoute, validateAfter, closeTimeout, closeTimeoutUnit, null); + } + + public AsyncEventHandler(int queueCapacity, + int numWorkers, + int maxConnections, + int connectionsPerRoute, + int validateAfter, + long closeTimeout, + TimeUnit closeTimeoutUnit, + @Nullable ThreadFactory threadFactory) { queueCapacity = validateInput("queueCapacity", queueCapacity, DEFAULT_QUEUE_CAPACITY); numWorkers = validateInput("numWorkers", numWorkers, DEFAULT_NUM_WORKERS); @@ -123,10 +136,12 @@ public AsyncEventHandler(int queueCapacity, .withEvictIdleConnections(1L, TimeUnit.MINUTES) .build(); + NamedThreadFactory namedThreadFactory = new NamedThreadFactory("optimizely-event-dispatcher-thread-%s", true, threadFactory); + this.workerExecutor = new ThreadPoolExecutor(numWorkers, numWorkers, - 0L, TimeUnit.MILLISECONDS, - new ArrayBlockingQueue<>(queueCapacity), - new NamedThreadFactory("optimizely-event-dispatcher-thread-%s", true)); + 0L, TimeUnit.MILLISECONDS, + new ArrayBlockingQueue<>(queueCapacity), + namedThreadFactory); this.closeTimeout = closeTimeout; this.closeTimeoutUnit = closeTimeoutUnit; From da19ebb6d2c5909a9d97ce63f4c16a15d975abf5 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Thu, 4 Apr 2024 10:07:24 -0700 Subject: [PATCH 60/80] [FSSDK-10041] fix to inject common httpclient to projectConfigManager, eventHandler and odpManager (#542) OptimizelyFactory method for injecting customHttpClient is fixed to share the customHttpClient for all modules using httpClient - HttpProjectConfigManager - AsyncEventHander - ODPManager --- .../java/com/optimizely/ab/Optimizely.java | 4 +- .../ab/event/BatchEventProcessor.java | 4 +- .../optimizely/ab/odp/ODPEventManager.java | 4 +- .../com/optimizely/ab/odp/ODPManager.java | 1 - .../optimizely/ab/odp/ODPSegmentManager.java | 5 +- .../com/optimizely/ab/OptimizelyFactory.java | 44 ++++++++++++---- .../optimizely/ab/OptimizelyHttpClient.java | 1 - .../ab/config/HttpProjectConfigManager.java | 3 +- .../ab/event/AsyncEventHandler.java | 51 +++++++++++++------ .../ab/odp/DefaultODPApiManager.java | 16 ++++-- .../optimizely/ab/OptimizelyFactoryTest.java | 46 +++++++++++------ .../config/HttpProjectConfigManagerTest.java | 2 - .../ab/event/AsyncEventHandlerTest.java | 30 ++++++++--- .../ab/odp/DefaultODPApiManagerTest.java | 1 - 14 files changed, 149 insertions(+), 63 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/Optimizely.java b/core-api/src/main/java/com/optimizely/ab/Optimizely.java index e64882ed6..fede007d5 100644 --- a/core-api/src/main/java/com/optimizely/ab/Optimizely.java +++ b/core-api/src/main/java/com/optimizely/ab/Optimizely.java @@ -78,7 +78,6 @@ public class Optimizely implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(Optimizely.class); final DecisionService decisionService; - @VisibleForTesting @Deprecated final EventHandler eventHandler; @VisibleForTesting @@ -88,7 +87,8 @@ public class Optimizely implements AutoCloseable { public final List<OptimizelyDecideOption> defaultDecideOptions; - private final ProjectConfigManager projectConfigManager; + @VisibleForTesting + final ProjectConfigManager projectConfigManager; @Nullable private final OptimizelyConfigManager optimizelyConfigManager; diff --git a/core-api/src/main/java/com/optimizely/ab/event/BatchEventProcessor.java b/core-api/src/main/java/com/optimizely/ab/event/BatchEventProcessor.java index 740cfb8c3..4f31b37e8 100644 --- a/core-api/src/main/java/com/optimizely/ab/event/BatchEventProcessor.java +++ b/core-api/src/main/java/com/optimizely/ab/event/BatchEventProcessor.java @@ -16,6 +16,7 @@ */ package com.optimizely.ab.event; +import com.optimizely.ab.annotations.VisibleForTesting; import com.optimizely.ab.config.ProjectConfig; import com.optimizely.ab.event.internal.EventFactory; import com.optimizely.ab.event.internal.UserEvent; @@ -58,7 +59,8 @@ public class BatchEventProcessor implements EventProcessor, AutoCloseable { private static final Object FLUSH_SIGNAL = new Object(); private final BlockingQueue<Object> eventQueue; - private final EventHandler eventHandler; + @VisibleForTesting + public final EventHandler eventHandler; final int batchSize; final long flushInterval; diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java index b50c16045..43727b501 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPEventManager.java @@ -53,8 +53,8 @@ public class ODPEventManager { // needs to see the change immediately. private volatile ODPConfig odpConfig; private EventDispatcherThread eventDispatcherThread; - - private final ODPApiManager apiManager; + @VisibleForTesting + public final ODPApiManager apiManager; // The eventQueue needs to be thread safe. We are not doing anything extra for thread safety here // because `LinkedBlockingQueue` itself is thread safe. diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java index 4f1ddc52d..3a47e3f04 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPManager.java @@ -21,7 +21,6 @@ import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; diff --git a/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java index 8cd917269..6caae29ca 100644 --- a/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java +++ b/core-api/src/main/java/com/optimizely/ab/odp/ODPSegmentManager.java @@ -16,6 +16,7 @@ */ package com.optimizely.ab.odp; +import com.optimizely.ab.annotations.VisibleForTesting; import com.optimizely.ab.internal.Cache; import com.optimizely.ab.internal.DefaultLRUCache; import com.optimizely.ab.odp.parser.ResponseJsonParser; @@ -31,8 +32,8 @@ public class ODPSegmentManager { private static final Logger logger = LoggerFactory.getLogger(ODPSegmentManager.class); private static final String SEGMENT_URL_PATH = "/v3/graphql"; - - private final ODPApiManager apiManager; + @VisibleForTesting + public final ODPApiManager apiManager; private volatile ODPConfig odpConfig; diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyFactory.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyFactory.java index 1c6ee2820..f26851375 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyFactory.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyFactory.java @@ -279,23 +279,37 @@ public static Optimizely newDefaultInstance(String sdkKey, String fallback, Stri * @param customHttpClient Customizable CloseableHttpClient to build OptimizelyHttpClient. * @return A new Optimizely instance */ - public static Optimizely newDefaultInstance(String sdkKey, String fallback, String datafileAccessToken, CloseableHttpClient customHttpClient) { + public static Optimizely newDefaultInstance( + String sdkKey, + String fallback, + String datafileAccessToken, + CloseableHttpClient customHttpClient + ) { + OptimizelyHttpClient optimizelyHttpClient = customHttpClient == null ? null : new OptimizelyHttpClient(customHttpClient); + NotificationCenter notificationCenter = new NotificationCenter(); - OptimizelyHttpClient optimizelyHttpClient = new OptimizelyHttpClient(customHttpClient); - HttpProjectConfigManager.Builder builder; - builder = HttpProjectConfigManager.builder() + + HttpProjectConfigManager.Builder builder = HttpProjectConfigManager.builder() .withDatafile(fallback) .withNotificationCenter(notificationCenter) - .withOptimizelyHttpClient(customHttpClient == null ? null : optimizelyHttpClient) + .withOptimizelyHttpClient(optimizelyHttpClient) .withSdkKey(sdkKey); if (datafileAccessToken != null) { builder.withDatafileAccessToken(datafileAccessToken); } - return newDefaultInstance(builder.build(), notificationCenter); - } + ProjectConfigManager configManager = builder.build(); + + EventHandler eventHandler = AsyncEventHandler.builder() + .withOptimizelyHttpClient(optimizelyHttpClient) + .build(); + ODPApiManager odpApiManager = new DefaultODPApiManager(optimizelyHttpClient); + + return newDefaultInstance(configManager, notificationCenter, eventHandler, odpApiManager); + } + /** * Returns a new Optimizely instance based on preset configuration. * EventHandler - {@link AsyncEventHandler} @@ -329,6 +343,19 @@ public static Optimizely newDefaultInstance(ProjectConfigManager configManager, * @return A new Optimizely instance * */ public static Optimizely newDefaultInstance(ProjectConfigManager configManager, NotificationCenter notificationCenter, EventHandler eventHandler) { + return newDefaultInstance(configManager, notificationCenter, eventHandler, null); + } + + /** + * Returns a new Optimizely instance based on preset configuration. + * + * @param configManager The {@link ProjectConfigManager} supplied to Optimizely instance. + * @param notificationCenter The {@link ProjectConfigManager} supplied to Optimizely instance. + * @param eventHandler The {@link EventHandler} supplied to Optimizely instance. + * @param odpApiManager The {@link ODPApiManager} supplied to Optimizely instance. + * @return A new Optimizely instance + * */ + public static Optimizely newDefaultInstance(ProjectConfigManager configManager, NotificationCenter notificationCenter, EventHandler eventHandler, ODPApiManager odpApiManager) { if (notificationCenter == null) { notificationCenter = new NotificationCenter(); } @@ -338,9 +365,8 @@ public static Optimizely newDefaultInstance(ProjectConfigManager configManager, .withNotificationCenter(notificationCenter) .build(); - ODPApiManager defaultODPApiManager = new DefaultODPApiManager(); ODPManager odpManager = ODPManager.builder() - .withApiManager(defaultODPApiManager) + .withApiManager(odpApiManager != null ? odpApiManager : new DefaultODPApiManager()) .build(); return Optimizely.builder() diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyHttpClient.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyHttpClient.java index f4040276f..363bce59c 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyHttpClient.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyHttpClient.java @@ -41,7 +41,6 @@ public class OptimizelyHttpClient implements Closeable { private static final Logger logger = LoggerFactory.getLogger(OptimizelyHttpClient.class); - private final CloseableHttpClient httpClient; OptimizelyHttpClient(CloseableHttpClient httpClient) { diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java index a583eae98..095e32a67 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java @@ -61,7 +61,8 @@ public class HttpProjectConfigManager extends PollingProjectConfigManager { private static final Logger logger = LoggerFactory.getLogger(HttpProjectConfigManager.class); - private final OptimizelyHttpClient httpClient; + @VisibleForTesting + public final OptimizelyHttpClient httpClient; private final URI uri; private final String datafileAccessToken; private String datafileLastModified; diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java index 539b8b642..434b29103 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java @@ -45,6 +45,7 @@ import java.util.concurrent.TimeUnit; import javax.annotation.CheckForNull; +import javax.annotation.Nullable; /** * {@link EventHandler} implementation that queues events and has a separate pool of threads responsible @@ -67,7 +68,8 @@ public class AsyncEventHandler implements EventHandler, AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(AsyncEventHandler.class); private static final ProjectConfigResponseHandler EVENT_RESPONSE_HANDLER = new ProjectConfigResponseHandler(); - private final OptimizelyHttpClient httpClient; + @VisibleForTesting + public final OptimizelyHttpClient httpClient; private final ExecutorService workerExecutor; private final long closeTimeout; @@ -110,7 +112,15 @@ public AsyncEventHandler(int queueCapacity, int validateAfter, long closeTimeout, TimeUnit closeTimeoutUnit) { - this(queueCapacity, numWorkers, maxConnections, connectionsPerRoute, validateAfter, closeTimeout, closeTimeoutUnit, null); + this(queueCapacity, + numWorkers, + maxConnections, + connectionsPerRoute, + validateAfter, + closeTimeout, + closeTimeoutUnit, + null, + null); } public AsyncEventHandler(int queueCapacity, @@ -120,24 +130,27 @@ public AsyncEventHandler(int queueCapacity, int validateAfter, long closeTimeout, TimeUnit closeTimeoutUnit, + @Nullable OptimizelyHttpClient httpClient, @Nullable ThreadFactory threadFactory) { + if (httpClient != null) { + this.httpClient = httpClient; + } else { + maxConnections = validateInput("maxConnections", maxConnections, DEFAULT_MAX_CONNECTIONS); + connectionsPerRoute = validateInput("connectionsPerRoute", connectionsPerRoute, DEFAULT_MAX_PER_ROUTE); + validateAfter = validateInput("validateAfter", validateAfter, DEFAULT_VALIDATE_AFTER_INACTIVITY); + this.httpClient = OptimizelyHttpClient.builder() + .withMaxTotalConnections(maxConnections) + .withMaxPerRoute(connectionsPerRoute) + .withValidateAfterInactivity(validateAfter) + // infrequent event discards observed. staled connections force-closed after a long idle time. + .withEvictIdleConnections(1L, TimeUnit.MINUTES) + .build(); + } queueCapacity = validateInput("queueCapacity", queueCapacity, DEFAULT_QUEUE_CAPACITY); numWorkers = validateInput("numWorkers", numWorkers, DEFAULT_NUM_WORKERS); - maxConnections = validateInput("maxConnections", maxConnections, DEFAULT_MAX_CONNECTIONS); - connectionsPerRoute = validateInput("connectionsPerRoute", connectionsPerRoute, DEFAULT_MAX_PER_ROUTE); - validateAfter = validateInput("validateAfter", validateAfter, DEFAULT_VALIDATE_AFTER_INACTIVITY); - - this.httpClient = OptimizelyHttpClient.builder() - .withMaxTotalConnections(maxConnections) - .withMaxPerRoute(connectionsPerRoute) - .withValidateAfterInactivity(validateAfter) - // infrequent event discards observed. staled connections force-closed after a long idle time. - .withEvictIdleConnections(1L, TimeUnit.MINUTES) - .build(); NamedThreadFactory namedThreadFactory = new NamedThreadFactory("optimizely-event-dispatcher-thread-%s", true, threadFactory); - this.workerExecutor = new ThreadPoolExecutor(numWorkers, numWorkers, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueCapacity), @@ -302,6 +315,7 @@ public static class Builder { int validateAfterInactivity = PropertyUtils.getInteger(CONFIG_VALIDATE_AFTER_INACTIVITY, DEFAULT_VALIDATE_AFTER_INACTIVITY); private long closeTimeout = Long.MAX_VALUE; private TimeUnit closeTimeoutUnit = TimeUnit.MILLISECONDS; + private OptimizelyHttpClient httpClient; public Builder withQueueCapacity(int queueCapacity) { if (queueCapacity <= 0) { @@ -344,6 +358,11 @@ public Builder withCloseTimeout(long closeTimeout, TimeUnit unit) { return this; } + public Builder withOptimizelyHttpClient(OptimizelyHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + public AsyncEventHandler build() { return new AsyncEventHandler( queueCapacity, @@ -352,7 +371,9 @@ public AsyncEventHandler build() { maxPerRoute, validateAfterInactivity, closeTimeout, - closeTimeoutUnit + closeTimeoutUnit, + httpClient, + null ); } } diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java index 3a7ae3291..b733427de 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/odp/DefaultODPApiManager.java @@ -27,6 +27,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Iterator; @@ -36,11 +37,13 @@ public class DefaultODPApiManager implements ODPApiManager { private static final Logger logger = LoggerFactory.getLogger(DefaultODPApiManager.class); - private final OptimizelyHttpClient httpClientSegments; - private final OptimizelyHttpClient httpClientEvents; + @VisibleForTesting + public final OptimizelyHttpClient httpClientSegments; + @VisibleForTesting + public final OptimizelyHttpClient httpClientEvents; public DefaultODPApiManager() { - this(OptimizelyHttpClient.builder().build()); + this(null); } public DefaultODPApiManager(int segmentFetchTimeoutMillis, int eventDispatchTimeoutMillis) { @@ -53,8 +56,11 @@ public DefaultODPApiManager(int segmentFetchTimeoutMillis, int eventDispatchTime } } - @VisibleForTesting - DefaultODPApiManager(OptimizelyHttpClient httpClient) { + public DefaultODPApiManager(@Nullable OptimizelyHttpClient customHttpClient) { + OptimizelyHttpClient httpClient = customHttpClient; + if (httpClient == null) { + httpClient = OptimizelyHttpClient.builder().build(); + } this.httpClientSegments = httpClient; this.httpClientEvents = httpClient; } diff --git a/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyFactoryTest.java b/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyFactoryTest.java index aaa3a67fa..a15085645 100644 --- a/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyFactoryTest.java +++ b/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyFactoryTest.java @@ -25,12 +25,10 @@ import com.optimizely.ab.event.BatchEventProcessor; import com.optimizely.ab.internal.PropertyUtils; import com.optimizely.ab.notification.NotificationCenter; -import org.apache.http.HttpHost; -import org.apache.http.conn.routing.HttpRoutePlanner; +import com.optimizely.ab.odp.DefaultODPApiManager; +import com.optimizely.ab.odp.ODPManager; import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.DefaultProxyRoutePlanner; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -247,21 +245,39 @@ public void newDefaultInstanceWithDatafileAccessToken() throws Exception { @Test public void newDefaultInstanceWithDatafileAccessTokenAndCustomHttpClient() throws Exception { - // Add custom Proxy and Port here - int port = 443; - String proxyHostName = "someProxy.com"; - HttpHost proxyHost = new HttpHost(proxyHostName, port); + CloseableHttpClient customHttpClient = HttpClients.custom().build(); - HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost); - - HttpClientBuilder clientBuilder = HttpClients.custom(); - clientBuilder = clientBuilder.setRoutePlanner(routePlanner); - - CloseableHttpClient httpClient = clientBuilder.build(); String datafileString = Resources.toString(Resources.getResource("valid-project-config-v4.json"), Charsets.UTF_8); - optimizely = OptimizelyFactory.newDefaultInstance("sdk-key", datafileString, "auth-token", httpClient); + optimizely = OptimizelyFactory.newDefaultInstance("sdk-key", datafileString, "auth-token", customHttpClient); assertTrue(optimizely.isValid()); + + // HttpProjectConfigManager should be using the customHttpClient + + HttpProjectConfigManager projectConfigManager = (HttpProjectConfigManager) optimizely.projectConfigManager; + assert(doesUseCustomHttpClient(projectConfigManager.httpClient, customHttpClient)); + + // AsyncEventHandler should be using the customHttpClient + + BatchEventProcessor eventProcessor = (BatchEventProcessor) optimizely.eventProcessor; + AsyncEventHandler eventHandler = (AsyncEventHandler)eventProcessor.eventHandler; + assert(doesUseCustomHttpClient(eventHandler.httpClient, customHttpClient)); + + // ODPManager should be using the customHttpClient + + ODPManager odpManager = optimizely.getODPManager(); + assert odpManager != null; + DefaultODPApiManager odpApiManager = (DefaultODPApiManager) odpManager.getEventManager().apiManager; + assert(doesUseCustomHttpClient(odpApiManager.httpClientSegments, customHttpClient)); + assert(doesUseCustomHttpClient(odpApiManager.httpClientEvents, customHttpClient)); + } + + boolean doesUseCustomHttpClient(OptimizelyHttpClient optimizelyHttpClient, CloseableHttpClient customHttpClient) { + if (optimizelyHttpClient == null) { + return false; + } + return optimizelyHttpClient.getHttpClient() == customHttpClient; } + public ProjectConfigManager projectConfigManagerReturningNull = new ProjectConfigManager() { @Override public ProjectConfig getConfig() { diff --git a/core-httpclient-impl/src/test/java/com/optimizely/ab/config/HttpProjectConfigManagerTest.java b/core-httpclient-impl/src/test/java/com/optimizely/ab/config/HttpProjectConfigManagerTest.java index 9cbc0bb01..77960d518 100644 --- a/core-httpclient-impl/src/test/java/com/optimizely/ab/config/HttpProjectConfigManagerTest.java +++ b/core-httpclient-impl/src/test/java/com/optimizely/ab/config/HttpProjectConfigManagerTest.java @@ -20,7 +20,6 @@ import com.google.common.io.Resources; import com.optimizely.ab.OptimizelyHttpClient; import org.apache.http.HttpHeaders; -import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; @@ -44,7 +43,6 @@ import static java.util.concurrent.TimeUnit.SECONDS; import static java.util.concurrent.TimeUnit.MINUTES; import static org.junit.Assert.*; -import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) diff --git a/core-httpclient-impl/src/test/java/com/optimizely/ab/event/AsyncEventHandlerTest.java b/core-httpclient-impl/src/test/java/com/optimizely/ab/event/AsyncEventHandlerTest.java index 79a4105a1..f87811b96 100644 --- a/core-httpclient-impl/src/test/java/com/optimizely/ab/event/AsyncEventHandlerTest.java +++ b/core-httpclient-impl/src/test/java/com/optimizely/ab/event/AsyncEventHandlerTest.java @@ -22,14 +22,9 @@ import com.optimizely.ab.event.internal.payload.EventBatch; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; import java.io.IOException; import java.util.HashMap; @@ -38,7 +33,6 @@ import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.mockito.runners.MockitoJUnitRunner; import static com.optimizely.ab.event.AsyncEventHandler.builder; @@ -124,6 +118,30 @@ public void testShutdownAndForcedTermination() throws Exception { verify(mockHttpClient).close(); } + @Test + public void testBuilderWithCustomHttpClient() { + OptimizelyHttpClient customHttpClient = OptimizelyHttpClient.builder().build(); + + AsyncEventHandler eventHandler = builder() + .withOptimizelyHttpClient(customHttpClient) + .withMaxTotalConnections(1) + .withMaxPerRoute(2) + .withCloseTimeout(10, TimeUnit.SECONDS) + .build(); + + assert eventHandler.httpClient == customHttpClient; + } + + @Test + public void testBuilderWithDefaultHttpClient() { + AsyncEventHandler eventHandler = builder() + .withMaxTotalConnections(3) + .withMaxPerRoute(4) + .withCloseTimeout(10, TimeUnit.SECONDS) + .build(); + assert(eventHandler.httpClient != null); + } + @Test public void testInvalidQueueCapacity() { AsyncEventHandler.Builder builder = builder(); diff --git a/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java b/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java index a268cacc7..780831ff2 100644 --- a/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java +++ b/core-httpclient-impl/src/test/java/com/optimizely/ab/odp/DefaultODPApiManagerTest.java @@ -33,7 +33,6 @@ import java.util.List; import static org.junit.Assert.*; -import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; public class DefaultODPApiManagerTest { From 8fdbfbf631085e08e2b6dd4577574892d0edb896 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Fri, 12 Apr 2024 12:57:48 -0700 Subject: [PATCH 61/80] prepare release 4.1.0 (#544) --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 764c83982..67458f732 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Optimizely Java X SDK Changelog +## [4.1.0] +April 12th, 2024 + +### New Features +* OptimizelyFactory method for injecting customHttpClient is fixed to share the customHttpClient for all modules using httpClient (HttpProjectConfigManager, AsyncEventHander, ODPManager) ([#542](https://github.com/optimizely/java-sdk/pull/542)). +* A custom ThreadFactory can be injected to support virtual threads (Loom) ([#540](https://github.com/optimizely/java-sdk/pull/540)). + + ## [4.0.0] January 16th, 2024 From 71f9e75c3ae9c408dd1d70d9ee8b94689675401c Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Wed, 8 May 2024 15:48:58 -0700 Subject: [PATCH 62/80] [FSSDK-10095] fix events dropped on staled connections. (#545) Events can be discarded for staled connections with httpclient connection pooling. This PR fixs it with - - reduce the time for connection validation from 5 to 1sec. - enable retries (x3) for event POST. --- .../ab/odp/ODPEventManagerTest.java | 5 - core-httpclient-impl/README.md | 10 +- core-httpclient-impl/build.gradle | 3 +- .../com/optimizely/ab/HttpClientUtils.java | 4 +- .../optimizely/ab/OptimizelyHttpClient.java | 23 +++- .../ab/event/AsyncEventHandler.java | 21 ++-- .../ab/OptimizelyHttpClientTest.java | 102 ++++++++++++++++-- .../ab/event/AsyncEventHandlerTest.java | 12 +++ 8 files changed, 147 insertions(+), 33 deletions(-) diff --git a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java index 8a7546300..0ade4652f 100644 --- a/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java +++ b/core-api/src/test/java/com/optimizely/ab/odp/ODPEventManagerTest.java @@ -51,11 +51,6 @@ public class ODPEventManagerTest { @Captor ArgumentCaptor<String> payloadCaptor; - @Before - public void setup() { - mockApiManager = mock(ODPApiManager.class); - } - @Test public void logAndDiscardEventWhenEventManagerIsNotRunning() { ODPConfig odpConfig = new ODPConfig("key", "host", null); diff --git a/core-httpclient-impl/README.md b/core-httpclient-impl/README.md index 8e70b2ddb..762acb31a 100644 --- a/core-httpclient-impl/README.md +++ b/core-httpclient-impl/README.md @@ -107,23 +107,23 @@ The number of workers determines the number of threads the thread pool uses. The following builder methods can be used to custom configure the `AsyncEventHandler`. |Method Name|Default Value|Description| -|---|---|---| +|---|---|-----------------------------------------------| |`withQueueCapacity(int)`|10000|Queue size for pending logEvents| |`withNumWorkers(int)`|2|Number of worker threads| |`withMaxTotalConnections(int)`|200|Maximum number of connections| |`withMaxPerRoute(int)`|20|Maximum number of connections per route| -|`withValidateAfterInactivity(int)`|5000|Time to maintain idol connections (in milliseconds)| +|`withValidateAfterInactivity(int)`|1000|Time to maintain idle connections (in milliseconds)| ### Advanced configuration The following properties can be set to override the default configuration. |Property Name|Default Value|Description| -|---|---|---| +|---|---|-----------------------------------------------| |**async.event.handler.queue.capacity**|10000|Queue size for pending logEvents| |**async.event.handler.num.workers**|2|Number of worker threads| |**async.event.handler.max.connections**|200|Maximum number of connections| |**async.event.handler.event.max.per.route**|20|Maximum number of connections per route| -|**async.event.handler.validate.after**|5000|Time to maintain idol connections (in milliseconds)| +|**async.event.handler.validate.after**|1000|Time to maintain idle connections (in milliseconds)| ## HttpProjectConfigManager @@ -243,4 +243,4 @@ Optimizely optimizely = OptimizelyFactory.newDefaultInstance(); to enable request batching to the Optimizely logging endpoint. By default, a maximum of 10 events are included in each batch for a maximum interval of 30 seconds. These parameters are configurable via systems properties or through the `OptimizelyFactory#setMaxEventBatchSize` and `OptimizelyFactory#setMaxEventBatchInterval` methods. - \ No newline at end of file + diff --git a/core-httpclient-impl/build.gradle b/core-httpclient-impl/build.gradle index b43c70269..e4cdd4b99 100644 --- a/core-httpclient-impl/build.gradle +++ b/core-httpclient-impl/build.gradle @@ -1,9 +1,8 @@ dependencies { compile project(':core-api') - compileOnly group: 'com.google.code.gson', name: 'gson', version: gsonVersion - compile group: 'org.apache.httpcomponents', name: 'httpclient', version: httpClientVersion + testCompile 'org.mock-server:mockserver-netty:5.1.1' } task exhaustiveTest { diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/HttpClientUtils.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/HttpClientUtils.java index dc786c4f6..bc697e642 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/HttpClientUtils.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/HttpClientUtils.java @@ -26,7 +26,9 @@ public final class HttpClientUtils { public static final int CONNECTION_TIMEOUT_MS = 10000; public static final int CONNECTION_REQUEST_TIMEOUT_MS = 5000; public static final int SOCKET_TIMEOUT_MS = 10000; - + public static final int DEFAULT_VALIDATE_AFTER_INACTIVITY = 1000; + public static final int DEFAULT_MAX_CONNECTIONS = 200; + public static final int DEFAULT_MAX_PER_ROUTE = 20; private static RequestConfig requestConfigWithTimeout; private HttpClientUtils() { diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyHttpClient.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyHttpClient.java index 363bce59c..5b515aea6 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyHttpClient.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/OptimizelyHttpClient.java @@ -17,11 +17,15 @@ package com.optimizely.ab; import com.optimizely.ab.annotations.VisibleForTesting; +import com.optimizely.ab.HttpClientUtils; + import org.apache.http.client.HttpClient; +import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; @@ -73,16 +77,20 @@ public static class Builder { // The following static values are public so that they can be tweaked if necessary. // These are the recommended settings for http protocol. https://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html // The maximum number of connections allowed across all routes. - private int maxTotalConnections = 200; + int maxTotalConnections = HttpClientUtils.DEFAULT_MAX_CONNECTIONS; // The maximum number of connections allowed for a route - private int maxPerRoute = 20; + int maxPerRoute = HttpClientUtils.DEFAULT_MAX_PER_ROUTE; // Defines period of inactivity in milliseconds after which persistent connections must be re-validated prior to being leased to the consumer. - private int validateAfterInactivity = 5000; + // If this is too long, it's expected to see more requests dropped on staled connections (dropped by the server or networks). + // We can configure retries (POST for AsyncEventDispatcher) to cover the staled connections. + int validateAfterInactivity = HttpClientUtils.DEFAULT_VALIDATE_AFTER_INACTIVITY; // force-close the connection after this idle time (with 0, eviction is disabled by default) long evictConnectionIdleTimePeriod = 0; + HttpRequestRetryHandler customRetryHandler = null; TimeUnit evictConnectionIdleTimeUnit = TimeUnit.MILLISECONDS; private int timeoutMillis = HttpClientUtils.CONNECTION_TIMEOUT_MS; + private Builder() { } @@ -107,6 +115,12 @@ public Builder withEvictIdleConnections(long maxIdleTime, TimeUnit maxIdleTimeUn this.evictConnectionIdleTimeUnit = maxIdleTimeUnit; return this; } + + // customize retryHandler (DefaultHttpRequestRetryHandler will be used by default) + public Builder withRetryHandler(HttpRequestRetryHandler retryHandler) { + this.customRetryHandler = retryHandler; + return this; + } public Builder setTimeoutMillis(int timeoutMillis) { this.timeoutMillis = timeoutMillis; @@ -124,6 +138,9 @@ public OptimizelyHttpClient build() { .setConnectionManager(poolingHttpClientConnectionManager) .disableCookieManagement() .useSystemProperties(); + if (customRetryHandler != null) { + builder.setRetryHandler(customRetryHandler); + } logger.debug("Creating HttpClient with timeout: " + timeoutMillis); diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java index 434b29103..2a9c10ec9 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/event/AsyncEventHandler.java @@ -16,6 +16,7 @@ */ package com.optimizely.ab.event; +import com.optimizely.ab.HttpClientUtils; import com.optimizely.ab.NamedThreadFactory; import com.optimizely.ab.OptimizelyHttpClient; import com.optimizely.ab.annotations.VisibleForTesting; @@ -31,6 +32,7 @@ import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,7 +47,6 @@ import java.util.concurrent.TimeUnit; import javax.annotation.CheckForNull; -import javax.annotation.Nullable; /** * {@link EventHandler} implementation that queues events and has a separate pool of threads responsible @@ -61,9 +62,7 @@ public class AsyncEventHandler implements EventHandler, AutoCloseable { public static final int DEFAULT_QUEUE_CAPACITY = 10000; public static final int DEFAULT_NUM_WORKERS = 2; - public static final int DEFAULT_MAX_CONNECTIONS = 200; - public static final int DEFAULT_MAX_PER_ROUTE = 20; - public static final int DEFAULT_VALIDATE_AFTER_INACTIVITY = 5000; + private static final Logger logger = LoggerFactory.getLogger(AsyncEventHandler.class); private static final ProjectConfigResponseHandler EVENT_RESPONSE_HANDLER = new ProjectConfigResponseHandler(); @@ -135,15 +134,17 @@ public AsyncEventHandler(int queueCapacity, if (httpClient != null) { this.httpClient = httpClient; } else { - maxConnections = validateInput("maxConnections", maxConnections, DEFAULT_MAX_CONNECTIONS); - connectionsPerRoute = validateInput("connectionsPerRoute", connectionsPerRoute, DEFAULT_MAX_PER_ROUTE); - validateAfter = validateInput("validateAfter", validateAfter, DEFAULT_VALIDATE_AFTER_INACTIVITY); + maxConnections = validateInput("maxConnections", maxConnections, HttpClientUtils.DEFAULT_MAX_CONNECTIONS); + connectionsPerRoute = validateInput("connectionsPerRoute", connectionsPerRoute, HttpClientUtils.DEFAULT_MAX_PER_ROUTE); + validateAfter = validateInput("validateAfter", validateAfter, HttpClientUtils.DEFAULT_VALIDATE_AFTER_INACTIVITY); this.httpClient = OptimizelyHttpClient.builder() .withMaxTotalConnections(maxConnections) .withMaxPerRoute(connectionsPerRoute) .withValidateAfterInactivity(validateAfter) // infrequent event discards observed. staled connections force-closed after a long idle time. .withEvictIdleConnections(1L, TimeUnit.MINUTES) + // enable retry on event POST (default: retry on GET only) + .withRetryHandler(new DefaultHttpRequestRetryHandler(3, true)) .build(); } @@ -310,9 +311,9 @@ public static class Builder { int queueCapacity = PropertyUtils.getInteger(CONFIG_QUEUE_CAPACITY, DEFAULT_QUEUE_CAPACITY); int numWorkers = PropertyUtils.getInteger(CONFIG_NUM_WORKERS, DEFAULT_NUM_WORKERS); - int maxTotalConnections = PropertyUtils.getInteger(CONFIG_MAX_CONNECTIONS, DEFAULT_MAX_CONNECTIONS); - int maxPerRoute = PropertyUtils.getInteger(CONFIG_MAX_PER_ROUTE, DEFAULT_MAX_PER_ROUTE); - int validateAfterInactivity = PropertyUtils.getInteger(CONFIG_VALIDATE_AFTER_INACTIVITY, DEFAULT_VALIDATE_AFTER_INACTIVITY); + int maxTotalConnections = PropertyUtils.getInteger(CONFIG_MAX_CONNECTIONS, HttpClientUtils.DEFAULT_MAX_CONNECTIONS); + int maxPerRoute = PropertyUtils.getInteger(CONFIG_MAX_PER_ROUTE, HttpClientUtils.DEFAULT_MAX_PER_ROUTE); + int validateAfterInactivity = PropertyUtils.getInteger(CONFIG_VALIDATE_AFTER_INACTIVITY, HttpClientUtils.DEFAULT_VALIDATE_AFTER_INACTIVITY); private long closeTimeout = Long.MAX_VALUE; private TimeUnit closeTimeoutUnit = TimeUnit.MILLISECONDS; private OptimizelyHttpClient httpClient; diff --git a/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyHttpClientTest.java b/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyHttpClientTest.java index 4667bec34..d80a4f1ef 100644 --- a/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyHttpClientTest.java +++ b/core-httpclient-impl/src/test/java/com/optimizely/ab/OptimizelyHttpClientTest.java @@ -16,27 +16,39 @@ */ package com.optimizely.ab; +import org.apache.http.HttpException; +import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.ResponseHandler; +import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.conn.HttpHostConnectException; import org.apache.http.impl.client.CloseableHttpClient; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; +import org.apache.http.protocol.HttpContext; +import org.junit.*; +import org.mockserver.integration.ClientAndServer; +import org.mockserver.model.ConnectionOptions; +import org.mockserver.model.HttpError; +import org.mockserver.model.HttpRequest; +import org.mockserver.model.HttpResponse; import java.io.IOException; +import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import static com.optimizely.ab.OptimizelyHttpClient.builder; import static java.util.concurrent.TimeUnit.*; import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; +import static org.mockserver.model.HttpForward.forward; +import static org.mockserver.model.HttpRequest.request; +import static org.mockserver.model.HttpResponse.*; +import static org.mockserver.model.HttpResponse.response; +import static org.mockserver.verify.VerificationTimes.exactly; public class OptimizelyHttpClientTest { - @Before public void setUp() { System.setProperty("https.proxyHost", "localhost"); @@ -51,7 +63,13 @@ public void tearDown() { @Test public void testDefaultConfiguration() { - OptimizelyHttpClient optimizelyHttpClient = builder().build(); + OptimizelyHttpClient.Builder builder = builder(); + assertEquals(builder.validateAfterInactivity, 1000); + assertEquals(builder.maxTotalConnections, 200); + assertEquals(builder.maxPerRoute, 20); + assertNull(builder.customRetryHandler); + + OptimizelyHttpClient optimizelyHttpClient = builder.build(); assertTrue(optimizelyHttpClient.getHttpClient() instanceof CloseableHttpClient); } @@ -101,4 +119,74 @@ public void testExecute() throws IOException { OptimizelyHttpClient optimizelyHttpClient = new OptimizelyHttpClient(mockHttpClient); assertTrue(optimizelyHttpClient.execute(httpUriRequest, responseHandler)); } + + @Test + public void testRetriesWithCustomRetryHandler() throws IOException { + + // [NOTE] Request retries are all handled inside HttpClient. Not easy for unit test. + // - "DefaultHttpRetryHandler" in HttpClient retries only with special types of Exceptions + // like "NoHttpResponseException", etc. + // Other exceptions (SocketTimeout, ProtocolException, etc.) all ignored. + // - Not easy to force the specific exception type in the low-level. + // - This test just validates custom retry handler injected ok by validating the number of retries. + + class CustomRetryHandler implements HttpRequestRetryHandler { + private final int maxRetries; + + public CustomRetryHandler(int maxRetries) { + this.maxRetries = maxRetries; + } + + @Override + public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { + // override to retry for any type of exceptions + return executionCount < maxRetries; + } + } + + int port = 9999; + ClientAndServer mockServer; + int retryCount; + + // default httpclient (retries enabled by default, but no retry for timeout connection) + + mockServer = ClientAndServer.startClientAndServer(port); + mockServer + .when(request().withMethod("GET").withPath("/")) + .error(HttpError.error()); + + OptimizelyHttpClient clientDefault = OptimizelyHttpClient.builder() + .setTimeoutMillis(100) + .build(); + + try { + clientDefault.execute(new HttpGet("http://localhost:" + port)); + fail(); + } catch (Exception e) { + retryCount = mockServer.retrieveRecordedRequests(request()).length; + assertEquals(1, retryCount); + } + mockServer.stop(); + + // httpclient with custom retry handler (5 times retries for any request) + + mockServer = ClientAndServer.startClientAndServer(port); + mockServer + .when(request().withMethod("GET").withPath("/")) + .error(HttpError.error()); + + OptimizelyHttpClient clientWithRetries = OptimizelyHttpClient.builder() + .withRetryHandler(new CustomRetryHandler(5)) + .setTimeoutMillis(100) + .build(); + + try { + clientWithRetries.execute(new HttpGet("http://localhost:" + port)); + fail(); + } catch (Exception e) { + retryCount = mockServer.retrieveRecordedRequests(request()).length; + assertEquals(5, retryCount); + } + mockServer.stop(); + } } diff --git a/core-httpclient-impl/src/test/java/com/optimizely/ab/event/AsyncEventHandlerTest.java b/core-httpclient-impl/src/test/java/com/optimizely/ab/event/AsyncEventHandlerTest.java index f87811b96..19f1faba9 100644 --- a/core-httpclient-impl/src/test/java/com/optimizely/ab/event/AsyncEventHandlerTest.java +++ b/core-httpclient-impl/src/test/java/com/optimizely/ab/event/AsyncEventHandlerTest.java @@ -124,6 +124,7 @@ public void testBuilderWithCustomHttpClient() { AsyncEventHandler eventHandler = builder() .withOptimizelyHttpClient(customHttpClient) + // these params will be ignored when customHttpClient is injected .withMaxTotalConnections(1) .withMaxPerRoute(2) .withCloseTimeout(10, TimeUnit.SECONDS) @@ -134,6 +135,17 @@ public void testBuilderWithCustomHttpClient() { @Test public void testBuilderWithDefaultHttpClient() { + AsyncEventHandler.Builder builder = builder(); + assertEquals(builder.validateAfterInactivity, 1000); + assertEquals(builder.maxTotalConnections, 200); + assertEquals(builder.maxPerRoute, 20); + + AsyncEventHandler eventHandler = builder.build(); + assert(eventHandler.httpClient != null); + } + + @Test + public void testBuilderWithDefaultHttpClientAndCustomParams() { AsyncEventHandler eventHandler = builder() .withMaxTotalConnections(3) .withMaxPerRoute(4) From 3b42949f16762ba06a88f68dc0af383b20b3be47 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Wed, 8 May 2024 16:30:32 -0700 Subject: [PATCH 63/80] prepare for v3.10.5 (#546) --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 67458f732..8bcd3276f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Optimizely Java X SDK Changelog + +## [3.10.5] +May 8th, 2024 + +### Fixes +- Fix logx events discarded for staled connections with httpclient connection pooling ([#545](https://github.com/optimizely/java-sdk/pull/545)). + + ## [4.1.0] April 12th, 2024 From 7cd42fc15d12d460793c41932f8aff25e84c3009 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Wed, 8 May 2024 17:33:19 -0700 Subject: [PATCH 64/80] prepare for 4.1.1 (#547) --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bcd3276f..d92e70fbe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,7 @@ # Optimizely Java X SDK Changelog -## [3.10.5] +## [4.1.1] May 8th, 2024 ### Fixes From e813bfe1910af25d1dc2be1daf5764b61ae42c9f Mon Sep 17 00:00:00 2001 From: Farhan Anjum <Farhan.Anjum@optimizely.com> Date: Tue, 24 Sep 2024 22:43:41 +0600 Subject: [PATCH 65/80] [FSSDK-10665] fix: Github Actions YAML files vulnerable to script injections corrected (#548) --- .github/workflows/integration_test.yml | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/.github/workflows/integration_test.yml b/.github/workflows/integration_test.yml index 9471458fc..c54149edd 100644 --- a/.github/workflows/integration_test.yml +++ b/.github/workflows/integration_test.yml @@ -23,15 +23,19 @@ jobs: path: 'home/runner/travisci-tools' ref: 'master' - name: set SDK Branch if PR + env: + HEAD_REF: ${{ github.head_ref }} if: ${{ github.event_name == 'pull_request' }} run: | - echo "SDK_BRANCH=${{ github.head_ref }}" >> $GITHUB_ENV - echo "TRAVIS_BRANCH=${{ github.head_ref }}" >> $GITHUB_ENV + echo "SDK_BRANCH=$HEAD_REF" >> $GITHUB_ENV + echo "TRAVIS_BRANCH=$HEAD_REF" >> $GITHUB_ENV - name: set SDK Branch if not pull request + env: + REF_NAME: ${{ github.ref_name }} if: ${{ github.event_name != 'pull_request' }} run: | - echo "SDK_BRANCH=${{ github.ref_name }}" >> $GITHUB_ENV - echo "TRAVIS_BRANCH=${{ github.ref_name }}" >> $GITHUB_ENV + echo "SDK_BRANCH=$REF_NAME" >> $GITHUB_ENV + echo "TRAVIS_BRANCH=$REF_NAME" >> $GITHUB_ENV - name: Trigger build env: SDK: java From fe503181eed8df601c356e4e226edae1af7bcdb0 Mon Sep 17 00:00:00 2001 From: Raju Ahmed <raju.ahmed@optimizely.com> Date: Wed, 23 Oct 2024 00:47:38 +0600 Subject: [PATCH 66/80] [FSSDK-10762] Implement UPS request batching for decideForKeys (#549) --- .../java/com/optimizely/ab/Optimizely.java | 128 ++++++++---- .../ab/bucketing/DecisionService.java | 188 ++++++++++++------ .../ab/bucketing/UserProfileTracker.java | 109 ++++++++++ .../ab/OptimizelyUserContextTest.java | 98 ++++++++- .../ab/bucketing/DecisionServiceTest.java | 76 ++++--- 5 files changed, 458 insertions(+), 141 deletions(-) create mode 100644 core-api/src/main/java/com/optimizely/ab/bucketing/UserProfileTracker.java diff --git a/core-api/src/main/java/com/optimizely/ab/Optimizely.java b/core-api/src/main/java/com/optimizely/ab/Optimizely.java index fede007d5..0e260072e 100644 --- a/core-api/src/main/java/com/optimizely/ab/Optimizely.java +++ b/core-api/src/main/java/com/optimizely/ab/Optimizely.java @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright 2016-2023, Optimizely, Inc. and contributors * + * Copyright 2016-2024, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * @@ -42,8 +42,10 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; + import java.io.Closeable; import java.util.*; +import java.util.stream.Collectors; import static com.optimizely.ab.internal.SafetyUtils.tryClose; @@ -1194,42 +1196,26 @@ private OptimizelyUserContext createUserContextCopy(@Nonnull String userId, @Non OptimizelyDecision decide(@Nonnull OptimizelyUserContext user, @Nonnull String key, @Nonnull List<OptimizelyDecideOption> options) { - ProjectConfig projectConfig = getProjectConfig(); if (projectConfig == null) { return OptimizelyDecision.newErrorDecision(key, user, DecisionMessage.SDK_NOT_READY.reason()); } - FeatureFlag flag = projectConfig.getFeatureKeyMapping().get(key); - if (flag == null) { - return OptimizelyDecision.newErrorDecision(key, user, DecisionMessage.FLAG_KEY_INVALID.reason(key)); - } - - String userId = user.getUserId(); - Map<String, Object> attributes = user.getAttributes(); - Boolean decisionEventDispatched = false; List<OptimizelyDecideOption> allOptions = getAllOptions(options); - DecisionReasons decisionReasons = DefaultDecisionReasons.newInstance(allOptions); + allOptions.remove(OptimizelyDecideOption.ENABLED_FLAGS_ONLY); - Map<String, ?> copiedAttributes = new HashMap<>(attributes); - FeatureDecision flagDecision; - - // Check Forced Decision - OptimizelyDecisionContext optimizelyDecisionContext = new OptimizelyDecisionContext(flag.getKey(), null); - DecisionResponse<Variation> forcedDecisionVariation = decisionService.validatedForcedDecision(optimizelyDecisionContext, projectConfig, user); - decisionReasons.merge(forcedDecisionVariation.getReasons()); - if (forcedDecisionVariation.getResult() != null) { - flagDecision = new FeatureDecision(null, forcedDecisionVariation.getResult(), FeatureDecision.DecisionSource.FEATURE_TEST); - } else { - // Regular decision - DecisionResponse<FeatureDecision> decisionVariation = decisionService.getVariationForFeature( - flag, - user, - projectConfig, - allOptions); - flagDecision = decisionVariation.getResult(); - decisionReasons.merge(decisionVariation.getReasons()); - } + return decideForKeys(user, Arrays.asList(key), allOptions, true).get(key); + } + + private OptimizelyDecision createOptimizelyDecision( + OptimizelyUserContext user, + String flagKey, + FeatureDecision flagDecision, + DecisionReasons decisionReasons, + List<OptimizelyDecideOption> allOptions, + ProjectConfig projectConfig + ) { + String userId = user.getUserId(); Boolean flagEnabled = false; if (flagDecision.variation != null) { @@ -1237,12 +1223,12 @@ OptimizelyDecision decide(@Nonnull OptimizelyUserContext user, flagEnabled = true; } } - logger.info("Feature \"{}\" is enabled for user \"{}\"? {}", key, userId, flagEnabled); + logger.info("Feature \"{}\" is enabled for user \"{}\"? {}", flagKey, userId, flagEnabled); Map<String, Object> variableMap = new HashMap<>(); if (!allOptions.contains(OptimizelyDecideOption.EXCLUDE_VARIABLES)) { DecisionResponse<Map<String, Object>> decisionVariables = getDecisionVariableMap( - flag, + projectConfig.getFeatureKeyMapping().get(flagKey), flagDecision.variation, flagEnabled); variableMap = decisionVariables.getResult(); @@ -1261,6 +1247,12 @@ OptimizelyDecision decide(@Nonnull OptimizelyUserContext user, // add to event metadata as well (currently set to experimentKey) String ruleKey = flagDecision.experiment != null ? flagDecision.experiment.getKey() : null; + + Boolean decisionEventDispatched = false; + + Map<String, Object> attributes = user.getAttributes(); + Map<String, ?> copiedAttributes = new HashMap<>(attributes); + if (!allOptions.contains(OptimizelyDecideOption.DISABLE_DECISION_EVENT)) { decisionEventDispatched = sendImpression( projectConfig, @@ -1268,7 +1260,7 @@ OptimizelyDecision decide(@Nonnull OptimizelyUserContext user, userId, copiedAttributes, flagDecision.variation, - key, + flagKey, decisionSource.toString(), flagEnabled); } @@ -1276,7 +1268,7 @@ OptimizelyDecision decide(@Nonnull OptimizelyUserContext user, DecisionNotification decisionNotification = DecisionNotification.newFlagDecisionNotificationBuilder() .withUserId(userId) .withAttributes(copiedAttributes) - .withFlagKey(key) + .withFlagKey(flagKey) .withEnabled(flagEnabled) .withVariables(variableMap) .withVariationKey(variationKey) @@ -1291,30 +1283,84 @@ OptimizelyDecision decide(@Nonnull OptimizelyUserContext user, flagEnabled, optimizelyJSON, ruleKey, - key, + flagKey, user, reasonsToReport); } Map<String, OptimizelyDecision> decideForKeys(@Nonnull OptimizelyUserContext user, + @Nonnull List<String> keys, + @Nonnull List<OptimizelyDecideOption> options) { + return decideForKeys(user, keys, options, false); + } + + private Map<String, OptimizelyDecision> decideForKeys(@Nonnull OptimizelyUserContext user, @Nonnull List<String> keys, - @Nonnull List<OptimizelyDecideOption> options) { + @Nonnull List<OptimizelyDecideOption> options, + boolean ignoreDefaultOptions) { Map<String, OptimizelyDecision> decisionMap = new HashMap<>(); ProjectConfig projectConfig = getProjectConfig(); if (projectConfig == null) { - logger.error("Optimizely instance is not valid, failing isFeatureEnabled call."); + logger.error("Optimizely instance is not valid, failing decideForKeys call."); return decisionMap; } if (keys.isEmpty()) return decisionMap; - List<OptimizelyDecideOption> allOptions = getAllOptions(options); + List<OptimizelyDecideOption> allOptions = ignoreDefaultOptions ? options: getAllOptions(options); + + Map<String, FeatureDecision> flagDecisions = new HashMap<>(); + Map<String, DecisionReasons> decisionReasonsMap = new HashMap<>(); + + List<FeatureFlag> flagsWithoutForcedDecision = new ArrayList<>(); + + List<String> validKeys = new ArrayList<>(); for (String key : keys) { - OptimizelyDecision decision = decide(user, key, options); - if (!allOptions.contains(OptimizelyDecideOption.ENABLED_FLAGS_ONLY) || decision.getEnabled()) { - decisionMap.put(key, decision); + FeatureFlag flag = projectConfig.getFeatureKeyMapping().get(key); + if (flag == null) { + decisionMap.put(key, OptimizelyDecision.newErrorDecision(key, user, DecisionMessage.FLAG_KEY_INVALID.reason(key))); + continue; + } + + validKeys.add(key); + + DecisionReasons decisionReasons = DefaultDecisionReasons.newInstance(allOptions); + decisionReasonsMap.put(key, decisionReasons); + + OptimizelyDecisionContext optimizelyDecisionContext = new OptimizelyDecisionContext(key, null); + DecisionResponse<Variation> forcedDecisionVariation = decisionService.validatedForcedDecision(optimizelyDecisionContext, projectConfig, user); + decisionReasons.merge(forcedDecisionVariation.getReasons()); + + if (forcedDecisionVariation.getResult() != null) { + flagDecisions.put(key, + new FeatureDecision(null, forcedDecisionVariation.getResult(), FeatureDecision.DecisionSource.FEATURE_TEST)); + } else { + flagsWithoutForcedDecision.add(flag); + } + } + + List<DecisionResponse<FeatureDecision>> decisionList = + decisionService.getVariationsForFeatureList(flagsWithoutForcedDecision, user, projectConfig, allOptions); + + for (int i = 0; i < flagsWithoutForcedDecision.size(); i++) { + DecisionResponse<FeatureDecision> decision = decisionList.get(i); + String flagKey = flagsWithoutForcedDecision.get(i).getKey(); + flagDecisions.put(flagKey, decision.getResult()); + decisionReasonsMap.get(flagKey).merge(decision.getReasons()); + } + + for (String key: validKeys) { + FeatureDecision flagDecision = flagDecisions.get(key); + DecisionReasons decisionReasons = decisionReasonsMap.get((key)); + + OptimizelyDecision optimizelyDecision = createOptimizelyDecision( + user, key, flagDecision, decisionReasons, allOptions, projectConfig + ); + + if (!allOptions.contains(OptimizelyDecideOption.ENABLED_FLAGS_ONLY) || optimizelyDecision.getEnabled()) { + decisionMap.put(key, optimizelyDecision); } } diff --git a/core-api/src/main/java/com/optimizely/ab/bucketing/DecisionService.java b/core-api/src/main/java/com/optimizely/ab/bucketing/DecisionService.java index 84d47d03f..ff48ffb99 100644 --- a/core-api/src/main/java/com/optimizely/ab/bucketing/DecisionService.java +++ b/core-api/src/main/java/com/optimizely/ab/bucketing/DecisionService.java @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright 2017-2022, Optimizely, Inc. and contributors * + * Copyright 2017-2022, 2024, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * @@ -81,18 +81,24 @@ public DecisionService(@Nonnull Bucketer bucketer, /** * Get a {@link Variation} of an {@link Experiment} for a user to be allocated into. * - * @param experiment The Experiment the user will be bucketed into. - * @param user The current OptimizelyUserContext - * @param projectConfig The current projectConfig - * @param options An array of decision options + * @param experiment The Experiment the user will be bucketed into. + * @param user The current OptimizelyUserContext + * @param projectConfig The current projectConfig + * @param options An array of decision options + * @param userProfileTracker tracker for reading and updating user profile of the user + * @param reasons Decision reasons * @return A {@link DecisionResponse} including the {@link Variation} that user is bucketed into (or null) and the decision reasons */ @Nonnull public DecisionResponse<Variation> getVariation(@Nonnull Experiment experiment, @Nonnull OptimizelyUserContext user, @Nonnull ProjectConfig projectConfig, - @Nonnull List<OptimizelyDecideOption> options) { - DecisionReasons reasons = DefaultDecisionReasons.newInstance(); + @Nonnull List<OptimizelyDecideOption> options, + @Nullable UserProfileTracker userProfileTracker, + @Nullable DecisionReasons reasons) { + if (reasons == null) { + reasons = DefaultDecisionReasons.newInstance(); + } if (!ExperimentUtils.isExperimentActive(experiment)) { String message = reasons.addInfo("Experiment \"%s\" is not running.", experiment.getKey()); @@ -116,39 +122,13 @@ public DecisionResponse<Variation> getVariation(@Nonnull Experiment experiment, return new DecisionResponse(variation, reasons); } - // fetch the user profile map from the user profile service - boolean ignoreUPS = options.contains(OptimizelyDecideOption.IGNORE_USER_PROFILE_SERVICE); - UserProfile userProfile = null; - - if (userProfileService != null && !ignoreUPS) { - try { - Map<String, Object> userProfileMap = userProfileService.lookup(user.getUserId()); - if (userProfileMap == null) { - String message = reasons.addInfo("We were unable to get a user profile map from the UserProfileService."); - logger.info(message); - } else if (UserProfileUtils.isValidUserProfileMap(userProfileMap)) { - userProfile = UserProfileUtils.convertMapToUserProfile(userProfileMap); - } else { - String message = reasons.addInfo("The UserProfileService returned an invalid map."); - logger.warn(message); - } - } catch (Exception exception) { - String message = reasons.addInfo(exception.getMessage()); - logger.error(message); - errorHandler.handleError(new OptimizelyRuntimeException(exception)); - } - - // check if user exists in user profile - if (userProfile != null) { - decisionVariation = getStoredVariation(experiment, userProfile, projectConfig); - reasons.merge(decisionVariation.getReasons()); - variation = decisionVariation.getResult(); - // return the stored variation if it exists - if (variation != null) { - return new DecisionResponse(variation, reasons); - } - } else { // if we could not find a user profile, make a new one - userProfile = new UserProfile(user.getUserId(), new HashMap<String, Decision>()); + if (userProfileTracker != null) { + decisionVariation = getStoredVariation(experiment, userProfileTracker.getUserProfile(), projectConfig); + reasons.merge(decisionVariation.getReasons()); + variation = decisionVariation.getResult(); + // return the stored variation if it exists + if (variation != null) { + return new DecisionResponse(variation, reasons); } } @@ -162,8 +142,8 @@ public DecisionResponse<Variation> getVariation(@Nonnull Experiment experiment, variation = decisionVariation.getResult(); if (variation != null) { - if (userProfileService != null && !ignoreUPS) { - saveVariation(experiment, variation, userProfile); + if (userProfileTracker != null) { + userProfileTracker.updateUserProfile(experiment, variation); } else { logger.debug("This decision will not be saved since the UserProfileService is null."); } @@ -177,6 +157,39 @@ public DecisionResponse<Variation> getVariation(@Nonnull Experiment experiment, return new DecisionResponse(null, reasons); } + /** + * Get a {@link Variation} of an {@link Experiment} for a user to be allocated into. + * + * @param experiment The Experiment the user will be bucketed into. + * @param user The current OptimizelyUserContext + * @param projectConfig The current projectConfig + * @param options An array of decision options + * @return A {@link DecisionResponse} including the {@link Variation} that user is bucketed into (or null) and the decision reasons + */ + @Nonnull + public DecisionResponse<Variation> getVariation(@Nonnull Experiment experiment, + @Nonnull OptimizelyUserContext user, + @Nonnull ProjectConfig projectConfig, + @Nonnull List<OptimizelyDecideOption> options) { + DecisionReasons reasons = DefaultDecisionReasons.newInstance(); + + // fetch the user profile map from the user profile service + boolean ignoreUPS = options.contains(OptimizelyDecideOption.IGNORE_USER_PROFILE_SERVICE); + UserProfileTracker userProfileTracker = null; + + if (userProfileService != null && !ignoreUPS) { + userProfileTracker = new UserProfileTracker(user.getUserId(), userProfileService, logger); + userProfileTracker.loadUserProfile(reasons, errorHandler); + } + + DecisionResponse<Variation> response = getVariation(experiment, user, projectConfig, options, userProfileTracker, reasons); + + if(userProfileService != null && !ignoreUPS) { + userProfileTracker.saveUserProfile(errorHandler); + } + return response; + } + @Nonnull public DecisionResponse<Variation> getVariation(@Nonnull Experiment experiment, @Nonnull OptimizelyUserContext user, @@ -198,31 +211,70 @@ public DecisionResponse<FeatureDecision> getVariationForFeature(@Nonnull Feature @Nonnull OptimizelyUserContext user, @Nonnull ProjectConfig projectConfig, @Nonnull List<OptimizelyDecideOption> options) { - DecisionReasons reasons = DefaultDecisionReasons.newInstance(); + return getVariationsForFeatureList(Arrays.asList(featureFlag), user, projectConfig, options).get(0); + } + + /** + * Get the variations the user is bucketed into for the list of feature flags + * + * @param featureFlags The feature flag list the user wants to access. + * @param user The current OptimizelyuserContext + * @param projectConfig The current projectConfig + * @param options An array of decision options + * @return A {@link DecisionResponse} including a {@link FeatureDecision} and the decision reasons + */ + @Nonnull + public List<DecisionResponse<FeatureDecision>> getVariationsForFeatureList(@Nonnull List<FeatureFlag> featureFlags, + @Nonnull OptimizelyUserContext user, + @Nonnull ProjectConfig projectConfig, + @Nonnull List<OptimizelyDecideOption> options) { + DecisionReasons upsReasons = DefaultDecisionReasons.newInstance(); - DecisionResponse<FeatureDecision> decisionVariationResponse = getVariationFromExperiment(projectConfig, featureFlag, user, options); - reasons.merge(decisionVariationResponse.getReasons()); + boolean ignoreUPS = options.contains(OptimizelyDecideOption.IGNORE_USER_PROFILE_SERVICE); + UserProfileTracker userProfileTracker = null; - FeatureDecision decision = decisionVariationResponse.getResult(); - if (decision != null) { - return new DecisionResponse(decision, reasons); + if (userProfileService != null && !ignoreUPS) { + userProfileTracker = new UserProfileTracker(user.getUserId(), userProfileService, logger); + userProfileTracker.loadUserProfile(upsReasons, errorHandler); } - DecisionResponse<FeatureDecision> decisionFeatureResponse = getVariationForFeatureInRollout(featureFlag, user, projectConfig); - reasons.merge(decisionFeatureResponse.getReasons()); - decision = decisionFeatureResponse.getResult(); + List<DecisionResponse<FeatureDecision>> decisions = new ArrayList<>(); - String message; - if (decision.variation == null) { - message = reasons.addInfo("The user \"%s\" was not bucketed into a rollout for feature flag \"%s\".", - user.getUserId(), featureFlag.getKey()); - } else { - message = reasons.addInfo("The user \"%s\" was bucketed into a rollout for feature flag \"%s\".", - user.getUserId(), featureFlag.getKey()); + for (FeatureFlag featureFlag: featureFlags) { + DecisionReasons reasons = DefaultDecisionReasons.newInstance(); + reasons.merge(upsReasons); + + DecisionResponse<FeatureDecision> decisionVariationResponse = getVariationFromExperiment(projectConfig, featureFlag, user, options, userProfileTracker); + reasons.merge(decisionVariationResponse.getReasons()); + + FeatureDecision decision = decisionVariationResponse.getResult(); + if (decision != null) { + decisions.add(new DecisionResponse(decision, reasons)); + continue; + } + + DecisionResponse<FeatureDecision> decisionFeatureResponse = getVariationForFeatureInRollout(featureFlag, user, projectConfig); + reasons.merge(decisionFeatureResponse.getReasons()); + decision = decisionFeatureResponse.getResult(); + + String message; + if (decision.variation == null) { + message = reasons.addInfo("The user \"%s\" was not bucketed into a rollout for feature flag \"%s\".", + user.getUserId(), featureFlag.getKey()); + } else { + message = reasons.addInfo("The user \"%s\" was bucketed into a rollout for feature flag \"%s\".", + user.getUserId(), featureFlag.getKey()); + } + logger.info(message); + + decisions.add(new DecisionResponse(decision, reasons)); } - logger.info(message); - return new DecisionResponse(decision, reasons); + if (userProfileService != null && !ignoreUPS) { + userProfileTracker.saveUserProfile(errorHandler); + } + + return decisions; } @Nonnull @@ -244,13 +296,15 @@ public DecisionResponse<FeatureDecision> getVariationForFeature(@Nonnull Feature DecisionResponse<FeatureDecision> getVariationFromExperiment(@Nonnull ProjectConfig projectConfig, @Nonnull FeatureFlag featureFlag, @Nonnull OptimizelyUserContext user, - @Nonnull List<OptimizelyDecideOption> options) { + @Nonnull List<OptimizelyDecideOption> options, + @Nullable UserProfileTracker userProfileTracker) { DecisionReasons reasons = DefaultDecisionReasons.newInstance(); if (!featureFlag.getExperimentIds().isEmpty()) { for (String experimentId : featureFlag.getExperimentIds()) { Experiment experiment = projectConfig.getExperimentIdMapping().get(experimentId); - DecisionResponse<Variation> decisionVariation = getVariationFromExperimentRule(projectConfig, featureFlag.getKey(), experiment, user, options); + DecisionResponse<Variation> decisionVariation = + getVariationFromExperimentRule(projectConfig, featureFlag.getKey(), experiment, user, options, userProfileTracker); reasons.merge(decisionVariation.getReasons()); Variation variation = decisionVariation.getResult(); @@ -365,6 +419,9 @@ DecisionResponse<Variation> getWhitelistedVariation(@Nonnull Experiment experime return new DecisionResponse(null, reasons); } + + // TODO: Logically, it makes sense to move this method to UserProfileTracker. But some tests are also calling this + // method, requiring us to refactor those tests as well. We'll look to refactor this later. /** * Get the {@link Variation} that has been stored for the user in the {@link UserProfileService} implementation. * @@ -615,11 +672,12 @@ public DecisionResponse<Variation> getForcedVariation(@Nonnull Experiment experi } - public DecisionResponse<Variation> getVariationFromExperimentRule(@Nonnull ProjectConfig projectConfig, + private DecisionResponse<Variation> getVariationFromExperimentRule(@Nonnull ProjectConfig projectConfig, @Nonnull String flagKey, @Nonnull Experiment rule, @Nonnull OptimizelyUserContext user, - @Nonnull List<OptimizelyDecideOption> options) { + @Nonnull List<OptimizelyDecideOption> options, + @Nullable UserProfileTracker userProfileTracker) { DecisionReasons reasons = DefaultDecisionReasons.newInstance(); String ruleKey = rule != null ? rule.getKey() : null; @@ -634,7 +692,7 @@ public DecisionResponse<Variation> getVariationFromExperimentRule(@Nonnull Proje return new DecisionResponse(variation, reasons); } //regular decision - DecisionResponse<Variation> decisionResponse = getVariation(rule, user, projectConfig, options); + DecisionResponse<Variation> decisionResponse = getVariation(rule, user, projectConfig, options, userProfileTracker, null); reasons.merge(decisionResponse.getReasons()); variation = decisionResponse.getResult(); diff --git a/core-api/src/main/java/com/optimizely/ab/bucketing/UserProfileTracker.java b/core-api/src/main/java/com/optimizely/ab/bucketing/UserProfileTracker.java new file mode 100644 index 000000000..2dee3d171 --- /dev/null +++ b/core-api/src/main/java/com/optimizely/ab/bucketing/UserProfileTracker.java @@ -0,0 +1,109 @@ +/**************************************************************************** + * Copyright 2024, Optimizely, Inc. and contributors * + * * + * Licensed under the Apache License, Version 2.0 (the "License"); * + * you may not use this file except in compliance with the License. * + * You may obtain a copy of the License at * + * * + * http://www.apache.org/licenses/LICENSE-2.0 * + * * + * Unless required by applicable law or agreed to in writing, software * + * distributed under the License is distributed on an "AS IS" BASIS, * + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * + * See the License for the specific language governing permissions and * + * limitations under the License. * + ***************************************************************************/ +package com.optimizely.ab.bucketing; + +import com.optimizely.ab.OptimizelyRuntimeException; +import com.optimizely.ab.config.Experiment; +import com.optimizely.ab.config.Variation; +import com.optimizely.ab.error.ErrorHandler; +import com.optimizely.ab.optimizelydecision.DecisionReasons; + +import javax.annotation.Nonnull; +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; + +class UserProfileTracker { + private UserProfileService userProfileService; + private Logger logger; + private UserProfile userProfile; + private boolean profileUpdated; + private String userId; + + UserProfileTracker( + @Nonnull String userId, + @Nonnull UserProfileService userProfileService, + @Nonnull Logger logger + ) { + this.userId = userId; + this.userProfileService = userProfileService; + this.logger = logger; + this.profileUpdated = false; + this.userProfile = null; + } + + public UserProfile getUserProfile() { + return userProfile; + } + + public void loadUserProfile(DecisionReasons reasons, ErrorHandler errorHandler) { + try { + Map<String, Object> userProfileMap = userProfileService.lookup(userId); + if (userProfileMap == null) { + String message = reasons.addInfo("We were unable to get a user profile map from the UserProfileService."); + logger.info(message); + } else if (UserProfileUtils.isValidUserProfileMap(userProfileMap)) { + userProfile = UserProfileUtils.convertMapToUserProfile(userProfileMap); + } else { + String message = reasons.addInfo("The UserProfileService returned an invalid map."); + logger.warn(message); + } + } catch (Exception exception) { + String message = reasons.addInfo(exception.getMessage()); + logger.error(message); + errorHandler.handleError(new OptimizelyRuntimeException(exception)); + } + + if (userProfile == null) { + userProfile = new UserProfile(userId, new HashMap<String, Decision>()); + } + } + + public void updateUserProfile(@Nonnull Experiment experiment, + @Nonnull Variation variation) { + String experimentId = experiment.getId(); + String variationId = variation.getId(); + Decision decision; + if (userProfile.experimentBucketMap.containsKey(experimentId)) { + decision = userProfile.experimentBucketMap.get(experimentId); + decision.variationId = variationId; + } else { + decision = new Decision(variationId); + } + userProfile.experimentBucketMap.put(experimentId, decision); + profileUpdated = true; + logger.info("Updated variation \"{}\" of experiment \"{}\" for user \"{}\".", + variationId, experimentId, userProfile.userId); + } + + public void saveUserProfile(ErrorHandler errorHandler) { + // if there were no updates, no need to save + if (!this.profileUpdated) { + return; + } + + try { + userProfileService.save(userProfile.toMap()); + logger.info("Saved user profile of user \"{}\".", + userProfile.userId); + } catch (Exception exception) { + logger.warn("Failed to save user profile of user \"{}\".", + userProfile.userId); + errorHandler.handleError(new OptimizelyRuntimeException(exception)); + } + } +} \ No newline at end of file diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java index 0c07ef56a..34cf61543 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java @@ -1,6 +1,6 @@ /** * - * Copyright 2021-2023, Optimizely and contributors + * Copyright 2021-2024, Optimizely and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,15 @@ import com.google.common.base.Charsets; import com.google.common.io.Resources; import com.optimizely.ab.bucketing.FeatureDecision; +import com.optimizely.ab.bucketing.UserProfile; import com.optimizely.ab.bucketing.UserProfileService; +import com.optimizely.ab.bucketing.UserProfileUtils; import com.optimizely.ab.config.*; import com.optimizely.ab.config.parser.ConfigParseException; +import com.optimizely.ab.event.EventHandler; +import com.optimizely.ab.event.EventProcessor; import com.optimizely.ab.event.ForwardingEventProcessor; +import com.optimizely.ab.event.internal.ImpressionEvent; import com.optimizely.ab.event.internal.payload.DecisionMetadata; import com.optimizely.ab.internal.LogbackVerifier; import com.optimizely.ab.notification.NotificationCenter; @@ -37,7 +42,10 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.CountDownLatch; @@ -345,9 +353,11 @@ public void decideAll_twoFlags() { @Test public void decideAll_allFlags() { + EventProcessor mockEventProcessor = mock(EventProcessor.class); + optimizely = new Optimizely.Builder() .withDatafile(datafile) - .withEventProcessor(new ForwardingEventProcessor(eventHandler, null)) + .withEventProcessor(mockEventProcessor) .build(); String flagKey1 = "feature_1"; @@ -361,8 +371,7 @@ public void decideAll_allFlags() { OptimizelyUserContext user = optimizely.createUserContext(userId, attributes); Map<String, OptimizelyDecision> decisions = user.decideAll(); - - assertTrue(decisions.size() == 3); + assertEquals(decisions.size(), 3); assertEquals( decisions.get(flagKey1), @@ -395,9 +404,84 @@ public void decideAll_allFlags() { user, Collections.emptyList())); - eventHandler.expectImpression("10390977673", "10389729780", userId, attributes); - eventHandler.expectImpression("10420810910", "10418551353", userId, attributes); - eventHandler.expectImpression(null, "", userId, attributes); + ArgumentCaptor<ImpressionEvent> argumentCaptor = ArgumentCaptor.forClass(ImpressionEvent.class); + verify(mockEventProcessor, times(3)).process(argumentCaptor.capture()); + + List<ImpressionEvent> sentEvents = argumentCaptor.getAllValues(); + assertEquals(sentEvents.size(), 3); + + assertEquals(sentEvents.get(0).getExperimentKey(), "exp_with_audience"); + assertEquals(sentEvents.get(0).getVariationKey(), "a"); + assertEquals(sentEvents.get(0).getUserContext().getUserId(), userId); + + + assertEquals(sentEvents.get(1).getExperimentKey(), "exp_no_audience"); + assertEquals(sentEvents.get(1).getVariationKey(), "variation_with_traffic"); + assertEquals(sentEvents.get(1).getUserContext().getUserId(), userId); + + assertEquals(sentEvents.get(2).getExperimentKey(), ""); + assertEquals(sentEvents.get(2).getUserContext().getUserId(), userId); + } + + @Test + public void decideForKeys_ups_batching() throws Exception { + UserProfileService ups = mock(UserProfileService.class); + + optimizely = new Optimizely.Builder() + .withDatafile(datafile) + .withUserProfileService(ups) + .build(); + + String flagKey1 = "feature_1"; + String flagKey2 = "feature_2"; + String flagKey3 = "feature_3"; + Map<String, Object> attributes = Collections.singletonMap("gender", "f"); + + OptimizelyUserContext user = optimizely.createUserContext(userId, attributes); + Map<String, OptimizelyDecision> decisions = user.decideForKeys(Arrays.asList( + flagKey1, flagKey2, flagKey3 + )); + + assertEquals(decisions.size(), 3); + + ArgumentCaptor<Map> argumentCaptor = ArgumentCaptor.forClass(Map.class); + + + verify(ups, times(1)).lookup(userId); + verify(ups, times(1)).save(argumentCaptor.capture()); + + Map<String, Object> savedUps = argumentCaptor.getValue(); + UserProfile savedProfile = UserProfileUtils.convertMapToUserProfile(savedUps); + + assertEquals(savedProfile.userId, userId); + } + + @Test + public void decideAll_ups_batching() throws Exception { + UserProfileService ups = mock(UserProfileService.class); + + optimizely = new Optimizely.Builder() + .withDatafile(datafile) + .withUserProfileService(ups) + .build(); + + Map<String, Object> attributes = Collections.singletonMap("gender", "f"); + + OptimizelyUserContext user = optimizely.createUserContext(userId, attributes); + Map<String, OptimizelyDecision> decisions = user.decideAll(); + + assertEquals(decisions.size(), 3); + + ArgumentCaptor<Map> argumentCaptor = ArgumentCaptor.forClass(Map.class); + + + verify(ups, times(1)).lookup(userId); + verify(ups, times(1)).save(argumentCaptor.capture()); + + Map<String, Object> savedUps = argumentCaptor.getValue(); + UserProfile savedProfile = UserProfileUtils.convertMapToUserProfile(savedUps); + + assertEquals(savedProfile.userId, userId); } @Test diff --git a/core-api/src/test/java/com/optimizely/ab/bucketing/DecisionServiceTest.java b/core-api/src/test/java/com/optimizely/ab/bucketing/DecisionServiceTest.java index 6057b43cf..d818826d4 100644 --- a/core-api/src/test/java/com/optimizely/ab/bucketing/DecisionServiceTest.java +++ b/core-api/src/test/java/com/optimizely/ab/bucketing/DecisionServiceTest.java @@ -1,5 +1,5 @@ /**************************************************************************** - * Copyright 2017-2022, Optimizely, Inc. and contributors * + * Copyright 2017-2022, 2024, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * @@ -24,6 +24,7 @@ import com.optimizely.ab.error.ErrorHandler; import com.optimizely.ab.internal.ControlAttribute; import com.optimizely.ab.internal.LogbackVerifier; +import com.optimizely.ab.optimizelydecision.DecisionReasons; import com.optimizely.ab.optimizelydecision.DecisionResponse; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.junit.Before; @@ -297,7 +298,9 @@ public void getVariationForFeatureReturnsNullWhenItGetsNoVariationsForExperiment any(Experiment.class), any(OptimizelyUserContext.class), any(ProjectConfig.class), - anyObject() + anyObject(), + anyObject(), + any(DecisionReasons.class) ); // do not bucket to any rollouts doReturn(DecisionResponse.responseNoReasons(new FeatureDecision(null, null, null))).when(decisionService).getVariationForFeatureInRollout( @@ -381,7 +384,9 @@ public void getVariationForFeatureReturnsVariationFromExperimentBeforeRollout() eq(featureExperiment), any(OptimizelyUserContext.class), any(ProjectConfig.class), - anyObject() + anyObject(), + anyObject(), + any(DecisionReasons.class) ); // return variation for rollout @@ -413,7 +418,9 @@ public void getVariationForFeatureReturnsVariationFromExperimentBeforeRollout() any(Experiment.class), any(OptimizelyUserContext.class), any(ProjectConfig.class), - anyObject() + anyObject(), + anyObject(), + any(DecisionReasons.class) ); } @@ -438,7 +445,9 @@ public void getVariationForFeatureReturnsVariationFromRolloutWhenExperimentFails eq(featureExperiment), any(OptimizelyUserContext.class), any(ProjectConfig.class), - anyObject() + anyObject(), + anyObject(), + any(DecisionReasons.class) ); // return variation for rollout @@ -470,7 +479,9 @@ public void getVariationForFeatureReturnsVariationFromRolloutWhenExperimentFails any(Experiment.class), any(OptimizelyUserContext.class), any(ProjectConfig.class), - anyObject() + anyObject(), + anyObject(), + any(DecisionReasons.class) ); logbackVerifier.expectMessage( @@ -480,6 +491,33 @@ public void getVariationForFeatureReturnsVariationFromRolloutWhenExperimentFails ); } + //========== getVariationForFeatureList tests ==========// + + @Test + public void getVariationsForFeatureListBatchesUpsLoadAndSave() throws Exception { + Bucketer bucketer = new Bucketer(); + ErrorHandler mockErrorHandler = mock(ErrorHandler.class); + UserProfileService mockUserProfileService = mock(UserProfileService.class); + + DecisionService decisionService = new DecisionService(bucketer, mockErrorHandler, mockUserProfileService); + + FeatureFlag featureFlag1 = FEATURE_FLAG_MULTI_VARIATE_FEATURE; + FeatureFlag featureFlag2 = FEATURE_FLAG_MULTI_VARIATE_FUTURE_FEATURE; + FeatureFlag featureFlag3 = FEATURE_FLAG_MUTEX_GROUP_FEATURE; + + List<DecisionResponse<FeatureDecision>> decisions = decisionService.getVariationsForFeatureList( + Arrays.asList(featureFlag1, featureFlag2, featureFlag3), + optimizely.createUserContext(genericUserId), + v4ProjectConfig, + new ArrayList<>() + ); + + assertEquals(decisions.size(), 3); + verify(mockUserProfileService, times(1)).lookup(genericUserId); + verify(mockUserProfileService, times(1)).save(anyObject()); + } + + //========== getVariationForFeatureInRollout tests ==========// /** @@ -743,27 +781,6 @@ public void getVariationFromDeliveryRuleTest() { assertFalse(skipToEveryoneElse); } - @Test - public void getVariationFromExperimentRuleTest() { - int index = 3; - Experiment experiment = ROLLOUT_2.getExperiments().get(index); - Variation expectedVariation = null; - for (Variation variation : experiment.getVariations()) { - if (variation.getKey().equals("3137445031")) { - expectedVariation = variation; - } - } - DecisionResponse<Variation> decisionResponse = decisionService.getVariationFromExperimentRule( - v4ProjectConfig, - FEATURE_FLAG_MULTI_VARIATE_FEATURE.getKey(), - experiment, - optimizely.createUserContext(genericUserId, Collections.singletonMap(ATTRIBUTE_NATIONALITY_KEY, AUDIENCE_ENGLISH_CITIZENS_VALUE)), - Collections.emptyList() - ); - - assertEquals(expectedVariation, decisionResponse.getResult()); - } - @Test public void validatedForcedDecisionWithRuleKey() { String userId = "testUser1"; @@ -961,9 +978,12 @@ public void getVariationSavesBucketedVariationIntoUserProfile() throws Exception experiment, optimizely.createUserContext(userProfileId, Collections.emptyMap()), noAudienceProjectConfig).getResult() ); logbackVerifier.expectMessage(Level.INFO, - String.format("Saved variation \"%s\" of experiment \"%s\" for user \"" + userProfileId + "\".", variation.getId(), + String.format("Updated variation \"%s\" of experiment \"%s\" for user \"" + userProfileId + "\".", variation.getId(), experiment.getId())); + logbackVerifier.expectMessage(Level.INFO, + String.format("Saved user profile of user \"%s\".", userProfileId)); + verify(userProfileService).save(eq(expectedUserProfile.toMap())); } From a763358be683909a4ae9112efc9a1ea3b69c5538 Mon Sep 17 00:00:00 2001 From: Raju Ahmed <raju.ahmed@optimizely.com> Date: Wed, 6 Nov 2024 19:51:14 +0600 Subject: [PATCH 67/80] [FSSDK-10839] prepare for release 4.2.0 (#551) --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d92e70fbe..104422c93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Optimizely Java X SDK Changelog +## [4.2.0] +November 6th, 2024 + +### New Features +* Batch UPS lookup and save calls in decideAll and decideForKeys methods ([#549](https://github.com/optimizely/java-sdk/pull/549)). + ## [4.1.1] May 8th, 2024 From 392d679971d88d889defebaa64edad5cdb4c96fa Mon Sep 17 00:00:00 2001 From: Muzahidul Islam <129880873+muzahidul-opti@users.noreply.github.com> Date: Thu, 2 Jan 2025 21:08:13 +0600 Subject: [PATCH 68/80] [FSSDK-11016] chore: update gradle from 6.5 to 7.2 (#553) Update gradle to 7.2 --- .github/workflows/java.yml | 2 +- build.gradle | 36 ++++++++++++++--------- core-api/build.gradle | 17 +++++++---- core-httpclient-impl/build.gradle | 9 +++--- gradle/wrapper/gradle-wrapper.jar | Bin 54333 -> 59536 bytes gradle/wrapper/gradle-wrapper.properties | 3 +- 6 files changed, 41 insertions(+), 26 deletions(-) diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml index 1c6c57a02..cec97cd7b 100644 --- a/.github/workflows/java.yml +++ b/.github/workflows/java.yml @@ -90,7 +90,7 @@ jobs: - name: Check on success if: always() && steps.unit_tests.outcome == 'success' run: | - ./gradlew coveralls uploadArchives --console plain + ./gradlew coveralls --console plain publish: if: startsWith(github.ref, 'refs/tags/') diff --git a/build.gradle b/build.gradle index b8405e39b..3301eda25 100644 --- a/build.gradle +++ b/build.gradle @@ -1,10 +1,11 @@ plugins { - id 'com.github.kt3k.coveralls' version '2.8.2' + id 'com.github.kt3k.coveralls' version '2.12.2' id 'jacoco' - id 'me.champeau.gradle.jmh' version '0.4.5' + id 'me.champeau.gradle.jmh' version '0.5.3' id 'nebula.optional-base' version '3.2.0' - id 'com.github.hierynomus.license' version '0.15.0' + id 'com.github.hierynomus.license' version '0.16.1' id 'com.github.spotbugs' version "4.5.0" + id 'maven-publish' } allprojects { @@ -94,23 +95,30 @@ configure(publishedProjects) { } dependencies { - compile group: 'commons-codec', name: 'commons-codec', version: commonCodecVersion + implementation group: 'commons-codec', name: 'commons-codec', version: commonCodecVersion - testCompile group: 'junit', name: 'junit', version: junitVersion - testCompile group: 'org.mockito', name: 'mockito-core', version: mockitoVersion - testCompile group: 'org.hamcrest', name: 'hamcrest-all', version: hamcrestVersion - testCompile group: 'com.google.guava', name: 'guava', version: guavaVersion + testImplementation group: 'junit', name: 'junit', version: junitVersion + testImplementation group: 'org.mockito', name: 'mockito-core', version: mockitoVersion + testImplementation group: 'org.hamcrest', name: 'hamcrest-all', version: hamcrestVersion + testImplementation group: 'com.google.guava', name: 'guava', version: guavaVersion // logging dependencies (logback) - testCompile group: 'ch.qos.logback', name: 'logback-classic', version: logbackVersion - testCompile group: 'ch.qos.logback', name: 'logback-core', version: logbackVersion + testImplementation group: 'ch.qos.logback', name: 'logback-classic', version: logbackVersion + testImplementation group: 'ch.qos.logback', name: 'logback-core', version: logbackVersion - testCompile group: 'com.google.code.gson', name: 'gson', version: gsonVersion - testCompile group: 'org.json', name: 'json', version: jsonVersion - testCompile group: 'com.googlecode.json-simple', name: 'json-simple', version: jsonSimpleVersion - testCompile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: jacksonVersion + testImplementation group: 'com.google.code.gson', name: 'gson', version: gsonVersion + testImplementation group: 'org.json', name: 'json', version: jsonVersion + testImplementation group: 'com.googlecode.json-simple', name: 'json-simple', version: jsonSimpleVersion + testImplementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: jacksonVersion } + configurations.all { + resolutionStrategy { + force "junit:junit:${junitVersion}" + } + } + + def docTitle = "Optimizely Java SDK" if (name.equals('core-httpclient-impl')) { docTitle = "Optimizely Java SDK: Httpclient" diff --git a/core-api/build.gradle b/core-api/build.gradle index d2609a97d..602131cd3 100644 --- a/core-api/build.gradle +++ b/core-api/build.gradle @@ -1,9 +1,10 @@ dependencies { - compile group: 'org.slf4j', name: 'slf4j-api', version: slf4jVersion - compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: jacksonVersion - - compile group: 'com.google.code.findbugs', name: 'annotations', version: findbugsAnnotationVersion - compile group: 'com.google.code.findbugs', name: 'jsr305', version: findbugsJsrVersion + implementation group: 'org.slf4j', name: 'slf4j-api', version: slf4jVersion + implementation group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: jacksonVersion + implementation group: 'com.google.code.findbugs', name: 'annotations', version: findbugsAnnotationVersion + implementation group: 'com.google.code.findbugs', name: 'jsr305', version: findbugsJsrVersion + testImplementation group: 'junit', name: 'junit', version: junitVersion + testImplementation group: 'ch.qos.logback', name: 'logback-classic', version: logbackVersion // an assortment of json parsers compileOnly group: 'com.google.code.gson', name: 'gson', version: gsonVersion, optional @@ -12,6 +13,11 @@ dependencies { compileOnly group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: jacksonVersion, optional } +tasks.named('processJmhResources') { + duplicatesStrategy = DuplicatesStrategy.WARN +} + + test { useJUnit { excludeCategories 'com.optimizely.ab.categories.ExhaustiveTest' @@ -24,6 +30,7 @@ task exhaustiveTest(type: Test) { } } + task generateVersionFile { // add the build version information into a file that'll go into the distribution ext.buildVersion = new File(projectDir, "src/main/resources/optimizely-build-version") diff --git a/core-httpclient-impl/build.gradle b/core-httpclient-impl/build.gradle index e4cdd4b99..4affcda17 100644 --- a/core-httpclient-impl/build.gradle +++ b/core-httpclient-impl/build.gradle @@ -1,8 +1,9 @@ dependencies { - compile project(':core-api') - compileOnly group: 'com.google.code.gson', name: 'gson', version: gsonVersion - compile group: 'org.apache.httpcomponents', name: 'httpclient', version: httpClientVersion - testCompile 'org.mock-server:mockserver-netty:5.1.1' + implementation project(':core-api') + implementation group: 'org.apache.httpcomponents', name: 'httpclient', version: httpClientVersion + implementation group: 'org.slf4j', name: 'slf4j-api', version: slf4jVersion + implementation group: 'com.google.code.findbugs', name: 'jsr305', version: findbugsJsrVersion + testImplementation 'org.mock-server:mockserver-netty:5.1.1' } task exhaustiveTest { diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index c44b679acd3f794ddbb3aa5e919244914911014a..7454180f2ae8848c63b8b4dea2cb829da983f2fa 100644 GIT binary patch literal 59536 zcma&NbC71ylI~qywr$(CZQJHswz}-9F59+k+g;UV+cs{`J?GrGXYR~=-ydruB3JCa zB64N^cILAcWk5iofq)<(fq;O7{th4@;QxID0)qN`mJ?GIqLY#rX8-|G{5M0pdVW5^ zzXk$-2kQTAC?_N@B`&6-N-rmVFE=$QD?>*=4<|!MJu@}isLc4AW#{m2if&A5T5g&~ ziuMQeS*U5sL6J698wOd)K@oK@1{peP5&Esut<#VH^u)gp`9H4)`uE!2$>RTctN+^u z=ASkePDZA-X8)rp%D<bsI~h4Rm^uAFQ<BLROWJ<`0bzjv0Wtj7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)9dnFtN>vD%?BeZ0SZ_L{S5e{2hstYLKp!2EfCQE E17(ftEC2ui diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index a9a50f830..ffed3a254 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Mon Sep 24 09:56:45 PDT 2018 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip From be78ee93f38de2b1371efe9efcb97b110a216168 Mon Sep 17 00:00:00 2001 From: alexjoeyyong <96444887+alexjoeyyong@users.noreply.github.com> Date: Wed, 22 Jan 2025 12:05:42 -0500 Subject: [PATCH 69/80] EC3-1687 workflow versions (#557) --- .github/workflows/java.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml index cec97cd7b..d13131ffd 100644 --- a/.github/workflows/java.yml +++ b/.github/workflows/java.yml @@ -17,7 +17,7 @@ jobs: lint_markdown_files: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: @@ -55,7 +55,7 @@ jobs: optimizely_default_parser: [GSON_CONFIG_PARSER, JACKSON_CONFIG_PARSER, JSON_CONFIG_PARSER, JSON_SIMPLE_CONFIG_PARSER] steps: - name: checkout - uses: actions/checkout@v2 + uses: actions/checkout@v4 - name: set up JDK ${{ matrix.jdk }} uses: AdoptOpenJDK/install-jdk@v1 @@ -67,7 +67,7 @@ jobs: run: chmod +x gradlew - name: Gradle cache - uses: actions/cache@v2 + uses: actions/cache@v4 with: path: | ~/.gradle/caches From 02aa4bb6ce837369a7d4d0d97d67528566fab5e3 Mon Sep 17 00:00:00 2001 From: Muzahidul Islam <129880873+muzahidul-opti@users.noreply.github.com> Date: Thu, 13 Feb 2025 23:41:25 +0600 Subject: [PATCH 70/80] [FSSDK-11075] chore: remove travis from doc (#558) * Remove travis udpate status from readme * remove travis token * update yml * Update branch --- .github/workflows/build.yml | 5 +---- .github/workflows/integration_test.yml | 13 +++---------- .github/workflows/java.yml | 4 +--- README.md | 1 - 4 files changed, 5 insertions(+), 18 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e7ba7782e..618bf5d61 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -6,9 +6,6 @@ on: action: required: true type: string - travis_tag: - required: true - type: string secrets: MAVEN_SIGNING_KEY_BASE64: required: true @@ -37,4 +34,4 @@ jobs: MAVEN_SIGNING_PASSPHRASE: ${{ secrets.MAVEN_SIGNING_PASSPHRASE }} MAVEN_CENTRAL_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }} MAVEN_CENTRAL_PASSWORD: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} - run: TRAVIS_TAG=${{ inputs.travis_tag }} ./gradlew ${{ inputs.action }} + run: ./gradlew ${{ inputs.action }} diff --git a/.github/workflows/integration_test.yml b/.github/workflows/integration_test.yml index c54149edd..35fb78590 100644 --- a/.github/workflows/integration_test.yml +++ b/.github/workflows/integration_test.yml @@ -9,8 +9,6 @@ on: secrets: CI_USER_TOKEN: required: true - TRAVIS_COM_TOKEN: - required: true jobs: test: runs-on: ubuntu-latest @@ -19,8 +17,8 @@ jobs: with: # You should create a personal access token and store it in your repository token: ${{ secrets.CI_USER_TOKEN }} - repository: 'optimizely/travisci-tools' - path: 'home/runner/travisci-tools' + repository: 'optimizely/ci-helper-tools' + path: 'home/runner/ci-helper-tools' ref: 'master' - name: set SDK Branch if PR env: @@ -28,14 +26,12 @@ jobs: if: ${{ github.event_name == 'pull_request' }} run: | echo "SDK_BRANCH=$HEAD_REF" >> $GITHUB_ENV - echo "TRAVIS_BRANCH=$HEAD_REF" >> $GITHUB_ENV - name: set SDK Branch if not pull request env: REF_NAME: ${{ github.ref_name }} if: ${{ github.event_name != 'pull_request' }} run: | echo "SDK_BRANCH=$REF_NAME" >> $GITHUB_ENV - echo "TRAVIS_BRANCH=$REF_NAME" >> $GITHUB_ENV - name: Trigger build env: SDK: java @@ -45,16 +41,13 @@ jobs: GITHUB_TOKEN: ${{ secrets.CI_USER_TOKEN }} EVENT_TYPE: ${{ github.event_name }} GITHUB_CONTEXT: ${{ toJson(github) }} - #REPO_SLUG: ${{ github.repository }} PULL_REQUEST_SLUG: ${{ github.repository }} UPSTREAM_REPO: ${{ github.repository }} PULL_REQUEST_SHA: ${{ github.event.pull_request.head.sha }} PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number }} UPSTREAM_SHA: ${{ github.sha }} - TOKEN: ${{ secrets.TRAVIS_COM_TOKEN }} - TRAVIS_COM_TOKEN: ${{ secrets.TRAVIS_COM_TOKEN }} EVENT_MESSAGE: ${{ github.event.message }} HOME: 'home/runner' run: | echo "$GITHUB_CONTEXT" - home/runner/travisci-tools/trigger-script-with-status-update.sh + home/runner/ci-helper-tools/trigger-script-with-status-update.sh diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml index d13131ffd..311686c26 100644 --- a/.github/workflows/java.yml +++ b/.github/workflows/java.yml @@ -31,10 +31,9 @@ jobs: integration_tests: if: ${{ startsWith(github.ref, 'refs/tags/') != true && github.event.inputs.SNAPSHOT != 'true' }} - uses: optimizely/java-sdk/.github/workflows/integration_test.yml@mnoman/fsc-gitaction-test + uses: optimizely/java-sdk/.github/workflows/integration_test.yml@master secrets: CI_USER_TOKEN: ${{ secrets.CI_USER_TOKEN }} - TRAVIS_COM_TOKEN: ${{ secrets.TRAVIS_COM_TOKEN }} fullstack_production_suite: if: ${{ startsWith(github.ref, 'refs/tags/') != true && github.event.inputs.SNAPSHOT != 'true' }} @@ -43,7 +42,6 @@ jobs: FULLSTACK_TEST_REPO: ProdTesting secrets: CI_USER_TOKEN: ${{ secrets.CI_USER_TOKEN }} - TRAVIS_COM_TOKEN: ${{ secrets.TRAVIS_COM_TOKEN }} test: if: ${{ startsWith(github.ref, 'refs/tags/') != true && github.event.inputs.SNAPSHOT != 'true' }} diff --git a/README.md b/README.md index 33e55928d..1f97786a1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,5 @@ # Optimizely Java SDK -[![Build Status](https://travis-ci.org/optimizely/java-sdk.svg?branch=master)](https://travis-ci.org/optimizely/java-sdk) [![Apache 2.0](https://img.shields.io/badge/license-APACHE%202.0-blue.svg)](http://www.apache.org/licenses/LICENSE-2.0) This repository houses the Java SDK for use with Optimizely Feature Experimentation and Optimizely Full Stack (legacy). From 8bc0136eeff5daa08a9a22531ed5edb09f32d70c Mon Sep 17 00:00:00 2001 From: Muzahidul Islam <129880873+muzahidul-opti@users.noreply.github.com> Date: Mon, 17 Feb 2025 23:19:02 +0600 Subject: [PATCH 71/80] [FSSDK-11075] chore: update github tag (#559) * update tag --- .github/workflows/build.yml | 3 +++ .github/workflows/java.yml | 4 ++-- README.md | 1 + 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 618bf5d61..e10de2d47 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -6,6 +6,9 @@ on: action: required: true type: string + github_tag: + required: true + type: string secrets: MAVEN_SIGNING_KEY_BASE64: required: true diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml index 311686c26..7ebc17304 100644 --- a/.github/workflows/java.yml +++ b/.github/workflows/java.yml @@ -95,7 +95,7 @@ jobs: uses: optimizely/java-sdk/.github/workflows/build.yml@master with: action: ship - travis_tag: ${GITHUB_REF#refs/*/} + github_tag: ${GITHUB_REF#refs/*/} secrets: MAVEN_SIGNING_KEY_BASE64: ${{ secrets.MAVEN_SIGNING_KEY_BASE64 }} MAVEN_SIGNING_PASSPHRASE: ${{ secrets.MAVEN_SIGNING_PASSPHRASE }} @@ -107,7 +107,7 @@ jobs: uses: optimizely/java-sdk/.github/workflows/build.yml@master with: action: ship - travis_tag: BB-SNAPSHOT + github_tag: BB-SNAPSHOT secrets: MAVEN_SIGNING_KEY_BASE64: ${{ secrets.MAVEN_SIGNING_KEY_BASE64 }} MAVEN_SIGNING_PASSPHRASE: ${{ secrets.MAVEN_SIGNING_PASSPHRASE }} diff --git a/README.md b/README.md index 1f97786a1..b4b1f0be1 100644 --- a/README.md +++ b/README.md @@ -175,3 +175,4 @@ License (Apache 2.0): [https://github.com/apache/httpcomponents-client/blob/mast - Ruby - https://github.com/optimizely/ruby-sdk - Swift - https://github.com/optimizely/swift-sdk + From ab02b4970418d4aec999df1d6f3b924fd3168df8 Mon Sep 17 00:00:00 2001 From: Muzahidul Islam <129880873+muzahidul-opti@users.noreply.github.com> Date: Wed, 19 Feb 2025 23:12:41 +0600 Subject: [PATCH 72/80] fix: long integer issue (#556) --- .../java/com/optimizely/ab/Optimizely.java | 170 ++++++++++---- .../com/optimizely/ab/OptimizelyTest.java | 221 +++++++++++------- .../ab/config/ValidProjectConfigV4.java | 13 ++ 3 files changed, 275 insertions(+), 129 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/Optimizely.java b/core-api/src/main/java/com/optimizely/ab/Optimizely.java index 0e260072e..4f942ff69 100644 --- a/core-api/src/main/java/com/optimizely/ab/Optimizely.java +++ b/core-api/src/main/java/com/optimizely/ab/Optimizely.java @@ -20,44 +20,80 @@ import com.optimizely.ab.bucketing.DecisionService; import com.optimizely.ab.bucketing.FeatureDecision; import com.optimizely.ab.bucketing.UserProfileService; -import com.optimizely.ab.config.*; +import com.optimizely.ab.config.AtomicProjectConfigManager; +import com.optimizely.ab.config.DatafileProjectConfig; +import com.optimizely.ab.config.EventType; +import com.optimizely.ab.config.Experiment; +import com.optimizely.ab.config.FeatureFlag; +import com.optimizely.ab.config.FeatureVariable; +import com.optimizely.ab.config.FeatureVariableUsageInstance; +import com.optimizely.ab.config.ProjectConfig; +import com.optimizely.ab.config.ProjectConfigManager; +import com.optimizely.ab.config.Variation; import com.optimizely.ab.config.parser.ConfigParseException; import com.optimizely.ab.error.ErrorHandler; import com.optimizely.ab.error.NoOpErrorHandler; -import com.optimizely.ab.event.*; -import com.optimizely.ab.event.internal.*; +import com.optimizely.ab.event.EventHandler; +import com.optimizely.ab.event.EventProcessor; +import com.optimizely.ab.event.ForwardingEventProcessor; +import com.optimizely.ab.event.LogEvent; +import com.optimizely.ab.event.NoopEventHandler; +import com.optimizely.ab.event.internal.BuildVersionInfo; +import com.optimizely.ab.event.internal.ClientEngineInfo; +import com.optimizely.ab.event.internal.EventFactory; +import com.optimizely.ab.event.internal.UserEvent; +import com.optimizely.ab.event.internal.UserEventFactory; import com.optimizely.ab.event.internal.payload.EventBatch; import com.optimizely.ab.internal.NotificationRegistry; -import com.optimizely.ab.notification.*; -import com.optimizely.ab.odp.*; +import com.optimizely.ab.notification.ActivateNotification; +import com.optimizely.ab.notification.DecisionNotification; +import com.optimizely.ab.notification.FeatureTestSourceInfo; +import com.optimizely.ab.notification.NotificationCenter; +import com.optimizely.ab.notification.NotificationHandler; +import com.optimizely.ab.notification.RolloutSourceInfo; +import com.optimizely.ab.notification.SourceInfo; +import com.optimizely.ab.notification.TrackNotification; +import com.optimizely.ab.notification.UpdateConfigNotification; +import com.optimizely.ab.odp.ODPEvent; +import com.optimizely.ab.odp.ODPManager; +import com.optimizely.ab.odp.ODPSegmentManager; +import com.optimizely.ab.odp.ODPSegmentOption; import com.optimizely.ab.optimizelyconfig.OptimizelyConfig; import com.optimizely.ab.optimizelyconfig.OptimizelyConfigManager; import com.optimizely.ab.optimizelyconfig.OptimizelyConfigService; -import com.optimizely.ab.optimizelydecision.*; +import com.optimizely.ab.optimizelydecision.DecisionMessage; +import com.optimizely.ab.optimizelydecision.DecisionReasons; +import com.optimizely.ab.optimizelydecision.DecisionResponse; +import com.optimizely.ab.optimizelydecision.DefaultDecisionReasons; +import com.optimizely.ab.optimizelydecision.OptimizelyDecideOption; +import com.optimizely.ab.optimizelydecision.OptimizelyDecision; import com.optimizely.ab.optimizelyjson.OptimizelyJSON; -import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; - import java.io.Closeable; -import java.util.*; -import java.util.stream.Collectors; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.locks.ReentrantLock; import static com.optimizely.ab.internal.SafetyUtils.tryClose; /** * Top-level container class for Optimizely functionality. * Thread-safe, so can be created as a singleton and safely passed around. - * + * <p> * Example instantiation: * <pre> * Optimizely optimizely = Optimizely.builder(projectWatcher, eventHandler).build(); * </pre> - * + * <p> * To activate an experiment and perform variation specific processing: * <pre> * Variation variation = optimizely.activate(experimentKey, userId, attributes); @@ -136,7 +172,9 @@ private Optimizely(@Nonnull EventHandler eventHandler, if (projectConfigManager.getSDKKey() != null) { NotificationRegistry.getInternalNotificationCenter(projectConfigManager.getSDKKey()). addNotificationHandler(UpdateConfigNotification.class, - configNotification -> { updateODPSettings(); }); + configNotification -> { + updateODPSettings(); + }); } } @@ -634,6 +672,53 @@ public Integer getFeatureVariableInteger(@Nonnull String featureKey, return variableValue; } + /** + * Get the Long value of the specified variable in the feature. + * + * @param featureKey The unique key of the feature. + * @param variableKey The unique key of the variable. + * @param userId The ID of the user. + * @return The Integer value of the integer single variable feature. + * Null if the feature or variable could not be found. + */ + @Nullable + public Long getFeatureVariableLong(@Nonnull String featureKey, + @Nonnull String variableKey, + @Nonnull String userId) { + return getFeatureVariableLong(featureKey, variableKey, userId, Collections.emptyMap()); + } + + /** + * Get the Integer value of the specified variable in the feature. + * + * @param featureKey The unique key of the feature. + * @param variableKey The unique key of the variable. + * @param userId The ID of the user. + * @param attributes The user's attributes. + * @return The Integer value of the integer single variable feature. + * Null if the feature or variable could not be found. + */ + @Nullable + public Long getFeatureVariableLong(@Nonnull String featureKey, + @Nonnull String variableKey, + @Nonnull String userId, + @Nonnull Map<String, ?> attributes) { + try { + return getFeatureVariableValueForType( + featureKey, + variableKey, + userId, + attributes, + FeatureVariable.INTEGER_TYPE + ); + + } catch (Exception exception) { + logger.error("NumberFormatException while trying to parse value as Long. {}", String.valueOf(exception)); + } + + return null; + } + /** * Get the String value of the specified variable in the feature. * @@ -828,8 +913,13 @@ Object convertStringToType(String variableValue, String type) { try { return Integer.parseInt(variableValue); } catch (NumberFormatException exception) { - logger.error("NumberFormatException while trying to parse \"" + variableValue + - "\" as Integer. " + exception.toString()); + try { + return Long.parseLong(variableValue); + } catch (NumberFormatException longException) { + logger.error("NumberFormatException while trying to parse \"{}\" as Integer. {}", + variableValue, + exception.toString()); + } } break; case FeatureVariable.JSON_TYPE: @@ -845,11 +935,10 @@ Object convertStringToType(String variableValue, String type) { /** * Get the values of all variables in the feature. * - * @param featureKey The unique key of the feature. - * @param userId The ID of the user. + * @param featureKey The unique key of the feature. + * @param userId The ID of the user. * @return An OptimizelyJSON instance for all variable values. * Null if the feature could not be found. - * */ @Nullable public OptimizelyJSON getAllFeatureVariables(@Nonnull String featureKey, @@ -860,12 +949,11 @@ public OptimizelyJSON getAllFeatureVariables(@Nonnull String featureKey, /** * Get the values of all variables in the feature. * - * @param featureKey The unique key of the feature. - * @param userId The ID of the user. - * @param attributes The user's attributes. + * @param featureKey The unique key of the feature. + * @param userId The ID of the user. + * @param attributes The user's attributes. * @return An OptimizelyJSON instance for all variable values. * Null if the feature could not be found. - * */ @Nullable public OptimizelyJSON getAllFeatureVariables(@Nonnull String featureKey, @@ -949,7 +1037,6 @@ public OptimizelyJSON getAllFeatureVariables(@Nonnull String featureKey, * @param attributes The user's attributes. * @return List of the feature keys that are enabled for the user if the userId is empty it will * return Empty List. - * */ public List<String> getEnabledFeatures(@Nonnull String userId, @Nonnull Map<String, ?> attributes) { List<String> enabledFeaturesList = new ArrayList(); @@ -1164,10 +1251,10 @@ public OptimizelyConfig getOptimizelyConfig() { /** * Create a context of the user for which decision APIs will be called. - * + * <p> * A user context will be created successfully even when the SDK is not fully configured yet. * - * @param userId The user ID to be used for bucketing. + * @param userId The user ID to be used for bucketing. * @param attributes: A map of attribute names to current user attribute values. * @return An OptimizelyUserContext associated with this OptimizelyClient. */ @@ -1289,15 +1376,15 @@ private OptimizelyDecision createOptimizelyDecision( } Map<String, OptimizelyDecision> decideForKeys(@Nonnull OptimizelyUserContext user, - @Nonnull List<String> keys, - @Nonnull List<OptimizelyDecideOption> options) { + @Nonnull List<String> keys, + @Nonnull List<OptimizelyDecideOption> options) { return decideForKeys(user, keys, options, false); } private Map<String, OptimizelyDecision> decideForKeys(@Nonnull OptimizelyUserContext user, - @Nonnull List<String> keys, - @Nonnull List<OptimizelyDecideOption> options, - boolean ignoreDefaultOptions) { + @Nonnull List<String> keys, + @Nonnull List<OptimizelyDecideOption> options, + boolean ignoreDefaultOptions) { Map<String, OptimizelyDecision> decisionMap = new HashMap<>(); ProjectConfig projectConfig = getProjectConfig(); @@ -1308,7 +1395,7 @@ private Map<String, OptimizelyDecision> decideForKeys(@Nonnull OptimizelyUserCon if (keys.isEmpty()) return decisionMap; - List<OptimizelyDecideOption> allOptions = ignoreDefaultOptions ? options: getAllOptions(options); + List<OptimizelyDecideOption> allOptions = ignoreDefaultOptions ? options : getAllOptions(options); Map<String, FeatureDecision> flagDecisions = new HashMap<>(); Map<String, DecisionReasons> decisionReasonsMap = new HashMap<>(); @@ -1351,7 +1438,7 @@ private Map<String, OptimizelyDecision> decideForKeys(@Nonnull OptimizelyUserCon decisionReasonsMap.get(flagKey).merge(decision.getReasons()); } - for (String key: validKeys) { + for (String key : validKeys) { FeatureDecision flagDecision = flagDecisions.get(key); DecisionReasons decisionReasons = decisionReasonsMap.get((key)); @@ -1484,9 +1571,9 @@ public int addLogEventNotificationHandler(NotificationHandler<LogEvent> handler) /** * Convenience method for adding NotificationHandlers * - * @param clazz The class of NotificationHandler + * @param clazz The class of NotificationHandler * @param handler NotificationHandler handler - * @param <T> This is the type parameter + * @param <T> This is the type parameter * @return A handler Id (greater than 0 if succeeded) */ public <T> int addNotificationHandler(Class<T> clazz, NotificationHandler<T> handler) { @@ -1535,10 +1622,10 @@ public ODPManager getODPManager() { /** * Send an event to the ODP server. * - * @param type the event type (default = "fullstack"). - * @param action the event action name. + * @param type the event type (default = "fullstack"). + * @param action the event action name. * @param identifiers a dictionary for identifiers. The caller must provide at least one key-value pair unless non-empty common identifiers have been set already with {@link ODPManager.Builder#withUserCommonIdentifiers(Map) }. - * @param data a dictionary for associated data. The default event data will be added to this data before sending to the ODP server. + * @param data a dictionary for associated data. The default event data will be added to this data before sending to the ODP server. */ public void sendODPEvent(@Nullable String type, @Nonnull String action, @Nullable Map<String, String> identifiers, @Nullable Map<String, Object> data) { ProjectConfig projectConfig = getProjectConfig(); @@ -1586,7 +1673,7 @@ private void updateODPSettings() { * {@link Builder#withDatafile(java.lang.String)} and * {@link Builder#withEventHandler(com.optimizely.ab.event.EventHandler)} * respectively. - * + * <p> * Example: * <pre> * Optimizely optimizely = Optimizely.builder() @@ -1595,7 +1682,7 @@ private void updateODPSettings() { * .build(); * </pre> * - * @param datafile A datafile + * @param datafile A datafile * @param eventHandler An EventHandler * @return An Optimizely builder */ @@ -1644,7 +1731,8 @@ public Builder(@Nonnull String datafile, this.datafile = datafile; } - public Builder() { } + public Builder() { + } public Builder withErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; @@ -1686,7 +1774,7 @@ public Builder withUserProfileService(UserProfileService userProfileService) { * Override the SDK name and version (for client SDKs like android-sdk wrapping the core java-sdk) to be included in events. * * @param clientEngineName the client engine name ("java-sdk", "android-sdk", "flutter-sdk", etc.). - * @param clientVersion the client SDK version. + * @param clientVersion the client SDK version. * @return An Optimizely builder */ public Builder withClientInfo(String clientEngineName, String clientVersion) { diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java index 260de9945..b444dbc26 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyTest.java @@ -1101,7 +1101,7 @@ public void trackEventWithNullAttributeValues() throws Exception { * (i.e., not in the config) is passed through. * <p> * In this case, the track event call should not remove the unknown attribute from the given map but should go on and track the event successfully. - * + * <p> * TODO: Is this a dupe?? Also not sure the intent of the test since the attributes are stripped by the EventFactory */ @Test @@ -1569,8 +1569,7 @@ private NotificationHandler<DecisionNotification> getDecisionListener( final String testType, final String testUserId, final Map<String, ?> testUserAttributes, - final Map<String, ?> testDecisionInfo) - { + final Map<String, ?> testDecisionInfo) { return decisionNotification -> { assertEquals(decisionNotification.getType(), testType); assertEquals(decisionNotification.getUserId(), testUserId); @@ -1609,10 +1608,10 @@ public void activateEndToEndWithDecisionListener() throws Exception { int notificationId = optimizely.notificationCenter.<DecisionNotification>getNotificationManager(DecisionNotification.class) .addHandler( - getDecisionListener(NotificationCenter.DecisionNotificationType.FEATURE_TEST.toString(), - userId, - testUserAttributes, - testDecisionInfoMap)); + getDecisionListener(NotificationCenter.DecisionNotificationType.FEATURE_TEST.toString(), + userId, + testUserAttributes, + testDecisionInfoMap)); // activate the experiment Variation actualVariation = optimizely.activate(activatedExperiment.getKey(), userId, null); @@ -1752,7 +1751,8 @@ public void getEnabledFeaturesWithNoFeatureEnabled() throws Exception { any(OptimizelyUserContext.class), any(ProjectConfig.class) ); - int notificationId = optimizely.addDecisionNotificationHandler( decisionNotification -> { }); + int notificationId = optimizely.addDecisionNotificationHandler(decisionNotification -> { + }); List<String> featureFlags = optimizely.getEnabledFeatures(genericUserId, Collections.emptyMap()); assertTrue(featureFlags.isEmpty()); @@ -2012,10 +2012,10 @@ public void getFeatureVariableWithListenerUserInExperimentFeatureOn() throws Exc testDecisionInfoMap)); assertEquals(optimizely.getFeatureVariableString( - validFeatureKey, - validVariableKey, - testUserId, - Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)), + validFeatureKey, + validVariableKey, + testUserId, + Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)), expectedValue); // Verify that listener being called @@ -2062,10 +2062,10 @@ public void getFeatureVariableWithListenerUserInExperimentFeatureOff() { testDecisionInfoMap)); assertEquals(optimizely.getFeatureVariableString( - validFeatureKey, - validVariableKey, - userID, - null), + validFeatureKey, + validVariableKey, + userID, + null), expectedValue); // Verify that listener being called @@ -2109,10 +2109,10 @@ public void getFeatureVariableWithListenerUserInRollOutFeatureOn() throws Except testDecisionInfoMap)); assertEquals(optimizely.getFeatureVariableString( - validFeatureKey, - validVariableKey, - genericUserId, - Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)), + validFeatureKey, + validVariableKey, + genericUserId, + Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)), expectedValue); // Verify that listener being called @@ -2156,10 +2156,10 @@ public void getFeatureVariableWithListenerUserNotInRollOutFeatureOff() { testDecisionInfoMap)); assertEquals(optimizely.getFeatureVariableBoolean( - validFeatureKey, - validVariableKey, - genericUserId, - Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)), + validFeatureKey, + validVariableKey, + genericUserId, + Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)), expectedValue); // Verify that listener being called @@ -2201,12 +2201,14 @@ public void getFeatureVariableIntegerWithListenerUserInRollOutFeatureOn() { testUserAttributes, testDecisionInfoMap)); - assertEquals((long) optimizely.getFeatureVariableInteger( - validFeatureKey, - validVariableKey, - genericUserId, - Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)), - (long) expectedValue); + assertEquals( + expectedValue, + (long) optimizely.getFeatureVariableInteger( + validFeatureKey, + validVariableKey, + genericUserId, + Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)) + ); // Verify that listener being called assertTrue(isListenerCalled); @@ -2251,10 +2253,10 @@ public void getFeatureVariableDoubleWithListenerUserInExperimentFeatureOn() thro testDecisionInfoMap)); assertEquals(optimizely.getFeatureVariableDouble( - validFeatureKey, - validVariableKey, - genericUserId, - Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_SLYTHERIN_VALUE)), + validFeatureKey, + validVariableKey, + genericUserId, + Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_SLYTHERIN_VALUE)), Math.PI, 2); // Verify that listener being called @@ -2453,7 +2455,7 @@ public void getAllFeatureVariablesWithListenerUserInExperimentFeatureOff() { assertTrue(isListenerCalled); assertTrue(optimizely.notificationCenter.removeNotificationListener(notificationId)); } - + /** * Verify that the {@link Optimizely#activate(String, String, Map<String, String>)} call * correctly builds an endpoint url and request params @@ -2526,7 +2528,7 @@ public void activateWithListenerNullAttributes() throws Exception { * com.optimizely.ab.notification.NotificationListener)} properly used * and the listener is * added and notified when an experiment is activated. - * + * <p> * Feels redundant with the above tests */ @SuppressWarnings("unchecked") @@ -2572,7 +2574,7 @@ public void addNotificationListenerFromNotificationCenter() throws Exception { /** * Verify that {@link com.optimizely.ab.notification.NotificationCenter} properly * calls and the listener is removed and no longer notified when an experiment is activated. - * + * <p> * TODO move this to NotificationCenter. */ @SuppressWarnings("unchecked") @@ -2619,7 +2621,7 @@ public void removeNotificationListenerNotificationCenter() throws Exception { * Verify that {@link com.optimizely.ab.notification.NotificationCenter} * clearAllListerners removes all listeners * and no longer notified when an experiment is activated. - * + * <p> * TODO Should be part of NotificationCenter tests. */ @SuppressWarnings("unchecked") @@ -2741,7 +2743,7 @@ public void trackEventWithListenerNullAttributes() throws Exception { //======== Feature Accessor Tests ========// /** - * Verify {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, FeatureVariable.VariableType)} + * Verify {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, String)} * returns null and logs a message * when it is called with a feature key that has no corresponding feature in the datafile. */ @@ -2770,7 +2772,7 @@ public void getFeatureVariableValueForTypeReturnsNullWhenFeatureNotFound() throw } /** - * Verify {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, FeatureVariable.VariableType)} + * Verify {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, String)} * returns null and logs a message * when the feature key is valid, but no variable could be found for the variable key in the feature. */ @@ -2796,7 +2798,7 @@ public void getFeatureVariableValueForTypeReturnsNullWhenVariableNotFoundInValid } /** - * Verify {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, FeatureVariable.VariableType)} + * Verify {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, String)} * returns null when the variable's type does not match the type with which it was attempted to be accessed. */ @Test @@ -2825,7 +2827,7 @@ public void getFeatureVariableValueReturnsNullWhenVariableTypeDoesNotMatch() thr } /** - * Verify {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, FeatureVariable.VariableType)} + * Verify {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, String)} * returns the String default value of a feature variable * when the feature is not attached to an experiment or a rollout. */ @@ -2866,7 +2868,7 @@ public void getFeatureVariableValueForTypeReturnsDefaultValueWhenFeatureIsNotAtt } /** - * Verify {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, FeatureVariable.VariableType)} + * Verify {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, String)} * returns the String default value for a feature variable * when the feature is attached to an experiment and no rollout, but the user is excluded from the experiment. */ @@ -2910,7 +2912,7 @@ public void getFeatureVariableValueReturnsDefaultValueWhenFeatureIsAttachedToOne } /** - * Verify {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, FeatureVariable.VariableType)} + * Verify {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, String)} * is called when the variation is not null and feature enabled is false * returns the default variable value */ @@ -2964,10 +2966,10 @@ public void getFeatureVariableUserInExperimentFeatureOn() throws Exception { Optimizely optimizely = optimizelyBuilder.build(); assertEquals(optimizely.getFeatureVariableString( - validFeatureKey, - validVariableKey, - testUserId, - Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)), + validFeatureKey, + validVariableKey, + testUserId, + Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)), expectedValue); logbackVerifier.expectMessage( @@ -2994,10 +2996,10 @@ public void getFeatureVariableUserInExperimentFeatureOff() { Optimizely optimizely = optimizelyBuilder.build(); assertEquals(optimizely.getFeatureVariableString( - validFeatureKey, - validVariableKey, - userID, - null), + validFeatureKey, + validVariableKey, + userID, + null), expectedValue); } @@ -3017,10 +3019,10 @@ public void getFeatureVariableUserInRollOutFeatureOn() throws Exception { Optimizely optimizely = optimizelyBuilder.build(); assertEquals(optimizely.getFeatureVariableString( - validFeatureKey, - validVariableKey, - genericUserId, - Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)), + validFeatureKey, + validVariableKey, + genericUserId, + Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)), expectedValue); } @@ -3040,10 +3042,10 @@ public void getFeatureVariableUserNotInRollOutFeatureOff() { Optimizely optimizely = optimizelyBuilder.build(); assertEquals(optimizely.getFeatureVariableBoolean( - validFeatureKey, - validVariableKey, - genericUserId, - Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)), + validFeatureKey, + validVariableKey, + genericUserId, + Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)), expectedValue); } @@ -3062,12 +3064,39 @@ public void getFeatureVariableIntegerUserInRollOutFeatureOn() { Optimizely optimizely = optimizelyBuilder.build(); - assertEquals((long) optimizely.getFeatureVariableInteger( - validFeatureKey, - validVariableKey, - genericUserId, - Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)), - (long) expectedValue); + assertEquals( + expectedValue, + (int) optimizely.getFeatureVariableInteger( + validFeatureKey, + validVariableKey, + genericUserId, + Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)) + ); + } + + /** + * Verify that the {@link Optimizely#getFeatureVariableInteger(String, String, String, Map)} + * is called when feature is in rollout and feature enabled is true + * return rollout variable value + */ + @Test + public void getFeatureVariableLongUserInRollOutFeatureOn() { + assumeTrue(datafileVersion >= Integer.parseInt(ProjectConfig.Version.V4.toString())); + + final String validFeatureKey = FEATURE_SINGLE_VARIABLE_INTEGER_KEY; + String validVariableKey = VARIABLE_INTEGER_VARIABLE_KEY; + int expectedValue = 7; + + Optimizely optimizely = optimizelyBuilder.build(); + + assertEquals( + expectedValue, + (int) optimizely.getFeatureVariableInteger( + validFeatureKey, + validVariableKey, + genericUserId, + Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE)) + ); } /** @@ -3085,15 +3114,15 @@ public void getFeatureVariableDoubleUserInExperimentFeatureOn() throws Exception Optimizely optimizely = optimizelyBuilder.build(); assertEquals(optimizely.getFeatureVariableDouble( - validFeatureKey, - validVariableKey, - genericUserId, - Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_SLYTHERIN_VALUE)), + validFeatureKey, + validVariableKey, + genericUserId, + Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_SLYTHERIN_VALUE)), Math.PI, 2); } /** - * Verify {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, FeatureVariable.VariableType)} + * Verify {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, String)} * returns the default value for the feature variable * when there is no variable usage present for the variation the user is bucketed into. */ @@ -4160,6 +4189,18 @@ public void convertStringToTypeIntegerCatchesExceptionFromParsing() throws Numbe ); } + /** + * Verify that {@link Optimizely#convertStringToType(String, String)} + * is able to parse Long. + */ + @Test + public void convertStringToTypeIntegerReturnsLongCorrectly() throws NumberFormatException { + String longValue = "8949425362117"; + + Optimizely optimizely = optimizelyBuilder.build(); + assertEquals(Long.valueOf(longValue), optimizely.convertStringToType(longValue, FeatureVariable.INTEGER_TYPE)); + } + /** * Verify {@link Optimizely#getFeatureVariableInteger(String, String, String)} * calls through to {@link Optimizely#getFeatureVariableInteger(String, String, String, Map)} @@ -4234,7 +4275,7 @@ public void getFeatureVariableIntegerReturnsNullWhenUserIdIsNull() throws Except * Verify {@link Optimizely#getFeatureVariableInteger(String, String, String)} * calls through to {@link Optimizely#getFeatureVariableInteger(String, String, String, Map)} * and both return the parsed Integer value from the value returned from - * {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, FeatureVariable.VariableType)}. + * {@link Optimizely#getFeatureVariableValueForType(String, String, String, Map, String)}. */ @Test public void getFeatureVariableIntegerReturnsWhatInternalReturns() throws Exception { @@ -4333,8 +4374,8 @@ public void getFeatureVariableJSONUserInExperimentFeatureOn() throws Exception { assertEquals(json.toMap().get("k1"), "s1"); assertEquals(json.toMap().get("k2"), 103.5); assertEquals(json.toMap().get("k3"), false); - assertEquals(((Map)json.toMap().get("k4")).get("kk1"), "ss1"); - assertEquals(((Map)json.toMap().get("k4")).get("kk2"), true); + assertEquals(((Map) json.toMap().get("k4")).get("kk1"), "ss1"); + assertEquals(((Map) json.toMap().get("k4")).get("kk2"), true); assertEquals(json.getValue("k1", String.class), "s1"); assertEquals(json.getValue("k4.kk2", Boolean.class), true); @@ -4368,15 +4409,15 @@ public void getFeatureVariableJSONUserInExperimentFeatureOff() throws Exception assertEquals(json.toMap().get("k1"), "v1"); assertEquals(json.toMap().get("k2"), 3.5); assertEquals(json.toMap().get("k3"), true); - assertEquals(((Map)json.toMap().get("k4")).get("kk1"), "vv1"); - assertEquals(((Map)json.toMap().get("k4")).get("kk2"), false); + assertEquals(((Map) json.toMap().get("k4")).get("kk1"), "vv1"); + assertEquals(((Map) json.toMap().get("k4")).get("kk2"), false); assertEquals(json.getValue("k1", String.class), "v1"); assertEquals(json.getValue("k4.kk2", Boolean.class), false); } /** - * Verify that the {@link Optimizely#getAllFeatureVariables(String,String, Map)} + * Verify that the {@link Optimizely#getAllFeatureVariables(String, String, Map)} * is called when feature is in experiment and feature enabled is true * returns variable value */ @@ -4398,12 +4439,12 @@ public void getAllFeatureVariablesUserInExperimentFeatureOn() throws Exception { assertEquals(json.toMap().get("first_letter"), "F"); assertEquals(json.toMap().get("rest_of_name"), "red"); - Map subMap = (Map)json.toMap().get("json_patched"); + Map subMap = (Map) json.toMap().get("json_patched"); assertEquals(subMap.get("k1"), "s1"); assertEquals(subMap.get("k2"), 103.5); assertEquals(subMap.get("k3"), false); - assertEquals(((Map)subMap.get("k4")).get("kk1"), "ss1"); - assertEquals(((Map)subMap.get("k4")).get("kk2"), true); + assertEquals(((Map) subMap.get("k4")).get("kk1"), "ss1"); + assertEquals(((Map) subMap.get("k4")).get("kk2"), true); assertEquals(json.getValue("first_letter", String.class), "F"); assertEquals(json.getValue("json_patched.k1", String.class), "s1"); @@ -4435,12 +4476,12 @@ public void getAllFeatureVariablesUserInExperimentFeatureOff() throws Exception assertEquals(json.toMap().get("first_letter"), "H"); assertEquals(json.toMap().get("rest_of_name"), "arry"); - Map subMap = (Map)json.toMap().get("json_patched"); + Map subMap = (Map) json.toMap().get("json_patched"); assertEquals(subMap.get("k1"), "v1"); assertEquals(subMap.get("k2"), 3.5); assertEquals(subMap.get("k3"), true); - assertEquals(((Map)subMap.get("k4")).get("kk1"), "vv1"); - assertEquals(((Map)subMap.get("k4")).get("kk2"), false); + assertEquals(((Map) subMap.get("k4")).get("kk1"), "vv1"); + assertEquals(((Map) subMap.get("k4")).get("kk2"), false); assertEquals(json.getValue("first_letter", String.class), "H"); assertEquals(json.getValue("json_patched.k1", String.class), "v1"); @@ -4448,7 +4489,7 @@ public void getAllFeatureVariablesUserInExperimentFeatureOff() throws Exception } /** - * Verify {@link Optimizely#getAllFeatureVariables(String,String, Map)} with invalid parameters + * Verify {@link Optimizely#getAllFeatureVariables(String, String, Map)} with invalid parameters */ @SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION") @Test @@ -4532,7 +4573,8 @@ public void testAddTrackNotificationHandler() { NotificationManager<TrackNotification> manager = optimizely.getNotificationCenter() .getNotificationManager(TrackNotification.class); - int notificationId = optimizely.addTrackNotificationHandler(message -> {}); + int notificationId = optimizely.addTrackNotificationHandler(message -> { + }); assertTrue(manager.remove(notificationId)); } @@ -4542,7 +4584,8 @@ public void testAddDecisionNotificationHandler() { NotificationManager<DecisionNotification> manager = optimizely.getNotificationCenter() .getNotificationManager(DecisionNotification.class); - int notificationId = optimizely.addDecisionNotificationHandler(message -> {}); + int notificationId = optimizely.addDecisionNotificationHandler(message -> { + }); assertTrue(manager.remove(notificationId)); } @@ -4552,7 +4595,8 @@ public void testAddUpdateConfigNotificationHandler() { NotificationManager<UpdateConfigNotification> manager = optimizely.getNotificationCenter() .getNotificationManager(UpdateConfigNotification.class); - int notificationId = optimizely.addUpdateConfigNotificationHandler(message -> {}); + int notificationId = optimizely.addUpdateConfigNotificationHandler(message -> { + }); assertTrue(manager.remove(notificationId)); } @@ -4562,7 +4606,8 @@ public void testAddLogEventNotificationHandler() { NotificationManager<LogEvent> manager = optimizely.getNotificationCenter() .getNotificationManager(LogEvent.class); - int notificationId = optimizely.addLogEventNotificationHandler(message -> {}); + int notificationId = optimizely.addLogEventNotificationHandler(message -> { + }); assertTrue(manager.remove(notificationId)); } diff --git a/core-api/src/test/java/com/optimizely/ab/config/ValidProjectConfigV4.java b/core-api/src/test/java/com/optimizely/ab/config/ValidProjectConfigV4.java index 0ed8d5945..faacfda76 100644 --- a/core-api/src/test/java/com/optimizely/ab/config/ValidProjectConfigV4.java +++ b/core-api/src/test/java/com/optimizely/ab/config/ValidProjectConfigV4.java @@ -266,6 +266,19 @@ public class ValidProjectConfigV4 { FeatureVariable.INTEGER_TYPE, null ); + private static final String FEATURE_SINGLE_VARIABLE_LONG_ID = "964006971"; + public static final String FEATURE_SINGLE_VARIABLE_LONG_KEY = "long_single_variable_feature"; + private static final String VARIABLE_LONG_VARIABLE_ID = "4339640697"; + public static final String VARIABLE_LONG_VARIABLE_KEY = "long_variable"; + private static final String VARIABLE_LONG_DEFAULT_VALUE = "379993881340"; + private static final FeatureVariable VARIABLE_LONG_VARIABLE = new FeatureVariable( + VARIABLE_LONG_VARIABLE_ID, + VARIABLE_LONG_VARIABLE_KEY, + VARIABLE_LONG_DEFAULT_VALUE, + null, + FeatureVariable.INTEGER_TYPE, + null + ); private static final String FEATURE_SINGLE_VARIABLE_BOOLEAN_ID = "2591051011"; public static final String FEATURE_SINGLE_VARIABLE_BOOLEAN_KEY = "boolean_single_variable_feature"; private static final String VARIABLE_BOOLEAN_VARIABLE_ID = "3974680341"; From 5a1b1c8ea8c4d029eb440e76137ebba6062ecca6 Mon Sep 17 00:00:00 2001 From: Muzahidul Islam <129880873+muzahidul-opti@users.noreply.github.com> Date: Thu, 20 Feb 2025 14:49:06 +0600 Subject: [PATCH 73/80] Update change log (#561) --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 104422c93..0db74cd39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Optimizely Java X SDK Changelog +## [4.2.1] +Feb 19th, 2025 + +### Fixes +- Fix big integer conversion ([#556](https://github.com/optimizely/java-sdk/pull/556)). + ## [4.2.0] November 6th, 2024 From f90da0c073ee28243e3fe98b8e38271d9486a38f Mon Sep 17 00:00:00 2001 From: Muzahidul Islam <129880873+muzahidul-opti@users.noreply.github.com> Date: Thu, 20 Feb 2025 23:18:17 +0600 Subject: [PATCH 74/80] [FSSDK-11076] fix: release tag (#562) * fix github tag * clean up * clean up --- .github/workflows/build.yml | 2 +- build.gradle | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e10de2d47..2965e4f9e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -37,4 +37,4 @@ jobs: MAVEN_SIGNING_PASSPHRASE: ${{ secrets.MAVEN_SIGNING_PASSPHRASE }} MAVEN_CENTRAL_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }} MAVEN_CENTRAL_PASSWORD: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} - run: ./gradlew ${{ inputs.action }} + run: GITHUB_TAG=${{ inputs.github_tag }} ./gradlew ${{ inputs.action }} diff --git a/build.gradle b/build.gradle index 3301eda25..4c8c2a513 100644 --- a/build.gradle +++ b/build.gradle @@ -24,7 +24,7 @@ allprojects { allprojects { group = 'com.optimizely.ab' - def travis_defined_version = System.getenv('TRAVIS_TAG') + def travis_defined_version = System.getenv('GITHUB_TAG') if (travis_defined_version != null) { version = travis_defined_version } From 84710ccace02a86da9b2e9159e94ae8528006b12 Mon Sep 17 00:00:00 2001 From: Jae Kim <45045038+jaeopt@users.noreply.github.com> Date: Wed, 23 Apr 2025 16:41:59 -0700 Subject: [PATCH 75/80] [FSSDK-1135] upgrade spotbugs to 4.8.5 (#565) --- .github/workflows/java.yml | 4 ++-- README.md | 2 +- build.gradle | 3 ++- core-httpclient-impl/build.gradle | 1 + .../com/optimizely/ab/config/HttpProjectConfigManager.java | 2 ++ 5 files changed, 8 insertions(+), 4 deletions(-) diff --git a/.github/workflows/java.yml b/.github/workflows/java.yml index 7ebc17304..95e8ccf8d 100644 --- a/.github/workflows/java.yml +++ b/.github/workflows/java.yml @@ -83,8 +83,8 @@ jobs: - name: Check on failures if: always() && steps.unit_tests.outcome != 'success' run: | - cat /home/runner/java-sdk/core-api/build/reports/findbugs/main.html - cat /home/runner/java-sdk/core-api/build/reports/findbugs/test.html + cat /Users/runner/work/java-sdk/core-api/build/reports/spotbugs/main.html + cat /Users/runner/work/java-sdk/core-api/build/reports/spotbugs/test.html - name: Check on success if: always() && steps.unit_tests.outcome == 'success' run: | diff --git a/README.md b/README.md index b4b1f0be1..1a7370c43 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ You can run all unit tests with: ### Checking for bugs -We utilize [FindBugs](http://findbugs.sourceforge.net/) to identify possible bugs in the SDK. To run the check: +We utilize [SpotBugs](https://spotbugs.github.io/) to identify possible bugs in the SDK. To run the check: ``` diff --git a/build.gradle b/build.gradle index 4c8c2a513..54426f6e7 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ plugins { id 'me.champeau.gradle.jmh' version '0.5.3' id 'nebula.optional-base' version '3.2.0' id 'com.github.hierynomus.license' version '0.16.1' - id 'com.github.spotbugs' version "4.5.0" + id 'com.github.spotbugs' version "6.0.14" id 'maven-publish' } @@ -73,6 +73,7 @@ configure(publishedProjects) { spotbugs { spotbugsJmh.enabled = false + reportLevel = com.github.spotbugs.snom.Confidence.valueOf('HIGH') } test { diff --git a/core-httpclient-impl/build.gradle b/core-httpclient-impl/build.gradle index 4affcda17..ab5644555 100644 --- a/core-httpclient-impl/build.gradle +++ b/core-httpclient-impl/build.gradle @@ -2,6 +2,7 @@ dependencies { implementation project(':core-api') implementation group: 'org.apache.httpcomponents', name: 'httpclient', version: httpClientVersion implementation group: 'org.slf4j', name: 'slf4j-api', version: slf4jVersion + implementation group: 'com.google.code.findbugs', name: 'annotations', version: findbugsAnnotationVersion implementation group: 'com.google.code.findbugs', name: 'jsr305', version: findbugsJsrVersion testImplementation 'org.mock-server:mockserver-netty:5.1.1' } diff --git a/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java b/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java index 095e32a67..2e99d3ae9 100644 --- a/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java +++ b/core-httpclient-impl/src/main/java/com/optimizely/ab/config/HttpProjectConfigManager.java @@ -24,6 +24,7 @@ import java.util.concurrent.ThreadFactory; import java.util.concurrent.locks.ReentrantLock; import javax.annotation.Nullable; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.http.*; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; @@ -309,6 +310,7 @@ public Builder withPollingInterval(Long period, TimeUnit timeUnit) { return this; } + @SuppressFBWarnings("EI_EXPOSE_REP2") public Builder withNotificationCenter(NotificationCenter notificationCenter) { this.notificationCenter = notificationCenter; return this; From 64868864d2480a0c7f1081b1086d0d149b4bb160 Mon Sep 17 00:00:00 2001 From: esrakartalOpt <102107327+esrakartalOpt@users.noreply.github.com> Date: Mon, 12 May 2025 09:09:07 -0500 Subject: [PATCH 76/80] [FSSDK-11448] Java Implementation: Add Experiment ID and Variation ID to Decision Notification (#566) * [FSSDK-11448] Java Implementation: Add Experiment ID and Variation ID to Decision Notification * Fix test * Fix test * Fix decision test * Fix test * Fix the tests * Fix test * Fix last test case * Fix the test case * Remove experiment decision changes * Fix test * Fix test * Fix test --- .../main/java/com/optimizely/ab/Optimizely.java | 6 ++++++ .../ab/notification/DecisionNotification.java | 16 ++++++++++++++++ .../optimizely/ab/OptimizelyUserContextTest.java | 4 ++++ 3 files changed, 26 insertions(+) diff --git a/core-api/src/main/java/com/optimizely/ab/Optimizely.java b/core-api/src/main/java/com/optimizely/ab/Optimizely.java index 4f942ff69..6eead11c6 100644 --- a/core-api/src/main/java/com/optimizely/ab/Optimizely.java +++ b/core-api/src/main/java/com/optimizely/ab/Optimizely.java @@ -1303,6 +1303,8 @@ private OptimizelyDecision createOptimizelyDecision( ProjectConfig projectConfig ) { String userId = user.getUserId(); + String experimentId = null; + String variationId = null; Boolean flagEnabled = false; if (flagDecision.variation != null) { @@ -1336,6 +1338,8 @@ private OptimizelyDecision createOptimizelyDecision( Boolean decisionEventDispatched = false; + experimentId = flagDecision.experiment != null ? flagDecision.experiment.getId() : null; + variationId = flagDecision.variation != null ? flagDecision.variation.getId() : null; Map<String, Object> attributes = user.getAttributes(); Map<String, ?> copiedAttributes = new HashMap<>(attributes); @@ -1362,6 +1366,8 @@ private OptimizelyDecision createOptimizelyDecision( .withRuleKey(ruleKey) .withReasons(reasonsToReport) .withDecisionEventDispatched(decisionEventDispatched) + .withExperimentId(experimentId) + .withVariationId(variationId) .build(); notificationCenter.send(decisionNotification); diff --git a/core-api/src/main/java/com/optimizely/ab/notification/DecisionNotification.java b/core-api/src/main/java/com/optimizely/ab/notification/DecisionNotification.java index d97e5bf40..ab3fdc03d 100644 --- a/core-api/src/main/java/com/optimizely/ab/notification/DecisionNotification.java +++ b/core-api/src/main/java/com/optimizely/ab/notification/DecisionNotification.java @@ -364,6 +364,8 @@ public static class FlagDecisionNotificationBuilder { public final static String RULE_KEY = "ruleKey"; public final static String REASONS = "reasons"; public final static String DECISION_EVENT_DISPATCHED = "decisionEventDispatched"; + public final static String EXPERIMENT_ID = "experimentId"; + public final static String VARIATION_ID = "variationId"; private String flagKey; private Boolean enabled; @@ -374,6 +376,8 @@ public static class FlagDecisionNotificationBuilder { private String ruleKey; private List<String> reasons; private Boolean decisionEventDispatched; + private String experimentId; + private String variationId; private Map<String, Object> decisionInfo; @@ -422,6 +426,16 @@ public FlagDecisionNotificationBuilder withDecisionEventDispatched(Boolean dispa return this; } + public FlagDecisionNotificationBuilder withExperimentId(String experimentId) { + this.experimentId = experimentId; + return this; + } + + public FlagDecisionNotificationBuilder withVariationId(String variationId) { + this.variationId = variationId; + return this; + } + public DecisionNotification build() { if (flagKey == null) { throw new OptimizelyRuntimeException("flagKey not set"); @@ -439,6 +453,8 @@ public DecisionNotification build() { put(RULE_KEY, ruleKey); put(REASONS, reasons); put(DECISION_EVENT_DISPATCHED, decisionEventDispatched); + put(EXPERIMENT_ID, experimentId); + put(VARIATION_ID, variationId); }}; return new DecisionNotification( diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java index 34cf61543..bb2d36192 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java @@ -707,6 +707,8 @@ public void decisionNotification() { OptimizelyJSON variables = optimizely.getAllFeatureVariables(flagKey, userId); String ruleKey = "exp_no_audience"; List<String> reasons = Collections.emptyList(); + String experimentId = "10420810910"; + String variationId = "10418551353"; final Map<String, Object> testDecisionInfoMap = new HashMap<>(); testDecisionInfoMap.put(FLAG_KEY, flagKey); @@ -715,6 +717,8 @@ public void decisionNotification() { testDecisionInfoMap.put(VARIABLES, variables.toMap()); testDecisionInfoMap.put(RULE_KEY, ruleKey); testDecisionInfoMap.put(REASONS, reasons); + testDecisionInfoMap.put(EXPERIMENT_ID, experimentId); + testDecisionInfoMap.put(VARIATION_ID, variationId); Map<String, Object> attributes = Collections.singletonMap("gender", "f"); OptimizelyUserContext user = optimizely.createUserContext(userId, attributes); From 52185b7b9f4540a94180ba9b705b76ad58f87af9 Mon Sep 17 00:00:00 2001 From: esrakartalOpt <102107327+esrakartalOpt@users.noreply.github.com> Date: Thu, 15 May 2025 10:06:57 -0500 Subject: [PATCH 77/80] =?UTF-8?q?Revert=20"[FSSDK-11448]=20Java=20Implemen?= =?UTF-8?q?tation:=20Add=20Experiment=20ID=20and=20Variation=20ID=E2=80=A6?= =?UTF-8?q?"=20(#567)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 64868864d2480a0c7f1081b1086d0d149b4bb160. --- .../main/java/com/optimizely/ab/Optimizely.java | 6 ------ .../ab/notification/DecisionNotification.java | 16 ---------------- .../optimizely/ab/OptimizelyUserContextTest.java | 4 ---- 3 files changed, 26 deletions(-) diff --git a/core-api/src/main/java/com/optimizely/ab/Optimizely.java b/core-api/src/main/java/com/optimizely/ab/Optimizely.java index 6eead11c6..4f942ff69 100644 --- a/core-api/src/main/java/com/optimizely/ab/Optimizely.java +++ b/core-api/src/main/java/com/optimizely/ab/Optimizely.java @@ -1303,8 +1303,6 @@ private OptimizelyDecision createOptimizelyDecision( ProjectConfig projectConfig ) { String userId = user.getUserId(); - String experimentId = null; - String variationId = null; Boolean flagEnabled = false; if (flagDecision.variation != null) { @@ -1338,8 +1336,6 @@ private OptimizelyDecision createOptimizelyDecision( Boolean decisionEventDispatched = false; - experimentId = flagDecision.experiment != null ? flagDecision.experiment.getId() : null; - variationId = flagDecision.variation != null ? flagDecision.variation.getId() : null; Map<String, Object> attributes = user.getAttributes(); Map<String, ?> copiedAttributes = new HashMap<>(attributes); @@ -1366,8 +1362,6 @@ private OptimizelyDecision createOptimizelyDecision( .withRuleKey(ruleKey) .withReasons(reasonsToReport) .withDecisionEventDispatched(decisionEventDispatched) - .withExperimentId(experimentId) - .withVariationId(variationId) .build(); notificationCenter.send(decisionNotification); diff --git a/core-api/src/main/java/com/optimizely/ab/notification/DecisionNotification.java b/core-api/src/main/java/com/optimizely/ab/notification/DecisionNotification.java index ab3fdc03d..d97e5bf40 100644 --- a/core-api/src/main/java/com/optimizely/ab/notification/DecisionNotification.java +++ b/core-api/src/main/java/com/optimizely/ab/notification/DecisionNotification.java @@ -364,8 +364,6 @@ public static class FlagDecisionNotificationBuilder { public final static String RULE_KEY = "ruleKey"; public final static String REASONS = "reasons"; public final static String DECISION_EVENT_DISPATCHED = "decisionEventDispatched"; - public final static String EXPERIMENT_ID = "experimentId"; - public final static String VARIATION_ID = "variationId"; private String flagKey; private Boolean enabled; @@ -376,8 +374,6 @@ public static class FlagDecisionNotificationBuilder { private String ruleKey; private List<String> reasons; private Boolean decisionEventDispatched; - private String experimentId; - private String variationId; private Map<String, Object> decisionInfo; @@ -426,16 +422,6 @@ public FlagDecisionNotificationBuilder withDecisionEventDispatched(Boolean dispa return this; } - public FlagDecisionNotificationBuilder withExperimentId(String experimentId) { - this.experimentId = experimentId; - return this; - } - - public FlagDecisionNotificationBuilder withVariationId(String variationId) { - this.variationId = variationId; - return this; - } - public DecisionNotification build() { if (flagKey == null) { throw new OptimizelyRuntimeException("flagKey not set"); @@ -453,8 +439,6 @@ public DecisionNotification build() { put(RULE_KEY, ruleKey); put(REASONS, reasons); put(DECISION_EVENT_DISPATCHED, decisionEventDispatched); - put(EXPERIMENT_ID, experimentId); - put(VARIATION_ID, variationId); }}; return new DecisionNotification( diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java index bb2d36192..34cf61543 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java @@ -707,8 +707,6 @@ public void decisionNotification() { OptimizelyJSON variables = optimizely.getAllFeatureVariables(flagKey, userId); String ruleKey = "exp_no_audience"; List<String> reasons = Collections.emptyList(); - String experimentId = "10420810910"; - String variationId = "10418551353"; final Map<String, Object> testDecisionInfoMap = new HashMap<>(); testDecisionInfoMap.put(FLAG_KEY, flagKey); @@ -717,8 +715,6 @@ public void decisionNotification() { testDecisionInfoMap.put(VARIABLES, variables.toMap()); testDecisionInfoMap.put(RULE_KEY, ruleKey); testDecisionInfoMap.put(REASONS, reasons); - testDecisionInfoMap.put(EXPERIMENT_ID, experimentId); - testDecisionInfoMap.put(VARIATION_ID, variationId); Map<String, Object> attributes = Collections.singletonMap("gender", "f"); OptimizelyUserContext user = optimizely.createUserContext(userId, attributes); From 81e46b8742c7500260adbd0fc2707fcb31e1ec46 Mon Sep 17 00:00:00 2001 From: esrakartalOpt <102107327+esrakartalOpt@users.noreply.github.com> Date: Wed, 28 May 2025 05:51:52 -0500 Subject: [PATCH 78/80] [FSSDK-11448] Java Implementation: Add Experiment ID and Variation ID to Decision Notification (#569) --- .../main/java/com/optimizely/ab/Optimizely.java | 6 ++++++ .../ab/notification/DecisionNotification.java | 16 ++++++++++++++++ .../optimizely/ab/OptimizelyUserContextTest.java | 4 ++++ 3 files changed, 26 insertions(+) diff --git a/core-api/src/main/java/com/optimizely/ab/Optimizely.java b/core-api/src/main/java/com/optimizely/ab/Optimizely.java index 4f942ff69..6eead11c6 100644 --- a/core-api/src/main/java/com/optimizely/ab/Optimizely.java +++ b/core-api/src/main/java/com/optimizely/ab/Optimizely.java @@ -1303,6 +1303,8 @@ private OptimizelyDecision createOptimizelyDecision( ProjectConfig projectConfig ) { String userId = user.getUserId(); + String experimentId = null; + String variationId = null; Boolean flagEnabled = false; if (flagDecision.variation != null) { @@ -1336,6 +1338,8 @@ private OptimizelyDecision createOptimizelyDecision( Boolean decisionEventDispatched = false; + experimentId = flagDecision.experiment != null ? flagDecision.experiment.getId() : null; + variationId = flagDecision.variation != null ? flagDecision.variation.getId() : null; Map<String, Object> attributes = user.getAttributes(); Map<String, ?> copiedAttributes = new HashMap<>(attributes); @@ -1362,6 +1366,8 @@ private OptimizelyDecision createOptimizelyDecision( .withRuleKey(ruleKey) .withReasons(reasonsToReport) .withDecisionEventDispatched(decisionEventDispatched) + .withExperimentId(experimentId) + .withVariationId(variationId) .build(); notificationCenter.send(decisionNotification); diff --git a/core-api/src/main/java/com/optimizely/ab/notification/DecisionNotification.java b/core-api/src/main/java/com/optimizely/ab/notification/DecisionNotification.java index d97e5bf40..ab3fdc03d 100644 --- a/core-api/src/main/java/com/optimizely/ab/notification/DecisionNotification.java +++ b/core-api/src/main/java/com/optimizely/ab/notification/DecisionNotification.java @@ -364,6 +364,8 @@ public static class FlagDecisionNotificationBuilder { public final static String RULE_KEY = "ruleKey"; public final static String REASONS = "reasons"; public final static String DECISION_EVENT_DISPATCHED = "decisionEventDispatched"; + public final static String EXPERIMENT_ID = "experimentId"; + public final static String VARIATION_ID = "variationId"; private String flagKey; private Boolean enabled; @@ -374,6 +376,8 @@ public static class FlagDecisionNotificationBuilder { private String ruleKey; private List<String> reasons; private Boolean decisionEventDispatched; + private String experimentId; + private String variationId; private Map<String, Object> decisionInfo; @@ -422,6 +426,16 @@ public FlagDecisionNotificationBuilder withDecisionEventDispatched(Boolean dispa return this; } + public FlagDecisionNotificationBuilder withExperimentId(String experimentId) { + this.experimentId = experimentId; + return this; + } + + public FlagDecisionNotificationBuilder withVariationId(String variationId) { + this.variationId = variationId; + return this; + } + public DecisionNotification build() { if (flagKey == null) { throw new OptimizelyRuntimeException("flagKey not set"); @@ -439,6 +453,8 @@ public DecisionNotification build() { put(RULE_KEY, ruleKey); put(REASONS, reasons); put(DECISION_EVENT_DISPATCHED, decisionEventDispatched); + put(EXPERIMENT_ID, experimentId); + put(VARIATION_ID, variationId); }}; return new DecisionNotification( diff --git a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java index 34cf61543..bb2d36192 100644 --- a/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java +++ b/core-api/src/test/java/com/optimizely/ab/OptimizelyUserContextTest.java @@ -707,6 +707,8 @@ public void decisionNotification() { OptimizelyJSON variables = optimizely.getAllFeatureVariables(flagKey, userId); String ruleKey = "exp_no_audience"; List<String> reasons = Collections.emptyList(); + String experimentId = "10420810910"; + String variationId = "10418551353"; final Map<String, Object> testDecisionInfoMap = new HashMap<>(); testDecisionInfoMap.put(FLAG_KEY, flagKey); @@ -715,6 +717,8 @@ public void decisionNotification() { testDecisionInfoMap.put(VARIABLES, variables.toMap()); testDecisionInfoMap.put(RULE_KEY, ruleKey); testDecisionInfoMap.put(REASONS, reasons); + testDecisionInfoMap.put(EXPERIMENT_ID, experimentId); + testDecisionInfoMap.put(VARIATION_ID, variationId); Map<String, Object> attributes = Collections.singletonMap("gender", "f"); OptimizelyUserContext user = optimizely.createUserContext(userId, attributes); From 8f7508543b314c7915d4b62cc13176ba89351950 Mon Sep 17 00:00:00 2001 From: Muzahidul Islam <129880873+muzahidul-opti@users.noreply.github.com> Date: Wed, 28 May 2025 18:32:57 +0600 Subject: [PATCH 79/80] Update for release 4.2.2 (#570) --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0db74cd39..565bfcd5d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Optimizely Java X SDK Changelog +## [4.2.2] +May 28th, 2025 + +### Fixes +- Added experimentId and variationId to decision notification ([#569](https://github.com/optimizely/java-sdk/pull/569)). + ## [4.2.1] Feb 19th, 2025 From 746e81530a9224fabcd7f610d81800358e6e34c9 Mon Sep 17 00:00:00 2001 From: Muzahidul Islam <129880873+muzahidul-opti@users.noreply.github.com> Date: Wed, 28 May 2025 21:05:07 +0600 Subject: [PATCH 80/80] [FSSDK-11465] chore: update github actions (#571) * Update build.yml * Update integration_test.yml * Update build.yml * Update java.yml * Update java.yml * Update build.yml * Update java.yml * Update build.yml * Update build.yml --- .github/workflows/build.yml | 3 +-- .github/workflows/integration_test.yml | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2965e4f9e..1cb2193c8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -22,13 +22,12 @@ jobs: run_build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: set up JDK 8 uses: actions/setup-java@v2 with: java-version: '8' distribution: 'temurin' - cache: gradle - name: Grant execute permission for gradlew run: chmod +x gradlew - name: ${{ inputs.action }} diff --git a/.github/workflows/integration_test.yml b/.github/workflows/integration_test.yml index 35fb78590..76fef5ad3 100644 --- a/.github/workflows/integration_test.yml +++ b/.github/workflows/integration_test.yml @@ -13,7 +13,7 @@ jobs: test: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: # You should create a personal access token and store it in your repository token: ${{ secrets.CI_USER_TOKEN }}