From 77fb254d698a55de286fa115407f9c8ee8a9588e Mon Sep 17 00:00:00 2001 From: Greg Curtis Date: Thu, 11 Sep 2014 14:54:04 -0700 Subject: [PATCH] Allow EventListeners to handle exceptions 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. --- src/main/java/com/box/sdk/EventListener.java | 2 ++ src/main/java/com/box/sdk/EventStream.java | 19 ++++++++++++++++++- .../java/com/box/sdk/EventStreamTest.java | 4 ++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/box/sdk/EventListener.java b/src/main/java/com/box/sdk/EventListener.java index 30db92bbc..edd862e93 100644 --- a/src/main/java/com/box/sdk/EventListener.java +++ b/src/main/java/com/box/sdk/EventListener.java @@ -2,4 +2,6 @@ public interface EventListener { void onEvent(BoxEvent event); + + boolean onException(Throwable e); } diff --git a/src/main/java/com/box/sdk/EventStream.java b/src/main/java/com/box/sdk/EventStream.java index ed2493df5..ce13c5ab4 100644 --- a/src/main/java/com/box/sdk/EventStream.java +++ b/src/main/java/com/box/sdk/EventStream.java @@ -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; } @@ -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; diff --git a/src/test/java/com/box/sdk/EventStreamTest.java b/src/test/java/com/box/sdk/EventStreamTest.java index c95b21e57..a001e17e0 100644 --- a/src/test/java/com/box/sdk/EventStreamTest.java +++ b/src/test/java/com/box/sdk/EventStreamTest.java @@ -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();