Search in sources :

Example 1 with OptimizelyJSON

use of com.optimizely.ab.optimizelyjson.OptimizelyJSON in project java-sdk by optimizely.

the class Optimizely method getFeatureVariableValueForType.

@VisibleForTesting
<T> T getFeatureVariableValueForType(@Nonnull String featureKey, @Nonnull String variableKey, @Nonnull String userId, @Nonnull Map<String, ?> attributes, @Nonnull String variableType) {
    if (featureKey == null) {
        logger.warn("The featureKey parameter must be nonnull.");
        return null;
    } else if (variableKey == null) {
        logger.warn("The variableKey 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 getFeatureVariableValueForType call. type: {}", variableType);
        return null;
    }
    FeatureFlag featureFlag = projectConfig.getFeatureKeyMapping().get(featureKey);
    if (featureFlag == null) {
        logger.info("No feature flag was found for key \"{}\".", featureKey);
        return null;
    }
    FeatureVariable variable = featureFlag.getVariableKeyToFeatureVariableMap().get(variableKey);
    if (variable == null) {
        logger.info("No feature variable was found for key \"{}\" in feature flag \"{}\".", variableKey, featureKey);
        return null;
    } else if (!variable.getType().equals(variableType)) {
        logger.info("The feature variable \"" + variableKey + "\" is actually of type \"" + variable.getType().toString() + "\" type. You tried to access it as type \"" + variableType.toString() + "\". Please use the appropriate feature variable accessor.");
        return null;
    }
    String variableValue = variable.getDefaultValue();
    Map<String, ?> copiedAttributes = copyAttributes(attributes);
    FeatureDecision featureDecision = decisionService.getVariationForFeature(featureFlag, createUserContext(userId, copiedAttributes), projectConfig).getResult();
    Boolean featureEnabled = false;
    if (featureDecision.variation != null) {
        if (featureDecision.variation.getFeatureEnabled()) {
            FeatureVariableUsageInstance featureVariableUsageInstance = featureDecision.variation.getVariableIdToFeatureVariableUsageInstanceMap().get(variable.getId());
            if (featureVariableUsageInstance != null) {
                variableValue = featureVariableUsageInstance.getValue();
                logger.info("Got variable value \"{}\" for variable \"{}\" of feature flag \"{}\".", variableValue, variableKey, featureKey);
            } else {
                variableValue = variable.getDefaultValue();
                logger.info("Value is not defined for variable \"{}\". Returning default value \"{}\".", variableKey, variableValue);
            }
        } else {
            logger.info("Feature \"{}\" is not enabled for user \"{}\". " + "Returning the default variable value \"{}\".", featureKey, userId, variableValue);
        }
        featureEnabled = featureDecision.variation.getFeatureEnabled();
    } else {
        logger.info("User \"{}\" was not bucketed into any variation for feature flag \"{}\". " + "The default value \"{}\" for \"{}\" is being returned.", userId, featureKey, variableValue, variableKey);
    }
    Object convertedValue = convertStringToType(variableValue, variableType);
    Object notificationValue = convertedValue;
    if (convertedValue instanceof OptimizelyJSON) {
        notificationValue = ((OptimizelyJSON) convertedValue).toMap();
    }
    DecisionNotification decisionNotification = DecisionNotification.newFeatureVariableDecisionNotificationBuilder().withUserId(userId).withAttributes(copiedAttributes).withFeatureKey(featureKey).withFeatureEnabled(featureEnabled).withVariableKey(variableKey).withVariableType(variableType).withVariableValue(notificationValue).withFeatureDecision(featureDecision).build();
    notificationCenter.send(decisionNotification);
    return (T) convertedValue;
}
Also used : OptimizelyJSON(com.optimizely.ab.optimizelyjson.OptimizelyJSON) FeatureDecision(com.optimizely.ab.bucketing.FeatureDecision) VisibleForTesting(com.optimizely.ab.annotations.VisibleForTesting)

Example 2 with OptimizelyJSON

use of com.optimizely.ab.optimizelyjson.OptimizelyJSON in project java-sdk by optimizely.

the class Example method processVisitor.

private void processVisitor(String userId, Map<String, Object> attributes) {
    OptimizelyUserContext user = optimizely.createUserContext(userId, attributes);
    OptimizelyDecision decision = user.decide("eet_feature");
    String variationKey = decision.getVariationKey();
    if (variationKey != null) {
        boolean enabled = decision.getEnabled();
        System.out.println("[Example] feature enabled: " + enabled);
        OptimizelyJSON variables = decision.getVariables();
        System.out.println("[Example] feature variables: " + variables.toString());
        user.trackEvent("eet_conversion");
    } else {
        System.out.println("[Example] decision failed: " + decision.getReasons().toString());
    }
}
Also used : OptimizelyJSON(com.optimizely.ab.optimizelyjson.OptimizelyJSON) OptimizelyDecision(com.optimizely.ab.optimizelydecision.OptimizelyDecision) OptimizelyUserContext(com.optimizely.ab.OptimizelyUserContext)

Example 3 with OptimizelyJSON

use of com.optimizely.ab.optimizelyjson.OptimizelyJSON in project java-sdk by optimizely.

the class OptimizelyTest method getFeatureVariableJSONWithListenerUserInExperimentFeatureOn.

/**
 * Verify that the {@link Optimizely#getFeatureVariableJSON(String, String, String, Map)}
 * notification listener of getFeatureVariableString is called when feature is in experiment and feature is true
 */
@Test
public void getFeatureVariableJSONWithListenerUserInExperimentFeatureOn() throws Exception {
    assumeTrue(datafileVersion >= Integer.parseInt(ProjectConfig.Version.V4.toString()));
    isListenerCalled = false;
    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();
    final Map<String, String> testUserAttributes = new HashMap<>();
    testUserAttributes.put(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE);
    final Map<String, String> testSourceInfo = new HashMap<>();
    testSourceInfo.put(EXPERIMENT_KEY, "multivariate_experiment");
    testSourceInfo.put(VARIATION_KEY, "Fred");
    final Map<String, Object> testDecisionInfoMap = new HashMap<>();
    testDecisionInfoMap.put(FEATURE_KEY, validFeatureKey);
    testDecisionInfoMap.put(FEATURE_ENABLED, true);
    testDecisionInfoMap.put(VARIABLE_KEY, validVariableKey);
    testDecisionInfoMap.put(VARIABLE_TYPE, FeatureVariable.JSON_TYPE);
    testDecisionInfoMap.put(VARIABLE_VALUE, parseJsonString(expectedString));
    testDecisionInfoMap.put(SOURCE, FeatureDecision.DecisionSource.FEATURE_TEST.toString());
    testDecisionInfoMap.put(SOURCE_INFO, testSourceInfo);
    int notificationId = optimizely.addDecisionNotificationHandler(getDecisionListener(NotificationCenter.DecisionNotificationType.FEATURE_VARIABLE.toString(), testUserId, testUserAttributes, testDecisionInfoMap));
    OptimizelyJSON json = optimizely.getFeatureVariableJSON(validFeatureKey, validVariableKey, testUserId, Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE));
    assertTrue(compareJsonStrings(json.toString(), expectedString));
    // Verify that listener being called
    assertTrue(isListenerCalled);
    assertTrue(optimizely.notificationCenter.removeNotificationListener(notificationId));
}
Also used : OptimizelyJSON(com.optimizely.ab.optimizelyjson.OptimizelyJSON) Test(org.junit.Test)

Example 4 with OptimizelyJSON

use of com.optimizely.ab.optimizelyjson.OptimizelyJSON in project java-sdk by optimizely.

the class OptimizelyTest method getAllFeatureVariablesUserInExperimentFeatureOff.

/**
 * Verify that the {@link Optimizely#getAllFeatureVariables(String, String, Map)}
 * is called when feature is in experiment and feature enabled is false
 * than default value will gets returned
 */
@SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION")
@Test
public void getAllFeatureVariablesUserInExperimentFeatureOff() throws Exception {
    assumeTrue(datafileVersion >= Integer.parseInt(ProjectConfig.Version.V4.toString()));
    final String validFeatureKey = FEATURE_MULTI_VARIATE_FEATURE_KEY;
    String expectedString = "{\"first_letter\":\"H\",\"rest_of_name\":\"arry\",\"json_patched\":{\"k1\":\"v1\",\"k2\":3.5,\"k3\":true,\"k4\":{\"kk1\":\"vv1\",\"kk2\":false}}}";
    String userID = "Gred";
    Optimizely optimizely = optimizelyBuilder.build();
    OptimizelyJSON json = optimizely.getAllFeatureVariables(validFeatureKey, userID, null);
    assertTrue(compareJsonStrings(json.toString(), expectedString));
    assertEquals(json.toMap().get("first_letter"), "H");
    assertEquals(json.toMap().get("rest_of_name"), "arry");
    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(json.getValue("first_letter", String.class), "H");
    assertEquals(json.getValue("json_patched.k1", String.class), "v1");
    assertEquals(json.getValue("json_patched.k4.kk2", Boolean.class), false);
}
Also used : OptimizelyJSON(com.optimizely.ab.optimizelyjson.OptimizelyJSON) ImmutableMap(com.google.common.collect.ImmutableMap) Test(org.junit.Test) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 5 with OptimizelyJSON

use of com.optimizely.ab.optimizelyjson.OptimizelyJSON in project java-sdk by optimizely.

the class OptimizelyTest method getAllFeatureVariablesUserInExperimentFeatureOn.

/**
 * Verify that the {@link Optimizely#getAllFeatureVariables(String,String, Map)}
 * is called when feature is in experiment and feature enabled is true
 * returns variable value
 */
@Test
public void getAllFeatureVariablesUserInExperimentFeatureOn() throws Exception {
    assumeTrue(datafileVersion >= Integer.parseInt(ProjectConfig.Version.V4.toString()));
    final String validFeatureKey = FEATURE_MULTI_VARIATE_FEATURE_KEY;
    String expectedString = "{\"first_letter\":\"F\",\"rest_of_name\":\"red\",\"json_patched\":{\"k1\":\"s1\",\"k2\":103.5,\"k3\":false,\"k4\":{\"kk1\":\"ss1\",\"kk2\":true}}}";
    Optimizely optimizely = optimizelyBuilder.build();
    OptimizelyJSON json = optimizely.getAllFeatureVariables(validFeatureKey, testUserId, Collections.singletonMap(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE));
    assertTrue(compareJsonStrings(json.toString(), expectedString));
    assertEquals(json.toMap().get("first_letter"), "F");
    assertEquals(json.toMap().get("rest_of_name"), "red");
    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(json.getValue("first_letter", String.class), "F");
    assertEquals(json.getValue("json_patched.k1", String.class), "s1");
    assertEquals(json.getValue("json_patched.k4.kk2", Boolean.class), true);
}
Also used : OptimizelyJSON(com.optimizely.ab.optimizelyjson.OptimizelyJSON) ImmutableMap(com.google.common.collect.ImmutableMap) Test(org.junit.Test)

Aggregations

OptimizelyJSON (com.optimizely.ab.optimizelyjson.OptimizelyJSON)21 Test (org.junit.Test)17 OptimizelyDecision (com.optimizely.ab.optimizelydecision.OptimizelyDecision)9 ForwardingEventProcessor (com.optimizely.ab.event.ForwardingEventProcessor)5 FlagDecisionNotificationBuilder (com.optimizely.ab.notification.DecisionNotification.FlagDecisionNotificationBuilder)5 DecisionMetadata (com.optimizely.ab.event.internal.payload.DecisionMetadata)4 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)4 FeatureDecision (com.optimizely.ab.bucketing.FeatureDecision)3 ImmutableMap (com.google.common.collect.ImmutableMap)2 OptimizelyUserContext (com.optimizely.ab.OptimizelyUserContext)2 VisibleForTesting (com.optimizely.ab.annotations.VisibleForTesting)1 ArrayList (java.util.ArrayList)1 Nullable (javax.annotation.Nullable)1