01: // $Id: DELAY.java,v 1.7 2005/08/08 12:45:42 belaban Exp $
02:
03: package org.jgroups.protocols;
04:
05: import org.jgroups.Event;
06: import org.jgroups.stack.Protocol;
07: import org.jgroups.util.Util;
08:
09: import java.util.Properties;
10:
11: /**
12: * Delays incoming/outgoing messages by a random number of milliseconds (range between 0 and n
13: * where n is determined by the user). Incoming messages can be delayed independently from
14: * outgoing messages (or not delayed at all).<p>
15: * This protocol should be inserted directly above the bottommost protocol (e.g. UDP).
16: */
17:
18: public class DELAY extends Protocol {
19: int in_delay = 0, out_delay = 0;
20:
21: /**
22: * All protocol names have to be unique !
23: */
24: public String getName() {
25: return "DELAY";
26: }
27:
28: public boolean setProperties(Properties props) {
29: String str;
30:
31: super .setProperties(props);
32:
33: str = props.getProperty("in_delay");
34: if (str != null) {
35: in_delay = Integer.parseInt(str);
36: props.remove("in_delay");
37: }
38:
39: str = props.getProperty("out_delay");
40: if (str != null) {
41: out_delay = Integer.parseInt(str);
42: props.remove("out_delay");
43: }
44:
45: if (props.size() > 0) {
46: log
47: .error("DELAY.setProperties(): these properties are not recognized: "
48: + props);
49:
50: return false;
51: }
52: return true;
53: }
54:
55: public void up(Event evt) {
56: int delay = in_delay > 0 ? computeDelay(in_delay) : 0;
57:
58: switch (evt.getType()) {
59: case Event.MSG: // Only delay messages, not other events !
60:
61: if (log.isInfoEnabled())
62: log.info("delaying incoming message for " + delay
63: + " milliseconds");
64: Util.sleep(delay);
65: break;
66: }
67:
68: passUp(evt); // Pass up to the layer above us
69: }
70:
71: public void down(Event evt) {
72: int delay = out_delay > 0 ? computeDelay(out_delay) : 0;
73:
74: switch (evt.getType()) {
75:
76: case Event.MSG: // Only delay messages, not other events !
77:
78: if (log.isInfoEnabled())
79: log.info("delaying outgoing message for " + delay
80: + " milliseconds");
81: Util.sleep(delay);
82: break;
83: }
84:
85: passDown(evt); // Pass on to the layer below us
86: }
87:
88: /**
89: * Compute a random number between 0 and n
90: */
91: static int computeDelay(int n) {
92: return (int) ((Math.random() * 1000000) % n);
93: }
94:
95: }
|