+
+ public void clear() {
+ messages.clear();
+ }
+
+ public static List<Object> getAllMessages(ActorRef actor) throws Exception {
+ FiniteDuration operationDuration = Duration.create(5, TimeUnit.SECONDS);
+ Timeout operationTimeout = new Timeout(operationDuration);
+ Future<Object> future = Patterns.ask(actor, "get-all-messages", operationTimeout);
+
+ return (List<Object>) Await.result(future, operationDuration);
+ }
+
+ /**
+ * Get the first message that matches the specified class
+ * @param actor
+ * @param clazz
+ * @return
+ */
+ public static <T> T getFirstMatching(ActorRef actor, Class<T> clazz) throws Exception {
+ List<Object> allMessages = getAllMessages(actor);
+
+ for(Object message : allMessages){
+ if(message.getClass().equals(clazz)){
+ return (T) message;
+ }
+ }
+
+ return null;
+ }
+
+ public static <T> T expectFirstMatching(ActorRef actor, Class<T> clazz) {
+ return expectFirstMatching(actor, clazz, 5000);
+ }
+
+ public static <T> T expectFirstMatching(ActorRef actor, Class<T> clazz, long timeout) {
+ int count = (int) (timeout / 50);
+ for(int i = 0; i < count; i++) {
+ try {
+ T message = getFirstMatching(actor, clazz);
+ if(message != null) {
+ return message;
+ }
+ } catch (Exception e) {}
+
+ Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
+ }
+
+ Assert.fail("Did not receive message of type " + clazz);
+ return null;
+ }
+
+ public static <T> List<T> getAllMatching(ActorRef actor, Class<T> clazz) throws Exception {
+ List<Object> allMessages = getAllMessages(actor);
+
+ List<T> output = Lists.newArrayList();
+
+ for(Object message : allMessages){
+ if(message.getClass().equals(clazz)){
+ output.add((T) message);
+ }
+ }
+
+ return output;
+ }
+
+ public static void waitUntilReady(ActorRef actor) throws Exception {
+ long timeout = 500;
+ FiniteDuration duration = Duration.create(timeout, TimeUnit.MILLISECONDS);
+ for(int i = 0; i < 10; i++) {
+ try {
+ Await.ready(Patterns.ask(actor, ARE_YOU_READY, timeout), duration);
+ return;
+ } catch (TimeoutException e) {
+ }
+ }
+
+ throw new TimeoutException("Actor not ready in time.");
+ }
+
+ public static Props props() {
+ return Props.create(MessageCollectorActor.class);
+ }