Merge "Fix non-generic references to NormalizedNode"
[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.UntypedActor;
13 import akka.pattern.Patterns;
14 import akka.util.Timeout;
15 import com.google.common.collect.Lists;
16 import scala.concurrent.Await;
17 import scala.concurrent.Future;
18 import scala.concurrent.duration.Duration;
19 import scala.concurrent.duration.FiniteDuration;
20
21 import java.util.ArrayList;
22 import java.util.List;
23 import java.util.concurrent.TimeUnit;
24
25
26 public class MessageCollectorActor extends UntypedActor {
27     private List<Object> messages = new ArrayList<>();
28
29     @Override public void onReceive(Object message) throws Exception {
30         if(message instanceof String){
31             if("get-all-messages".equals(message)){
32                 getSender().tell(messages, getSelf());
33             }
34         } else {
35             messages.add(message);
36         }
37     }
38
39     public static List<Object> getAllMessages(ActorRef actor) throws Exception {
40         FiniteDuration operationDuration = Duration.create(5, TimeUnit.SECONDS);
41         Timeout operationTimeout = new Timeout(operationDuration);
42         Future<Object> future = Patterns.ask(actor, "get-all-messages", operationTimeout);
43
44         try {
45             return (List<Object>) Await.result(future, operationDuration);
46         } catch (Exception e) {
47             throw e;
48         }
49     }
50
51     /**
52      * Get the first message that matches the specified class
53      * @param actor
54      * @param clazz
55      * @return
56      */
57     public static Object getFirstMatching(ActorRef actor, Class<?> clazz) throws Exception {
58         List<Object> allMessages = getAllMessages(actor);
59
60         for(Object message : allMessages){
61             if(message.getClass().equals(clazz)){
62                 return message;
63             }
64         }
65
66         return null;
67     }
68
69     public static List<Object> getAllMatching(ActorRef actor, Class<?> clazz) throws Exception {
70         List<Object> allMessages = getAllMessages(actor);
71
72         List<Object> output = Lists.newArrayList();
73
74         for(Object message : allMessages){
75             if(message.getClass().equals(clazz)){
76                 output.add(message);
77             }
78         }
79
80         return output;
81     }
82
83 }