View Javadoc
1   package loadfromxml;
2   
3   import java.awt.Color;
4   import java.io.ByteArrayInputStream;
5   import java.io.File;
6   import java.io.IOException;
7   import java.nio.charset.StandardCharsets;
8   import java.nio.file.Files;
9   import java.nio.file.Paths;
10  import java.rmi.RemoteException;
11  import java.util.ArrayList;
12  
13  import javax.naming.NamingException;
14  import javax.swing.JFileChooser;
15  import javax.swing.JOptionPane;
16  import javax.swing.filechooser.FileFilter;
17  import javax.xml.parsers.ParserConfigurationException;
18  
19  import org.djunits.unit.DurationUnit;
20  import org.djunits.unit.SpeedUnit;
21  import org.djunits.value.ValueException;
22  import org.djunits.value.vdouble.scalar.Acceleration;
23  import org.djunits.value.vdouble.scalar.Duration;
24  import org.djunits.value.vdouble.scalar.Length;
25  import org.djunits.value.vdouble.scalar.Speed;
26  import org.djunits.value.vdouble.scalar.Time;
27  import org.opentrafficsim.base.modelproperties.Property;
28  import org.opentrafficsim.base.modelproperties.PropertyException;
29  import org.opentrafficsim.base.parameters.ParameterException;
30  import org.opentrafficsim.core.dsol.OTSModelInterface;
31  import org.opentrafficsim.core.geometry.OTSGeometryException;
32  import org.opentrafficsim.core.gtu.GTUException;
33  import org.opentrafficsim.core.gtu.GTUType;
34  import org.opentrafficsim.core.gtu.animation.AccelerationGTUColorer;
35  import org.opentrafficsim.core.gtu.animation.GTUColorer;
36  import org.opentrafficsim.core.gtu.animation.IDGTUColorer;
37  import org.opentrafficsim.core.gtu.animation.SpeedGTUColorer;
38  import org.opentrafficsim.core.gtu.animation.SwitchableGTUColorer;
39  import org.opentrafficsim.core.network.NetworkException;
40  import org.opentrafficsim.core.network.OTSLink;
41  import org.opentrafficsim.core.network.OTSNetwork;
42  import org.opentrafficsim.core.network.OTSNode;
43  import org.opentrafficsim.road.animation.AnimationToggles;
44  import org.opentrafficsim.road.gtu.animation.BlockingColorer;
45  import org.opentrafficsim.road.gtu.animation.DesiredSpeedColorer;
46  import org.opentrafficsim.road.gtu.animation.FixedColor;
47  import org.opentrafficsim.road.gtu.animation.GTUTypeColorer;
48  import org.opentrafficsim.road.gtu.animation.SplitColorer;
49  import org.opentrafficsim.road.gtu.lane.plan.operational.LaneOperationalPlanBuilder;
50  import org.opentrafficsim.road.network.factory.xml.XmlNetworkLaneParser;
51  import org.opentrafficsim.road.network.lane.conflict.ConflictBuilder;
52  import org.opentrafficsim.road.network.lane.object.SpeedSign;
53  import org.opentrafficsim.simulationengine.AbstractWrappableAnimation;
54  import org.opentrafficsim.simulationengine.OTSSimulationException;
55  import org.xml.sax.SAXException;
56  
57  import nl.tudelft.simulation.dsol.SimRuntimeException;
58  import nl.tudelft.simulation.dsol.simtime.SimTimeDoubleUnit;
59  import nl.tudelft.simulation.dsol.simulators.DEVSSimulatorInterface;
60  import nl.tudelft.simulation.dsol.simulators.SimulatorInterface;
61  import nl.tudelft.simulation.event.EventProducer;
62  
63  /**
64   * Select a OTS-network XML file, load it and run it.
65   * <p>
66   * Copyright (c) 2013-2018 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
67   * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
68   * <p>
69   * @version $Revision$, $LastChangedDate$, by $Author$, initial version Apr 21, 2017 <br>
70   * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
71   * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
72   * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
73   */
74  public class LoadXML extends AbstractWrappableAnimation
75  {
76  
77      /** */
78      private static final long serialVersionUID = 20170421L;
79  
80      /** Name of the XML file. */
81      private String fileName = null;
82  
83      /** The XML code. */
84      private String xml = null;
85  
86      /**
87       * Load a network from an XML file; program entry point.
88       * @param args String[]; the command line arguments; optional name of file to load
89       * @throws IOException when the file could not be read
90       * @throws PropertyException should never happen
91       * @throws OTSSimulationException when an error occurs during simulation
92       * @throws NamingException when a name collision is detected
93       * @throws SimRuntimeException should never happen
94       */
95      public static void main(final String[] args)
96              throws IOException, SimRuntimeException, NamingException, OTSSimulationException, PropertyException
97      {
98          LaneOperationalPlanBuilder.INSTANT_LANE_CHANGES = true;
99          LoadXML loadXML = new LoadXML();
100         if (0 == args.length)
101         {
102             JFileChooser fileChooser = new JFileChooser();
103             fileChooser.addChoosableFileFilter(new FileFilter()
104             {
105 
106                 @Override
107                 public boolean accept(final File f)
108                 {
109                     String name = f.getName();
110                     int length = name.length();
111                     if (length < 5)
112                     {
113                         return false;
114                     }
115                     String type = name.substring(length - 4);
116                     return type.equalsIgnoreCase(".xml");
117                 }
118 
119                 @Override
120                 public String getDescription()
121                 {
122                     return "XML files";
123                 }
124             });
125             fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
126             if (JFileChooser.APPROVE_OPTION != fileChooser.showOpenDialog(null))
127             {
128                 System.out.println("No file chosen; exiting");
129                 System.exit(0);
130             }
131             loadXML.fileName = fileChooser.getSelectedFile().getAbsolutePath();
132         }
133         else
134         {
135             loadXML.fileName = args[0];
136         }
137         loadXML.xml = new String(Files.readAllBytes(Paths.get(loadXML.fileName)));
138         try
139         {
140             loadXML.buildAnimator(Time.ZERO, Duration.ZERO, new Duration(3600, DurationUnit.SI), new ArrayList<Property<?>>(),
141                     null, true);
142         }
143         catch (SimRuntimeException sre)
144         {
145             JOptionPane.showMessageDialog(null, sre.getMessage(), "Exception occured", JOptionPane.ERROR_MESSAGE);
146             System.exit(1);
147         }
148     }
149 
150     /** {@inheritDoc} */
151     @Override
152     public final String shortName()
153     {
154         return this.fileName;
155     }
156 
157     /** {@inheritDoc} */
158     @Override
159     public final String description()
160     {
161         return "OTS network from " + this.fileName;
162     }
163 
164     /** Currently active XML model. */
165     private XMLModel model = null;
166 
167     /** GTU colorer. */
168     private GTUColorer colorer = SwitchableGTUColorer.builder().addActiveColorer(new FixedColor(Color.BLUE, "Blue"))
169             .addColorer(GTUTypeColorer.DEFAULT).addColorer(new IDGTUColorer())
170             .addColorer(new SpeedGTUColorer(new Speed(150, SpeedUnit.KM_PER_HOUR)))
171             .addColorer(new DesiredSpeedColorer(new Speed(50, SpeedUnit.KM_PER_HOUR), new Speed(150, SpeedUnit.KM_PER_HOUR)))
172             .addColorer(new AccelerationGTUColorer(Acceleration.createSI(-6.0), Acceleration.createSI(2)))
173             .addColorer(new SplitColorer()).addColorer(new BlockingColorer()).build();
174 
175     /** {@inheritDoc} */
176     @Override
177     protected final OTSModelInterface makeModel() throws OTSSimulationException
178     {
179         this.model = new XMLModel();
180         return this.model;
181     }
182 
183     /** {@inheritDoc} */
184     @Override
185     protected final void addAnimationToggles()
186     {
187         AnimationToggles.setIconAnimationTogglesFull(this);
188         toggleAnimationClass(OTSLink.class);
189         toggleAnimationClass(OTSNode.class);
190         showAnimationClass(SpeedSign.class);
191     }
192 
193     /**
194      * The network.
195      */
196     class XMLModel extends EventProducer implements OTSModelInterface
197     {
198 
199         /** */
200         private static final long serialVersionUID = 20170421L;
201 
202         /** The network. */
203         private OTSNetwork network;
204 
205         /** The simulator. */
206         private SimulatorInterface<Time, Duration, SimTimeDoubleUnit> simulator;
207 
208         /** {@inheritDoc} */
209         @SuppressWarnings("synthetic-access")
210         @Override
211         public void constructModel(final SimulatorInterface<Time, Duration, SimTimeDoubleUnit> theSimulator)
212                 throws SimRuntimeException
213         {
214             this.simulator = theSimulator;
215             XmlNetworkLaneParser nlp = new XmlNetworkLaneParser((DEVSSimulatorInterface.TimeDoubleUnit) theSimulator, getColorer());
216             try
217             {
218                 this.network = nlp.build(new ByteArrayInputStream(LoadXML.this.xml.getBytes(StandardCharsets.UTF_8)), false);
219                 ConflictBuilder.buildConflicts(this.network, GTUType.VEHICLE, (DEVSSimulatorInterface.TimeDoubleUnit) theSimulator,
220                         new ConflictBuilder.FixedWidthGenerator(Length.createSI(2.0)));
221             }
222             catch (NetworkException | ParserConfigurationException | SAXException | IOException | NamingException | GTUException
223                     | OTSGeometryException | ValueException | ParameterException exception)
224             {
225                 exception.printStackTrace();
226                 // Abusing the SimRuntimeException to propagate the message to the main method (the problem could actually be a
227                 // SAXException)
228                 throw new SimRuntimeException(exception.getMessage());
229             }
230         }
231 
232         /** {@inheritDoc} */
233         @Override
234         public SimulatorInterface<Time, Duration, SimTimeDoubleUnit> getSimulator()
235         {
236             return this.simulator;
237         }
238 
239         /** {@inheritDoc} */
240         @Override
241         public OTSNetwork getNetwork()
242         {
243             return this.network;
244         }
245 
246     }
247 
248     /** {@inheritDoc} */
249     @Override
250     public GTUColorer getColorer()
251     {
252         return this.colorer;
253     }
254 
255 }