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

Revision 103, 9.8 KB checked in by jtorres, 9 years ago (diff)

trunk/src/atmsdriver/ConsoleDriver.java: Created console driver for ATMSDriver, completed and very nice. Still need to apply correct vol/occ values to actually change the colors. Still need to write a JUnit test for it. trunk/src/atmsdriver/ATMSDriver.java: Refactored to run the console driver. ATMSDriver runs in thread, console driver runs, and they share the highways instance. Renamed NetworkLoader?.java to FEPLineLoader.java. trunk/src/atmsdriver/model/Highways.java: refactored loadHighways() method to conform to new undirected highway abstraction. trunk/src/atmsdriver/model/Station.java: added updateByDirection(DIRECTION dir) method and supporting utility methods. trunk/test/atmsdriver/model/LoadHighwaysTest.java: Conformed LoadHighways? test to new undirected highway abstraction. trunk/test/atmsdriver/model/StationTest.java: Conformed StationTest?.java to new changes - very minor stuff. Went through all model classes and changed any final privates with a getter method to final public, for good OOP practice and simplicity. Went through ALL FILES and commented everything very well. minor application custom configuration changes. Removed all .class or .o.d files from svn repository

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