Skip to content

Commit 471f8f8

Browse files
committed
Add methods to add new context on Message
1 parent a7641c5 commit 471f8f8

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

analytics/src/main/java/com/segment/analytics/Analytics.java

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,8 @@
99
import com.segment.analytics.internal.AnalyticsVersion;
1010
import com.segment.analytics.messages.Message;
1111
import com.segment.analytics.messages.MessageBuilder;
12-
import java.util.ArrayList;
13-
import java.util.Arrays;
14-
import java.util.Collections;
15-
import java.util.Date;
16-
import java.util.List;
12+
13+
import java.util.*;
1714
import java.util.concurrent.ExecutorService;
1815
import java.util.concurrent.ThreadFactory;
1916
import java.util.concurrent.TimeUnit;
@@ -45,6 +42,7 @@ public class Analytics {
4542
private final List<MessageTransformer> messageTransformers;
4643
private final List<MessageInterceptor> messageInterceptors;
4744
private final Log log;
45+
private Map<String, Object> externalContext;
4846

4947
Analytics(
5048
AnalyticsClient client,
@@ -55,6 +53,7 @@ public class Analytics {
5553
this.messageTransformers = messageTransformers;
5654
this.messageInterceptors = messageInterceptors;
5755
this.log = log;
56+
this.externalContext = null;
5857
}
5958

6059
/**
@@ -114,7 +113,11 @@ private Message buildMessage(MessageBuilder builder) {
114113
return null;
115114
}
116115
}
116+
117+
Map<String, Object> newContext = this.existExternalContext(builder.build());
118+
builder.context(newContext);
117119
Message message = builder.build();
120+
118121
for (MessageInterceptor messageInterceptor : messageInterceptors) {
119122
message = messageInterceptor.intercept(message);
120123
if (message == null) {
@@ -125,6 +128,26 @@ private Message buildMessage(MessageBuilder builder) {
125128
return message;
126129
}
127130

131+
private void addExternalContext(String contextKey, Object contextValue) {
132+
this.externalContext = new HashMap<>();
133+
this.externalContext.put(contextKey, contextValue);
134+
}
135+
136+
private Map<String, Object> existExternalContext(Message message) {
137+
138+
// Retrieve the existing context if it exists
139+
Map<String, ?> existingContext = message.context();
140+
if (existingContext == null) {
141+
existingContext = new HashMap<>();
142+
}
143+
144+
// Augment the existing context with new context
145+
Map<String, Object> newContext = new HashMap<>(existingContext);
146+
newContext.putAll(this.externalContext);
147+
148+
return newContext;
149+
}
150+
128151
/** Fluent API for creating {@link Analytics} instances. */
129152
public static class Builder {
130153
private static final String DEFAULT_ENDPOINT = "https://api.segment.io";

0 commit comments

Comments
 (0)