KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > nl > justobjects > pushlet > test > TestEventPushSources


1 // Copyright (c) 2000 Just Objects B.V. <just@justobjects.nl>
2
// Distributable under LGPL license. See terms of license at gnu.org.
3

4 package nl.justobjects.pushlet.test;
5
6 import nl.justobjects.pushlet.core.Dispatcher;
7 import nl.justobjects.pushlet.core.Event;
8 import nl.justobjects.pushlet.core.EventSource;
9
10 import java.io.BufferedReader JavaDoc;
11 import java.io.IOException JavaDoc;
12 import java.io.InputStream JavaDoc;
13 import java.io.InputStreamReader JavaDoc;
14 import java.net.URL JavaDoc;
15 import java.util.Random JavaDoc;
16 import java.util.StringTokenizer JavaDoc;
17 import java.util.Vector JavaDoc;
18
19 /**
20  * Event sources that push events (for testing).
21  *
22  * @version $Id: TestEventPushSources.java,v 1.9 2005/02/28 09:14:56 justb Exp $
23  * @author Just van den Broecke - Just Objects &copy;
24  **/

25 public class TestEventPushSources {
26
27     static public class AEXStocksEventPushSourceABN {
28         String JavaDoc pageURL = "http://ri2.rois.com/E36msPtnZC0e15CVb4KT97JAGfGSfCcrvv6*FcyZIoNyh/CTIB/RI2APISNAP?RIC=0%23.AEX&FORMAT=XML";
29         // This could be further expanded: getting the Reuters AEX stocks
30
// as XML from ABN with this URL, but we may get into legal problems...
31
}
32
33     /** Produces events from REAL stocks from the AEX. */
34     static public class AEXStocksEventPushSource implements EventSource, Runnable JavaDoc {
35         /** Here we get our stocks from. */
36         String JavaDoc pageURL = "http://www.debeurs.nl/koersen/aex.asp";
37         Thread JavaDoc thread = null;
38         volatile boolean active = false;
39
40         // Since Baan has been thrown out...
41
public final static int NR_OF_STOCKS = 24;
42
43         public final static String JavaDoc EMPTY = "wait...";
44         private int restarts = 1;
45
46         class Stock {
47             public String JavaDoc name = EMPTY;
48             public String JavaDoc rate = EMPTY;
49             volatile public boolean modified = false;
50         }
51
52         Vector JavaDoc stocksCache = new Vector JavaDoc(NR_OF_STOCKS);
53
54         public AEXStocksEventPushSource() {
55             for (int i = 0; i < NR_OF_STOCKS; i++) {
56                 stocksCache.addElement(new Stock());
57             }
58             // updateCache();
59
}
60
61         /** Activate the event source. */
62         synchronized public void activate() {
63             e("activating...");
64             // Stop a possibly running thread
65
stopThread();
66
67             // Start new thread and
68
thread = new Thread JavaDoc(this, "AEXStocksPublisher-" + (restarts++));
69             active = true;
70             thread.start();
71             e("activated");
72         }
73
74         /** Deactivate the event source. */
75         synchronized public void passivate() {
76             e("passivating...");
77             active = false;
78             stopThread();
79
80             // Mark the cache modified so we'll send the contents
81
// on the next activation.
82
for (int i = 0; i < NR_OF_STOCKS; i++) {
83                 ((Stock) stocksCache.elementAt(i)).modified = true;
84             }
85
86             e("passivated");
87         }
88
89
90         /** Deactivate the event source. */
91         synchronized public void stop() {
92         }
93
94         public void run() {
95             // Publish cache content (if any) first.
96
publishStocks();
97
98             int count = 5; // enforce update first
99
while (active) {
100
101                 // Only do work if active
102
// Update cache every 10 secs.
103
if (count == 5) {
104                     updateCache();
105                     count = 0;
106                 }
107                 count++;
108
109                 // Do updates for changed stock rates
110
sendUpdates();
111
112                 // If we were interrupted just return.
113
if (thread == null || thread.isInterrupted()) {
114                     break;
115                 }
116
117                 // Sleep 2 secs before sending next updates
118
try {
119                     thread.sleep(2000);
120                 } catch (InterruptedException JavaDoc ie) {
121                     break;
122                 }
123             }
124
125             // Loop terminated: reset vars
126
thread = null;
127             active = false;
128         }
129
130         private String JavaDoc getStocksLine() {
131             BufferedReader JavaDoc br = null;
132             InputStream JavaDoc is = null;
133             String JavaDoc nextLine = "";
134
135             // Read line from server
136
try {
137                 is = new URL JavaDoc(pageURL).openStream();
138                 br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is));
139                 boolean foundLine = false;
140                 while (!foundLine) {
141                     nextLine = br.readLine();
142                     if (nextLine == null) {
143                         return "";
144                     }
145                     foundLine = (nextLine.indexOf("details.asp?iid=14053&parent=aex") != -1);
146                 }
147             } catch (Exception JavaDoc e) {
148                 e("could not open or read URL pageURL=" + pageURL + " ex=" + e);
149                 return "";
150             } finally {
151                 try {
152                     if (is != null) is.close();
153                 } catch (IOException JavaDoc ignore) {
154                 }
155             }
156             return nextLine;
157         }
158
159         private void publishStocks() {
160             // Publish only modified stocks from the cache
161
for (int i = 0; i < NR_OF_STOCKS; i++) {
162                 Stock nextStock = (Stock) stocksCache.elementAt(i);
163
164                 // Publish modified stocks
165
if (nextStock.modified) {
166                     publishStock(i, nextStock.name, nextStock.rate);
167                     nextStock.modified = false;
168                     try {
169                         Thread.sleep(400);
170                     } catch (InterruptedException JavaDoc ie) {
171                         return;
172                     }
173                 }
174             }
175         }
176
177         private void publishStock(int index, String JavaDoc name, String JavaDoc rate) {
178             Event event = Event.createDataEvent("/stocks/aex");
179             event.setField("number", index + "");
180             event.setField("name", name);
181             event.setField("rate", rate);
182             p("publish: nr=" + index + " name=" + name + " rate=" + rate);
183             Dispatcher.getInstance().multicast(event);
184         }
185
186         private void sendUpdates() {
187             p("sending updates");
188             // In any case send a random stock value by
189
// making it modified, just to see something moving...
190
int randomIndex = randomInt(0, NR_OF_STOCKS - 1);
191             Stock randomStock = (Stock) stocksCache.elementAt(randomIndex);
192             randomStock.modified = true;
193
194             publishStocks();
195         }
196
197         private void stopThread() {
198             if (thread != null) {
199                 thread.interrupt();
200                 thread = null;
201             }
202         }
203
204         private void updateCache() {
205             p("updating Cache");
206
207             // Get the line with all stocks from HTML page
208
String JavaDoc stocksLine = getStocksLine();
209             if ("".equals(stocksLine)) {
210                 e("updateCache: stocksLine == null");
211                 return;
212             }
213
214             // Parse the stocksline and put in cache.
215
// Beware: this is the messy part!!
216
// We assume that stock/names and rates are located at
217
// regular positions in the line.
218
String JavaDoc delim = "<>";
219             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(stocksLine, delim);
220             String JavaDoc nextToken = "";
221             int count = 0;
222             String JavaDoc nextStock = "";
223             String JavaDoc nextQuote = "";
224             String JavaDoc currentQuote = null;
225             int index = -1;
226             while (st.hasMoreTokens()) {
227                 nextToken = st.nextToken();
228                 count++;
229                 // The <TD> with the stock name
230
if ((count - 5) % 57 == 0) {
231                     p("c=" + count + " s=" + nextToken);
232                     nextStock = nextToken;
233                 }
234
235                 // The <TD> with the stock rate
236
if ((count - 10) % 57 == 0) {
237                     nextQuote = nextToken;
238                     index++;
239                     p("c=" + count + " val=" + nextQuote);
240                     Stock currentStock = (Stock) stocksCache.elementAt(index);
241
242                     // Only update new or modified stocks
243
if (EMPTY.equals(currentStock.rate) || !currentStock.rate.equals(nextQuote)) {
244                         p("modified: " + nextStock);
245                         currentStock.name = nextStock;
246                         currentStock.rate = nextQuote;
247                         currentStock.modified = true;
248                     }
249                 }
250             }
251         }
252     }
253
254     private static Random JavaDoc random = new Random JavaDoc();
255
256     /** Util: generate a random int between min and max value.*/
257     public static int randomInt(int min, int max) {
258         int nextRandom = random.nextInt();
259         return min + (nextRandom < 0 ? -nextRandom : nextRandom) % (max - min + 1);
260     }
261
262
263     /** Util: stderr print method.*/
264     public static void e(String JavaDoc s) {
265         System.out.println("AEXStocksEventPushSource: " + s);
266     }
267
268     /** Util: stdout print method.*/
269     public static void p(String JavaDoc s) {
270         // System.out.println(s);
271
}
272
273
274     public static void main(String JavaDoc[] args) {
275         // new TestEventPushSources$AEXStocksEventPushSource();
276
}
277 }
278
279 /*
280  * $Log: TestEventPushSources.java,v $
281  * Revision 1.9 2005/02/28 09:14:56 justb
282  * sessmgr/dispatcher factory/singleton support
283  *
284  * Revision 1.8 2005/02/21 16:59:17 justb
285  * SessionManager and session lease introduced
286  *
287  * Revision 1.7 2005/02/18 10:07:23 justb
288  * many renamings of classes (make names compact)
289  *
290  * Revision 1.6 2005/02/18 09:54:15 justb
291  * refactor: rename Publisher Dispatcher and single Subscriber class
292  *
293  * Revision 1.5 2004/09/03 22:35:37 justb
294  * Almost complete rewrite, just checking in now
295  *
296  * Revision 1.4 2004/03/10 15:45:55 justb
297  * many cosmetic changes
298  *
299  * Revision 1.3 2003/08/15 08:37:41 justb
300  * fix/add Copyright+LGPL file headers and footers
301  *
302  * Revision 1.2 2003/05/18 16:15:08 justb
303  * support for XML encoded Events
304  *
305  * Revision 1.1.1.1 2002/09/24 21:02:33 justb
306  * import to sourceforge
307  *
308  * Revision 1.1.1.1 2002/09/20 22:48:20 justb
309  * import to SF
310  *
311  * Revision 1.1.1.1 2002/09/20 14:19:02 justb
312  * first import into SF
313  *
314  * Revision 1.6 2001/02/18 23:45:13 just
315  * fixes for AEX
316  *
317  * Revision 1.5 2000/10/30 14:16:09 just
318  * no message
319  *
320  * Revision 1.4 2000/09/24 21:02:43 just
321  * chnages due to changed webpage in debeurs.nl
322  *
323  * Revision 1.3 2000/08/31 12:49:50 just
324  * added CVS comment tags for log and copyright
325  *
326  *
327  */

328
Popular Tags