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 org.opendaylight.controller.cluster.example.messages.KeyValue;
15 import org.opendaylight.controller.cluster.example.messages.KeyValueSaved;
16 import org.opendaylight.controller.cluster.example.messages.PrintRole;
17 import org.opendaylight.controller.cluster.example.messages.PrintState;
18 import org.opendaylight.controller.cluster.raft.RaftActor;
19 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
21 import java.util.HashMap;
25 * A sample actor showing how the RaftActor is to be extended
27 public class ExampleActor extends RaftActor {
29 private final Map<String, String> state = new HashMap();
31 private long persistIdentifier = 1;
34 public ExampleActor(String id, Map<String, String> peerAddresses) {
35 super(id, peerAddresses);
38 public static Props props(final String id, final Map<String, String> peerAddresses){
39 return Props.create(new Creator<ExampleActor>(){
41 @Override public ExampleActor create() throws Exception {
42 return new ExampleActor(id, peerAddresses);
47 @Override public void onReceiveCommand(Object message){
48 if(message instanceof KeyValue){
50 String persistId = Long.toString(persistIdentifier++);
51 persistData(getSender(), persistId, (Payload) message);
53 if(getLeader() != null) {
54 getLeader().forward(message, getContext());
58 } else if (message instanceof PrintState) {
59 LOG.debug("State of the node:"+getId() + " has = "+state.size() + " entries");
61 } else if (message instanceof PrintRole) {
62 LOG.debug(getId() + " = " + getRaftState());
64 super.onReceiveCommand(message);
68 @Override protected void applyState(ActorRef clientActor, String identifier,
70 if(data instanceof KeyValue){
71 KeyValue kv = (KeyValue) data;
72 state.put(kv.getKey(), kv.getValue());
73 if(clientActor != null) {
74 clientActor.tell(new KeyValueSaved(), getSelf());
79 @Override protected Object createSnapshot() {
83 @Override protected void applySnapshot(Object snapshot) {
85 state.putAll((HashMap) snapshot);
88 @Override public void onReceiveRecover(Object message) {
89 super.onReceiveRecover(message);
92 @Override public String persistenceId() {