KickJava   Java API By Example, From Geeks To Geeks.

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


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

3
4 package org.jgroups.demos;
5
6
7 import org.jgroups.*;
8 import org.jgroups.Event;
9 import org.jgroups.util.Util;
10
11 import javax.swing.*;
12 import java.awt.*;
13 import java.awt.event.*;
14 import java.io.ByteArrayOutputStream JavaDoc;
15 import java.io.ObjectOutputStream JavaDoc;
16 import java.util.Random JavaDoc;
17
18
19
20
21 /**
22  * Same as Draw but using 2 channels: one for view changes (control channel) and the other one for drawing
23  * (data channel). Ported to use Swing Nov 1 2001, not tested.
24  * @author Bela Ban, Nov 1 2001
25  */

26 public class Draw2Channels implements ActionListener {
27     private final ByteArrayOutputStream JavaDoc out=new ByteArrayOutputStream JavaDoc();
28     private final String JavaDoc control_groupname="Draw2ChannelsGroup-Control";
29     private final String JavaDoc data_groupname="Draw2ChannelsGroup-Data";
30     private Channel control_channel=null;
31     private Channel data_channel=null;
32     String JavaDoc control_props=null, data_props=null;
33     private Thread JavaDoc control_receiver=null;
34     private Thread JavaDoc data_receiver=null;
35     private int member_size=1;
36     final boolean first=true;
37     final boolean cummulative=true;
38     private JFrame mainFrame=null;
39     private JPanel sub_panel=null;
40     private DrawPanel panel=null;
41     private JButton clear_button, leave_button;
42     private final Random JavaDoc random=new Random JavaDoc(System.currentTimeMillis());
43     private final Font default_font=new Font("Helvetica",Font.PLAIN,12);
44     private final Color draw_color=selectColor();
45     private final Color background_color=Color.white;
46     boolean no_channel=false;
47
48
49
50
51
52     public Draw2Channels(String JavaDoc control_props, String JavaDoc data_props, boolean no_channel) throws Exception JavaDoc {
53
54     this.control_props=control_props;
55     this.data_props=data_props;
56     this.no_channel=no_channel;
57     if(no_channel)
58         return;
59     }
60
61
62
63
64
65
66    public static void main(String JavaDoc[] args) {
67     Draw2Channels draw=null;
68     String JavaDoc control_props=null, data_props=null;
69     boolean no_channel=false;
70
71     for(int i=0; i < args.length; i++) {
72         if("-help".equals(args[i])) {
73         help();
74         return;
75         }
76         if("-no_channel".equals(args[i])) {
77         no_channel=true;
78         continue;
79         }
80         help();
81         return;
82     }
83
84
85
86        control_props="UDP(mcast_addr=224.0.0.35;mcast_port=45566;ip_ttl=32;" +
87                "mcast_send_buf_size=150000;mcast_recv_buf_size=80000):" +
88                "PING(timeout=2000;num_initial_members=3):" +
89                "MERGE2(min_interval=5000;max_interval=10000):" +
90                "FD_SOCK:" +
91                "VERIFY_SUSPECT(timeout=1500):" +
92                "pbcast.NAKACK(gc_lag=50;retransmit_timeout=300,600,1200,2400,4800):" +
93                "UNICAST(timeout=5000):" +
94                "pbcast.STABLE(desired_avg_gossip=20000):" +
95                "FRAG(frag_size=4096;down_thread=false;up_thread=false):" +
96                "pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;" +
97                "shun=false;print_local_addr=true)";
98
99
100     data_props="UDP(mcast_addr=224.10.10.200;mcast_port=5679)";
101
102     /*
103     data_props="UDP(mcast_addr=224.0.1.1;mcast_port=10000):" +
104         "PING:" +
105         "FD:" +
106         "pbcast.PBCAST(gossip_interval=5000;gc_lag=50):" +
107         "UNICAST:" +
108         "pbcast.GMS";
109     */

110
111
112
113
114
115     /*
116     props="TCP(start_port=7800):" +
117         "TCPPING(initial_hosts=dev1-150[7800];port_range=5;timeout=3000;" +
118         "num_initial_members=3;up_thread=true;down_thread=true):" +
119         "VERIFY_SUSPECT(timeout=1500;down_thread=false;up_thread=false):" +
120         "pbcast.STABLE(desired_avg_gossip=20000;down_thread=false;up_thread=false):" +
121         "pbcast.NAKACK(down_thread=true;up_thread=true;gc_lag=100;retransmit_timeout=3000):" +
122         "pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;shun=false;" +
123         "print_local_addr=false;down_thread=true;up_thread=true)";
124     */

125
126
127
128     
129     /*
130     // Gianluca's stack properties
131     props="UDP:" +
132         "PING:" +
133         "FD(timeout=6000;shun=false):" +
134         "STABLE:" +
135         "MERGE:" +
136         "NAKACK:" +
137         "FLUSH:" +
138         "GMS:" +
139         "VIEW_ENFORCER:" +
140         "FLOWCONTROL:" +
141         "QUEUE";
142     */

143
144
145     /*
146     // Bill Burke's props
147     props="UDP:" +
148         "PING:" +
149         "FD(timeout=5000):" +
150         "STABLE:" +
151         "VERIFY_SUSPECT(timeout=1500):" +
152         "MERGE:" +
153         "NAKACK:" +
154         "UNICAST(timeout=5000)" +
155         ":FRAG:" +
156         "FLUSH:" +
157         "GMS:" +
158         "STATE_TRANSFER:" +
159         "QUEUE";
160     */

161
162
163
164     try {
165
166         draw=new Draw2Channels(control_props, data_props, no_channel);
167         draw.go();
168     }
169     catch(Exception JavaDoc e) {
170         System.err.println(e);
171         System.exit(0);
172     }
173     }
174
175
176     static void help() {
177     System.out.println("Draw2Channels [-help] [-no_channel]");
178     }
179
180
181     private Color selectColor() {
182     int red=(Math.abs(random.nextInt()) % 255);
183     int green=(Math.abs(random.nextInt()) % 255);
184     int blue=(Math.abs(random.nextInt()) % 255);
185     return new Color(red, green, blue);
186     }
187
188
189
190     public void go() {
191     try {
192         if(!no_channel) {
193         System.out.println("Creating control channel");
194         control_channel=new JChannel(control_props);
195         System.out.println("Connecting control channel");
196         control_channel.connect(control_groupname);
197         System.out.println("Creating data channel");
198         data_channel=new JChannel(data_props);
199         // data_channel.SetOpt(Channel.VIEW, Boolean.FALSE);
200
System.out.println("Connecting data channel");
201         data_channel.connect(data_groupname);
202         }
203         mainFrame=new JFrame();
204         mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
205         panel=new DrawPanel();
206         panel.setBackground(background_color);
207         sub_panel=new JPanel();
208         mainFrame.getContentPane().add("Center", panel);
209         clear_button=new JButton("Clear");
210         clear_button.setFont(default_font);
211         clear_button.addActionListener(this);
212         leave_button=new JButton("Leave & Exit");
213         leave_button.setFont(default_font);
214         leave_button.addActionListener(this);
215         sub_panel.add("South", clear_button);
216         sub_panel.add("South", leave_button);
217         mainFrame.getContentPane().add("South", sub_panel);
218         mainFrame.setVisible(true);
219         mainFrame.setBackground(background_color);
220         clear_button.setForeground(Color.blue);
221         leave_button.setForeground(Color.blue);
222         setTitle();
223         mainFrame.pack();
224         mainFrame.setLocation(15, 25);
225         mainFrame.setVisible(true);
226         if(!no_channel) {
227         System.out.println("Starting control receiver thread");
228         control_receiver=new ControlReceiver();
229         control_receiver.start();
230         
231         
232         System.out.println("Starting data receiver thread");
233         data_receiver=new DataReceiver();
234         data_receiver.start();
235         }
236     }
237     catch(Exception JavaDoc e) {
238         System.err.println(e);
239         return;
240     }
241     }
242
243
244
245
246     void setTitle() {
247     String JavaDoc title="";
248     if(no_channel) {
249         mainFrame.setTitle(" Draw Demo ");
250         return;
251     }
252     if(control_channel.getLocalAddress() != null)
253         title+=control_channel.getLocalAddress();
254     title+=" (" + member_size + ") mbrs";
255     mainFrame.setTitle(title);
256     }
257
258
259     /*
260     public void mainLoop() {
261     Object tmp;
262     Message msg=null;
263     DrawCommand comm;
264     boolean fl=true;
265
266     while(fl) {
267         try {
268         tmp=channel.Receive(0);
269         if(tmp == null) continue;
270
271         if(tmp instanceof View) {
272             View v=(View)tmp;
273             System.out.println("** View=" + v);
274             member_size=v.Size();
275             if(mainFrame != null)
276             SetTitle();
277             continue;
278         }
279
280         if(tmp instanceof ExitEvent) {
281             System.out.println("-- Draw2Channels.main(): received EXIT, waiting for ChannelReconnected callback");
282             break;
283         }
284
285         if(!(tmp instanceof Message))
286             continue;
287
288         msg=(Message)tmp;
289         comm=null;
290
291         Object obj=Util.ObjectFromByteBuffer(msg.GetBuffer());
292         if(obj instanceof DrawCommand)
293             comm=(DrawCommand)obj;
294         else if(obj instanceof Message) {
295             System.out.println("*** Draw2Channels.run(): message is " + Util.PrintMessage((Message)obj));
296             Util.DumpStack(false);
297             continue;
298         }
299         else {
300             if(obj != null)
301             System.out.println("*** Draw2Channels.run(): obj is " + obj.getClass() +
302                        ", hdrs are" + msg.PrintObjectHeaders());
303             else
304             System.out.println("*** Draw2Channels.run(): hdrs are" + msg.PrintObjectHeaders());
305             Util.DumpStack(false);
306             continue;
307         }
308
309         switch(comm.mode) {
310         case DrawCommand.DRAW:
311             if(panel != null)
312             panel.drawPoint(comm);
313             break;
314         case DrawCommand.CLEAR:
315             ClearPanel();
316             continue;
317         default:
318             System.err.println("***** Draw2Channels.run(): received invalid draw command " + comm.mode);
319             break;
320         }
321
322         }
323         catch(ChannelNotConnected not) {
324         System.err.println("Draw2Channels: " + not);
325         break;
326         }
327         catch(ChannelClosed closed) {
328         break;
329         }
330         catch(Exception e) {
331         System.err.println(e);
332         continue;
333         }
334     }
335     }
336     */

337
338
339
340
341     /* --------------- Callbacks --------------- */
342
343
344
345     public void clearPanel() {
346     if(panel != null)
347         panel.clear();
348     }
349
350     public void sendClearPanelMsg() {
351     int tmp[]=new int[1]; tmp[0]=0;
352     DrawCommand comm=new DrawCommand(DrawCommand.CLEAR);
353     ObjectOutputStream JavaDoc os;
354
355     try {
356         out.reset();
357         os=new ObjectOutputStream JavaDoc(out);
358         os.writeObject(comm);
359         os.flush();
360         data_channel.send(new Message(null, null, out.toByteArray()));
361     }
362     catch(Exception JavaDoc ex) {
363         System.err.println(ex);
364     }
365     }
366
367
368     public void actionPerformed(ActionEvent e) {
369     String JavaDoc command=e.getActionCommand();
370     if("Clear".equals(command)) {
371         if(no_channel) {
372         clearPanel();
373         return;
374         }
375         sendClearPanelMsg();
376     }
377     else if("Leave & Exit".equals(command)) {
378         if(!no_channel) {
379         try {
380             control_channel.close();
381         }
382         catch(Exception JavaDoc ex) {
383             System.err.println(ex);
384         }
385         try {
386             data_channel.close();
387         }
388         catch(Exception JavaDoc ex) {
389             System.err.println(ex);
390         }
391         }
392         mainFrame.setVisible(false);
393         mainFrame.dispose();
394         System.exit(0);
395     }
396     else
397         System.out.println("Unknown action");
398     }
399
400
401
402
403
404
405
406     private class DrawPanel extends JPanel implements MouseMotionListener {
407     final Dimension preferred_size=new Dimension(235, 170);
408     Image img=null; // for drawing pixels
409
Dimension d, imgsize;
410     Graphics gr=null;
411
412     
413     public DrawPanel() {
414         addMouseMotionListener(this);
415         addComponentListener(new ComponentAdapter() {
416         public void componentResized(ComponentEvent e) {
417             if(getWidth() <= 0 || getHeight() <= 0) return;
418             createOffscreenImage();
419         }
420         });
421     }
422
423
424
425     void createOffscreenImage() {
426         d=getSize();
427         if(img == null || imgsize == null || imgsize.width != d.width || imgsize.height != d.height) {
428         img=createImage(d.width, d.height);
429         gr=img.getGraphics();
430         imgsize=d;
431         }
432     }
433
434
435     /* ---------------------- MouseMotionListener interface------------------------- */
436
437     public void mouseMoved(MouseEvent e) {}
438     
439     public void mouseDragged(MouseEvent e) {
440         ObjectOutputStream JavaDoc os;
441         int x=e.getX(), y=e.getY();
442         DrawCommand comm=new DrawCommand(DrawCommand.DRAW, x, y,
443                              draw_color.getRed(), draw_color.getGreen(), draw_color.getBlue());
444
445         if(no_channel) {
446         drawPoint(comm);
447         return;
448         }
449
450         try {
451         out.reset();
452         os=new ObjectOutputStream JavaDoc(out);
453         os.writeObject(comm);
454         os.flush();
455         data_channel.send(new Message(null, null, out.toByteArray()));
456         Thread.yield(); // gives the repainter some breath
457
}
458         catch(Exception JavaDoc ex) {
459         System.err.println(ex);
460         }
461     }
462     
463     /* ------------------- End of MouseMotionListener interface --------------------- */
464
465
466     /**
467      * Adds pixel to queue and calls repaint() whenever we have MAX_ITEMS pixels in the queue
468      * or when MAX_TIME msecs have elapsed (whichever comes first). The advantage compared to just calling
469      * repaint() after adding a pixel to the queue is that repaint() can most often draw multiple points
470      * at the same time.
471      */

472     public void drawPoint(DrawCommand c) {
473         if(c == null) return;
474         gr.setColor(new Color(c.r, c.g, c.b));
475         gr.fillOval(c.x, c.y, 10, 10);
476         repaint();
477     }
478
479
480     
481     public void clear() {
482         gr.clearRect(0, 0, getSize().width, getSize().height);
483         repaint();
484     }
485
486     
487     public Dimension getPreferredSize() {
488         return preferred_size;
489     }
490
491
492     public void paintComponent(Graphics g) {
493         super.paintComponent(g);
494         if(img != null) {
495         g.drawImage(img, 0, 0, null);
496         }
497     }
498
499     }
500
501
502
503     class ControlReceiver extends Thread JavaDoc {
504     public void run() {
505         Object JavaDoc tmp;
506
507         while(true) {
508         try {
509             tmp=control_channel.receive(0);
510         
511             if(tmp == null) continue;
512         
513             if(tmp instanceof View) {
514             View v=(View)tmp;
515
516             data_channel.down(new Event(Event.VIEW_CHANGE, v));
517
518             member_size=v.size();
519             if(mainFrame != null)
520                 mainFrame.setTitle(member_size + " mbrs");
521             continue;
522             }
523         }
524         catch(ChannelNotConnectedException not) {
525             break;
526         }
527         catch(ChannelClosedException closed) {
528             return;
529         }
530         catch(Exception JavaDoc e) {
531             System.err.println("Draw2Channels.ControlReceiver.run(): " + e);
532             break;
533         }
534         }
535     }
536     
537     }
538
539
540     class DataReceiver extends Thread JavaDoc {
541
542     public void run() {
543         Object JavaDoc tmp;
544         Message msg=null;
545         DrawCommand comm;
546
547         while(true) {
548         try {
549             tmp=data_channel.receive(0);
550             if(tmp == null) continue;
551
552             if(tmp instanceof View) {
553             View v=(View)tmp;
554             System.out.println("** View=" + v);
555             member_size=v.size();
556             if(mainFrame != null)
557                 setTitle();
558             continue;
559             }
560
561             if(tmp instanceof ExitEvent) {
562             System.out.println("-- Draw2Channels.main(): received EXIT, waiting for ChannelReconnected callback");
563             break;
564             }
565
566             if(!(tmp instanceof Message))
567             continue;
568
569             msg=(Message)tmp;
570             comm=null;
571
572             Object JavaDoc obj=msg.getObject();
573             if(obj instanceof DrawCommand)
574             comm=(DrawCommand)obj;
575             else if(obj instanceof Message) {
576             System.out.println("*** Draw2Channels.run(): message is " + Util.printMessage((Message)obj));
577             Util.dumpStack(false);
578             continue;
579             }
580             else {
581             if(obj != null)
582                 System.out.println("*** Draw2Channels.run(): obj is " + obj.getClass() +
583                            ", hdrs are" + msg.printObjectHeaders());
584             else
585                 System.out.println("*** Draw2Channels.run(): hdrs are" + msg.printObjectHeaders());
586             Util.dumpStack(false);
587             continue;
588             }
589
590             switch(comm.mode) {
591             case DrawCommand.DRAW:
592             if(panel != null)
593                 panel.drawPoint(comm);
594             break;
595             case DrawCommand.CLEAR:
596             clearPanel();
597             continue;
598             default:
599             System.err.println("***** Draw2Channels.run(): received invalid draw command " + comm.mode);
600             break;
601             }
602
603         }
604         catch(ChannelNotConnectedException not) {
605             System.err.println("Draw2Channels: " + not);
606             break;
607         }
608         catch(ChannelClosedException closed) {
609             break;
610         }
611         catch(Exception JavaDoc e) {
612             System.err.println(e);
613             continue;
614         }
615         }
616     }
617
618     }
619
620
621
622     
623 }
624
625
626
627
Popular Tags