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 @ 170

Revision 170, 10.1 KB checked in by jtorres, 9 years ago (diff)

Full LDS data list now working

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            System.out.println("BYTES: " + this.toXML().toCharArray().length + 1);
217            out.println(this.toXML());
218            sock.close();
219        } catch (IOException ex) {
220            Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
221            System.out.println("Highway Model failed writing to FEPSim.");
222            throw new SimulationException(SimulationException.BINDING);
223        }
224    }
225
226    // CHECK: DO WE EVEN NEED TO DO THIS?
227    private void updateSequences() {
228        for (FEPLine line : lines) {
229            line.updateSequences();
230        }
231    }
232
233    /**
234     * Returns the network metadata in condensed form. This is just a quick
235     * script function to make a proper highway metadata configuration file, so
236     * that we can read the network faster.
237     *
238     * @return Network metadata
239     */
240    public void writeHighwaysMeta(String fileName) {
241
242        try {
243            FileWriter fw = new FileWriter(new File(fileName));
244            StringBuilder build = new StringBuilder();
245            build.append(lines.size());
246            build.append("\n");
247            System.out.println(lines.size());
248            fw.write(build.toString());
249            int count = 1;
250            for (FEPLine line : lines) {
251                System.out.println("Writing num: " + count);
252                count++;
253                fw.write(line.getLineMeta());
254
255            }
256        } catch (IOException ex) {
257            Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
258        }
259    }
260
261    public String toXML() {
262        String xml = null;
263        try {
264            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
265            DocumentBuilder builder = factory.newDocumentBuilder();
266            Document theDoc = builder.newDocument();
267
268            Element networkElement = theDoc.createElement(XML_TAGS.NETWORK.tag);
269            theDoc.appendChild(networkElement);
270
271            for (FEPLine line : lines) {
272                line.toXML(networkElement);
273            }
274
275            Transformer tf = TransformerFactory.newInstance().newTransformer();
276
277            tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
278            tf.setOutputProperty(OutputKeys.INDENT, "yes");
279            tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
280
281            Writer out = new StringWriter();
282            tf.transform(new DOMSource(theDoc), new StreamResult(out));
283            xml = out.toString();
284            out.close();
285        } catch (Exception ex) {
286            Logger.getLogger(Highways.class.getName()).log(Level.SEVERE, null, ex);
287        }
288        return xml;
289
290    }
291
292    public Highway getHighwayByRouteNumber(Integer routeNum) {
293        Highway returnHwy = null;
294        for(Highway hwy : highways)
295        {
296            if(hwy.routeNumber.equals(routeNum))
297            {
298                returnHwy = hwy;
299                break;
300            }
301        }
302        return returnHwy;
303    }
304
305    private static enum XML_TAGS {
306
307        NETWORK("Network");
308
309        String tag;
310
311        private XML_TAGS(String n) {
312            tag = n;
313        }
314    }
315}
Note: See TracBrowser for help on using the repository browser.