KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sample > jms > StockExample > StockPublisherExample


1 package sample.jms.StockExample;
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 lital kasif.
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  * Created on Dec 30, 2004
49  *
50  * Coridan LTD
51  */

52
53 /**
54  * An example uses the JMS API that allows to make queries to a Queue
55  * (Point-to-Point) inserting a company's name and recieve as a result
56  * its stock value on another topic (Pub/Sub). A stock that had been
57  * queriesd once would also get fluent updates of its value published at
58  * the same topic every 3 seconds.
59  *
60  * For instructions on how to run this sample please refer to the file
61  * sample\jms\StockExample\Readme.txt under the MantaRay installation directory.
62  *
63  * @author lital kasif
64  */

65 import javax.swing.*;
66
67 import java.awt.*;
68 import java.awt.event.*;
69 import java.util.HashMap JavaDoc;
70
71 import org.mr.api.jms.MantaConnectionFactory;
72 import javax.jms.ConnectionFactory JavaDoc;
73 import javax.jms.JMSException JavaDoc;
74 import javax.jms.Message JavaDoc;
75 import javax.jms.MessageConsumer JavaDoc;
76 import javax.jms.MessageProducer JavaDoc;
77 import javax.jms.Session JavaDoc;
78
79 public class StockPublisherExample implements ActionListener, javax.jms.MessageListener JavaDoc{
80
81     public static String JavaDoc companyValueSeperator = "}";
82     static StockStatus stockStatus=null;
83     public static ConnectionFactory conFactory=null;
84     //the map holds all the stocks current inforamtion as received from the stocks topic
85
public HashMap JavaDoc stocksMap=null;
86     //GUI definations
87
JFrame stockFrame;
88     JPanel stockPanel;
89     JTextField companyName;
90     JLabel instructions;
91     JButton makeQuery;
92     StocksTable model = new StocksTable();
93
94     //JMS definations
95
private static final int MESSAGE_TTL = 0;
96     private javax.jms.Connection JavaDoc con = null;
97     private javax.jms.Session JavaDoc pubSession = null;
98     private javax.jms.Session JavaDoc subSession = null;
99     private javax.jms.MessageProducer JavaDoc qSender = null;
100     private javax.jms.Topic JavaDoc stockConsumer=null;
101     private javax.jms.Queue JavaDoc queryProducer=null;
102
103     /**
104      * creates the GUI frame and panels
105      *
106      */

107     public StockPublisherExample() {
108         //Create and set up the window.
109
stockFrame = new JFrame("Present Stock Values");
110         JFrame.setDefaultLookAndFeelDecorated(true);
111         stockFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
112         //create botton and label
113
companyName = new JTextField(10);
114         makeQuery = new JButton("Query");
115         instructions = new JLabel("Enter company name then press Query", SwingConstants.LEFT);
116         //Listen to events from the Query button.
117
makeQuery.addActionListener(this);
118         //create table holding the stocks inofmtaion
119
JTable table = new JTable(model);
120         table.setPreferredScrollableViewportSize(new Dimension(250, 50));
121
122         // Create and set up the panells
123
JScrollPane scrollPane = new JScrollPane(table);
124         stockPanel = (JPanel)stockFrame.getContentPane();
125         stockPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
126         Box top = new Box(BoxLayout.Y_AXIS);
127         Box instructionsPanel = new Box(BoxLayout.X_AXIS);
128         instructionsPanel.add(instructions);
129         instructionsPanel.add(Box.createHorizontalGlue());
130         top.add(instructionsPanel);
131         Box queryPanel = new Box(BoxLayout.X_AXIS);
132         queryPanel.add(companyName);
133         queryPanel.add(makeQuery);
134         top.add(queryPanel);
135         stockPanel.add(top, BorderLayout.NORTH);
136         stockPanel.add(scrollPane, BorderLayout.CENTER);
137
138         //Display the window.
139
stockFrame.pack();
140         stockFrame.setVisible(true);
141     }
142
143     /**
144      * Operated when the query botton is pressed and causes a creation of a query with
145      * the inserted company's name to be sent to the query queue.
146      */

147     public void actionPerformed(ActionEvent event) {
148         String JavaDoc name=companyName.getText();
149         this.sendQuery(name);
150
151     }//actionPerformed
152

153     /**
154      * Create the GUI and show it, then causes the registration on the topic and queue.
155      * For thread safety, this method should be invoked from the event-dispatching thread.
156      */

157     private static void createAndShowGUI() {
158         //Make decorations.
159
JFrame.setDefaultLookAndFeelDecorated(true);
160         StockPublisherExample converter = new StockPublisherExample();
161         converter.createDestinations();
162     }//createAndShowGUI()
163

164     /**
165      * createDestinations() creates a producer to the query queue and a consumer to the
166      * stock status topic
167      */

168     public void createDestinations(){
169         // Create a connection and two ways sessions.
170
try
171         {
172             //Set up the JMS objects needed
173
con = StockPublisherExample.conFactory.createConnection();
174             //both sessions are not transacted.
175
pubSession = con.createSession(false,Session.AUTO_ACKNOWLEDGE);
176             subSession = con.createSession(false,Session.AUTO_ACKNOWLEDGE);
177         }
178         catch (javax.jms.JMSException JavaDoc jmse)
179         {
180             jmse.printStackTrace();
181             System.exit(1);
182         }
183         try {
184             //create a consumer to the 'stocks status' topic
185
stockConsumer = subSession.createTopic("SampleTopic1");
186             MessageConsumer JavaDoc consumer = subSession.createConsumer(stockConsumer);
187             consumer.setMessageListener(this);
188             //create a producer to the 'query stocks' queue
189
queryProducer = pubSession.createQueue("q1");
190             qSender = (MessageProducer JavaDoc)pubSession.createProducer(queryProducer);
191             con.start();
192         } catch (JMSException JavaDoc e) {
193             e.printStackTrace();
194         }//catch
195
}//createDestinations()
196

197     /**
198      * produces a query to the 'stock query' queue
199      */

200     public void sendQuery(String JavaDoc company){
201         try{
202             if(company==null||company.equals(""))
203                 return;
204             //produce a message with the query in it to the query queue
205
javax.jms.TextMessage JavaDoc msg = this.pubSession.createTextMessage();
206             msg.setText(company);
207             // for PERSISTENT replace NON_PERSISTENT in PERSISTENT
208
// Hold messages for MESSAGE_TTL millisecs.
209
qSender.send( msg,
210                    javax.jms.DeliveryMode.NON_PERSISTENT,
211                    javax.jms.Message.DEFAULT_PRIORITY,
212                    MESSAGE_TTL);
213         }
214         catch ( javax.jms.JMSException JavaDoc jmse )
215         {
216             jmse.printStackTrace();
217         }
218     }//sendQuery
219

220     /* (non-Javadoc)
221      * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
222      */

223     public void onMessage(Message JavaDoc message) {
224         //Cast the message as a text message
225
javax.jms.TextMessage JavaDoc stockValuesMessage = (javax.jms.TextMessage JavaDoc) message;
226         String JavaDoc stockInfo=null;
227         //gets the text out of the message
228
try
229         {
230             stockInfo = stockValuesMessage.getText();
231         }catch (javax.jms.JMSException JavaDoc jmse){
232                 jmse.printStackTrace();
233         }
234         //splits the company name from its stock value
235
String JavaDoc[] newValues=stockInfo.split(companyValueSeperator);
236         //calls for an update of the companies value in the table model
237
model.updateCompany(newValues[0],newValues[1]);
238     }//onMessage
239

240     public static void main(String JavaDoc[] args) {
241         System.out.println("MANTARAY STOCK PUBLISHER EXAMPLE IS STARTING");
242         conFactory = new MantaConnectionFactory();
243         //create a 'stockStatus' that would listen to the query queue and publish the stocks values
244
stockStatus = new StockStatus();
245         stockStatus.createDestinations();
246         //creating and showing this application's GUI.
247
javax.swing.SwingUtilities.invokeLater(new Runnable JavaDoc() {
248             public void run() {
249                 createAndShowGUI();
250             }
251         });
252         stockStatus.start();
253     }//main
254

255 }//StockPublisherExample
256
Popular Tags