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

source: tmcsimulator-scriptbuilder/trunk/src/scriptbuilder/structures/SimulationScript.java @ 158

Revision 158, 11.9 KB checked in by jdalbey, 6 years ago (diff)

ScriptBuilderFrame?.java added new helper method loadCHPunits(). SimulationScript?.java changed load units method to accept an InputStream? instead of a File.

RevLine 
1package scriptbuilder.structures;
2
3import java.awt.Color;
4import java.io.BufferedWriter;
5import java.io.File;
6import java.io.FileWriter;
7import java.io.IOException;
8import java.util.ArrayList;
9import java.util.List;
10import java.util.Observable;
11import java.util.Vector;
12import javax.xml.parsers.SAXParserFactory;
13import scriptbuilder.structures.ScriptIncident.IncidentFocusedEvent;
14import scriptbuilder.structures.ScriptIncident.SliceChangedEvent;
15import scriptbuilder.structures.events.*;
16import scriptbuilder.structures.units.Unit;
17import java.nio.file.Path;
18import java.nio.file.Paths;
19import java.util.TreeMap;
20
21/**
22 * Representation of the script to be run by the TMC Simulator. Holds a list of
23 * incidents, which have start and end times and contain events.
24 *
25 * @author Greg Eddington <geddingt@calpoly.edu>
26 *
27 * @author Bryan McGuffin <bmcguffi@calpoly.edu>
28 * @author Sebastien Danthinne <sdanthin@calpoly.edu>
29 * @version 2017/06/22
30 */
31public class SimulationScript extends Observable implements I_XML_Writable
32{
33
34    /**
35     * All default options for GUI colorings of incidents.
36     */
37    public static final Color[] incidentColors =
38    {
39        Color.BLACK,
40        Color.BLUE,
41        Color.RED,
42        new Color(0x38, 0x5E, 0x0F),
43        new Color(128, 0, 128),
44        Color.MAGENTA,
45        new Color(0x23, 0x6B, 0x8E),
46        Color.ORANGE,
47        new Color(0x60, 0x33, 0x11),
48        Color.GRAY
49    };
50
51    /**
52     * The file to which this script will be saved.
53     */
54    public File saveFile = null;
55
56    /**
57     * The name of this script.
58     */
59    public String title = "";
60
61    /**
62     * The incidents displayed by the GUI.
63     */
64    public List<ScriptIncident> incidents;
65
66    /**
67     * The units which participate in Unit events.
68     */
69    public List<Unit> units; 
70
71    //Somewhere in the code, something assumes that the list of incidents
72    //contains exactly 10 items. Until I can find and un-break that, this will do.
73    //todo: this incident fill count error
74    private final int INCIDENT_FILL_COUNT = 10;
75
76    /**
77     * Number of incidents currently displayed.
78     */
79    public int numberOfIncidents;
80
81    /**
82     * Script handler for parsing incoming XML files.
83     */
84    private MyScriptHandler sh;
85   
86    public boolean saved;
87
88    //TODO: Pretty much everything in this constructor is dummy data.
89    //Replace all of it.
90    /**
91     * Constructor. Backfill incident list with null objects, to be replaced
92     * later.
93     */
94    public SimulationScript()
95    {
96        sh = new MyScriptHandler(this);
97        incidents = new ArrayList<ScriptIncident>();
98        units = new ArrayList<Unit>();
99        numberOfIncidents = 0;
100        saved = true;
101
102        //Backfill with null incidents
103        for (int i = numberOfIncidents; i < INCIDENT_FILL_COUNT; i++)
104        {
105            incidents.add(null);
106        }
107    }
108   
109    /**
110     * checks and sees if this object has the unit passed.
111     * @param unitID
112     * @return does this SimulationScript have unitnum?
113     */
114    public boolean hasUnit(String unitID){
115        boolean indicator = false;
116        if(units.size()!=0){
117            for(Unit u : units){
118               if(unitID.equals(u.UnitNum)){
119                   indicator = true;
120               }
121            }
122        }
123           
124        return indicator;
125    }
126    /**
127     * creates a dummy unit that only has unit number
128     * @param unitNum
129     */
130    public void addDummyUnit(String unitNum){
131        Unit dummy = new Unit();
132        dummy.UnitNum = unitNum;
133        units.add(dummy);
134    }
135    /**
136     * Update the script's observers.
137     *
138     */
139    public void update()
140    {
141        // The script has changed, notify observers
142        //use to rewrite the save indicator
143        //System.out.println("Script changed");
144        setChanged();
145        notifyObservers(this);
146        saved = false;
147       
148       
149    }
150   
151
152    /**
153     * Tell this script's observers that there is a new slice event.
154     *
155     * @param e the slice focus event
156     */
157    public void broadcastEvent(SliceChangedEvent e)
158    {
159        // The slice focus has changed; pass the message
160        setChanged();
161        notifyObservers(e);
162    }
163
164    /**
165     * Tell this script's observers that there is a new slice event.
166     *
167     * @param e the incident focus event
168     */
169    public void broadcastEvent(IncidentFocusedEvent e)
170    {
171        // The slice focus has changed; pass the message
172        setChanged();
173        notifyObservers(e);
174    }
175
176    /**
177     * Load in an existing script from an XML file.
178     *
179     * @param f the file containing the script
180     */
181    public void loadScriptFromFile(File f)
182    {
183        try
184        {
185
186            SAXParserFactory.newInstance().newSAXParser().parse(f, sh);
187
188            Vector<ScriptIncident> inc = sh.getIncidents();
189            units = sh.getUnits();
190            for (ScriptIncident sci : inc)
191            {
192                addIncident(sci);
193            }
194        }
195        catch (Exception ex)
196        {
197            System.out.println("ERROR LOADING SCRIPT");
198            ex.printStackTrace();
199        }
200        System.out.println("H");
201        for(Unit testUnit : units){
202            System.out.println(testUnit.toXML());
203        }
204        this.update();
205    }
206   
207    /**
208     * Load in an existing list of units from an XML file.
209     * @param inStream the input stream for the file containing the units
210     */
211    public void loadUnitsFromFile(java.io.InputStream inStream){
212        try
213        {
214            SAXParserFactory.newInstance().newSAXParser().parse(inStream, sh);
215            units.addAll(sh.getUnits());
216        }
217        catch (Exception ex)
218        {
219            System.out.println("ERROR LOADING UNITS");
220            ex.printStackTrace();
221        }
222        this.update();
223    }
224
225    /**
226     * Add a new incident to the script.
227     *
228     * @param sci the incident to be added.
229     * @return true if there was enough room to add this incident.
230     */
231    public boolean addIncident(ScriptIncident sci)
232    {
233        if (numberOfIncidents < INCIDENT_FILL_COUNT)
234        {
235            incidents.set(numberOfIncidents++, sci);
236            return true;
237        }
238        return false;
239    }
240
241    /**
242     * Write this script, in proper XML format, to the file in question.
243     *
244     * @param f the destination savefile to be written.
245     */
246    public void saveScriptToFile(File f)
247    {
248        try
249        {
250            f.createNewFile();
251
252            BufferedWriter bw = new BufferedWriter(new FileWriter(f));
253            bw.write(this.toXML());
254            bw.flush();
255            bw.close();
256
257        }
258        catch (Exception ex)
259        {
260            System.out.println("ERROR SAVING SCRIPT");
261            ex.printStackTrace();
262        }
263        try
264        {
265            createAudioDirectory(Paths.get(f.getCanonicalPath()).getParent());
266        }
267        catch(IOException ex)
268        {
269            System.err.println("there was a problem creating the audio directories.");
270        }
271       
272       
273        saved = true;
274    }
275    private void createAudioDirectory(Path path){
276        File f = new File(path.toString()+"/audio");
277        if(!f.exists())
278        {
279            f.mkdir();
280            //scan through to see what is already there and then make changes accordingly.
281        }
282        for(ScriptIncident i : incidents)
283        {
284            if(i!=null)
285            {
286                String name = ((Integer) i.number).toString();
287                File incidentFolder = new File(path.toString()+"/audio/"+name);
288                if(incidentFolder.exists())
289                {
290                    //check to see if there are already files for the given incidents
291                    //not sure how the ordering of the files should be.
292                    //check to see if folder needs filling
293                }else
294                {
295
296                    //create an incidentfolder since one does not already exist
297                    incidentFolder.mkdir();
298                    int fileCount = 1;
299                    for(TimeSlice slice : i.getSlices())
300                    {
301                        for(I_ScriptEvent event : slice.events)
302                        {
303                            if(event.getScriptEventType().equals(ScriptEvent.ScriptEventType.CHP_RADIO_EVENT))
304                            {
305                                //if the event is a chp radio event
306                                //then add the dummy file to the subdirectory created
307                                CHPRadioEvent radioEvent = (CHPRadioEvent) event;
308                               
309                                String output = radioEvent.toScriptFile();
310                               
311                                File newAudioScript = new File(path.toString()+"/audio/"+name+"/"+name+fileCount+".txt");
312                               
313                                fileCount++;
314                                try
315                                {
316                                    newAudioScript.createNewFile();
317                                    BufferedWriter bw = new BufferedWriter(new FileWriter(newAudioScript));
318                                    bw.write(output);
319                                    bw.flush();
320                                    bw.close();
321                                }catch(Exception e)
322                                {
323                                    System.err.println("there was a problem creating your text files");
324                                }
325
326                            }
327                        }
328                    }
329
330                }
331            }
332
333           
334        }
335       
336       
337    }
338    @Override
339    public String toXML()
340    {
341        ArrayList<TimeSlice> slices = arrangeAllSlices();
342        String output = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
343        output += XMLWriter.internalDTD();
344        output += XMLWriter.openTag(ELEMENT.TMC_SCRIPT.tag + " title=\"" + this.title + "\"");
345
346        if (units.size() > 0)
347        {
348            output += XMLWriter.openTag(ELEMENT.SCRIPT_DATA.tag);
349            for (Unit unit : units)
350            {
351                output += unit.toXML();
352            }
353            output += XMLWriter.closeTag(ELEMENT.SCRIPT_DATA.tag);
354        }
355        for (TimeSlice slice : slices)
356        {
357            output += slice.toXML();
358        }
359        output += XMLWriter.closeTag(ELEMENT.TMC_SCRIPT.tag);
360        return output;
361    }
362
363    /**
364     * Arranges all timeslices in this script in chronological order, then by
365     * incident number.
366     *
367     * @return a list of all timeslices in the simulation script
368     */
369    public ArrayList<TimeSlice> arrangeAllSlices()
370    {
371        ArrayList<TimeSlice> list = new ArrayList<TimeSlice>();
372        int length = absoluteLength();
373
374        for (int i = 0; i < length; i++)
375        {
376            for (ScriptIncident inc : incidents)
377            {
378
379                if (inc != null && inc.slices.get(i) != null)
380                {
381                    list.add(inc.slices.get(i));
382                }
383            }
384        }
385        return list;
386    }
387
388    /**
389     * Gets the total length of the simulation in seconds.
390     *
391     * @return
392     */
393    public int absoluteLength()
394    {
395        int length = 0;
396        for (ScriptIncident inc : incidents)
397        {
398            if (inc != null)
399            {
400                inc.updateLength();
401                int currentLength = inc.length + inc.offset;
402                if (currentLength > length)
403                {
404                    length = currentLength;
405                }
406            }
407        }
408        return length;
409    }
410
411    /**
412     * Counts the number of incidents currently running.
413     *
414     * @return the number of non-null incidents currently in the script. A
415     * number between 0 and INCIDENT_FILL_COUNT, inclusive.
416     */
417    public int incidentCount()
418    {
419        int count = 0;
420        for (ScriptIncident inc : incidents)
421        {
422            if (inc != null)
423            {
424                count++;
425            }
426        }
427        return count;
428    }
429
430}
Note: See TracBrowser for help on using the repository browser.