Test RaftActor using a simple program
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / example / ExampleActor.java
1 /*
2  * Copyright (c) 2014 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.example;
10
11 import akka.actor.ActorRef;
12 import akka.actor.Props;
13 import akka.japi.Creator;
14 import org.opendaylight.controller.cluster.example.messages.KeyValue;
15 import org.opendaylight.controller.cluster.example.messages.KeyValueSaved;
16 import org.opendaylight.controller.cluster.raft.RaftActor;
17
18 import java.util.HashMap;
19 import java.util.Map;
20
21 /**
22  * A sample actor showing how the RaftActor is to be extended
23  */
24 public class ExampleActor extends RaftActor {
25
26     private final Map<String, String> state = new HashMap();
27
28     private long persistIdentifier = 1;
29
30
31     public ExampleActor(String id, Map<String, String> peerAddresses) {
32         super(id, peerAddresses);
33     }
34
35     public static Props props(final String id, final Map<String, String> peerAddresses){
36         return Props.create(new Creator<ExampleActor>(){
37
38             @Override public ExampleActor create() throws Exception {
39                 return new ExampleActor(id, peerAddresses);
40             }
41         });
42     }
43
44     @Override public void onReceiveCommand(Object message){
45         if(message instanceof KeyValue){
46
47             if(isLeader()) {
48                 String persistId = Long.toString(persistIdentifier++);
49                 persistData(getSender(), persistId, message);
50             } else {
51                 getLeader().forward(message, getContext());
52             }
53         }
54         super.onReceiveCommand(message);
55     }
56
57     @Override protected void applyState(ActorRef clientActor, String identifier,
58         Object data) {
59         if(data instanceof KeyValue){
60             KeyValue kv = (KeyValue) data;
61             state.put(kv.getKey(), kv.getValue());
62             if(clientActor != null) {
63                 clientActor.tell(new KeyValueSaved(), getSelf());
64             }
65         }
66     }
67
68     @Override public void onReceiveRecover(Object message) {
69         super.onReceiveRecover(message);
70     }
71
72     @Override public String persistenceId() {
73         return getId();
74     }
75 }