Merge "Bug 1025: Fixed incorrect revision in sal-remote-augment, which caused log...
[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 scala.concurrent.Await;
16 import scala.concurrent.Future;
17 import scala.concurrent.duration.Duration;
18 import scala.concurrent.duration.FiniteDuration;
19
20 import java.util.ArrayList;
21 import java.util.List;
22 import java.util.concurrent.TimeUnit;
23
24
25 public class MessageCollectorActor extends UntypedActor {
26     private List<Object> messages = new ArrayList<>();
27
28     @Override public void onReceive(Object message) throws Exception {
29         if(message instanceof String){
30             if("get-all-messages".equals(message)){
31                 getSender().tell(messages, getSelf());
32             }
33         } else {
34             messages.add(message);
35         }
36     }
37
38     public static List<Object> getAllMessages(ActorRef actor) throws Exception {
39         FiniteDuration operationDuration = Duration.create(5, TimeUnit.SECONDS);
40         Timeout operationTimeout = new Timeout(operationDuration);
41         Future<Object> future = Patterns.ask(actor, "get-all-messages", operationTimeout);
42
43         try {
44             return (List<Object>) Await.result(future, operationDuration);
45         } catch (Exception e) {
46             throw e;
47         }
48     }
49
50     /**
51      * Get the first message that matches the specified class
52      * @param actor
53      * @param clazz
54      * @return
55      */
56     public static Object getFirstMatching(ActorRef actor, Class clazz) throws Exception {
57         List<Object> allMessages = getAllMessages(actor);
58
59         for(Object message : allMessages){
60             if(message.getClass().equals(clazz)){
61                 return message;
62             }
63         }
64
65         return null;
66     }
67
68 }