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.example;
11 import akka.actor.ActorRef;
12 import akka.actor.Props;
13 import akka.japi.Creator;
14 import com.google.common.base.Optional;
15 import org.opendaylight.controller.cluster.example.messages.KeyValue;
16 import org.opendaylight.controller.cluster.example.messages.KeyValueSaved;
17 import org.opendaylight.controller.cluster.example.messages.PrintRole;
18 import org.opendaylight.controller.cluster.example.messages.PrintState;
19 import org.opendaylight.controller.cluster.raft.ConfigParams;
20 import org.opendaylight.controller.cluster.raft.RaftActor;
21 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
23 import java.util.HashMap;
27 * A sample actor showing how the RaftActor is to be extended
29 public class ExampleActor extends RaftActor {
31 private final Map<String, String> state = new HashMap();
33 private long persistIdentifier = 1;
36 public ExampleActor(String id, Map<String, String> peerAddresses,
37 Optional<ConfigParams> configParams) {
38 super(id, peerAddresses, configParams);
41 public static Props props(final String id, final Map<String, String> peerAddresses,
42 final Optional<ConfigParams> configParams){
43 return Props.create(new Creator<ExampleActor>(){
45 @Override public ExampleActor create() throws Exception {
46 return new ExampleActor(id, peerAddresses, configParams);
51 @Override public void onReceiveCommand(Object message){
52 if(message instanceof KeyValue){
54 String persistId = Long.toString(persistIdentifier++);
55 persistData(getSender(), persistId, (Payload) message);
57 if(getLeader() != null) {
58 getLeader().forward(message, getContext());
62 } else if (message instanceof PrintState) {
63 LOG.debug("State of the node:{} has entries={}, {}",
64 getId(), state.size(), getReplicatedLogState());
66 } else if (message instanceof PrintRole) {
67 LOG.debug("{} = {}, Peers={}", getId(), getRaftState(),getPeers());
70 super.onReceiveCommand(message);
74 @Override protected void applyState(ActorRef clientActor, String identifier,
76 if(data instanceof KeyValue){
77 KeyValue kv = (KeyValue) data;
78 state.put(kv.getKey(), kv.getValue());
79 if(clientActor != null) {
80 clientActor.tell(new KeyValueSaved(), getSelf());
85 @Override protected Object createSnapshot() {
89 @Override protected void applySnapshot(Object snapshot) {
91 state.putAll((HashMap) snapshot);
92 LOG.debug("Snapshot applied to state :" + ((HashMap) snapshot).size());
95 @Override protected void onStateChanged() {
99 @Override public void onReceiveRecover(Object message) {
100 super.onReceiveRecover(message);
103 @Override public String persistenceId() {