Skip to content

Commit 8351d57

Browse files
author
Tanooj Luthra
committed
Added event listener for stream position changes
1 parent e59b051 commit 8351d57

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

src/main/java/com/box/sdk/EventListener.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ public interface EventListener {
1010
*/
1111
void onEvent(BoxEvent event);
1212

13+
/**
14+
* Invoked when an updated stream position is received from the API.
15+
* @param position of the stream.
16+
*/
17+
void onNextPosition(long position);
18+
1319
/**
1420
* Invoked when an error occurs while waiting for events to be received.
1521
*

src/main/java/com/box/sdk/EventStream.java

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,14 @@ protected boolean isDuplicate(String eventID) {
131131
return !this.receivedEvents.add(eventID);
132132
}
133133

134+
private void notifyNextPosition(long position) {
135+
synchronized (this.listenerLock) {
136+
for (EventListener listener : this.listeners) {
137+
listener.onNextPosition(position);
138+
}
139+
}
140+
}
141+
134142
private void notifyEvent(BoxEvent event) {
135143
synchronized (this.listenerLock) {
136144
boolean isDuplicate = this.isDuplicate(event.getID());
@@ -184,12 +192,13 @@ public void run() {
184192
EVENT_URL.build(EventStream.this.api.getBaseURL(), position), "GET");
185193
BoxJSONResponse response = (BoxJSONResponse) request.send();
186194
JsonObject jsonObject = JsonObject.readFrom(response.getJSON());
187-
position = jsonObject.get("next_stream_position").asLong();
188195
JsonArray entriesArray = jsonObject.get("entries").asArray();
189196
for (JsonValue entry : entriesArray) {
190197
BoxEvent event = new BoxEvent(EventStream.this.api, entry.asObject());
191198
EventStream.this.notifyEvent(event);
192199
}
200+
position = jsonObject.get("next_stream_position").asLong();
201+
EventStream.this.notifyNextPosition(position);
193202
}
194203
}
195204
}

src/test/java/com/box/sdk/EventStreamTest.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,17 @@ public void receiveEventsForFolderCreateAndFolderDelete() throws InterruptedExce
3333
BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken());
3434
EventStream stream = new EventStream(api);
3535
stream.addListener(new EventListener() {
36+
@Override
3637
public void onEvent(BoxEvent event) {
3738
observedEvents.add(event);
3839
}
3940

41+
@Override
42+
public void onNextPosition(long position) {
43+
return;
44+
}
45+
46+
@Override
4047
public boolean onException(Throwable e) {
4148
return true;
4249
}

0 commit comments

Comments
 (0)