use of com.optimizely.ab.optimizelyjson.OptimizelyJSON in project java-sdk by optimizely.
the class OptimizelyUserContextTest method decide_featureTest.
// decide
@Test
public void decide_featureTest() {
optimizely = new Optimizely.Builder().withDatafile(datafile).withEventProcessor(new ForwardingEventProcessor(eventHandler, null)).build();
String flagKey = "feature_2";
String experimentKey = "exp_no_audience";
String variationKey = "variation_with_traffic";
String experimentId = "10420810910";
String variationId = "10418551353";
OptimizelyJSON variablesExpected = optimizely.getAllFeatureVariables(flagKey, userId);
OptimizelyUserContext user = optimizely.createUserContext(userId);
OptimizelyDecision decision = user.decide(flagKey);
assertEquals(decision.getVariationKey(), variationKey);
assertTrue(decision.getEnabled());
assertEquals(decision.getVariables().toMap(), variablesExpected.toMap());
assertEquals(decision.getRuleKey(), experimentKey);
assertEquals(decision.getFlagKey(), flagKey);
assertEquals(decision.getUserContext(), user);
assertTrue(decision.getReasons().isEmpty());
DecisionMetadata metadata = new DecisionMetadata.Builder().setFlagKey(flagKey).setRuleKey(experimentKey).setRuleType(FeatureDecision.DecisionSource.FEATURE_TEST.toString()).setVariationKey(variationKey).setEnabled(true).build();
eventHandler.expectImpression(experimentId, variationId, userId, Collections.emptyMap(), metadata);
}
use of com.optimizely.ab.optimizelyjson.OptimizelyJSON in project java-sdk by optimizely.
the class Optimizely method getAllFeatureVariables.
/**
* 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.
* @return An OptimizelyJSON instance for all variable values.
* Null if the feature could not be found.
*/
@Nullable
public OptimizelyJSON getAllFeatureVariables(@Nonnull String featureKey, @Nonnull String userId, @Nonnull Map<String, ?> attributes) {
if (featureKey == null) {
logger.warn("The featureKey parameter must be nonnull.");
return null;
} else if (userId == null) {
logger.warn("The userId parameter must be nonnull.");
return null;
}
ProjectConfig projectConfig = getProjectConfig();
if (projectConfig == null) {
logger.error("Optimizely instance is not valid, failing getAllFeatureVariableValues call. type");
return null;
}
FeatureFlag featureFlag = projectConfig.getFeatureKeyMapping().get(featureKey);
if (featureFlag == null) {
logger.info("No feature flag was found for key \"{}\".", featureKey);
return null;
}
Map<String, ?> copiedAttributes = copyAttributes(attributes);
FeatureDecision featureDecision = decisionService.getVariationForFeature(featureFlag, createUserContext(userId, copiedAttributes), projectConfig, Collections.emptyList()).getResult();
Boolean featureEnabled = false;
Variation variation = featureDecision.variation;
if (variation != null) {
featureEnabled = variation.getFeatureEnabled();
if (featureEnabled) {
logger.info("Feature \"{}\" is enabled for user \"{}\".", featureKey, userId);
} else {
logger.info("Feature \"{}\" is not enabled for user \"{}\".", featureKey, userId);
}
} else {
logger.info("User \"{}\" was not bucketed into any variation for feature flag \"{}\". " + "The default values are being returned.", userId, featureKey);
}
Map<String, Object> valuesMap = new HashMap<String, Object>();
for (FeatureVariable variable : featureFlag.getVariables()) {
String value = variable.getDefaultValue();
if (featureEnabled) {
FeatureVariableUsageInstance instance = variation.getVariableIdToFeatureVariableUsageInstanceMap().get(variable.getId());
if (instance != null) {
value = instance.getValue();
}
}
Object convertedValue = convertStringToType(value, variable.getType());
if (convertedValue instanceof OptimizelyJSON) {
convertedValue = ((OptimizelyJSON) convertedValue).toMap();
}
valuesMap.put(variable.getKey(), convertedValue);
}
DecisionNotification decisionNotification = DecisionNotification.newFeatureVariableDecisionNotificationBuilder().withUserId(userId).withAttributes(copiedAttributes).withFeatureKey(featureKey).withFeatureEnabled(featureEnabled).withVariableValues(valuesMap).withFeatureDecision(featureDecision).build();
notificationCenter.send(decisionNotification);
return new OptimizelyJSON(valuesMap);
}
use of com.optimizely.ab.optimizelyjson.OptimizelyJSON in project java-sdk by optimizely.
the class Optimizely method decide.
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);
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());
}
Boolean flagEnabled = false;
if (flagDecision.variation != null) {
if (flagDecision.variation.getFeatureEnabled()) {
flagEnabled = true;
}
}
logger.info("Feature \"{}\" is enabled for user \"{}\"? {}", key, userId, flagEnabled);
Map<String, Object> variableMap = new HashMap<>();
if (!allOptions.contains(OptimizelyDecideOption.EXCLUDE_VARIABLES)) {
DecisionResponse<Map<String, Object>> decisionVariables = getDecisionVariableMap(flag, flagDecision.variation, flagEnabled);
variableMap = decisionVariables.getResult();
decisionReasons.merge(decisionVariables.getReasons());
}
OptimizelyJSON optimizelyJSON = new OptimizelyJSON(variableMap);
FeatureDecision.DecisionSource decisionSource = FeatureDecision.DecisionSource.ROLLOUT;
if (flagDecision.decisionSource != null) {
decisionSource = flagDecision.decisionSource;
}
List<String> reasonsToReport = decisionReasons.toReport();
String variationKey = flagDecision.variation != null ? flagDecision.variation.getKey() : null;
// TODO: add ruleKey values when available later. use a copy of experimentKey until then.
// add to event metadata as well (currently set to experimentKey)
String ruleKey = flagDecision.experiment != null ? flagDecision.experiment.getKey() : null;
if (!allOptions.contains(OptimizelyDecideOption.DISABLE_DECISION_EVENT)) {
decisionEventDispatched = sendImpression(projectConfig, flagDecision.experiment, userId, copiedAttributes, flagDecision.variation, key, decisionSource.toString(), flagEnabled);
}
DecisionNotification decisionNotification = DecisionNotification.newFlagDecisionNotificationBuilder().withUserId(userId).withAttributes(copiedAttributes).withFlagKey(key).withEnabled(flagEnabled).withVariables(variableMap).withVariationKey(variationKey).withRuleKey(ruleKey).withReasons(reasonsToReport).withDecisionEventDispatched(decisionEventDispatched).build();
notificationCenter.send(decisionNotification);
return new OptimizelyDecision(variationKey, flagEnabled, optimizelyJSON, ruleKey, key, user, reasonsToReport);
}
use of com.optimizely.ab.optimizelyjson.OptimizelyJSON in project java-sdk by optimizely.
the class OptimizelyDecisionTest method testOptimizelyDecision.
@Test
public void testOptimizelyDecision() {
String variationKey = "var1";
boolean enabled = true;
OptimizelyJSON variables = new OptimizelyJSON("{\"k1\":\"v1\"}");
String ruleKey = null;
String flagKey = "flag1";
OptimizelyUserContext userContext = new OptimizelyUserContext(Optimizely.builder().build(), "tester");
List<String> reasons = new ArrayList<>();
OptimizelyDecision decision = new OptimizelyDecision(variationKey, enabled, variables, ruleKey, flagKey, userContext, reasons);
assertEquals(decision.getVariationKey(), variationKey);
assertEquals(decision.getEnabled(), enabled);
assertEquals(decision.getVariables(), variables);
assertEquals(decision.getRuleKey(), ruleKey);
assertEquals(decision.getFlagKey(), flagKey);
assertEquals(decision.getUserContext(), userContext);
assertEquals(decision.getReasons(), reasons);
}
use of com.optimizely.ab.optimizelyjson.OptimizelyJSON in project java-sdk by optimizely.
the class OptimizelyTest method getFeatureVariableJSONUserInExperimentFeatureOn.
/**
* Verify that the {@link Optimizely#getFeatureVariableJSON(String, String, String, Map)}
* is called when feature is in experiment and feature enabled is true
* returns variable value
*/
@Test
public void getFeatureVariableJSONUserInExperimentFeatureOn() throws Exception {
assumeTrue(datafileVersion >= Integer.parseInt(ProjectConfig.Version.V4.toString()));
final String validFeatureKey = FEATURE_MULTI_VARIATE_FEATURE_KEY;
String validVariableKey = VARIABLE_JSON_PATCHED_TYPE_KEY;
String expectedString = "{\"k1\":\"s1\",\"k2\":103.5,\"k3\":false,\"k4\":{\"kk1\":\"ss1\",\"kk2\":true}}";
Optimizely optimizely = optimizelyBuilder.build();
OptimizelyJSON json = optimizely.getFeatureVariableJSON(validFeatureKey, validVariableKey, testUserId, Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE));
assertTrue(compareJsonStrings(json.toString(), expectedString));
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(json.getValue("k1", String.class), "s1");
assertEquals(json.getValue("k4.kk2", Boolean.class), true);
}
Aggregations