e947aede3b7bec14bec92abeb6ae77e33c68c2d8
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / test / java / org / opendaylight / controller / cluster / raft / utils / MessageCollectorActor.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.cluster.raft.utils;
10
11 import akka.actor.ActorRef;
12 import akka.actor.Props;
13 import akka.actor.UntypedActor;
14 import akka.pattern.Patterns;
15 import akka.util.Timeout;
16 import com.google.common.base.Predicate;
17 import com.google.common.base.Predicates;
18 import com.google.common.base.Throwables;
19 import com.google.common.collect.Iterables;
20 import com.google.common.collect.Lists;
21 import com.google.common.util.concurrent.Uninterruptibles;
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.List;
25 import java.util.concurrent.TimeUnit;
26 import java.util.concurrent.TimeoutException;
27 import org.junit.Assert;
28 import scala.concurrent.Await;
29 import scala.concurrent.Future;
30 import scala.concurrent.duration.Duration;
31 import scala.concurrent.duration.FiniteDuration;
32
33 public class MessageCollectorActor extends UntypedActor {
34     private static final String ARE_YOU_READY = "ARE_YOU_READY";
35     public static final String GET_ALL_MESSAGES = "messages";
36     private static final String CLEAR_MESSAGES = "clear-messages";
37
38     private final List<Object> messages = new ArrayList<>();
39
40     @Override public void onReceive(Object message) throws Exception {
41         if (message.equals(ARE_YOU_READY)) {
42             getSender().tell("yes", getSelf());
43             return;
44         }
45
46         if (GET_ALL_MESSAGES.equals(message)) {
47             getSender().tell(new ArrayList<>(messages), getSelf());
48         } else if (CLEAR_MESSAGES.equals(message)) {
49             clear();
50         } else if (message != null) {
51             messages.add(message);
52         }
53     }
54
55     public void clear() {
56         messages.clear();
57     }
58
59     @SuppressWarnings("unchecked")
60     private static List<Object> getAllMessages(ActorRef actor) throws Exception {
61         FiniteDuration operationDuration = Duration.create(5, TimeUnit.SECONDS);
62         Timeout operationTimeout = new Timeout(operationDuration);
63         Future<Object> future = Patterns.ask(actor, GET_ALL_MESSAGES, operationTimeout);
64
65         return (List<Object>) Await.result(future, operationDuration);
66     }
67
68     public static void clearMessages(ActorRef actor) {
69         actor.tell(CLEAR_MESSAGES, ActorRef.noSender());
70     }
71
72     /**
73      * Get the first message that matches the specified class.
74      *
75      * @param actor the MessageCollectorActor reference
76      * @param clazz the class to match
77      * @return the first matching message
78      */
79     public static <T> T getFirstMatching(ActorRef actor, Class<T> clazz) throws Exception {
80         List<Object> allMessages = getAllMessages(actor);
81
82         for (Object message : allMessages) {
83             if (message.getClass().equals(clazz)) {
84                 return clazz.cast(message);
85             }
86         }
87
88         return null;
89     }
90
91     @SuppressWarnings("checkstyle:IllegalCatch")
92     public static <T> List<T> expectMatching(ActorRef actor, Class<T> clazz, int count) {
93         return expectMatching(actor, clazz, count, msg -> true);
94     }
95
96     @SuppressWarnings("checkstyle:IllegalCatch")
97     public static <T> List<T> expectMatching(ActorRef actor, Class<T> clazz, int count,
98             Predicate<T> matcher) {
99         int timeout = 5000;
100         Exception lastEx = null;
101         List<T> messages = Collections.emptyList();
102         for (int i = 0; i < timeout / 50; i++) {
103             try {
104                 messages = getAllMatching(actor, clazz);
105                 Iterables.removeIf(messages, Predicates.not(matcher));
106                 if (messages.size() >= count) {
107                     return messages;
108                 }
109
110                 lastEx = null;
111             } catch (Exception e)  {
112                 lastEx = e;
113             }
114
115             Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
116         }
117
118         throw new AssertionError(String.format("Expected %d messages of type %s. Actual received was %d: %s", count,
119                 clazz, messages.size(), messages), lastEx);
120     }
121
122     public static <T> T expectFirstMatching(ActorRef actor, Class<T> clazz) {
123         return expectFirstMatching(actor, clazz, 5000);
124     }
125
126     @SuppressWarnings("checkstyle:IllegalCatch")
127     public static <T> T expectFirstMatching(ActorRef actor, Class<T> clazz, long timeout) {
128         Exception lastEx = null;
129         int count = (int) (timeout / 50);
130         for (int i = 0; i < count; i++) {
131             try {
132                 T message = getFirstMatching(actor, clazz);
133                 if (message != null) {
134                     return message;
135                 }
136
137                 lastEx = null;
138             } catch (Exception e) {
139                 lastEx = e;
140             }
141
142             Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
143         }
144
145         throw new AssertionError("Did not receive message of type " + clazz, lastEx);
146     }
147
148     @SuppressWarnings("checkstyle:IllegalCatch")
149     public static <T> T expectFirstMatching(ActorRef actor, Class<T> clazz, Predicate<T> matcher) {
150         int timeout = 5000;
151         Exception lastEx = null;
152         T lastMessage = null;
153         for (int i = 0; i < timeout / 50; i++) {
154             try {
155                 List<T> messages = getAllMatching(actor, clazz);
156                 for (T msg : messages) {
157                     if (matcher.apply(msg)) {
158                         return msg;
159                     }
160
161                     lastMessage = msg;
162                 }
163
164                 lastEx = null;
165             } catch (Exception e) {
166                 lastEx = e;
167             }
168
169             Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
170         }
171
172         throw new AssertionError(String.format("Expected specific message of type %s. Last message received was: %s",
173                 clazz, lastMessage), lastEx);
174     }
175
176     public static <T> void assertNoneMatching(ActorRef actor, Class<T> clazz) {
177         assertNoneMatching(actor, clazz, 5000);
178     }
179
180     @SuppressWarnings("checkstyle:IllegalCatch")
181     public static <T> void assertNoneMatching(ActorRef actor, Class<T> clazz, long timeout) {
182         Exception lastEx = null;
183         int count = (int) (timeout / 50);
184         for (int i = 0; i < count; i++) {
185             try {
186                 T message = getFirstMatching(actor, clazz);
187                 if (message != null) {
188                     Assert.fail("Unexpected message received" +  message.toString());
189                     return;
190                 }
191
192                 lastEx = null;
193             } catch (Exception e) {
194                 lastEx = e;
195             }
196
197             Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
198         }
199
200         if (lastEx != null) {
201             Throwables.propagate(lastEx);
202         }
203
204         return;
205     }
206
207
208     public static <T> List<T> getAllMatching(ActorRef actor, Class<T> clazz) throws Exception {
209         List<Object> allMessages = getAllMessages(actor);
210
211         List<T> output = Lists.newArrayList();
212
213         for (Object message : allMessages) {
214             if (message.getClass().equals(clazz)) {
215                 output.add(clazz.cast(message));
216             }
217         }
218
219         return output;
220     }
221
222     public static void waitUntilReady(ActorRef actor) throws Exception {
223         long timeout = 500;
224         FiniteDuration duration = Duration.create(timeout, TimeUnit.MILLISECONDS);
225         for (int i = 0; i < 10; i++) {
226             try {
227                 Await.ready(Patterns.ask(actor, ARE_YOU_READY, timeout), duration);
228                 return;
229             } catch (TimeoutException e) {
230                 // will fall through below
231             }
232         }
233
234         throw new TimeoutException("Actor not ready in time.");
235     }
236
237     public static Props props() {
238         return Props.create(MessageCollectorActor.class);
239     }
240 }