Search in sources :

Example 16 with LogEvent

use of com.optimizely.ab.event.LogEvent in project java-sdk by optimizely.

the class OptimizelyTest method activateWithNullAttributes.

/**
 * Verify that {@link Optimizely#activate(String, String, Map)} ignores null attributes.
 */
@Test
@SuppressFBWarnings(value = "NP_NONNULL_PARAM_VIOLATION", justification = "testing nullness contract violation")
public void activateWithNullAttributes() throws Exception {
    Experiment activatedExperiment = noAudienceProjectConfig.getExperiments().get(0);
    Variation bucketedVariation = activatedExperiment.getVariations().get(0);
    // setup a mock event builder to return expected impression params
    EventBuilder mockEventBuilder = mock(EventBuilder.class);
    Optimizely optimizely = Optimizely.builder(noAudienceDatafile, mockEventHandler).withBucketing(mockBucketer).withEventBuilder(mockEventBuilder).withConfig(noAudienceProjectConfig).withErrorHandler(mockErrorHandler).build();
    Map<String, String> testParams = new HashMap<String, String>();
    testParams.put("test", "params");
    LogEvent logEventToDispatch = new LogEvent(RequestMethod.GET, "test_url", testParams, "");
    when(mockEventBuilder.createImpressionEvent(eq(noAudienceProjectConfig), eq(activatedExperiment), eq(bucketedVariation), eq(testUserId), eq(Collections.<String, String>emptyMap()))).thenReturn(logEventToDispatch);
    when(mockBucketer.bucket(activatedExperiment, testUserId)).thenReturn(bucketedVariation);
    // activate the experiment
    Map<String, String> attributes = null;
    Variation actualVariation = optimizely.activate(activatedExperiment.getKey(), testUserId, attributes);
    logbackVerifier.expectMessage(Level.WARN, "Attributes is null when non-null was expected. Defaulting to an empty attributes map.");
    // verify that the bucketing algorithm was called correctly
    verify(mockBucketer).bucket(activatedExperiment, testUserId);
    assertThat(actualVariation, is(bucketedVariation));
    // setup the attribute map captor (so we can verify its content)
    ArgumentCaptor<Map> attributeCaptor = ArgumentCaptor.forClass(Map.class);
    verify(mockEventBuilder).createImpressionEvent(eq(noAudienceProjectConfig), eq(activatedExperiment), eq(bucketedVariation), eq(testUserId), attributeCaptor.capture());
    Map<String, String> actualValue = attributeCaptor.getValue();
    assertThat(actualValue, is(Collections.<String, String>emptyMap()));
    // verify that dispatchEvent was called with the correct LogEvent object
    verify(mockEventHandler).dispatchEvent(logEventToDispatch);
}
Also used : EventBuilder(com.optimizely.ab.event.internal.EventBuilder) HashMap(java.util.HashMap) LogEvent(com.optimizely.ab.event.LogEvent) Experiment(com.optimizely.ab.config.Experiment) Matchers.anyString(org.mockito.Matchers.anyString) Variation(com.optimizely.ab.config.Variation) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) EventBuilderTest.createExperimentVariationMap(com.optimizely.ab.event.internal.EventBuilderTest.createExperimentVariationMap) Test(org.junit.Test) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 17 with LogEvent

use of com.optimizely.ab.event.LogEvent in project java-sdk by optimizely.

the class OptimizelyTest method activateEndToEnd.

// ======== activate tests ========//
/**
 * Verify that the {@link Optimizely#activate(Experiment, String, Map)} call correctly builds an endpoint url and
 * request params and passes them through {@link EventHandler#dispatchEvent(LogEvent)}.
 */
@Test
public void activateEndToEnd() throws Exception {
    Experiment activatedExperiment;
    Map<String, String> testUserAttributes = new HashMap<String, String>();
    String bucketingKey = testBucketingIdKey;
    String userId = testUserId;
    String bucketingId = testBucketingId;
    if (datafileVersion >= 4) {
        activatedExperiment = validProjectConfig.getExperimentKeyMapping().get(EXPERIMENT_MULTIVARIATE_EXPERIMENT_KEY);
        testUserAttributes.put(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE);
    } else {
        activatedExperiment = validProjectConfig.getExperiments().get(0);
        testUserAttributes.put("browser_type", "chrome");
    }
    testUserAttributes.put(bucketingKey, bucketingId);
    Variation bucketedVariation = activatedExperiment.getVariations().get(0);
    EventBuilder mockEventBuilder = mock(EventBuilder.class);
    Optimizely optimizely = Optimizely.builder(validDatafile, mockEventHandler).withBucketing(mockBucketer).withEventBuilder(mockEventBuilder).withConfig(validProjectConfig).withErrorHandler(mockErrorHandler).build();
    Map<String, String> testParams = new HashMap<String, String>();
    testParams.put("test", "params");
    LogEvent logEventToDispatch = new LogEvent(RequestMethod.GET, "test_url", testParams, "");
    when(mockEventBuilder.createImpressionEvent(validProjectConfig, activatedExperiment, bucketedVariation, testUserId, testUserAttributes)).thenReturn(logEventToDispatch);
    when(mockBucketer.bucket(activatedExperiment, bucketingId)).thenReturn(bucketedVariation);
    logbackVerifier.expectMessage(Level.INFO, "Activating user \"userId\" in experiment \"" + activatedExperiment.getKey() + "\".");
    logbackVerifier.expectMessage(Level.DEBUG, "Dispatching impression event to URL test_url with params " + testParams + " and payload \"\"");
    // activate the experiment
    Variation actualVariation = optimizely.activate(activatedExperiment.getKey(), userId, testUserAttributes);
    // verify that the bucketing algorithm was called correctly
    verify(mockBucketer).bucket(activatedExperiment, bucketingId);
    assertThat(actualVariation, is(bucketedVariation));
    // verify that dispatchEvent was called with the correct LogEvent object
    verify(mockEventHandler).dispatchEvent(logEventToDispatch);
}
Also used : EventBuilder(com.optimizely.ab.event.internal.EventBuilder) HashMap(java.util.HashMap) LogEvent(com.optimizely.ab.event.LogEvent) Experiment(com.optimizely.ab.config.Experiment) Matchers.anyString(org.mockito.Matchers.anyString) Variation(com.optimizely.ab.config.Variation) Test(org.junit.Test)

Example 18 with LogEvent

use of com.optimizely.ab.event.LogEvent in project java-sdk by optimizely.

the class EventFactory method createLogEvent.

public static LogEvent createLogEvent(List<UserEvent> userEvents) {
    EventBatch.Builder builder = new EventBatch.Builder();
    List<Visitor> visitors = new ArrayList<>(userEvents.size());
    for (UserEvent userEvent : userEvents) {
        if (userEvent == null) {
            continue;
        }
        if (userEvent instanceof ImpressionEvent) {
            visitors.add(createVisitor((ImpressionEvent) userEvent));
        }
        if (userEvent instanceof ConversionEvent) {
            visitors.add(createVisitor((ConversionEvent) userEvent));
        }
        // This needs an interface.
        UserContext userContext = userEvent.getUserContext();
        ProjectConfig projectConfig = userContext.getProjectConfig();
        builder.setClientName(ClientEngineInfo.getClientEngine().getClientEngineValue()).setClientVersion(BuildVersionInfo.VERSION).setAccountId(projectConfig.getAccountId()).setAnonymizeIp(projectConfig.getAnonymizeIP()).setProjectId(projectConfig.getProjectId()).setRevision(projectConfig.getRevision());
    }
    if (visitors.isEmpty()) {
        return null;
    }
    builder.setVisitors(visitors);
    return new LogEvent(LogEvent.RequestMethod.POST, EVENT_ENDPOINT, Collections.emptyMap(), builder.build());
}
Also used : ProjectConfig(com.optimizely.ab.config.ProjectConfig) Visitor(com.optimizely.ab.event.internal.payload.Visitor) LogEvent(com.optimizely.ab.event.LogEvent) ArrayList(java.util.ArrayList) EventBatch(com.optimizely.ab.event.internal.payload.EventBatch)

Example 19 with LogEvent

use of com.optimizely.ab.event.LogEvent in project java-sdk by optimizely.

the class EventHandlerRule method dispatchEvent.

@Override
public void dispatchEvent(LogEvent logEvent) {
    logger.info("Receiving event: {}", logEvent);
    actualCalls++;
    List<Visitor> visitors = logEvent.getEventBatch().getVisitors();
    if (visitors == null) {
        return;
    }
    for (Visitor visitor : visitors) {
        for (Snapshot snapshot : visitor.getSnapshots()) {
            List<Decision> decisions = snapshot.getDecisions();
            if (decisions == null) {
                decisions = new ArrayList<>();
            }
            if (decisions.isEmpty()) {
                decisions.add(new Decision());
            }
            for (Decision decision : decisions) {
                for (Event event : snapshot.getEvents()) {
                    CanonicalEvent actual = new CanonicalEvent(decision.getExperimentId(), decision.getVariationId(), event.getKey(), visitor.getVisitorId(), visitor.getAttributes().stream().filter(attribute -> !attribute.getKey().startsWith(RESERVED_ATTRIBUTE_PREFIX)).collect(Collectors.toMap(Attribute::getKey, Attribute::getValue)), event.getTags(), decision.getMetadata());
                    logger.info("Adding dispatched, event: {}", actual);
                    actualEvents.add(actual);
                }
            }
        }
    }
}
Also used : LogEvent(com.optimizely.ab.event.LogEvent)

Example 20 with LogEvent

use of com.optimizely.ab.event.LogEvent in project java-sdk by optimizely.

the class TrackNotificationListener method notify.

/**
 * Base notify called with var args.  This method parses the parameters and calls the abstract method.
 *
 * @param args - variable argument list based on the type of notification.
 *
 * @deprecated by {@link TrackNotificationListener#handle(TrackNotification)}
 */
@Override
@Deprecated
public final void notify(Object... args) {
    assert (args[0] instanceof String);
    String eventKey = (String) args[0];
    assert (args[1] instanceof String);
    String userId = (String) args[1];
    Map<String, ?> attributes = null;
    if (args[2] != null) {
        assert (args[2] instanceof java.util.Map);
        attributes = (Map<String, ?>) args[2];
    }
    Map<String, ?> eventTags = null;
    if (args[3] != null) {
        assert (args[3] instanceof java.util.Map);
        eventTags = (Map<String, ?>) args[3];
    }
    assert (args[4] instanceof LogEvent);
    LogEvent logEvent = (LogEvent) args[4];
    onTrack(eventKey, userId, attributes, eventTags, logEvent);
}
Also used : LogEvent(com.optimizely.ab.event.LogEvent) Map(java.util.Map)

Aggregations

LogEvent (com.optimizely.ab.event.LogEvent)66 Test (org.junit.Test)58 Experiment (com.optimizely.ab.config.Experiment)37 Variation (com.optimizely.ab.config.Variation)34 EventBatch (com.optimizely.ab.event.internal.payload.EventBatch)32 HashMap (java.util.HashMap)25 EventType (com.optimizely.ab.config.EventType)23 EventBuilder (com.optimizely.ab.event.internal.EventBuilder)21 Matchers.anyString (org.mockito.Matchers.anyString)21 ControlAttribute (com.optimizely.ab.internal.ControlAttribute)17 Map (java.util.Map)14 ImmutableMap (com.google.common.collect.ImmutableMap)11 Bucketer (com.optimizely.ab.bucketing.Bucketer)11 EventBuilderTest.createExperimentVariationMap (com.optimizely.ab.event.internal.EventBuilderTest.createExperimentVariationMap)11 ProjectConfig (com.optimizely.ab.config.ProjectConfig)10 Attribute (com.optimizely.ab.config.Attribute)9 Decision (com.optimizely.ab.event.internal.payload.Decision)9 DecisionService (com.optimizely.ab.bucketing.DecisionService)8 UserProfileService (com.optimizely.ab.bucketing.UserProfileService)6 NoOpErrorHandler (com.optimizely.ab.error.NoOpErrorHandler)6