source: tmcsimulator/trunk/src/atmsdriver/ExchangeReader.java @ 79

Revision 79, 7.5 KB checked in by jtorres, 9 years ago (diff)

new atmsdriver package in trunk. fep_rpc_client dynamic data packing added in branches. fep_rpc_client refactored data packing code into static DataPacker? class. Added vds_data folder into config/. Added new project configuration for ATMSDriver.

Line 
1package atmsdriver;
2
3import java.io.BufferedReader;
4import java.io.File;
5import java.io.FileNotFoundException;
6import java.io.FileReader;
7import java.io.FileWriter;
8import java.io.IOException;
9import java.io.StringReader;
10import java.util.logging.Level;
11import java.util.logging.Logger;
12import javax.xml.parsers.ParserConfigurationException;
13import javax.xml.parsers.SAXParserFactory;
14import org.xml.sax.Attributes;
15import org.xml.sax.InputSource;
16import org.xml.sax.SAXException;
17import org.xml.sax.SAXParseException;
18import org.xml.sax.helpers.DefaultHandler;
19
20/**
21 *
22 * @author John A Torres
23 */
24public class ExchangeReader {
25        /** Error Log **/
26        private static Logger ATMSDriverLogger = Logger.getLogger("atmsdriver");
27       
28        /** A SAX Handler that is used to parse received Incident Status Node. **/
29        private IncidentStatusHandler ish = null;
30       
31        /** The current networkId **/
32        private int networkId = 1;
33       
34        /** The Paramics Simulation Info for the most recent incident read **/
35        private ExchangeInfo exInfo = null;
36       
37        /** Value (seconds since 1/1/1970) of input file's last modification time. */
38        private long lastModified = 0;
39       
40        /**
41         * Constructor.
42         */
43        public ExchangeReader() 
44        {               
45                ish = new IncidentStatusHandler();
46        }
47       
48        /**
49         * This method parses the received XML node with the local CameraStatusHandler.
50         * All updated camera information is sent to the ParamicsSimulationManager.
51         *
52         * If a successful read of the file occurs, the file is written with an empty string
53         * and the date of the last modification is stored.
54         *
55         * @param filename The file to check for message in.
56         * @return A ParamicsSimulationInfo object containing the file's information
57         *                 A null pointer on:
58         *                   - The file does not exist
59         *                   - No new modification
60         *                   - An error opening file             
61         *           - An empty file
62         *           - An error parsing the file
63         *           
64         *         The caller is able to call this function to check if there are any new messages
65         *         in the file.  If there are, a PSI object is returned.  If there aren't any new
66         *         messages, a null pointer is returned.
67         */
68        public ExchangeInfo parse(String filename) 
69        {       
70                ExchangeInfo exInfo = null;
71               
72                File f = new File(filename);
73                BufferedReader r = null;
74               
75                // File does not exist: No information
76                if (!(f.exists()))
77                {
78                        return null;
79                }
80               
81                // File not modified: No new information
82                if (f.lastModified() <= lastModified)
83                {
84                        return null;
85                }
86               
87                try 
88                {
89                        // Try to open the file
90                        r = new BufferedReader(new FileReader(f));
91                       
92                        // Read the file to the end
93                        StringBuilder xml = new StringBuilder("");
94                        String line = r.readLine();
95                        while (line != null)
96                        {
97                                xml.append(line + "\n");
98                                line = r.readLine();
99                        }
100                       
101                        // If the file has contents in it, read them and returned a PSI describing the contents
102                        if(xml.length() > 0) 
103                        {
104                                // Parse the file
105                                SAXParserFactory.newInstance().newSAXParser().parse(new InputSource(new StringReader(xml.toString())), ish);
106                                exInfo = new ExchangeInfo(networkId, xml.toString());
107                        }
108                        else if (xml.length() == 0)
109                        {
110                                lastModified = modifyFile(f);
111                                r.close();
112                        }
113                }
114                catch (FileNotFoundException fnfe)
115                {
116                        ATMSDriverLogger.logp(Level.SEVERE, "ParamicsIncidentReader", "parse", 
117                                        filename + " dissapeared before reading.", fnfe);
118                        exInfo = null;
119                }
120                catch (IOException ioe)
121                {
122                        ATMSDriverLogger.logp(Level.SEVERE, "ParamicsIncidentReader", "parse", 
123                                        "Error while reading file " + filename + ".", ioe);
124                        exInfo = null;
125                }
126                catch (SAXException saxe)
127                {
128                        ATMSDriverLogger.logp(Level.SEVERE, "ParamicsIncidentReader", "parse", 
129                                        "Error while parsing file " + filename + ".", saxe);
130                        exInfo = null;
131                }
132                catch (ParserConfigurationException pce)
133                {
134                        ATMSDriverLogger.logp(Level.SEVERE, "ParamicsIncidentReader", "parse", 
135                                        "Error while configuring parser.", pce);
136                }
137               
138                // If a incident was read
139                if (exInfo != null)
140                {
141                        lastModified = modifyFile(f);
142                        try
143                        {
144                                r.close();
145                        }
146                        catch (IOException e)
147                        {
148                                ATMSDriverLogger.logp(Level.SEVERE, "ParamicsIncidentReader", "parse", 
149                                                "Error while closing file" + filename + ".", e);
150                        }                       
151                }
152               
153                // Return no object if there was an error while reading, or the psi created from
154                // parsing the file if the operation was successful.
155                return exInfo;
156        }
157       
158        private long modifyFile(File f)
159        {
160                FileWriter w = null;
161               
162                // Write to the file to show that it was read.
163                try
164                {
165                        w = new FileWriter(f);
166                        w.write("");
167                        w.close();
168                }
169                catch (IOException e)
170                {
171                        ATMSDriverLogger.logp(Level.SEVERE, "ParamicsIncidentReader", "parse", 
172                                        "Error while writing to file " + f.getName() + " to show that file was read.", e);
173                }
174               
175                // Save the last modified time
176                return f.lastModified();
177        }
178
179    /**
180     * Internal SAX Handler used to parse the Incident Status Document read by
181     * the remote Status Reader.  The schema for this document is: <br/>
182     *
183         * <CAD_DATA><br>
184         *    <Basic><br>
185         *       <Comm_Interval/><br/>
186         *       <Network_ID/><br/>
187         *       <Simulation/><br/>
188         *       <Incident/><br/>
189         *    </Basic>
190         *
191         *    <Simulation_Data>
192         *       <Simulation_speed/><br/>
193         *       <CAD_clock><br/>
194         *          <hour/><br/>
195         *          <minute/><br/>
196         *          <second/><br/>
197         *          <Location><br/>
198         *       </CAD_clock><br/>
199         *    </Simulation_Data>
200         *   
201         *    <CAD_Incidents>
202         *       <Incident><br/>
203         *          <Identifier/><br/>
204         *          <Status/><br/>
205         *          <Location><br/>
206         *              <Route/><br/>
207         *              <Direction/><br/>
208         *              <Location_type/><br/>
209         *              <Postmile/><br/>
210         *          </Location><br/>
211         *          <Incident_type/><br/>
212         *          <Lanes><br/>
213         *             <Lane_number/><br/>
214         *             ...
215         *          </Lanes><br/>
216         *       </Incident><br/>
217         *       ...
218         *    </CAD_Incidents>   
219         *   
220         *    <Management>
221         *       <Diversion>
222     *          <Diversion_path>
223     *             <Identifier/>
224     *             <Percentage/>
225     *          <Diversion_path>
226     *          ...
227     *       </Diversion>
228     *       ...
229         *    </Management>
230         * 
231         * </CAD_DATA>
232     */ 
233        protected class IncidentStatusHandler extends DefaultHandler
234        {
235                private final String NETWORK_ID   = "Network_ID";
236               
237                /** A buffer for reading characters **/
238                private StringBuffer parsedValue  = new StringBuffer();
239
240                public void startDocument() 
241                { 
242                }       
243               
244                /** Appends characters to the xmlMessage and parsedValue buffers **/
245                public void characters(char[] ch, int start, int length) 
246                {
247                        parsedValue.append(new String(ch, start, length).trim());
248                }
249               
250            public void startElement (String uri, String localName, String qName, Attributes attributes)
251                        throws SAXException
252                {
253            }
254               
255                public void endElement(String uri, String localName, String qName) 
256                {
257                        if(qName.equals(NETWORK_ID)) { networkId = Integer.parseInt(parsedValue.toString()); }
258                       
259                        parsedValue.setLength(0);
260                }       
261               
262                public void error(SAXParseException e) 
263                {
264                        ATMSDriverLogger.logp(Level.SEVERE, "ParamicsIncidentReader", "error", 
265                                        "Error in parsing received incident status.", e);
266                }
267               
268                public void fatalError(SAXParseException e) 
269                {
270                        ATMSDriverLogger.logp(Level.SEVERE, "ParamicsIncidentReader", "fatalError", 
271                                        "Fatal error in parsing received incident status.", e);
272                }
273               
274                public void warning(SAXParseException e) 
275                {
276                        ATMSDriverLogger.logp(Level.WARNING, "ParamicsIncidentReader", "warning", 
277                                        "Warning in parsing received incident status.", e);
278                }               
279        }
280}
Note: See TracBrowser for help on using the repository browser.