2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.cluster.datastore.utils;
11 import akka.actor.ActorRef;
12 import akka.actor.UntypedActor;
13 import akka.pattern.Patterns;
14 import akka.util.Timeout;
15 import com.google.common.collect.Lists;
16 import com.google.common.util.concurrent.Uninterruptibles;
17 import java.util.ArrayList;
18 import java.util.List;
19 import java.util.concurrent.TimeUnit;
20 import org.junit.Assert;
21 import scala.concurrent.Await;
22 import scala.concurrent.Future;
23 import scala.concurrent.duration.Duration;
24 import scala.concurrent.duration.FiniteDuration;
27 * MessageCollectorActor collects messages as it receives them. It can send
28 * those collected messages to any sender which sends it the "messages" message
30 * This class would be useful as a mock to test whether messages were sent
31 * to a remote actor or not.
34 public class MessageCollectorActor extends UntypedActor {
35 private final List<Object> messages = new ArrayList<>();
37 @Override public void onReceive(Object message) throws Exception {
38 if(message instanceof String){
39 if("messages".equals(message)){
40 getSender().tell(new ArrayList<>(messages), getSelf());
43 messages.add(message);
51 public static List<Object> getAllMessages(ActorRef actor) throws Exception {
52 FiniteDuration operationDuration = Duration.create(5, TimeUnit.SECONDS);
53 Timeout operationTimeout = new Timeout(operationDuration);
54 Future<Object> future = Patterns.ask(actor, "messages", operationTimeout);
57 return (List<Object>) Await.result(future, operationDuration);
58 } catch (Exception e) {
64 * Get the first message that matches the specified class
69 public static Object getFirstMatching(ActorRef actor, Class<?> clazz) throws Exception {
70 List<Object> allMessages = getAllMessages(actor);
72 for(Object message : allMessages){
73 if(message.getClass().equals(clazz)){
81 public static List<Object> getAllMatching(ActorRef actor, Class<?> clazz) throws Exception {
82 List<Object> allMessages = getAllMessages(actor);
84 List<Object> output = Lists.newArrayList();
86 for(Object message : allMessages){
87 if(message.getClass().equals(clazz)){
95 public static <T> T expectFirstMatching(ActorRef actor, Class<T> clazz) {
96 int count = 5000 / 50;
97 for(int i = 0; i < count; i++) {
99 T message = (T) getFirstMatching(actor, clazz);
100 if(message != null) {
103 } catch (Exception e) {}
105 Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
108 Assert.fail("Did not receive message of type " + clazz);