This repository was archived by the owner on Jul 10, 2024. It is now read-only.
forked from dstendardi/snowplow-java-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBatchEmitter.java
More file actions
85 lines (69 loc) · 2.45 KB
/
Copy pathBatchEmitter.java
File metadata and controls
85 lines (69 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package com.snowplowanalytics.snowplow.tracker.emitter;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.snowplowanalytics.snowplow.tracker.Constants;
import com.snowplowanalytics.snowplow.tracker.http.HttpClientAdapter;
import com.snowplowanalytics.snowplow.tracker.payload.SchemaPayload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* An emitter that emit a batch of events in a single call
* It uses the post method of under-laying http adapter
*/
public class BatchEmitter extends AbstractEmitter implements Closeable {
private static final Logger LOGGER = LoggerFactory.getLogger(BatchEmitter.class);
private int bufferSize = 10;
private List<Map<String,Object>> buffer = new ArrayList<Map<String,Object>>();
public BatchEmitter(HttpClientAdapter httpClientAdapter) {
super(httpClientAdapter);
}
@Override
public synchronized void emit(Map<String, Object> payload) {
buffer.add(payload);
if (buffer.size() >= bufferSize) {
flushBuffer();
}
}
/**
* Flush buffer when buffer
* reaches com.snowplowanalytics.snowplow.tracker.emitter.BatchEmitter#bufferSize
*/
void flushBuffer() {
if (buffer.isEmpty()) {
LOGGER.debug("Buffer is empty, exiting flush operation..");
return;
}
final List<Map<String, Object>> toSendPayloads = Lists.newArrayList(buffer);
buffer.clear();
final SchemaPayload selfDescribedJson = new SchemaPayload();
selfDescribedJson.setSchema(Constants.SCHEMA_PAYLOAD_DATA);
selfDescribedJson.setData(toSendPayloads);
try {
httpClientAdapter.post(selfDescribedJson);
} catch (Exception e) {
throw new RuntimeException(String.format("Failed to emit %d events", toSendPayloads.size()));
}
}
@Override
public void close() {
flushBuffer();
}
/**
* Customize the bxzzuffer sizxe
*
* @param bufferSize number of events to collect
*/
public void setBufferSize(int bufferSize) {
Preconditions.checkArgument(bufferSize > 0);
this.bufferSize = bufferSize;
}
@VisibleForTesting
public List<Map<String, Object>> getBuffer() {
return buffer;
}
}