Skip to content

Commit

Permalink
Allow EventListeners to handle exceptions
Browse files Browse the repository at this point in the history
Any uncaught exceptions on the EventStream's polling thread will be sent
to the EventStream listeners through the onException(Throwable e)
method. The exception will be sent to each listener (in the order in
which they were added) until one of them returns true, indicating that
the exception was handled.
  • Loading branch information
gcurtis committed Sep 11, 2014
1 parent 9496aba commit 77fb254
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/main/java/com/box/sdk/EventListener.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@

public interface EventListener {
void onEvent(BoxEvent event);

boolean onException(Throwable e);
}
19 changes: 18 additions & 1 deletion src/main/java/com/box/sdk/EventStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,13 @@ public void start() {
final long initialPosition = jsonObject.get("next_stream_position").asLong();
this.poller = new Poller(initialPosition);

new Thread(this.poller).start();
Thread pollerThread = new Thread(this.poller);
pollerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
EventStream.this.notifyException(e);
}
});
pollerThread.start();

this.started = true;
}
Expand All @@ -74,6 +80,17 @@ private void notifyListeners(BoxEvent event) {
}
}

private void notifyException(Throwable e) {
this.stop();
synchronized (this.listenerLock) {
for (EventListener listener : this.listeners) {
if (listener.onException(e)) {
return;
}
}
}
}

private class Poller implements Runnable {
private final long initialPosition;
private final Object setServerLock;
Expand Down
4 changes: 4 additions & 0 deletions src/test/java/com/box/sdk/EventStreamTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ public void receiveEventsForFolderCreateAndFolderDelete() throws InterruptedExce
public void onEvent(BoxEvent event) {
observedEvents.add(event);
}

public boolean onException(Throwable e) {
return true;
}
});
stream.start();

Expand Down

0 comments on commit 77fb254

Please sign in to comment.