Skip to content

Commit 4dbefaf

Browse files
authored
feat: support init SDK with custom configuration (#75)
1 parent eff7fe2 commit 4dbefaf

23 files changed

+566
-487
lines changed

README.md

+36-8
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Clickstream Android SDK supports Android 4.1 (API level 16) and later.
1616

1717
## Integrate SDK
1818

19-
**1.Include SDK**
19+
### 1. Include SDK
2020

2121
Add the following dependency to your `app` module's `build.gradle` file.
2222

@@ -28,7 +28,7 @@ dependencies {
2828

2929
then sync your project, if you have problem to build your app, please check [troubleshooting](#Troubleshooting)
3030

31-
**2.Parameter configuration**
31+
### 2. Parameter configuration
3232

3333
Find the res directory under your `project/app/src/main` , and manually create a raw folder in the res directory.
3434

@@ -41,7 +41,7 @@ Download your `amplifyconfiguration.json` file from your clickstream control pla
4141
"analytics": {
4242
"plugins": {
4343
"awsClickstreamPlugin": {
44-
"appId": "appId",
44+
"appId": "your appId",
4545
"endpoint": "https://example.com/collect",
4646
"isCompressEvents": true,
4747
"autoFlushEventsInterval": 10000,
@@ -60,16 +60,16 @@ Your `appId` and `endpoint` are already set up in it, here's an explanation of e
6060
- **autoFlushEventsInterval**: event sending interval, the default is `10s`
6161
- **isTrackAppExceptionEvents**: whether auto track exception event in app, default is `false`
6262

63-
**3.Initialize the SDK**
63+
### 3. Initialize the SDK
6464

65-
It is recommended that you initialize the SDK in the Application `onCreate()` method. Please note that the initialization code needs to run in the main thread.
65+
It is recommended that you initialize the SDK in your application's `onCreate()` method. Please note that the initialization code needs to run in the main thread.
6666

67+
#### 3.1 Initialize the SDK with default configuration
6768
```java
6869
import software.aws.solution.clickstream.ClickstreamAnalytics;
6970

7071
public void onCreate() {
7172
super.onCreate();
72-
7373
try{
7474
ClickstreamAnalytics.init(getApplicationContext());
7575
Log.i("MyApp", "Initialized ClickstreamAnalytics");
@@ -78,10 +78,36 @@ public void onCreate() {
7878
}
7979
}
8080
```
81+
#### 3.2 Initialize the SDK with global attributes and custom configuration
82+
```java
83+
import software.aws.solution.clickstream.ClickstreamAnalytics;
84+
85+
public void onCreate() {
86+
super.onCreate();
87+
try{
88+
ClickstreamAttribute globalAttributes = ClickstreamAttribute.builder()
89+
.add("_traffic_source_name", "Summer promotion")
90+
.add("_traffic_source_medium", "Search engine")
91+
.build();
92+
ClickstreamConfiguration configuration = new ClickstreamConfiguration()
93+
.withAppId("your appId")
94+
.withEndpoint("http://example.com/collect")
95+
.withLogEvents(true)
96+
.withInitialGlobalAttributes(globalAttributes);
97+
ClickstreamAnalytics.init(getApplicationContext(), configuration);
98+
Log.i("MyApp", "Initialized ClickstreamAnalytics");
99+
} catch (AmplifyException error){
100+
Log.e("MyApp", "Could not initialize ClickstreamAnalytics", error);
101+
}
102+
}
103+
```
104+
By default, we will use the configurations in `amplifyconfiguration.json` file. If you add a custom configuration, the added configuration items will override the default values.
81105

82-
**4.Config the SDK**
106+
You can also add all the configuration parameters you need in the `init` method without using the `amplifyconfiguration.json` file.
83107

84-
After initial the SDK we can use the following code to custom configure it.
108+
### 4. Update Configuration
109+
110+
After initial the SDK we can use the following code to up configure it.
85111

86112
```java
87113
import software.aws.solution.clickstream.ClickstreamAnalytics;
@@ -146,6 +172,8 @@ ClickstreamAnalytics.addGlobalAttributes(globalAttribute);
146172
ClickstreamAnalytics.deleteGlobalAttributes("level");
147173
```
148174

175+
It is recommended to set global attributes when initializing the SDK, global attributes will be included in all events that occur after it is set.
176+
149177
#### Login and logout
150178

151179
```java

build.gradle

+1
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ ext {
6666
okhttp: 'com.squareup.okhttp3:okhttp:4.9.1',
6767
junit: 'junit:junit:4.13.2',
6868
mockito: 'org.mockito:mockito-core:4.11.0',
69+
mockitoinline: 'org.mockito:mockito-inline:4.11.0',
6970
moco: 'com.github.dreamhead:moco-core:1.4.0',
7071
robolectric: 'org.robolectric:robolectric:4.9.2',
7172
]

clickstream/build.gradle

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ dependencies {
2525

2626
testImplementation dependency.junit
2727
testImplementation dependency.mockito
28+
testImplementation dependency.mockitoinline
2829
testImplementation dependency.robolectric
2930
testImplementation dependency.androidx.test
3031
testImplementation dependency.moco

clickstream/src/main/java/software/aws/solution/clickstream/AWSClickstreamPlugin.java

+60-91
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,13 @@
3737
import software.aws.solution.clickstream.client.Event;
3838

3939
import java.util.Map;
40+
import java.util.Objects;
4041

4142
/**
4243
* The plugin implementation for Clickstream in Analytics category.
4344
*/
4445
public final class AWSClickstreamPlugin extends AnalyticsPlugin<Object> {
45-
46+
static final String PLUGIN_KEY = "awsClickstreamPlugin";
4647
private static final Log LOG = LogFactory.getLog(AWSClickstreamPlugin.class);
4748
private final Context context;
4849
private AnalyticsClient analyticsClient;
@@ -63,12 +64,10 @@ public AWSClickstreamPlugin(final Context context) {
6364
@Override
6465
public void identifyUser(@NonNull String userId, @Nullable UserProfile profile) {
6566
if (userId.equals(Event.ReservedAttribute.USER_ID_UNSET)) {
66-
if (profile instanceof ClickstreamUserAttribute) {
67-
for (Map.Entry<String, AnalyticsPropertyBehavior<?>> entry :
68-
((ClickstreamUserAttribute) profile).getUserAttributes()) {
69-
AnalyticsPropertyBehavior<?> property = entry.getValue();
70-
analyticsClient.addUserAttribute(entry.getKey(), property.getValue());
71-
}
67+
for (Map.Entry<String, AnalyticsPropertyBehavior<?>> entry :
68+
((ClickstreamUserAttribute) Objects.requireNonNull(profile)).getUserAttributes()) {
69+
AnalyticsPropertyBehavior<?> property = entry.getValue();
70+
analyticsClient.addUserAttribute(entry.getKey(), property.getValue());
7271
}
7372
} else {
7473
analyticsClient.updateUserId(userId);
@@ -114,11 +113,9 @@ public void recordEvent(@NonNull AnalyticsEventBehavior analyticsEvent) {
114113
analyticsClient.createEvent(event.getName());
115114

116115
if (clickstreamEvent != null) {
117-
if (analyticsEvent.getProperties() != null) {
118-
for (Map.Entry<String, AnalyticsPropertyBehavior<?>> entry : analyticsEvent.getProperties()) {
119-
AnalyticsPropertyBehavior<?> property = entry.getValue();
120-
clickstreamEvent.addAttribute(entry.getKey(), property.getValue());
121-
}
116+
for (Map.Entry<String, AnalyticsPropertyBehavior<?>> entry : analyticsEvent.getProperties()) {
117+
AnalyticsPropertyBehavior<?> property = entry.getValue();
118+
clickstreamEvent.addAttribute(entry.getKey(), property.getValue());
122119
}
123120
clickstreamEvent.addItems(event.getItems());
124121
recordAnalyticsEvent(clickstreamEvent);
@@ -156,7 +153,7 @@ public void flushEvents() {
156153
@NonNull
157154
@Override
158155
public String getPluginKey() {
159-
return "awsClickstreamPlugin";
156+
return PLUGIN_KEY;
160157
}
161158

162159
@Override
@@ -171,31 +168,46 @@ public void configure(
171168
getPluginKey() + " under the analytics category."
172169
);
173170
}
174-
175-
AWSClickstreamPluginConfiguration.Builder configurationBuilder =
176-
AWSClickstreamPluginConfiguration.builder();
177-
171+
ClickstreamConfiguration configuration = ClickstreamConfiguration.getDefaultConfiguration();
178172
// Read all the data from the configuration object to be used for record event
179173
try {
180-
configurationBuilder.withAppId(pluginConfiguration
181-
.getString(ConfigurationKey.APP_ID.getConfigurationKey()));
174+
configuration.withAppId(pluginConfiguration.getString(ConfigurationKey.APP_ID));
175+
configuration.withEndpoint(pluginConfiguration
176+
.getString(ConfigurationKey.ENDPOINT));
182177

183-
configurationBuilder.withEndpoint(pluginConfiguration
184-
.getString(ConfigurationKey.ENDPOINT.getConfigurationKey()));
185-
186-
if (pluginConfiguration.has(ConfigurationKey.SEND_EVENTS_INTERVAL.getConfigurationKey())) {
187-
configurationBuilder.withSendEventsInterval(pluginConfiguration
188-
.getLong(ConfigurationKey.SEND_EVENTS_INTERVAL.getConfigurationKey()));
178+
if (pluginConfiguration.has(ConfigurationKey.SEND_EVENTS_INTERVAL)) {
179+
configuration.withSendEventsInterval(pluginConfiguration
180+
.getLong(ConfigurationKey.SEND_EVENTS_INTERVAL));
189181
}
190-
191-
if (pluginConfiguration.has(ConfigurationKey.COMPRESS_EVENTS.getConfigurationKey())) {
192-
configurationBuilder.withCompressEvents(
193-
pluginConfiguration.getBoolean(ConfigurationKey.COMPRESS_EVENTS.getConfigurationKey()));
182+
if (pluginConfiguration.has(ConfigurationKey.IS_COMPRESS_EVENTS)) {
183+
configuration.withCompressEvents(
184+
pluginConfiguration.getBoolean(ConfigurationKey.IS_COMPRESS_EVENTS));
194185
}
195-
196-
if (pluginConfiguration.has(ConfigurationKey.TRACK_APP_EXCEPTION_EVENTS.getConfigurationKey())) {
197-
configurationBuilder.withTrackAppExceptionEvents(pluginConfiguration
198-
.getBoolean(ConfigurationKey.TRACK_APP_EXCEPTION_EVENTS.getConfigurationKey()));
186+
if (pluginConfiguration.has(ConfigurationKey.IS_TRACK_APP_EXCEPTION_EVENTS)) {
187+
configuration.withTrackAppExceptionEvents(pluginConfiguration
188+
.getBoolean(ConfigurationKey.IS_TRACK_APP_EXCEPTION_EVENTS));
189+
}
190+
if (pluginConfiguration.has(ConfigurationKey.IS_LOG_EVENTS)) {
191+
configuration.withLogEvents(pluginConfiguration.getBoolean(ConfigurationKey.IS_LOG_EVENTS));
192+
}
193+
if (pluginConfiguration.has(ConfigurationKey.IS_TRACK_SCREEN_VIEW_EVENTS)) {
194+
configuration.withTrackScreenViewEvents(
195+
pluginConfiguration.getBoolean(ConfigurationKey.IS_TRACK_SCREEN_VIEW_EVENTS));
196+
}
197+
if (pluginConfiguration.has(ConfigurationKey.IS_TRACK_USER_ENGAGEMENT_EVENTS)) {
198+
configuration.withTrackUserEngagementEvents(
199+
pluginConfiguration.getBoolean(ConfigurationKey.IS_TRACK_USER_ENGAGEMENT_EVENTS));
200+
}
201+
if (pluginConfiguration.has(ConfigurationKey.SESSION_TIMEOUT_DURATION)) {
202+
configuration.withSessionTimeoutDuration(
203+
pluginConfiguration.getLong(ConfigurationKey.SESSION_TIMEOUT_DURATION));
204+
}
205+
if (pluginConfiguration.has(ConfigurationKey.AUTH_COOKIE)) {
206+
configuration.withAuthCookie(pluginConfiguration.getString(ConfigurationKey.AUTH_COOKIE));
207+
}
208+
if (pluginConfiguration.has(ConfigurationKey.GLOBAL_ATTRIBUTES)) {
209+
configuration.withInitialGlobalAttributes(
210+
(ClickstreamAttribute) pluginConfiguration.get(ConfigurationKey.GLOBAL_ATTRIBUTES));
199211
}
200212
} catch (JSONException exception) {
201213
throw new AnalyticsException(
@@ -204,16 +216,10 @@ public void configure(
204216
"Please take a look at the documentation for expected format of amplifyconfiguration.json."
205217
);
206218
}
207-
208-
AWSClickstreamPluginConfiguration clickstreamPluginConfiguration = configurationBuilder.build();
209-
clickstreamManager = ClickstreamManagerFactory.create(
210-
context,
211-
clickstreamPluginConfiguration
212-
);
219+
clickstreamManager = new ClickstreamManager(context, configuration);
213220
this.analyticsClient = clickstreamManager.getAnalyticsClient();
214221

215-
LOG.debug("AWSClickstreamPlugin create AutoEventSubmitter.");
216-
autoEventSubmitter = new AutoEventSubmitter(clickstreamPluginConfiguration.getSendEventsInterval());
222+
autoEventSubmitter = new AutoEventSubmitter(configuration.getSendEventsInterval());
217223
autoEventSubmitter.start();
218224

219225
activityLifecycleManager = new ActivityLifecycleManager(clickstreamManager);
@@ -232,57 +238,20 @@ public String getVersion() {
232238
}
233239

234240
/**
235-
* Clickstream configuration in amplifyconfiguration.json contains following values.
241+
* The Clickstream configuration keys.
236242
*/
237-
public enum ConfigurationKey {
238-
239-
/**
240-
* The Clickstream appId.
241-
*/
242-
APP_ID("appId"),
243-
244-
/**
245-
* the Clickstream Endpoint.
246-
*/
247-
ENDPOINT("endpoint"),
248-
249-
/**
250-
* Time interval after which the events are automatically submitted to server.
251-
*/
252-
SEND_EVENTS_INTERVAL("sendEventsInterval"),
253-
254-
/**
255-
* Whether to compress events.
256-
*/
257-
COMPRESS_EVENTS("isCompressEvents"),
258-
259-
/**
260-
* Whether to track app exception events automatically.
261-
*/
262-
TRACK_APP_EXCEPTION_EVENTS("isTrackAppExceptionEvents");
263-
264-
/**
265-
* The key this property is listed under in the config JSON.
266-
*/
267-
private final String configurationKey;
268-
269-
/**
270-
* Construct the enum with the config key.
271-
*
272-
* @param configurationKey The key this property is listed under in the config JSON.
273-
*/
274-
ConfigurationKey(final String configurationKey) {
275-
this.configurationKey = configurationKey;
276-
}
277-
278-
/**
279-
* Returns the key this property is listed under in the config JSON.
280-
*
281-
* @return The key as a string
282-
*/
283-
public String getConfigurationKey() {
284-
return configurationKey;
285-
}
243+
static class ConfigurationKey {
244+
static final String APP_ID = "appId";
245+
static final String ENDPOINT = "endpoint";
246+
static final String SEND_EVENTS_INTERVAL = "autoFlushEventsInterval";
247+
static final String IS_COMPRESS_EVENTS = "isCompressEvents";
248+
static final String IS_LOG_EVENTS = "isLogEvents";
249+
static final String AUTH_COOKIE = "authCookie";
250+
static final String SESSION_TIMEOUT_DURATION = "sessionTimeoutDuration";
251+
static final String IS_TRACK_APP_EXCEPTION_EVENTS = "isTrackAppExceptionEvents";
252+
static final String IS_TRACK_SCREEN_VIEW_EVENTS = "isTrackScreenViewEvents";
253+
static final String IS_TRACK_USER_ENGAGEMENT_EVENTS = "isTrackUserEngagementEvents";
254+
static final String GLOBAL_ATTRIBUTES = "globalAttributes";
286255
}
287256
}
288257

0 commit comments

Comments
 (0)