9
9
import com .segment .analytics .internal .AnalyticsVersion ;
10
10
import com .segment .analytics .messages .Message ;
11
11
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 .*;
17
14
import java .util .concurrent .ExecutorService ;
18
15
import java .util .concurrent .ThreadFactory ;
19
16
import java .util .concurrent .TimeUnit ;
@@ -45,6 +42,7 @@ public class Analytics {
45
42
private final List <MessageTransformer > messageTransformers ;
46
43
private final List <MessageInterceptor > messageInterceptors ;
47
44
private final Log log ;
45
+ private Map <String , Object > externalContext ;
48
46
49
47
Analytics (
50
48
AnalyticsClient client ,
@@ -55,6 +53,7 @@ public class Analytics {
55
53
this .messageTransformers = messageTransformers ;
56
54
this .messageInterceptors = messageInterceptors ;
57
55
this .log = log ;
56
+ this .externalContext = null ;
58
57
}
59
58
60
59
/**
@@ -114,7 +113,11 @@ private Message buildMessage(MessageBuilder builder) {
114
113
return null ;
115
114
}
116
115
}
116
+
117
+ Map <String , Object > newContext = this .existExternalContext (builder .build ());
118
+ builder .context (newContext );
117
119
Message message = builder .build ();
120
+
118
121
for (MessageInterceptor messageInterceptor : messageInterceptors ) {
119
122
message = messageInterceptor .intercept (message );
120
123
if (message == null ) {
@@ -125,6 +128,26 @@ private Message buildMessage(MessageBuilder builder) {
125
128
return message ;
126
129
}
127
130
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
+
128
151
/** Fluent API for creating {@link Analytics} instances. */
129
152
public static class Builder {
130
153
private static final String DEFAULT_ENDPOINT = "https://api.segment.io" ;
0 commit comments