View Javadoc

1   /*
2    * $Id: TickFeed.java 22164 2011-06-09 18:46:19Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.example.cep;
12  
13  import org.mule.api.MuleEventContext;
14  import org.mule.api.lifecycle.Callable;
15  import org.mule.api.lifecycle.Initialisable;
16  import org.mule.api.lifecycle.InitialisationException;
17  import org.mule.util.IOUtils;
18  
19  import java.io.IOException;
20  import java.io.InputStream;
21  import java.text.MessageFormat;
22  import java.util.Iterator;
23  import java.util.List;
24  import java.util.Locale;
25  
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  
29  public class TickFeed implements Initialisable, Callable
30  {
31      public static final String DATA_FILE = "stocktickstream.dat";
32  	private static final MessageFormat lineFormat = new MessageFormat("{0,number,0};{1};{2,number,currency}", Locale.US);
33      
34      private Iterator<String> lines;
35      
36      protected transient Log logger = LogFactory.getLog(getClass());
37      
38      public void initialise() throws InitialisationException
39      {
40          try
41          {
42              lines = readStockTickDataFile();
43          }
44          catch (IOException e)
45          {
46              throw new InitialisationException(e, this);
47          }
48      }
49  
50      private Iterator<String> readStockTickDataFile() throws IOException
51      {
52          InputStream is = IOUtils.getResourceAsStream(DATA_FILE, TickFeed.class, false, false);
53          try
54          {
55              List<String> linesList = IOUtils.readLines(is);
56              logger.debug("Read data file, " + linesList.size() + " lines");
57              return linesList.iterator();
58          }
59          finally
60          {
61              is.close();
62          }
63      }
64      
65      public Object onCall(MuleEventContext eventContext) throws Exception
66      {
67          // If we've gone through the entire datafile, start over again from the beginning.
68          if (!lines.hasNext())
69          {
70              lines = readStockTickDataFile();
71          }
72  
73          Object[] results = lineFormat.parse(lines.next());
74          StockTick tick = new StockTick((String)results[1],
75                                         ((Number)results[2]).doubleValue(),
76                                         ((Number)results[0]).longValue());
77          logger.info("New Stock Tick: " + tick);
78          return tick;
79      }
80  }
81  
82