Changeset 204 in tmcsimulator for trunk


Ignore:
Timestamp:
10/31/2017 02:08:33 PM (9 years ago)
Author:
jdalbey
Message:

TrafficModelManager?.java Refactor for code sharing with TrafficModelEventDriver?. Write unit test.

Location:
trunk
Files:
2 added
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/atmsdriver/model/TrafficEvent.java

    r197 r204  
    66import java.util.Date; 
    77import java.util.Scanner; 
     8 
    89 
    910/** 
     
    2728    public final double range; 
    2829    public final String rawString; 
     30     
    2931    private final static SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); 
    3032 
     
    6163        return rawString; 
    6264    } 
     65    @Override  
     66    public boolean equals(Object other) 
     67    { 
     68        Boolean result = false; 
     69        if (other == null) return false; 
     70        if ( other instanceof TrafficEvent  ) 
     71        { 
     72          TrafficEvent that = (TrafficEvent) other; 
     73          result = that.incident.equals(this.incident) 
     74                  && that.eventTime.equals(this.eventTime) 
     75                  && ((int) that.postmile) == ((int) this.postmile) 
     76                  && that.dir == this.dir 
     77                  && that.color == this.color; 
     78        } 
     79        return result;     
     80    }             
    6381} 
  • trunk/src/tmcsim/cadsimulator/managers/TrafficModelManager.java

    r197 r204  
    4747     * Error Logger. 
    4848     */ 
    49     private static Logger atmsLogger = Logger.getLogger("tmcsim.cadsimulator.managers"); 
     49    private static Logger logger = Logger.getLogger("tmcsim.cadsimulator.managers"); 
    5050 
    5151    /** 
     
    5656    private static enum PROPERTIES 
    5757    { 
    58         /** 
    59          * 
    60          */ 
    6158        HIGHWAYS_MAP_FILE("Highways_Map_File"), 
    62         /** 
    63          * 
    64          */ 
    6559        FEPSIM_IP_ADDR("FEPSim_IP_addr"), 
    66         /** 
    67          * 
    68          */ 
    6960        EVENTS_FILE("Events_File"), 
    7061        OUTPUT_DEST("Output_Destination"); 
     
    8273     * Properties Object. 
    8374     */ 
    84     private Properties atmsProperties = null; 
     75    private Properties props = null; 
    8576    /** 
    8677     * Highways in traffic network 
     
    113104            throws SimulationException  
    114105    { 
    115         if (!loadProperties(propertiesFile)) 
    116         { 
    117             System.exit(0); 
    118         } 
    119 //        final Coordinator theCoordinator = theCoordinator; 
     106        props = loadProperties(propertiesFile); 
    120107        // Initialize the highway model 
    121108        incidents = new HashMap<String, List<TrafficEvent>>(); 
    122109        highways = new Highways( 
    123                 atmsProperties.getProperty(PROPERTIES.HIGHWAYS_MAP_FILE.name), 
    124                 //"config/vds_data/highways_fullmap.txt", 
    125                 //        "192.168.251.46", 8080);  //IP address of FEP Sim Linux VM 
    126                 atmsProperties.getProperty(PROPERTIES.FEPSIM_IP_ADDR.name), 
     110                props.getProperty(PROPERTIES.HIGHWAYS_MAP_FILE.name), 
     111                props.getProperty(PROPERTIES.FEPSIM_IP_ADDR.name), 
    127112                8080);  
    128113 
    129         // READ THE BATCH FILE OF COMMANDS and put in a queue 
    130         eventQueue = readBatchFile(); 
    131         // Launch the display 
     114        // Read the text file of events and put in a queue 
     115        FileInputStream fis = null; 
     116        try 
     117        { 
     118            fis = new FileInputStream(props.getProperty(PROPERTIES.EVENTS_FILE.name)); 
     119        } catch (FileNotFoundException ex) 
     120        { 
     121            Logger.getLogger(TrafficModelManager.class.getName()).log(Level.SEVERE, null,  
     122                    "Missing Traffic Events file " + props.getProperty(PROPERTIES.EVENTS_FILE.name)); 
     123            System.exit(-1); 
     124        } 
     125        // Read all lines from the file of events 
     126        Scanner fileScanner = new Scanner(fis);         
     127        eventQueue = readBatchFile(fileScanner); 
     128        // Extract the incidents and create a map 
     129        incidents = createIncidentMap(eventQueue); 
     130        // Launch the GUI display 
    132131        theView = new TrafficModelViewer(this, new ArrayList<String>(incidents.keySet())); 
    133132        theView.setVisible(true); 
     
    147146                { 
    148147                    long simtime = theCoordinator.getCurrentSimulationTime(); 
    149                     currentClock = formatInterval(simtime); 
     148                    currentClock = formatTimeInSeconds(simtime); 
    150149                    // For Debugging, show the ATMS time 
    151150//                    long ATMStime = theCoorInt.getATMStime();        
     
    159158                    { 
    160159                        Logger.getLogger(TrafficModelManager.class.getName()).log(Level.SEVERE, null, ex); 
    161                         System.out.println("Invalid simulation clock time found in ATMSDriverClient"); 
     160                        System.out.println("Invalid simulation clock time found"); 
    162161                        System.exit(-1); 
    163162                    } 
    164                     //System.out.println("Current clock: " + currentClock); 
    165163                } 
    166164                catch (RemoteException ex) 
     
    175173                    TrafficEvent nextEvent = eventQueue.peek(); 
    176174                    Date eventTime = nextEvent.eventDate; 
    177                     //System.out.println("Next event will be launched at: " + formatter.format(eventTime)); 
    178175                    // Check the queue of events to see if the first 
    179176                    // item should be launched.  IF so,  
     
    195192        timer.start(); 
    196193 
    197         if (atmsProperties.getProperty(PROPERTIES.OUTPUT_DEST.name).equals("FEP")) 
     194        if (props.getProperty(PROPERTIES.OUTPUT_DEST.name).equals("FEP")) 
    198195        { 
    199196            // Start the FEP thread (to update ATMS every 30 sec). (See class def below) 
     
    210207 
    211208    /** 
    212      * This method verifies that the CAD Simulator Host and Port values are not 
    213      * null. Also, if a CAD Position or User ID do not exist in the properties 
    214      * file, the user is prompted to enter values. These values are written to 
    215      * the properties file. If the user cancels the process of entering these 
    216      * values, the verification fails. 
     209     * This method verifies that the needed configuration properties are not 
     210     * null.  
    217211     * 
    218212     * @param propertiesFile File path (absolute or relative) to the properties 
    219213     * file containing configuration data. 
    220      * @return True if the properties file is valid, false if not. 
     214     * @return The Properties loaded 
    221215     * @throws SimulationException if there is an exception in verifying the 
    222      * properties file, or if the user cancels input. 
    223      */ 
    224     private boolean loadProperties(String propertiesFile) 
     216     * properties file 
     217     */ 
     218    public static Properties loadProperties(String propertiesFile) 
    225219            throws SimulationException 
    226220    { 
     221        Properties props; 
    227222        // Load the properties file. 
    228223        try 
    229224        { 
    230             atmsProperties = new Properties(); 
    231             atmsProperties.load(new FileInputStream(propertiesFile)); 
     225            props = new Properties(); 
     226            props.load(new FileInputStream(propertiesFile)); 
    232227 
    233228        } catch (Exception e) 
    234229        { 
    235             atmsLogger.logp(Level.SEVERE, "TrafficModelManager", "Constructor", 
    236                     "Exception in parsing properties file.", e); 
    237             throw new SimulationException(SimulationException.INITIALIZE_ERROR, 
    238                     e);             
    239         } 
    240  
     230            throw new SimulationException(SimulationException.INITIALIZE_ERROR); 
     231        } 
    241232 
    242233        // Ensure that the properties file does not have null values for the 
    243234        // required information. 
    244         if (atmsProperties.getProperty(PROPERTIES.HIGHWAYS_MAP_FILE.name) == null 
    245                 || atmsProperties.getProperty(PROPERTIES.FEPSIM_IP_ADDR.name) == null 
    246                 || atmsProperties.getProperty(PROPERTIES.EVENTS_FILE.name) == null 
    247                 || atmsProperties.getProperty(PROPERTIES.OUTPUT_DEST.name) == null) 
    248         { 
    249             atmsLogger.logp(Level.SEVERE, "TrafficModelManager", 
    250                     "Constructor", "Null value in properties file."); 
     235        if (props.getProperty(PROPERTIES.HIGHWAYS_MAP_FILE.name) == null 
     236                || props.getProperty(PROPERTIES.FEPSIM_IP_ADDR.name) == null 
     237                || props.getProperty(PROPERTIES.EVENTS_FILE.name) == null 
     238                || props.getProperty(PROPERTIES.OUTPUT_DEST.name) == null) 
     239        { 
     240            System.out.println("Missing property value in "+propertiesFile); 
    251241            throw new SimulationException(SimulationException.INITIALIZE_ERROR); 
    252242        } 
    253243 
    254         return true; 
     244        return props; 
    255245    } 
    256246    /** 
    257247     * Read a file of traffic events.   
     248     * @param filename the name of the events file 
    258249     * @return the chronologically ordered list of events 
    259250     */ 
    260     // Method is package private to facilitate unit testing. 
    261     LinkedList<TrafficEvent> readBatchFile() 
    262     { 
    263         FileInputStream fis; 
     251    public static LinkedList<TrafficEvent> readBatchFile(Scanner scan) 
     252    { 
    264253        LinkedList<TrafficEvent> eventList = new LinkedList<TrafficEvent>(); 
    265         try 
    266         { 
    267             fis = new FileInputStream( 
    268                     //"config/vds_data/atmsBatchEvents.txt"); 
    269             atmsProperties.getProperty(PROPERTIES.EVENTS_FILE.name)); 
    270             // Read all lines from the file of events 
    271             Scanner scan = new Scanner(fis); 
    272254            while (scan.hasNext()) 
    273255            { 
     
    281263                        evt = new TrafficEvent(line); 
    282264                        eventList.add(evt); 
    283                         String incident = evt.incident; 
    284                         // Add the line to the list for the corresponding incident 
    285                         List evtList; 
    286                         if (incidents.containsKey(evt.incident)) 
    287                         { 
    288                             evtList = incidents.get(evt.incident); 
    289                         } 
    290                         else 
    291                         { 
    292                             evtList = new ArrayList<String>(); 
    293                         } 
    294                         evtList.add(evt); 
    295                         // and put it back in the map 
    296                         incidents.put(incident, evtList); 
    297265                    } 
    298266                    catch (ParseException ex) 
     
    304272                } 
    305273            } 
    306         } 
    307         catch (FileNotFoundException ex) 
    308         { 
    309             Logger.getLogger(TrafficModelManager.class.getName()).log(Level.SEVERE, null, ex); 
    310         } 
    311274        System.out.println("Events file read, " + eventList.size() + " events queued."); 
    312275        // Put the events in chronological order 
     
    315278    } 
    316279 
     280    static Map<String, List<TrafficEvent>> createIncidentMap(LinkedList<TrafficEvent> eventList) 
     281    { 
     282        Map<String, List<TrafficEvent>> incidents = new HashMap<String, List<TrafficEvent>>(); 
     283        for (TrafficEvent evt: eventList) 
     284        { 
     285            // Add the line to the list for the corresponding incident 
     286            List evtList; 
     287            if (incidents.containsKey(evt.incident)) 
     288            { 
     289                evtList = incidents.get(evt.incident); 
     290            } 
     291            else 
     292            { 
     293                evtList = new ArrayList<String>(); 
     294            } 
     295            evtList.add(evt); 
     296            // and put it back in the map 
     297            incidents.put(evt.incident, evtList); 
     298        }         
     299        return incidents; 
     300    } 
     301     
    317302    /** 
    318303     * Clear an incident. For each event associated with an incident, turn the 
     
    349334     * Format a time in seconds as HH:MM:SS 
    350335     * 
    351      * @param l 
    352      * @return 
    353      */ 
    354     private String formatInterval(final long l) 
    355     { 
    356         final long hr = TimeUnit.SECONDS.toHours(l); 
    357         final long min = TimeUnit.SECONDS.toMinutes(l - TimeUnit.HOURS.toSeconds(hr)); 
    358         final long sec = TimeUnit.SECONDS.toSeconds(l - TimeUnit.HOURS.toSeconds(hr) - TimeUnit.MINUTES.toSeconds(min)); 
     336     * @param seconds 
     337     * @return HH:MM:SS formatted string 
     338     */ 
     339    public static String formatTimeInSeconds(final long seconds) 
     340    { 
     341        final long hr = TimeUnit.SECONDS.toHours(seconds); 
     342        final long min = TimeUnit.SECONDS.toMinutes(seconds - TimeUnit.HOURS.toSeconds(hr)); 
     343        final long sec = TimeUnit.SECONDS.toSeconds(seconds - TimeUnit.HOURS.toSeconds(hr) - TimeUnit.MINUTES.toSeconds(min)); 
    359344        return String.format("%02d:%02d:%02d", hr, min, sec); 
    360345    } 
     
    384369        catch (Exception e) 
    385370        { 
    386             atmsLogger.logp(Level.SEVERE, "SimulationManager", "Main", 
     371            logger.logp(Level.SEVERE, "SimulationManager", "Main", 
    387372                    "Error initializing application."); 
    388373 
     
    409394                try 
    410395                { 
    411                     Thread.sleep(1000); 
     396                    Thread.sleep(5000); 
    412397                } 
    413398                catch (InterruptedException ie) 
  • trunk/test/atmsdriver/TrafficModelEventDriver.java

    r194 r204  
    66import java.io.FileNotFoundException; 
    77import java.rmi.RemoteException; 
    8 import java.text.ParseException; 
    9 import java.text.SimpleDateFormat; 
    10 import java.util.ArrayList; 
    11 import java.util.Collections; 
    128import java.util.HashMap; 
    139import java.util.LinkedList; 
    1410import java.util.List; 
    1511import java.util.Map; 
     12import java.util.Properties; 
    1613import java.util.Scanner; 
    1714import java.util.logging.Level; 
     
    1916import javax.swing.JOptionPane; 
    2017import javax.swing.JWindow; 
     18import tmcsim.cadsimulator.managers.TrafficModelManager; 
     19import tmcsim.common.SimulationException; 
    2120 
    2221/** 
    23  * Skeleton for ATMS Driver that reads a "batch" file of highway status update 
    24  * commands.  A console display of the highway network is output 
     22 * Read and process all Traffic Events in a file and show 
     23 * resulting highway network.  
     24 * A console display of the highway network is output 
    2525 * for each event. 
     26 * This application is used by Traffic Event authors to assist 
     27 * in verifying the correctness of their data file. 
     28 * Because the output is sent immediately to the console the 
     29 * author doesn't have to sit through simulation time to 
     30 * observe dots changing on ATMS client. 
    2631 * @author jdalbey 
    2732 */ 
     
    5156     * 
    5257     */ 
    53     public TrafficModelEventDriver() throws RemoteException 
     58    public TrafficModelEventDriver() throws RemoteException, SimulationException 
    5459    { 
    5560        // Initialize the highway model 
     
    5762        highways = new Highways( 
    5863                "config/vds_data/highways_fullmap.txt", 
    59                 //        "192.168.251.46", 8080);  //IP address of FEP Sim Linux VM 
     64                // following aren't used by this application 
    6065                "localhost", 8080); 
     66        final String CONFIG_FILE_NAME = "traffic_model_config.properties"; 
     67        String propertiesFile = "config" + System.getProperty("file.separator")  
     68                 + CONFIG_FILE_NAME; 
     69        Properties props = TrafficModelManager.loadProperties(propertiesFile); 
    6170 
    62         // READ THE BATCH FILE OF COMMANDS and put in a queue 
    63         readBatchFile(); 
     71        FileInputStream fis = null; 
     72        try 
     73        { 
     74            fis = new FileInputStream(props.getProperty("Events_File")); 
     75        } catch (FileNotFoundException ex) 
     76        { 
     77            Logger.getLogger(TrafficModelManager.class.getName()).log(Level.SEVERE, null,  
     78                    "Missing Traffic Events file " + props.getProperty("Events_File")); 
     79            System.exit(-1); 
     80        } 
     81        Scanner fileScanner = new Scanner(fis);         
     82        // Read all lines from the file of events and put in a queue 
     83        eventQueue = TrafficModelManager.readBatchFile(fileScanner); 
    6484    } 
    6585    public void run() 
     
    7898            eventQueue.remove(); 
    7999        } 
    80     } 
    81  
    82     private void readBatchFile() 
    83     { 
    84         FileInputStream fis; 
    85         try 
    86         { 
    87             fis = new FileInputStream("config/vds_data/atmsBatchEvents.txt"); 
    88             eventQueue = new LinkedList<TrafficEvent>(); 
    89             // Read all lines from the file of events 
    90             Scanner scan = new Scanner(fis); 
    91             while (scan.hasNext()) 
    92             { 
    93                 // Read a line and add it to the event queue 
    94                 String line = scan.nextLine().trim(); 
    95                 if (line.charAt(0) != '#') 
    96                 { 
    97                     TrafficEvent evt; 
    98                     try 
    99                     { 
    100                         evt = new TrafficEvent(line); 
    101                         eventQueue.add(evt); 
    102                         String incident = evt.incident; 
    103                         // Add the line to the list for the corresponding incident 
    104                         List evtList; 
    105                         if (incidents.containsKey(evt.incident)) 
    106                         { 
    107                             evtList = incidents.get(evt.incident); 
    108                         } 
    109                         else 
    110                         { 
    111                             evtList = new ArrayList<String>(); 
    112                         } 
    113                         evtList.add(evt); 
    114                         // and put it back in the map 
    115                         incidents.put(incident, evtList); 
    116                     } 
    117                     catch (ParseException ex) 
    118                     { 
    119                         Logger.getLogger(TrafficModelEventDriver.class.getName()).log(Level.SEVERE, null, ex); 
    120                         System.out.println("Wrong format data in batch event file: " + line + " \nskipping."); 
    121                         System.out.println("Skipping badly formatted event."); 
    122                     } 
    123                 } 
    124             } 
    125         } 
    126         catch (FileNotFoundException ex) 
    127         { 
    128             Logger.getLogger(TrafficModelEventDriver.class.getName()).log(Level.SEVERE, null, ex); 
    129         } 
    130         System.out.println("Events file read, " + eventQueue.size() + " events queued."); 
    131         // Put the events in chronological order 
    132         Collections.sort(eventQueue); 
    133100    } 
    134101 
Note: See TracChangeset for help on using the changeset viewer.