Warning: Can't use blame annotator:
svn blame failed on trunk/src/atmsdriver/model/Highways.java: ("Can't find a temporary directory: Internal error", 20014)

source: tmcsimulator/trunk/src/atmsdriver/model/Highways.java @ 128

Revision 128, 10.0 KB checked in by jdalbey, 9 years ago (diff)

ATMSBatchDriver.java Added a GUI to display event queue. Highways.java modified to throw an exception when writeToFEP can't connect to FEP_Sim.

RevLine 
1package atmsdriver.model;
2
3import atmsdriver.FEPLineLoader;
4import java.io.File;
5import java.io.FileWriter;
6import java.io.IOException;
7import java.io.PrintWriter;
8import java.io.StringWriter;
9import java.io.Writer;
10import java.net.Socket;
11import java.util.ArrayList;
12import java.util.Collections;
13import java.util.HashMap;
14import java.util.Map;
15import java.util.Observable;
16import java.util.Observer;
17import java.util.Set;
18import java.util.logging.Level;
19import java.util.logging.Logger;
20import javax.xml.parsers.DocumentBuilder;
21import javax.xml.parsers.DocumentBuilderFactory;
22import javax.xml.transform.OutputKeys;
23import javax.xml.transform.Transformer;
24import javax.xml.transform.TransformerFactory;
25import javax.xml.transform.dom.DOMSource;
26import javax.xml.transform.stream.StreamResult;
27import org.w3c.dom.Document;
28import org.w3c.dom.Element;
29import tmcsim.common.SimulationException;
30
31/** The Highways class aggregates all Highway instances within a geographic
32 *  region, and all of the FEPLines within an electronic detector
33 *  network, in the same geographic region. An instance of Highways.java
34 *  comprises the underlying model for the ATMSDriver application.
35 *
36 *  Highways uses method writeToFEP() to communicate with the FEP Simulator.
37 *  It creates a socket client which sends the FEP Simulator a highways status
38 *  message over the socket. This message is in the XML format required by the
39 *  FEP Simulator, which is provided by the resident toXML() method.
40 *
41 *  Currently, there is no driving logic within the highways class. It is only
42 *  done through an instance of the ConsoleDriver.java class. Eventually, it
43 *  will receive incident data (from exchange.xml or better yet, directly from
44 *  the TMCSimulator itself) and drive the highways using resident logic.
45 *
46 * @author John A. Torres
47 */
48public class Highways {
49
50    final private ArrayList<FEPLine> lines;
51    final private String FEPHostName;
52    final private int FEPPortNum;
53   
54    final public ArrayList<Highway> highways;
55   
56    public Highways(String ldsFileName, String loopsFileName,
57            String highwayMetaFileName, String FEPHostName, int FEPPortNum) {
58        /*
59         lines = loadLines(highwayMetaFileName);
60         System.out.println("SIZE: " + toXML().toCharArray().length);
61         */
62
63        FEPLineLoader ldr = new FEPLineLoader(new File(ldsFileName), new File(loopsFileName));
64        this.lines = (ArrayList<FEPLine>) ldr.getFEPLines();
65        this.FEPHostName = FEPHostName;
66        this.FEPPortNum = FEPPortNum;
67        this.highways = loadHighways();
68        //writeHighwaysMeta("hard.txt");
69    }
70   
71    private ArrayList<Highway> loadHighways() {
72        System.out.println("Loading highways...");
73        // The list of highways to return
74        ArrayList<Highway> highways = new ArrayList<Highway>();
75       
76        Map<Integer, ArrayList<Station>>
77                highwayMap = new HashMap<>();
78       
79        for (FEPLine line : lines)
80        {
81            ArrayList<Station> lineStations = (ArrayList<Station>) line.stations;
82            for(Station station : lineStations)
83            {
84                Integer hwyNum = station.routeNumber;
85
86                if(!highwayMap.containsKey(hwyNum))
87                {
88                    ArrayList<Station> stnList = new ArrayList<>();
89                    stnList.add(station);
90                    highwayMap.put(hwyNum, stnList);
91                }
92                else
93                {
94                    highwayMap.get(hwyNum).add(station);
95                }
96            }
97        }
98       
99        Set<Integer> hwyKeys = highwayMap.keySet();
100        for(Integer hwyKey : hwyKeys)
101        {
102            ArrayList<Station> hwyStations = highwayMap.get(hwyKey);
103            Collections.sort(hwyStations);
104            System.out.println("Loaded highway " + hwyKey + "...");
105            highways.add(new Highway(hwyKey, 
106                    hwyStations));
107        }
108        System.out.println("");
109        return highways;
110    }
111   
112    /*
113     private ArrayList<FEPLine> loadLines(String highwayMetaFileName) {
114     ArrayList<FEPLine> lines = new ArrayList<>();
115     try {
116     Scanner sc = new Scanner(new File(highwayMetaFileName));
117     String firstLine = sc.nextLine();
118
119     Scanner linesc = new Scanner(firstLine);
120     int numLines = linesc.nextInt();
121     linesc.close();
122
123     for (int i = 0; i < numLines; i++) {
124     System.out.println("CURR: " + i);
125     lines.add(loadLine(sc));
126     }
127     sc.close();
128
129     } catch (FileNotFoundException ex) {
130     Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
131     }
132     return lines;
133     }
134
135     private FEPLine loadLine(Scanner sc) {
136     String line = sc.nextLine();
137     System.out.println(line);
138     Scanner scline = new Scanner(line);
139
140     int lineNum = scline.nextInt();
141     int count = scline.nextInt();
142     int numStations = scline.nextInt();
143     ArrayList<Station> stations = new ArrayList<>();
144     for (int i = 0; i < numStations; i++) {
145     stations.add(loadStation(sc, lineNum));
146     }
147
148     return new FEPLine(lineNum, stations, count);
149     }
150
151     private Station loadStation(Scanner sc, int lineNum) {
152     String line = sc.nextLine();
153     System.out.println(line);
154     Scanner scline = new Scanner(line);
155     int ldsID = scline.nextInt();
156     int drop = scline.nextInt();
157     int fwy = scline.nextInt();
158     DIRECTION dir = DIRECTION.getEnum(scline.next());
159     double postmile = scline.nextDouble();
160     int numLoops = scline.nextInt();
161     String location = getStationLoc(line);
162     ArrayList<LoopDetector> loops = new ArrayList<>();
163     for (int i = 0; i < numLoops; i++) {
164     loops.add(loadLoop(sc));
165     }
166
167     return new Station(lineNum, ldsID, drop, location, loops, fwy, dir, postmile);
168     }
169
170     private LoopDetector loadLoop(Scanner sc) {
171     String line = sc.nextLine();
172     Scanner scline = new Scanner(line);
173
174     int loopID = scline.nextInt();
175     int laneNum = scline.nextInt();
176     String loopLoc = getLoopLoc(line); // NEED GET LOOPLOC
177     scline.close();
178     return new LoopDetector(loopID, loopLoc, laneNum);
179     }
180
181     private String getLoopLoc(String line) {
182     Scanner sc = new Scanner(line);
183     sc.nextInt();
184     sc.nextInt();
185
186     // GRABS FROM CURRENT TO END OF LINE
187         
188     sc.useDelimiter("\\z");
189     String loc = sc.next().trim();
190     sc.close();
191     return loc;
192     }
193
194     // Returns the loction given the whole line from the lookup file
195     private String getStationLoc(String line) {
196     Scanner scline = new Scanner(line);
197     scline.nextInt();
198     scline.nextInt();
199     scline.nextInt();
200     scline.next();
201     scline.nextDouble();
202     scline.nextInt();
203
204     // GRABS FROM CURRENT TO END OF LINE
205     scline.useDelimiter("\\z");
206     String loc = scline.next().trim();
207     scline.close();
208     return loc;
209     }
210     */
211
212    public void writeToFEP() throws SimulationException {
213        try {
214            Socket sock = new Socket(FEPHostName /*"192.168.251.130"*/, 8080);
215            PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
216            out.println(this.toXML());
217            sock.close();
218        } catch (IOException ex) {
219            Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
220            System.out.println("Highway Model failed writing to FEPSim.");
221            throw new SimulationException(SimulationException.BINDING);
222        }
223    }
224
225    // CHECK: DO WE EVEN NEED TO DO THIS?
226    private void updateSequences() {
227        for (FEPLine line : lines) {
228            line.updateSequences();
229        }
230    }
231
232    /**
233     * Returns the network metadata in condensed form. This is just a quick
234     * script function to make a proper highway metadata configuration file, so
235     * that we can read the network faster.
236     *
237     * @return Network metadata
238     */
239    public void writeHighwaysMeta(String fileName) {
240
241        try {
242            FileWriter fw = new FileWriter(new File(fileName));
243            StringBuilder build = new StringBuilder();
244            build.append(lines.size());
245            build.append("\n");
246            System.out.println(lines.size());
247            fw.write(build.toString());
248            int count = 1;
249            for (FEPLine line : lines) {
250                System.out.println("Writing num: " + count);
251                count++;
252                fw.write(line.getLineMeta());
253
254            }
255        } catch (IOException ex) {
256            Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
257        }
258    }
259
260    public String toXML() {
261        String xml = null;
262        try {
263            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
264            DocumentBuilder builder = factory.newDocumentBuilder();
265            Document theDoc = builder.newDocument();
266
267            Element networkElement = theDoc.createElement(XML_TAGS.NETWORK.tag);
268            theDoc.appendChild(networkElement);
269
270            for (FEPLine line : lines) {
271                line.toXML(networkElement);
272            }
273
274            Transformer tf = TransformerFactory.newInstance().newTransformer();
275
276            tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
277            tf.setOutputProperty(OutputKeys.INDENT, "yes");
278            tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
279
280            Writer out = new StringWriter();
281            tf.transform(new DOMSource(theDoc), new StreamResult(out));
282            xml = out.toString();
283            out.close();
284        } catch (Exception ex) {
285            Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
286        }
287        return xml;
288
289    }
290
291    public Highway getHighwayByRouteNumber(Integer routeNum) {
292        Highway returnHwy = null;
293        for(Highway hwy : highways)
294        {
295            if(hwy.routeNumber.equals(routeNum))
296            {
297                returnHwy = hwy;
298                break;
299            }
300        }
301        return returnHwy;
302    }
303
304    private static enum XML_TAGS {
305
306        NETWORK("Network");
307
308        String tag;
309
310        private XML_TAGS(String n) {
311            tag = n;
312        }
313    }
314}
Note: See TracBrowser for help on using the repository browser.