use of com.optimizely.ab.config.Attribute in project java-sdk by optimizely.
the class EventBuilderTest method createImpressionEvent.
/**
* Verify {@link com.optimizely.ab.event.internal.payload.EventBatch} event creation
*/
@Test
public void createImpressionEvent() throws Exception {
// use the "valid" project config and its associated experiment, variation, and attributes
ProjectConfig projectConfig = validProjectConfigV2();
Experiment activatedExperiment = projectConfig.getExperiments().get(0);
Variation bucketedVariation = activatedExperiment.getVariations().get(0);
Attribute attribute = projectConfig.getAttributes().get(0);
String userId = "userId";
Map<String, String> attributeMap = Collections.singletonMap(attribute.getKey(), "value");
Decision expectedDecision = new Decision(activatedExperiment.getLayerId(), activatedExperiment.getId(), bucketedVariation.getId(), false);
com.optimizely.ab.event.internal.payload.Attribute feature = new com.optimizely.ab.event.internal.payload.Attribute(attribute.getId(), attribute.getKey(), com.optimizely.ab.event.internal.payload.Attribute.CUSTOM_ATTRIBUTE_TYPE, "value");
List<com.optimizely.ab.event.internal.payload.Attribute> expectedUserFeatures = Collections.singletonList(feature);
LogEvent impressionEvent = builder.createImpressionEvent(projectConfig, activatedExperiment, bucketedVariation, userId, attributeMap);
// verify that request endpoint is correct
assertThat(impressionEvent.getEndpointUrl(), is(EventBuilder.EVENT_ENDPOINT));
EventBatch eventBatch = gson.fromJson(impressionEvent.getBody(), EventBatch.class);
// verify payload information
assertThat(eventBatch.getVisitors().get(0).getVisitorId(), is(userId));
assertThat((double) eventBatch.getVisitors().get(0).getSnapshots().get(0).getEvents().get(0).getTimestamp(), closeTo((double) System.currentTimeMillis(), 1000.0));
assertFalse(eventBatch.getVisitors().get(0).getSnapshots().get(0).getDecisions().get(0).getIsCampaignHoldback());
assertThat(eventBatch.getAnonymizeIp(), is(projectConfig.getAnonymizeIP()));
assertThat(eventBatch.getProjectId(), is(projectConfig.getProjectId()));
assertThat(eventBatch.getVisitors().get(0).getSnapshots().get(0).getDecisions().get(0), is(expectedDecision));
assertThat(eventBatch.getVisitors().get(0).getSnapshots().get(0).getDecisions().get(0).getCampaignId(), is(activatedExperiment.getLayerId()));
assertThat(eventBatch.getAccountId(), is(projectConfig.getAccountId()));
assertThat(eventBatch.getVisitors().get(0).getAttributes(), is(expectedUserFeatures));
assertThat(eventBatch.getClientName(), is(EventBatch.ClientEngine.JAVA_SDK.getClientEngineValue()));
assertThat(eventBatch.getClientVersion(), is(BuildVersionInfo.VERSION));
assertNull(eventBatch.getVisitors().get(0).getSessionId());
}
use of com.optimizely.ab.config.Attribute in project java-sdk by optimizely.
the class EventBuilderTest method createConversionEvent.
/**
* Verify {@link com.optimizely.ab.event.internal.payload.EventBatch} event creation
*/
@Test
public void createConversionEvent() throws Exception {
// use the "valid" project config and its associated experiment, variation, and attributes
Attribute attribute = validProjectConfig.getAttributes().get(0);
EventType eventType = validProjectConfig.getEventTypes().get(0);
String userId = "userId";
Bucketer mockBucketAlgorithm = mock(Bucketer.class);
List<Experiment> allExperiments = validProjectConfig.getExperiments();
List<Experiment> experimentsForEventKey = validProjectConfig.getExperimentsForEventKey(eventType.getKey());
// call the bucket function.
for (Experiment experiment : allExperiments) {
when(mockBucketAlgorithm.bucket(experiment, userId)).thenReturn(experiment.getVariations().get(0));
}
DecisionService decisionService = new DecisionService(mockBucketAlgorithm, mock(ErrorHandler.class), validProjectConfig, mock(UserProfileService.class));
Map<String, String> attributeMap = Collections.singletonMap(attribute.getKey(), AUDIENCE_GRYFFINDOR_VALUE);
Map<String, Object> eventTagMap = new HashMap<String, Object>();
eventTagMap.put("boolean_param", false);
eventTagMap.put("string_param", "123");
Map<Experiment, Variation> experimentVariationMap = createExperimentVariationMap(validProjectConfig, decisionService, eventType.getKey(), userId, attributeMap);
LogEvent conversionEvent = builder.createConversionEvent(validProjectConfig, experimentVariationMap, userId, eventType.getId(), eventType.getKey(), attributeMap, eventTagMap);
List<Decision> expectedDecisions = new ArrayList<Decision>();
for (Experiment experiment : experimentsForEventKey) {
if (experiment.isRunning()) {
Decision layerState = new Decision(experiment.getLayerId(), experiment.getId(), experiment.getVariations().get(0).getId(), false);
expectedDecisions.add(layerState);
}
}
// verify that the request endpoint is correct
assertThat(conversionEvent.getEndpointUrl(), is(EventBuilder.EVENT_ENDPOINT));
EventBatch conversion = gson.fromJson(conversionEvent.getBody(), EventBatch.class);
// verify payload information
assertThat(conversion.getVisitors().get(0).getVisitorId(), is(userId));
assertThat((double) conversion.getVisitors().get(0).getSnapshots().get(0).getEvents().get(0).getTimestamp(), closeTo((double) System.currentTimeMillis(), 120.0));
assertThat(conversion.getProjectId(), is(validProjectConfig.getProjectId()));
assertThat(conversion.getAccountId(), is(validProjectConfig.getAccountId()));
com.optimizely.ab.event.internal.payload.Attribute feature = new com.optimizely.ab.event.internal.payload.Attribute(attribute.getId(), attribute.getKey(), com.optimizely.ab.event.internal.payload.Attribute.CUSTOM_ATTRIBUTE_TYPE, AUDIENCE_GRYFFINDOR_VALUE);
List<com.optimizely.ab.event.internal.payload.Attribute> expectedUserFeatures = Collections.singletonList(feature);
assertEquals(conversion.getVisitors().get(0).getAttributes(), expectedUserFeatures);
assertThat(conversion.getVisitors().get(0).getSnapshots().get(0).getDecisions(), containsInAnyOrder(expectedDecisions.toArray()));
assertEquals(conversion.getVisitors().get(0).getSnapshots().get(0).getEvents().get(0).getEntityId(), eventType.getId());
assertEquals(conversion.getVisitors().get(0).getSnapshots().get(0).getEvents().get(0).getKey(), eventType.getKey());
assertEquals(conversion.getVisitors().get(0).getSnapshots().get(0).getEvents().get(0).getRevenue(), null);
assertTrue(conversion.getVisitors().get(0).getAttributes().containsAll(expectedUserFeatures));
assertTrue(conversion.getVisitors().get(0).getSnapshots().get(0).getEvents().get(0).getTags().equals(eventTagMap));
assertFalse(conversion.getVisitors().get(0).getSnapshots().get(0).getDecisions().get(0).getIsCampaignHoldback());
assertEquals(conversion.getAnonymizeIp(), validProjectConfig.getAnonymizeIP());
assertEquals(conversion.getClientName(), EventBatch.ClientEngine.JAVA_SDK.getClientEngineValue());
assertEquals(conversion.getClientVersion(), BuildVersionInfo.VERSION);
}
use of com.optimizely.ab.config.Attribute in project java-sdk by optimizely.
the class OptimizelyTest method trackEventWithListenerAttributes.
/**
* Add notificaiton listener for track {@link com.optimizely.ab.notification.NotificationCenter}. Verify called and
* remove.
* @throws Exception
*/
@Test
@SuppressWarnings("unchecked")
public void trackEventWithListenerAttributes() throws Exception {
final Attribute attribute = validProjectConfig.getAttributes().get(0);
final EventType eventType;
if (datafileVersion >= 4) {
eventType = validProjectConfig.getEventNameMapping().get(EVENT_BASIC_EVENT_KEY);
} else {
eventType = validProjectConfig.getEventTypes().get(0);
}
// setup a mock event builder to return expected conversion params
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");
final Map<String, String> attributes = ImmutableMap.of(attribute.getKey(), "attributeValue");
Map<Experiment, Variation> experimentVariationMap = createExperimentVariationMap(validProjectConfig, mockDecisionService, eventType.getKey(), genericUserId, attributes);
LogEvent logEventToDispatch = new LogEvent(RequestMethod.GET, "test_url", testParams, "");
when(mockEventBuilder.createConversionEvent(eq(validProjectConfig), eq(experimentVariationMap), eq(genericUserId), eq(eventType.getId()), eq(eventType.getKey()), anyMapOf(String.class, String.class), eq(Collections.<String, Object>emptyMap()))).thenReturn(logEventToDispatch);
logbackVerifier.expectMessage(Level.INFO, "Tracking event \"" + eventType.getKey() + "\" for user \"" + genericUserId + "\".");
logbackVerifier.expectMessage(Level.DEBUG, "Dispatching conversion event to URL test_url with params " + testParams + " and payload \"\"");
TrackNotificationListener trackNotification = new TrackNotificationListener() {
@Override
public void onTrack(@Nonnull String eventKey, @Nonnull String userId, @Nonnull Map<String, String> _attributes, @Nonnull Map<String, ?> eventTags, @Nonnull LogEvent event) {
assertEquals(eventType.getKey(), eventKey);
assertEquals(genericUserId, userId);
assertEquals(attributes, _attributes);
assertTrue(eventTags.isEmpty());
}
};
int notificationId = optimizely.notificationCenter.addNotificationListener(NotificationCenter.NotificationType.Track, trackNotification);
// call track
optimizely.track(eventType.getKey(), genericUserId, attributes);
optimizely.notificationCenter.removeNotificationListener(notificationId);
// setup the attribute map captor (so we can verify its content)
ArgumentCaptor<Map> attributeCaptor = ArgumentCaptor.forClass(Map.class);
// verify that the event builder was called with the expected attributes
verify(mockEventBuilder).createConversionEvent(eq(validProjectConfig), eq(experimentVariationMap), eq(genericUserId), eq(eventType.getId()), eq(eventType.getKey()), attributeCaptor.capture(), eq(Collections.<String, Object>emptyMap()));
Map<String, String> actualValue = attributeCaptor.getValue();
assertThat(actualValue, hasEntry(attribute.getKey(), "attributeValue"));
verify(mockEventHandler).dispatchEvent(logEventToDispatch);
}
use of com.optimizely.ab.config.Attribute in project java-sdk by optimizely.
the class ProjectConfigGsonDeserializer method deserialize.
@Override
public ProjectConfig deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
String accountId = jsonObject.get("accountId").getAsString();
String projectId = jsonObject.get("projectId").getAsString();
String revision = jsonObject.get("revision").getAsString();
String version = jsonObject.get("version").getAsString();
int datafileVersion = Integer.parseInt(version);
// generic list type tokens
Type groupsType = new TypeToken<List<Group>>() {
}.getType();
Type experimentsType = new TypeToken<List<Experiment>>() {
}.getType();
Type attributesType = new TypeToken<List<Attribute>>() {
}.getType();
Type eventsType = new TypeToken<List<EventType>>() {
}.getType();
Type audienceType = new TypeToken<List<Audience>>() {
}.getType();
List<Group> groups = context.deserialize(jsonObject.get("groups").getAsJsonArray(), groupsType);
List<Experiment> experiments = context.deserialize(jsonObject.get("experiments").getAsJsonArray(), experimentsType);
List<Attribute> attributes;
attributes = context.deserialize(jsonObject.get("attributes"), attributesType);
List<EventType> events = context.deserialize(jsonObject.get("events").getAsJsonArray(), eventsType);
List<Audience> audiences = context.deserialize(jsonObject.get("audiences").getAsJsonArray(), audienceType);
boolean anonymizeIP = false;
// live variables should be null if using V2
List<LiveVariable> liveVariables = null;
if (datafileVersion >= Integer.parseInt(ProjectConfig.Version.V3.toString())) {
Type liveVariablesType = new TypeToken<List<LiveVariable>>() {
}.getType();
liveVariables = context.deserialize(jsonObject.getAsJsonArray("variables"), liveVariablesType);
anonymizeIP = jsonObject.get("anonymizeIP").getAsBoolean();
}
List<FeatureFlag> featureFlags = null;
List<Rollout> rollouts = null;
if (datafileVersion >= Integer.parseInt(ProjectConfig.Version.V4.toString())) {
Type featureFlagsType = new TypeToken<List<FeatureFlag>>() {
}.getType();
featureFlags = context.deserialize(jsonObject.getAsJsonArray("featureFlags"), featureFlagsType);
Type rolloutsType = new TypeToken<List<Rollout>>() {
}.getType();
rollouts = context.deserialize(jsonObject.get("rollouts").getAsJsonArray(), rolloutsType);
}
return new ProjectConfig(accountId, anonymizeIP, projectId, revision, version, attributes, audiences, events, experiments, featureFlags, groups, liveVariables, rollouts);
}
use of com.optimizely.ab.config.Attribute in project java-sdk by optimizely.
the class JsonSimpleConfigParser method parseAttributes.
private List<Attribute> parseAttributes(JSONArray attributeJson) {
List<Attribute> attributes = new ArrayList<Attribute>(attributeJson.size());
for (Object obj : attributeJson) {
JSONObject attributeObject = (JSONObject) obj;
String id = (String) attributeObject.get("id");
String key = (String) attributeObject.get("key");
String segmentId = (String) attributeObject.get("segmentId");
attributes.add(new Attribute(id, key, segmentId));
}
return attributes;
}
Aggregations