6ef8a07d9dfa9891c2c0805536be75be143c3415
[controller.git] / opendaylight / md-sal / sal-akka-raft-example / src / main / java / org / opendaylight / controller / cluster / example / LogGenerator.java
1 /*
2  * Copyright (c) 2014, 2015 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 package org.opendaylight.controller.cluster.example;
9
10 import akka.actor.ActorRef;
11 import java.util.HashMap;
12 import java.util.Map;
13 import java.util.Random;
14 import org.opendaylight.controller.cluster.example.messages.KeyValue;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
17
18 /**
19  * Created by kramesha on 7/16/14.
20  */
21 public class LogGenerator {
22     private static final Logger LOG = LoggerFactory.getLogger(LogGenerator.class);
23
24     private final Map<ActorRef, LoggingThread> clientToLoggingThread = new HashMap<>();
25
26     public void startLoggingForClient(final ActorRef client) {
27         LoggingThread lt = new LoggingThread(client);
28         clientToLoggingThread.put(client, lt);
29         new Thread(lt).start();
30     }
31
32     public void stopLoggingForClient(final ActorRef client) {
33         clientToLoggingThread.get(client).stopLogging();
34         clientToLoggingThread.remove(client);
35     }
36
37     public static class LoggingThread implements Runnable {
38
39         private final ActorRef clientActor;
40         private volatile boolean stopLogging = false;
41
42         public LoggingThread(final ActorRef clientActor) {
43             this.clientActor = clientActor;
44         }
45
46         @Override
47         public void run() {
48             Random random = new Random();
49             while (true) {
50                 if (stopLogging) {
51                     LOG.info("Logging stopped for client: {}", clientActor.path());
52                     break;
53                 }
54                 String key = clientActor.path().name();
55                 int randomInt = random.nextInt(100);
56                 clientActor.tell(new KeyValue(key + "-key-" + randomInt, "value-" + randomInt), null);
57
58                 try {
59                     Thread.sleep(randomInt % 10 * 1000L);
60                 } catch (InterruptedException e) {
61                     LOG.info("Interrupted while sleeping", e);
62                 }
63             }
64         }
65
66         public void stopLogging() {
67             stopLogging = true;
68         }
69
70         public void startLogging() {
71             stopLogging = false;
72         }
73     }
74 }