Search in sources :

Example 6 with Variation

use of com.optimizely.ab.config.Variation in project java-sdk by optimizely.

the class DecisionServiceTest method getVariationBucketingId.

@Test
public void getVariationBucketingId() throws Exception {
    Bucketer bucketer = mock(Bucketer.class);
    DecisionService decisionService = spy(new DecisionService(bucketer, mockErrorHandler, validProjectConfig, null));
    Experiment experiment = validProjectConfig.getExperiments().get(0);
    Variation expectedVariation = experiment.getVariations().get(0);
    when(bucketer.bucket(experiment, "bucketId")).thenReturn(expectedVariation);
    Map<String, String> attr = new HashMap<String, String>();
    attr.put(DecisionService.BUCKETING_ATTRIBUTE, "bucketId");
    // user excluded without audiences and whitelisting
    assertThat(decisionService.getVariation(experiment, genericUserId, attr), is(expectedVariation));
}
Also used : HashMap(java.util.HashMap) Experiment(com.optimizely.ab.config.Experiment) Matchers.anyString(org.mockito.Matchers.anyString) Variation(com.optimizely.ab.config.Variation) Test(org.junit.Test)

Example 7 with Variation

use of com.optimizely.ab.config.Variation in project java-sdk by optimizely.

the class Optimizely method track.

public void track(@Nonnull String eventName, @Nonnull String userId, @Nonnull Map<String, String> attributes, @Nonnull Map<String, ?> eventTags) throws UnknownEventTypeException {
    ProjectConfig currentConfig = getProjectConfig();
    EventType eventType = getEventTypeOrThrow(currentConfig, eventName);
    if (eventType == null) {
        // if no matching event type could be found, do not dispatch an event
        logger.info("Not tracking event \"{}\" for user \"{}\".", eventName, userId);
        return;
    }
    // determine whether all the given attributes are present in the project config. If not, filter out the unknown
    // attributes.
    Map<String, String> filteredAttributes = filterAttributes(currentConfig, attributes);
    if (eventTags == null) {
        logger.warn("Event tags is null when non-null was expected. Defaulting to an empty event tags map.");
        eventTags = Collections.<String, String>emptyMap();
    }
    List<Experiment> experimentsForEvent = projectConfig.getExperimentsForEventKey(eventName);
    Map<Experiment, Variation> experimentVariationMap = new HashMap<Experiment, Variation>(experimentsForEvent.size());
    for (Experiment experiment : experimentsForEvent) {
        if (experiment.isRunning()) {
            Variation variation = decisionService.getVariation(experiment, userId, filteredAttributes);
            if (variation != null) {
                experimentVariationMap.put(experiment, variation);
            }
        } else {
            logger.info("Not tracking event \"{}\" for experiment \"{}\" because experiment has status \"Launched\".", eventType.getKey(), experiment.getKey());
        }
    }
    // create the conversion event request parameters, then dispatch
    LogEvent conversionEvent = eventBuilder.createConversionEvent(projectConfig, experimentVariationMap, userId, eventType.getId(), eventType.getKey(), filteredAttributes, eventTags);
    if (conversionEvent == null) {
        logger.info("There are no valid experiments for event \"{}\" to track.", eventName);
        logger.info("Not tracking event \"{}\" for user \"{}\".", eventName, userId);
        return;
    }
    logger.info("Tracking event \"{}\" for user \"{}\".", eventName, userId);
    logger.debug("Dispatching conversion event to URL {} with params {} and payload \"{}\".", conversionEvent.getEndpointUrl(), conversionEvent.getRequestParams(), conversionEvent.getBody());
    try {
        eventHandler.dispatchEvent(conversionEvent);
    } catch (Exception e) {
        logger.error("Unexpected exception in event dispatcher", e);
    }
    notificationCenter.sendNotifications(NotificationCenter.NotificationType.Track, eventName, userId, filteredAttributes, eventTags, conversionEvent);
}
Also used : ProjectConfig(com.optimizely.ab.config.ProjectConfig) EventType(com.optimizely.ab.config.EventType) HashMap(java.util.HashMap) LogEvent(com.optimizely.ab.event.LogEvent) Experiment(com.optimizely.ab.config.Experiment) Variation(com.optimizely.ab.config.Variation) ConfigParseException(com.optimizely.ab.config.parser.ConfigParseException)

Example 8 with Variation

use of com.optimizely.ab.config.Variation in project java-sdk by optimizely.

the class GroupJacksonDeserializer method parseExperiment.

private Experiment parseExperiment(JsonNode experimentJson, String groupId) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    String id = experimentJson.get("id").textValue();
    String key = experimentJson.get("key").textValue();
    String status = experimentJson.get("status").textValue();
    JsonNode layerIdJson = experimentJson.get("layerId");
    String layerId = layerIdJson == null ? null : layerIdJson.textValue();
    List<String> audienceIds = mapper.readValue(experimentJson.get("audienceIds").toString(), new TypeReference<List<String>>() {
    });
    List<Variation> variations = mapper.readValue(experimentJson.get("variations").toString(), new TypeReference<List<Variation>>() {
    });
    List<TrafficAllocation> trafficAllocations = mapper.readValue(experimentJson.get("trafficAllocation").toString(), new TypeReference<List<TrafficAllocation>>() {
    });
    Map<String, String> userIdToVariationKeyMap = mapper.readValue(experimentJson.get("forcedVariations").toString(), new TypeReference<Map<String, String>>() {
    });
    return new Experiment(id, key, status, layerId, audienceIds, variations, userIdToVariationKeyMap, trafficAllocations, groupId);
}
Also used : Experiment(com.optimizely.ab.config.Experiment) JsonNode(com.fasterxml.jackson.databind.JsonNode) TrafficAllocation(com.optimizely.ab.config.TrafficAllocation) ArrayList(java.util.ArrayList) List(java.util.List) Variation(com.optimizely.ab.config.Variation) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 9 with Variation

use of com.optimizely.ab.config.Variation in project java-sdk by optimizely.

the class DecisionService method getStoredVariation.

/**
 * Get the {@link Variation} that has been stored for the user in the {@link UserProfileService} implementation.
 * @param experiment {@link Experiment} in which the user was bucketed.
 * @param userProfile {@link UserProfile} of the user.
 * @return null if the {@link UserProfileService} implementation is null or the user was not previously bucketed.
 *      else return the {@link Variation} the user was previously bucketed into.
 */
@Nullable
Variation getStoredVariation(@Nonnull Experiment experiment, @Nonnull UserProfile userProfile) {
    // ---------- Check User Profile for Sticky Bucketing ----------
    // If a user profile instance is present then check it for a saved variation
    String experimentId = experiment.getId();
    String experimentKey = experiment.getKey();
    Decision decision = userProfile.experimentBucketMap.get(experimentId);
    if (decision != null) {
        String variationId = decision.variationId;
        Variation savedVariation = projectConfig.getExperimentIdMapping().get(experimentId).getVariationIdToVariationMap().get(variationId);
        if (savedVariation != null) {
            logger.info("Returning previously activated variation \"{}\" of experiment \"{}\" " + "for user \"{}\" from user profile.", savedVariation.getKey(), experimentKey, userProfile.userId);
            // A variation is stored for this combined bucket id
            return savedVariation;
        } else {
            logger.info("User \"{}\" was previously bucketed into variation with ID \"{}\" for experiment \"{}\", " + "but no matching variation was found for that user. We will re-bucket the user.", userProfile.userId, variationId, experimentKey);
            return null;
        }
    } else {
        logger.info("No previously activated variation of experiment \"{}\" " + "for user \"{}\" found in user profile.", experimentKey, userProfile.userId);
        return null;
    }
}
Also used : Variation(com.optimizely.ab.config.Variation) Nullable(javax.annotation.Nullable)

Example 10 with Variation

use of com.optimizely.ab.config.Variation in project java-sdk by optimizely.

the class Optimizely method activate.

@Nullable
private Variation activate(@Nonnull ProjectConfig projectConfig, @Nonnull Experiment experiment, @Nonnull String userId, @Nonnull Map<String, String> attributes) {
    // determine whether all the given attributes are present in the project config. If not, filter out the unknown
    // attributes.
    Map<String, String> filteredAttributes = filterAttributes(projectConfig, attributes);
    // bucket the user to the given experiment and dispatch an impression event
    Variation variation = decisionService.getVariation(experiment, userId, filteredAttributes);
    if (variation == null) {
        logger.info("Not activating user \"{}\" for experiment \"{}\".", userId, experiment.getKey());
        return null;
    }
    sendImpression(projectConfig, experiment, userId, filteredAttributes, variation);
    return variation;
}
Also used : Variation(com.optimizely.ab.config.Variation) Nullable(javax.annotation.Nullable)

Aggregations

Variation (com.optimizely.ab.config.Variation)81 Experiment (com.optimizely.ab.config.Experiment)77 Test (org.junit.Test)68 LogEvent (com.optimizely.ab.event.LogEvent)39 HashMap (java.util.HashMap)37 Matchers.anyString (org.mockito.Matchers.anyString)37 EventBuilder (com.optimizely.ab.event.internal.EventBuilder)21 EventType (com.optimizely.ab.config.EventType)20 Map (java.util.Map)14 EventBatch (com.optimizely.ab.event.internal.payload.EventBatch)12 ImmutableMap (com.google.common.collect.ImmutableMap)11 EventBuilderTest.createExperimentVariationMap (com.optimizely.ab.event.internal.EventBuilderTest.createExperimentVariationMap)11 Bucketer (com.optimizely.ab.bucketing.Bucketer)9 Attribute (com.optimizely.ab.config.Attribute)9 ProjectConfig (com.optimizely.ab.config.ProjectConfig)9 Rollout (com.optimizely.ab.config.Rollout)7 NoOpErrorHandler (com.optimizely.ab.error.NoOpErrorHandler)7 DecisionService (com.optimizely.ab.bucketing.DecisionService)6 UserProfileService (com.optimizely.ab.bucketing.UserProfileService)6 ArrayList (java.util.ArrayList)6