KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgroups > demos > TotalTokenDemo


1 //$Id: TotalTokenDemo.java,v 1.8 2004/09/23 16:29:35 belaban Exp $
2

3 package org.jgroups.demos;
4
5 import org.jgroups.*;
6 import org.jgroups.stack.Protocol;
7 import org.jgroups.stack.ProtocolStack;
8 import org.jgroups.util.Util;
9
10 import javax.swing.*;
11 import java.awt.*;
12 import java.awt.event.ActionEvent JavaDoc;
13 import java.awt.event.ActionListener JavaDoc;
14 import java.io.Serializable JavaDoc;
15 import java.util.Iterator JavaDoc;
16 import java.util.Random JavaDoc;
17 import java.util.Vector JavaDoc;
18
19
20 /**
21  *<p>
22  * Demonstration of TOTAL_TOKEN protocol stack implementing total
23  * order. TotalTokenDemo could however be used by any other
24  * stack configuration which does not neccesarily have to satisfy
25  * total order. If using stack configuration other than TOTAL_TOKEN
26  * an appropriate xml configuration file should be used. See -help for
27  * details.
28  * <p>
29  * TotalTokenDemo will verify :
30  * <p>
31  * total ordering of messages - by computing a color to be displayed
32  * in a gui window.
33  * <p>
34  * virtual synchrony - by displaying number of messages transmitted
35  * in last view.
36  * <p>
37  *
38  *@author Vladimir Blagojevic vladimir@cs.yorku.ca
39  *@author Ivan Bilenjkij ivan@ibossa.com
40  *@version $Revision: 1.8 $
41  *
42  *@see org.jgroups.protocols.TOTAL_TOKEN
43  *
44  **/

45
46
47 public class TotalTokenDemo extends JFrame implements Runnable JavaDoc
48 {
49     private JChannel channel;
50     //main tabbed pane
51

52     final JTabbedPane tabbedPane;
53
54     private ReceiverThread receiverThread;
55
56     private ColorPanel colorPanel;
57     private final ControlPanel control;
58     private int mSize = 1024;
59     private volatile boolean transmitting = false;
60     private final String JavaDoc channelProperties;
61     private Dimension preffered;
62
63     public TotalTokenDemo(String JavaDoc props)
64     {
65         super();
66         tabbedPane = new JTabbedPane();
67         control = new ControlPanel();
68         channelProperties = props;
69
70         try
71         {
72             channel = new JChannel(channelProperties);
73         }
74         catch (ChannelException e)
75         {
76             System.err.println("Could not create channel, exiting ....");
77             e.printStackTrace(System.err);
78         }
79
80         addPanel("Control", control);
81         getContentPane().add(tabbedPane);
82         connect();
83
84     }
85     public void addPanel(String JavaDoc name, JPanel panel)
86     {
87
88
89         if(tabbedPane.getTabCount() == 0)
90         {
91             preffered = panel.getPreferredSize();
92         }
93
94
95         panel.setPreferredSize(preffered);
96         tabbedPane.add(name,panel);
97     }
98
99     public JChannel getChannel()
100     {
101         return channel;
102     }
103
104
105     public void connect()
106     {
107         try
108         {
109             channel.connect("TOTAL_TOKEN_DEMO_GROUP");
110         }
111         catch (ChannelException e)
112         {
113             e.printStackTrace();
114         }
115         receiverThread = new ReceiverThread();
116         receiverThread.start();
117         Address a = channel.getLocalAddress();
118         if(a != null) setTitle(a.toString());
119         else setTitle("Not connected");
120         control.connected();
121     }
122     public void run()
123     {
124         Random JavaDoc r = new Random JavaDoc();
125
126         while (true)
127         {
128             Util.sleep(10);
129             try
130             {
131                 if (transmitting)
132                 {
133                     channel.send(new Message(null, null, new TotalPayload(r.nextInt(255))));
134                 }
135                 else
136                 {
137                     Util.sleep(200);
138                 }
139
140             }
141             catch (Exception JavaDoc e)
142             {
143                 e.printStackTrace();
144             }
145         }
146     }
147
148     public void disconnect()
149     {
150         transmitting = false;
151         receiverThread.shutDown();
152         channel.disconnect();
153         control.disconnected();
154         setTitle("Not connected");
155     }
156
157     private class ReceiverThread extends Thread JavaDoc
158     {
159         volatile boolean running = true;
160         Thread JavaDoc nullifier = null;
161         private long startTimeThroughput = System.currentTimeMillis();
162         private final long oneSecond = 1000;
163         private long throughput = 1;
164
165         public ReceiverThread()
166         {
167             nullifier = new Thread JavaDoc(new Runnable JavaDoc()
168             {
169                 public void run()
170                 {
171                     //nullifies throughput display
172
while (running)
173                     {
174                         Util.sleep(2000);
175                         if ((System.currentTimeMillis() - startTimeThroughput) > 2000)
176                         {
177                             control.throughput.setText("0 KB/sec");
178                         }
179                     }
180                 }
181             });
182             nullifier.start();
183         }
184
185         public void shutDown()
186         {
187             running = false;
188         }
189
190         private void measureThrougput(long size)
191         {
192             if ((System.currentTimeMillis() - startTimeThroughput) > oneSecond)
193             {
194                 control.throughput.setText("" + (throughput / 1024) + " KB/sec");
195                 startTimeThroughput = System.currentTimeMillis();
196                 throughput = 0;
197             }
198             else
199             {
200                 throughput += size;
201             }
202         }
203
204
205         public void run()
206         {
207             Object JavaDoc tmp;
208             Message msg = null;
209             int counter = 0;
210             Vector JavaDoc v = new Vector JavaDoc();
211             while (running)
212             {
213                 Util.sleep(10);
214                 try
215                 {
216
217                     tmp = channel.receive(0);
218                     if (tmp == null) continue;
219
220                     if (tmp instanceof View)
221                     {
222                         View vw = (View) tmp;
223                         control.viewNumber.setText("" + vw.getVid().getId());
224                         control.numMessagesInLastView.setText("" + counter);
225                         counter = 0;
226                         v.clear();
227                         continue;
228                     }
229
230                     if (tmp instanceof ExitEvent)
231                     {
232                         System.out.println("received EXIT");
233                         break;
234                     }
235
236                     if (!(tmp instanceof Message))
237                         continue;
238
239                     msg = (Message) tmp;
240
241                     measureThrougput(msg.size());
242                     TotalPayload p =null;
243
244                     p=(TotalPayload)msg.getObject();
245                     v.addElement(new Integer JavaDoc(p.getRandomSequence()));
246                     int size = v.size();
247                     if (size % 50 == 0)
248                     {
249                         int value = 0;
250                         int i = 0;
251                         Iterator JavaDoc iter = v.iterator();
252                         while (iter.hasNext())
253                         {
254                             i++;
255                             int seq = ((Integer JavaDoc) iter.next()).intValue();
256                             if (i % 2 == 0)
257                             {
258                                 value *= seq;
259                             }
260                             else if (i % 3 == 0)
261                             {
262                                 value -= seq;
263                             }
264                             else
265                                 value += seq;
266                         }
267                         v.clear();
268                         value = Math.abs(value);
269                         int r = value % 85;
270                         int g = value % 170;
271                         int b = value % 255;
272                         colorPanel.setSeq(r, g, b);
273                     }
274                     counter++;
275                 }
276                 catch (ChannelNotConnectedException e)
277                 {
278                     e.printStackTrace();
279                 }
280                 catch (ChannelClosedException e)
281                 {
282                     e.printStackTrace();
283                 }
284                 catch (TimeoutException e)
285                 {
286                     e.printStackTrace();
287                 }
288             }
289
290         }
291     }
292
293     public static class TotalPayload implements Serializable JavaDoc
294     {
295         private final int seqRandom;
296
297         public TotalPayload(int random)
298         {
299             seqRandom = random;
300         }
301
302         public int getRandomSequence()
303         {
304             return seqRandom;
305         }
306
307     }
308
309     class TransmitAction extends AbstractAction
310     {
311
312         private static final String JavaDoc TRANSMIT_OFF = "transmit off";
313         private static final String JavaDoc TRANSMIT_ON = "transmit on";
314
315         TransmitAction()
316         {
317             putValue(NAME, TRANSMIT_OFF);
318         }
319
320         public void actionPerformed(ActionEvent JavaDoc e)
321         {
322             if (getValue(NAME) == TRANSMIT_OFF)
323             {
324                 putValue(NAME, TRANSMIT_ON);
325                 transmitting = true;
326             }
327             else
328             {
329                 putValue(NAME, TRANSMIT_OFF);
330                 transmitting = false;
331             }
332         }
333
334
335     }
336
337     class ControlPanel extends JPanel
338     {
339
340         private static final String JavaDoc DISCONNECT = "Disconnect";
341         private static final String JavaDoc CONNECT = "Connect";
342         final JTextField numMessagesInLastView;
343         final JTextField throughput;
344         final JTextField viewNumber;
345         final JTextField messageSize;
346         final JTextField state;
347         final JButton transmit;
348         final JButton connectButton;
349
350         JTabbedPane pane;
351
352         public ControlPanel()
353         {
354             super();
355
356             //Layout the labels in a panel
357
JPanel labelPane = new JPanel();
358             labelPane.setLayout(new GridLayout(0, 1));
359             labelPane.add(new JLabel("Message size"));
360             labelPane.add(new JLabel("Current view"));
361             labelPane.add(new JLabel("Throughput"));
362             labelPane.add(new JLabel("Last view count"));
363
364
365             colorPanel = new ColorPanel();
366             connectButton = new JButton(DISCONNECT);
367
368             connectButton.addActionListener(new ActionListener JavaDoc()
369             {
370                 public void actionPerformed(ActionEvent JavaDoc e)
371                 {
372                     JButton b = (JButton) e.getSource();
373                     String JavaDoc current_state = b.getText();
374                     if (CONNECT.equals(current_state))
375                     {
376                         connect();
377                     }
378                     else if (DISCONNECT.equals(current_state))
379                     {
380                         disconnect();
381                     }
382                 }
383             });
384
385             transmit = new JButton(new TransmitAction());
386             labelPane.add(connectButton);
387             labelPane.add(transmit);
388
389
390             int size = 10;
391             messageSize = new JTextField(size);
392             messageSize.setText("" + mSize);
393             messageSize.addActionListener(new ActionListener JavaDoc()
394             {
395                 /**
396                  * Invoked when an action occurs.
397                  */

398                 public void actionPerformed(ActionEvent JavaDoc e)
399                 {
400                     mSize = Integer.parseInt(messageSize.getText());
401                 }
402             });
403             viewNumber = new JTextField(size);
404             viewNumber.setEditable(false);
405             throughput = new JTextField(size);
406             throughput.setEditable(false);
407             numMessagesInLastView = new JTextField(size);
408             numMessagesInLastView.setEditable(false);
409
410             state = new JTextField(size);
411             state.setEditable(false);
412
413
414             //Layout the text fields in a panel
415
JPanel fieldPane = new JPanel();
416             fieldPane.setLayout(new GridLayout(0, 1));
417             fieldPane.add(messageSize);
418             fieldPane.add(viewNumber);
419             fieldPane.add(throughput);
420             fieldPane.add(numMessagesInLastView);
421             fieldPane.add(state);
422             fieldPane.add(colorPanel);
423
424
425
426             //Put the panels in another panel, labels on left,
427
//text fields on right
428
JPanel contentPane = new JPanel();
429             contentPane.setBorder(BorderFactory.createTitledBorder("Control"));
430             contentPane.setLayout(new BorderLayout());
431             contentPane.add(labelPane, BorderLayout.CENTER);
432             contentPane.add(fieldPane, BorderLayout.EAST);
433             this.setLayout(new BorderLayout());
434             this.add(contentPane);
435         }
436
437         public void connected()
438         {
439             connectButton.setText(DISCONNECT);
440             state.setText("connected ok");
441         }
442
443         public void disconnected()
444         {
445             connectButton.setText(CONNECT);
446             state.setText("disconnected ok");
447         }
448     }
449
450     class ColorPanel extends JPanel
451     {
452
453         long seq1,seq2,seq3;
454
455         public ColorPanel()
456         {
457             super();
458             setOpaque(false);
459             this.setLayout(new BorderLayout());
460             //setBorder(BorderFactory.createLineBorder(Color.black));
461
}
462
463         public Dimension getPreferredSize()
464         {
465             Dimension layoutSize = super.getPreferredSize();
466             int max = Math.max(layoutSize.width, layoutSize.height);
467             return new Dimension(max + 20, max + 20);
468         }
469
470         public void setSeq(long seq1, long seq2, long seq3)
471         {
472             this.seq1 = seq1;
473             this.seq2 = seq2;
474             this.seq3 = seq3;
475             this.repaint();
476         }
477
478         protected void paintComponent(Graphics g)
479         {
480             Dimension size = this.getSize();
481             int x = 0;
482             int y = 0;
483             g.setColor(new Color((int) seq1, (int) seq2, (int) seq3));
484             g.fillRect(x, y, size.width, size.height);
485         }
486     }
487     class StackPanel extends JPanel
488     {
489         final ProtocolStack stack;
490         public StackPanel(JChannel channel)
491         {
492             super();
493             setBorder(BorderFactory.createTitledBorder("ProtocolStack"));
494             this.setLayout(new GridLayout(0, 2));
495             this.stack = channel.getProtocolStack();
496             Iterator JavaDoc iter = stack.getProtocols().iterator();
497             String JavaDoc debugLevels [] = new String JavaDoc[]{"DEBUG","INFO","ERROR"};
498             while (iter.hasNext())
499             {
500                 Protocol p = (Protocol) iter.next();
501                 JLabel field = new JLabel(p.getName());
502                 JComboBox pane = new JComboBox(debugLevels);
503                 this.add(field);
504                 this.add(pane);
505
506             }
507         }
508     }
509
510     static void help()
511     {
512         System.out.println("\nTotalTokenDemo [-help] [-props <protocol stack definition>]");
513         System.out.println("-props: argument can be an old-style protocol stack specification, or it can be " +
514                            "a URL. In the latter case, the protocol specification will be read from the URL\n");
515     }
516
517
518     public static void main(String JavaDoc args[])
519     {
520         String JavaDoc props = null;
521
522         for (int i = 0; i < args.length; i++)
523         {
524             if ("-help".equals(args[i]))
525             {
526                 help();
527                 return;
528             }
529             if ("-props".equals(args[i]))
530             {
531                 props = args[++i];
532                 continue;
533             }
534             help();
535             return;
536         }
537
538         if (props == null)
539         {
540             props = "UDP(mcast_addr=224.0.0.35;mcast_port=45566;ip_ttl=32;" +
541                     "mcast_send_buf_size=150000;mcast_recv_buf_size=80000):" +
542                     "PING(timeout=2000;num_initial_members=5):" +
543                     "FD_SOCK:" +
544                     "VERIFY_SUSPECT(timeout=1500):" +
545                     "UNICAST(timeout=5000):" +
546                     "FRAG(frag_size=8192;down_thread=false;up_thread=false):" +
547                     "TOTAL_TOKEN(block_sending=50;unblock_sending=10):" +
548                     "pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;" +
549                     "shun=false;print_local_addr=true)";
550
551
552         }
553
554
555
556         TotalTokenDemo ttd = new TotalTokenDemo(props);
557         //StackPanel not_done_yet = new StackPanel(ttd.getChannel());
558
//ttd.addPanel("Debug", not_done_yet);
559
ttd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
560         ttd.pack();
561         ttd.show();
562         new Thread JavaDoc(ttd).start();
563     }
564 }
565
566
Popular Tags