KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgroups > protocols > DELAY


1 // $Id: DELAY.java,v 1.5 2004/07/05 14:17:15 belaban Exp $
2

3 package org.jgroups.protocols;
4
5 import org.jgroups.Event;
6 import org.jgroups.stack.Protocol;
7 import org.jgroups.util.Util;
8
9 import java.util.Properties JavaDoc;
10
11
12 /**
13  * Delays incoming/outgoing messages by a random number of milliseconds (range between 0 and n
14  * where n is determined by the user). Incoming messages can be delayed independently from
15  * outgoing messages (or not delayed at all).<p>
16  * This protocol should be inserted directly above the bottommost protocol (e.g. UDP).
17  */

18
19 public class DELAY extends Protocol {
20     int in_delay=0, out_delay=0;
21
22     /**
23      * All protocol names have to be unique !
24      */

25     public String JavaDoc getName() {
26         return "DELAY";
27     }
28
29
30     public boolean setProperties(Properties JavaDoc props) {
31         String JavaDoc str;
32
33         super.setProperties(props);
34
35         str=props.getProperty("in_delay");
36         if(str != null) {
37             in_delay=Integer.parseInt(str);
38             props.remove("in_delay");
39         }
40
41         str=props.getProperty("out_delay");
42         if(str != null) {
43             out_delay=Integer.parseInt(str);
44             props.remove("out_delay");
45         }
46
47         if(props.size() > 0) {
48             System.err.println("DELAY.setProperties(): these properties are not recognized:");
49             props.list(System.out);
50             return false;
51         }
52         return true;
53     }
54
55
56     public void up(Event evt) {
57         int delay=in_delay > 0 ? computeDelay(in_delay) : 0;
58
59
60         switch(evt.getType()) {
61             case Event.MSG: // Only delay messages, not other events !
62

63                 if(log.isInfoEnabled()) log.info("delaying incoming message for " + delay + " milliseconds");
64                 Util.sleep(delay);
65                 break;
66         }
67
68         passUp(evt); // Pass up to the layer above us
69
}
70
71
72     public void down(Event evt) {
73         int delay=out_delay > 0 ? computeDelay(out_delay) : 0;
74
75         switch(evt.getType()) {
76
77             case Event.MSG: // Only delay messages, not other events !
78

79                 if(log.isInfoEnabled()) log.info("delaying outgoing message for " + delay + " milliseconds");
80                 Util.sleep(delay);
81                 break;
82         }
83
84         passDown(evt); // Pass on to the layer below us
85
}
86
87
88     /**
89      * Compute a random number between 0 and n
90      */

91     int computeDelay(int n) {
92         return (int)((Math.random() * 1000000) % n);
93     }
94
95
96 }
97
Popular Tags