source: tmcsimulator/trunk/src/archive/paramsim/paramicssimulator/ParamicsIncidentReader.java @ 66

Revision 66, 7.6 KB checked in by jdalbey, 9 years ago (diff)

Import Paramics Simulator.

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