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.raft;
12 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
14 * This program and the accompanying materials are made available under the
15 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
16 * and is available at http://www.eclipse.org/legal/epl-v10.html
19 import akka.actor.Actor;
20 import akka.actor.ActorRef;
21 import akka.actor.ActorSystem;
22 import akka.actor.PoisonPill;
23 import akka.actor.Props;
24 import akka.testkit.TestActorRef;
25 import java.util.LinkedList;
26 import java.util.List;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
31 * TestActorFactory provides methods to create both normal and test actors and to kill them when the factory is closed
32 * The ideal usage for TestActorFactory is with try with resources, <br/>
35 * try (TestActorFactory factory = new TestActorFactory(getSystem())){
36 * factory.createActor(props);
37 * factory.createTestActor(props);
38 * factory.generateActorId("leader-");
42 public class TestActorFactory implements AutoCloseable {
43 private final ActorSystem system;
44 List<ActorRef> createdActors = new LinkedList<>();
45 Logger LOG = LoggerFactory.getLogger(getClass());
46 private static int actorCount = 1;
48 public TestActorFactory(ActorSystem system){
53 * Create a normal actor with an auto-generated name
58 public ActorRef createActor(Props props){
59 ActorRef actorRef = system.actorOf(props);
60 createdActors.add(actorRef);
65 * Create a normal actor with the passed in name
67 * @param actorId name of actor
70 public ActorRef createActor(Props props, String actorId){
71 ActorRef actorRef = system.actorOf(props, actorId);
72 createdActors.add(actorRef);
77 * Create a test actor with the passed in name
83 public <T extends Actor> TestActorRef<T> createTestActor(Props props, String actorId){
84 TestActorRef<T> actorRef = TestActorRef.create(system, props, actorId);
85 createdActors.add(actorRef);
90 * Create a test actor with an auto-generated name
95 public <T extends Actor> TestActorRef<T> createTestActor(Props props){
96 TestActorRef<T> actorRef = TestActorRef.create(system, props);
97 createdActors.add(actorRef);
102 * Generate a friendly but unique actor id/name
106 public String generateActorId(String prefix){
107 return prefix + actorCount++;
111 public void close() throws Exception {
112 for(ActorRef actor : createdActors){
113 LOG.info("Killing actor {}", actor);
114 actor.tell(PoisonPill.getInstance(), null);