KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sample > jms > topics > draw > DrawAgent


1 package sample.jms.topics.draw;
2
3 /*
4  * Copyright 2002 by
5  * <a HREF="http://www.coridan.com">Coridan</a>
6  * <a HREF="mailto: support@coridan.com ">support@coridan.com</a>
7  *
8  * The contents of this file are subject to the Mozilla Public License Version
9  * 1.1 (the "License"); you may not use this file except in compliance with the
10  * License. You may obtain a copy of the License at
11  * http://www.mozilla.org/MPL/
12  *
13  * Software distributed under the License is distributed on an "AS IS" basis,
14  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
15  * for the specific language governing rights and limitations under the
16  * License.
17  *
18  * The Original Code is "MantaRay" (TM).
19  *
20  * The Initial Developer of the Original Code is Coridan.
21  * Portions created by the Initial Developer are Copyright (C) 2006
22  * Coridan Inc. All Rights Reserved.
23  *
24  * Contributor(s): all the names of the contributors are added in the source
25  * code where applicable.
26  *
27  * Alternatively, the contents of this file may be used under the terms of the
28  * LGPL license (the "GNU LESSER GENERAL PUBLIC LICENSE"), in which case the
29  * provisions of LGPL are applicable instead of those above. If you wish to
30  * allow use of your version of this file only under the terms of the LGPL
31  * License and not to allow others to use your version of this file under
32  * the MPL, indicate your decision by deleting the provisions above and
33  * replace them with the notice and other provisions required by the LGPL.
34  * If you do not delete the provisions above, a recipient may use your version
35  * of this file under either the MPL or the GNU LESSER GENERAL PUBLIC LICENSE.
36  
37  *
38  * This library is free software; you can redistribute it and/or modify it
39  * under the terms of the MPL as stated above or under the terms of the GNU
40  * Lesser General Public License as published by the Free Software Foundation;
41  * either version 2.1 of the License, or any later version.
42  *
43  * This library is distributed in the hope that it will be useful, but WITHOUT
44  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
45  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
46  * License for more details.
47  */

48
49 import java.awt.BorderLayout JavaDoc;
50 import java.awt.Color JavaDoc;
51 import java.awt.Dimension JavaDoc;
52 import java.awt.Graphics2D JavaDoc;
53 import java.awt.event.ActionEvent JavaDoc;
54 import java.awt.event.ActionListener JavaDoc;
55 import java.awt.event.MouseEvent JavaDoc;
56 import java.awt.event.MouseMotionListener JavaDoc;
57 import java.awt.event.WindowEvent JavaDoc;
58 import java.awt.event.WindowListener JavaDoc;
59 import java.awt.image.BufferedImage JavaDoc;
60 import java.io.ByteArrayOutputStream JavaDoc;
61 import java.io.DataOutputStream JavaDoc;
62 import java.io.IOException JavaDoc;
63 import java.util.HashMap JavaDoc;
64 import java.util.Iterator JavaDoc;
65 import java.util.Map JavaDoc;
66
67 import javax.jms.BytesMessage JavaDoc;
68 import javax.jms.JMSException JavaDoc;
69 import javax.jms.Session JavaDoc;
70 import javax.jms.TopicConnectionFactory JavaDoc;
71 import javax.swing.ButtonGroup JavaDoc;
72 import javax.swing.ImageIcon JavaDoc;
73 import javax.swing.JFrame JavaDoc;
74 import javax.swing.JLabel JavaDoc;
75 import javax.swing.JMenu JavaDoc;
76 import javax.swing.JMenuBar JavaDoc;
77 import javax.swing.JRadioButtonMenuItem JavaDoc;
78 import javax.swing.SwingUtilities JavaDoc;
79
80 import org.mr.MantaAgent;
81 import org.mr.api.jms.MantaTopicConnectionFactory;
82
83
84 /*==============================================================================
85   For instructions on how to run this sample please refer to the file
86   sample\jms\topics\draw\Readme.txt under the MantaRay installation directory.
87 ==============================================================================*/

88
89
90 public class DrawAgent extends JFrame JavaDoc
91                     implements WindowListener JavaDoc, MouseMotionListener JavaDoc, javax.jms.MessageListener JavaDoc {
92
93     public static final Map JavaDoc nameToColorMap;
94
95     static {
96         nameToColorMap = new HashMap JavaDoc();
97         nameToColorMap.put("Blue", Color.blue);
98         nameToColorMap.put("Red", Color.red);
99         nameToColorMap.put("Green", Color.green);
100         nameToColorMap.put("Yellow", Color.yellow);
101         nameToColorMap.put("Black", Color.black);
102     }
103
104     private static final int MESSAGE_TTL = 6000000;
105
106     private ByteArrayOutputStream JavaDoc bout = null;
107     private DataOutputStream JavaDoc dout = null;
108
109     private javax.jms.TopicConnection JavaDoc connect = null;
110     private javax.jms.TopicSession JavaDoc pubSession = null;
111     private javax.jms.TopicPublisher JavaDoc publisher = null;
112     private javax.jms.TopicSession JavaDoc subSession = null;
113     private javax.jms.TopicSubscriber JavaDoc subscriber = null;
114
115     protected final int BUFFER_SIZE = 32*1024;
116
117     protected BufferedImage JavaDoc onscreenImage = null;
118     protected Graphics2D JavaDoc onscreen = null;
119     protected Color JavaDoc background = Color.WHITE;
120     protected String JavaDoc myColor = null;
121     protected int appHight = 127;
122     protected int appWidth = 127;
123     protected JLabel JavaDoc label = null;
124
125     protected Map JavaDoc peerDataMap = null;
126     protected Map JavaDoc peerColorMap = null;
127     
128     private Runnable JavaDoc painter = null;
129
130
131     public DrawAgent() {
132         super("DrawAgent");
133
134         painter = new Runnable JavaDoc() {
135             public void run() {
136                 repaint();
137             }
138         };
139         // initialize UI
140
initUI();
141
142         // create the map to hold data from peers
143
peerDataMap = new HashMap JavaDoc();
144         peerColorMap = new HashMap JavaDoc();
145
146         // prepare byte output streams for capture
147
bout = new ByteArrayOutputStream JavaDoc(BUFFER_SIZE);
148         dout = new DataOutputStream JavaDoc(bout);
149
150         // initialize JSM
151
this.initJMS();
152     }
153
154     // initialize the UI
155
private void initUI() {
156         onscreenImage = new BufferedImage JavaDoc(appWidth, appHight, BufferedImage.TYPE_INT_RGB);
157         onscreen = (Graphics2D JavaDoc) onscreenImage.getGraphics();
158         onscreen.setColor((Color JavaDoc)nameToColorMap.get(myColor));
159         clear();
160         ImageIcon JavaDoc icon = new ImageIcon JavaDoc(onscreenImage);
161         this.getContentPane().setLayout(new BorderLayout JavaDoc(0, 0));
162         label = new JLabel JavaDoc(icon);
163         label.setPreferredSize(new Dimension JavaDoc(appWidth, appHight));
164         this.getContentPane().add(label, BorderLayout.CENTER);
165         this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
166         this.addWindowListener(this);
167         label.addMouseMotionListener(this);
168         chooseColor();
169         this.createMenu();
170         this.pack();
171     }
172
173     // create the color menu
174
private void createMenu() {
175         JMenuBar JavaDoc menuBar = new JMenuBar JavaDoc();
176         JMenu JavaDoc colorMenu = new JMenu JavaDoc("Color");
177         menuBar.add(colorMenu);
178         final ButtonGroup JavaDoc group = new ButtonGroup JavaDoc();
179         JRadioButtonMenuItem JavaDoc item = null;
180
181         ActionListener JavaDoc radioHandler = new ActionListener JavaDoc() {
182             public void actionPerformed(ActionEvent JavaDoc e) {
183                 myColor = group.getSelection().getActionCommand();
184                 onscreen.setColor((Color JavaDoc)nameToColorMap.get(myColor));
185                 sendMessage();
186                 drawData();
187             }
188         };
189         Iterator JavaDoc i = nameToColorMap.keySet().iterator();
190         while (i.hasNext()) {
191             String JavaDoc name = i.next().toString();
192             item = new JRadioButtonMenuItem JavaDoc(name);
193             item.setActionCommand(name);
194             if (name.equals(this.myColor)) {
195                 item.setSelected(true);
196             }
197             group.add(item);
198             item.addActionListener(radioHandler);
199             colorMenu.add(item);
200         }
201         this.setJMenuBar(menuBar);
202     }
203
204     // initialize the JMS layer
205
private void initJMS() {
206         // Create a connection.
207
try {
208             TopicConnectionFactory JavaDoc factory;
209             factory = new MantaTopicConnectionFactory();
210             connect = factory.createTopicConnection();
211             pubSession = connect.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
212             subSession = connect.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
213         } catch (javax.jms.JMSException JavaDoc jmse) {
214             System.err.println("error while creating connection - " + jmse.toString());
215             jmse.printStackTrace();
216             System.exit(1);
217         }
218
219         // Create Publisher to 'Draw' topics
220
try {
221             javax.jms.Topic JavaDoc topic = pubSession.createTopic("Draw");
222             publisher = pubSession.createPublisher(topic);
223             subscriber = subSession.createSubscriber(topic);
224             subscriber.setMessageListener(this);
225
226             // Now that setup is complete, start the Connection
227
connect.start();
228         } catch (javax.jms.JMSException JavaDoc jmse) {
229             jmse.printStackTrace();
230         }
231     }
232
233     // randomly select a color
234
private void chooseColor() {
235         int num = (int)(Math.random()*10%5);
236         Iterator JavaDoc i = nameToColorMap.keySet().iterator();
237         Object JavaDoc o = null;
238         while (num >= 0) {
239             o = i.next();
240             num--;
241         }
242         this.myColor = o.toString();
243     }
244
245     // draw the image
246
protected void drawData() {
247         clear();
248         Iterator JavaDoc it = this.peerDataMap.keySet().iterator();
249         while (it.hasNext()) {
250             String JavaDoc peerId = (String JavaDoc)it.next();
251             byte[] data = (byte[])peerDataMap.get(peerId);
252             String JavaDoc peerColor = (String JavaDoc)peerColorMap.get(peerId);
253             onscreen.setColor((Color JavaDoc)nameToColorMap.get(peerColor));
254
255             for (int i = 0 ; i < data.length ; i++) {
256                 onscreen.drawRect(data[i],data[++i],1,1);
257             }
258         }
259         SwingUtilities.invokeLater(painter);
260     }
261
262     // clears the image
263
protected void clear(){
264         //Color currentColor = onscreen.getColor();
265
onscreen.setColor(background);
266         onscreen.fillRect(0,0,appWidth,appHight);
267         SwingUtilities.invokeLater(painter);
268         onscreen.setColor((Color JavaDoc)nameToColorMap.get(myColor));
269     }
270
271
272     /**
273      * Handle the message
274      * (as specified in the javax.jms.MessageListener interface).
275      */

276     public void onMessage(javax.jms.Message JavaDoc aMessage)
277     {
278         javax.jms.BytesMessage JavaDoc bytesMessage = null;
279         int size = 0;
280
281         try {
282             bytesMessage = (javax.jms.BytesMessage JavaDoc) aMessage;
283             size = (int)bytesMessage.getBodyLength();
284             byte[] peerData = new byte[size];
285             //System.out.println("read size="+size+"buffer size="+data.length);
286
bytesMessage.readBytes(peerData, size);
287             String JavaDoc peerId = bytesMessage.getStringProperty("id");
288             String JavaDoc peerColor = bytesMessage.getStringProperty("color");
289             this.peerDataMap.put(peerId, peerData);
290             this.peerColorMap.put(peerId, peerColor);
291         } catch (javax.jms.JMSException JavaDoc jmse) {
292             jmse.printStackTrace();
293             return;
294         } catch (java.lang.RuntimeException JavaDoc rte) {
295             rte.printStackTrace();
296             return;
297         } catch (java.lang.Exception JavaDoc e) {
298             e.printStackTrace();
299             return;
300         }
301         this.drawData();
302     }
303
304     // closes all resources and exits program
305
public void exit() {
306         try {
307             connect.close();
308         } catch (javax.jms.JMSException JavaDoc jmse) {
309             jmse.printStackTrace();
310         } catch (Exception JavaDoc e) {
311             e.printStackTrace();
312         }
313         try {
314             dout.close();
315         } catch (IOException JavaDoc e) {
316             e.printStackTrace();
317         } catch (Exception JavaDoc e) {
318             e.printStackTrace();
319         }
320         try {
321             bout.close();
322         } catch (IOException JavaDoc e) {
323         } catch (Exception JavaDoc e) {
324             e.printStackTrace();
325         }
326         bout = null;
327         dout = null;
328         connect = null;
329
330         System.exit(0);
331     }
332
333     // sends the message to the topic
334
private void sendMessage() {
335         try {
336             BytesMessage JavaDoc msg = pubSession.createBytesMessage();
337             byte[] data = bout.toByteArray();
338             int size = bout.size();
339             msg.writeBytes(data, 0, size);
340             msg.setStringProperty("id", MantaAgent.getInstance().getAgentName());
341             msg.setStringProperty("color", myColor);
342             //publisher.publish(msg);
343
publisher.publish(msg,
344                               javax.jms.DeliveryMode.NON_PERSISTENT,
345                               javax.jms.Message.DEFAULT_PRIORITY,
346                               MESSAGE_TTL);
347         } catch (JMSException JavaDoc ex) {
348             System.out.println("Error sending message");
349             ex.printStackTrace();
350         }
351     }
352
353     // Implementing MouseMotionListener
354
public void mouseDragged(MouseEvent JavaDoc e) {
355         // add the new coordinates to the local data
356
try {
357             dout.writeByte(e.getX());
358             dout.writeByte(e.getY());
359         } catch (IOException JavaDoc ex) {
360         }
361
362         // redraw the image
363
drawData();
364
365         // sent the local data to other peers
366
sendMessage();
367     }
368     public void mouseMoved(MouseEvent JavaDoc e) {}
369
370     // Implement WindowListener
371
public void windowClosing(WindowEvent JavaDoc arg0) {
372         System.out.println("Closing the window");
373         this.exit();
374     }
375     public void windowActivated(WindowEvent JavaDoc arg0) {}
376     public void windowClosed(WindowEvent JavaDoc arg0) {}
377     public void windowDeactivated(WindowEvent JavaDoc arg0) {}
378     public void windowDeiconified(WindowEvent JavaDoc arg0) {}
379     public void windowIconified(WindowEvent JavaDoc arg0) {}
380     public void windowOpened(WindowEvent JavaDoc arg0) {}
381
382
383     public static void main(String JavaDoc[] args) throws IOException JavaDoc {
384         final DrawAgent agent = new DrawAgent();
385         SwingUtilities.invokeLater(new Runnable JavaDoc() {
386             public void run() {
387                 agent.setVisible(true);
388             }
389         });
390     }
391
392 }
393
Popular Tags