View Javadoc
1   package loadfromxml;
2   
3   import java.awt.Dimension;
4   import java.io.ByteArrayInputStream;
5   import java.io.File;
6   import java.io.IOException;
7   import java.io.Serializable;
8   import java.net.URISyntaxException;
9   import java.nio.charset.StandardCharsets;
10  import java.nio.file.Files;
11  import java.nio.file.Paths;
12  import java.util.LinkedHashMap;
13  import java.util.Map;
14  
15  import javax.naming.NamingException;
16  import javax.swing.JFileChooser;
17  import javax.swing.JOptionPane;
18  import javax.swing.filechooser.FileFilter;
19  import javax.xml.bind.JAXBException;
20  import javax.xml.parsers.ParserConfigurationException;
21  
22  import org.djunits.value.vdouble.scalar.Duration;
23  import org.djunits.value.vdouble.scalar.Length;
24  import org.djunits.value.vdouble.scalar.Time;
25  import org.opentrafficsim.core.dsol.AbstractOTSModel;
26  import org.opentrafficsim.core.dsol.OTSAnimator;
27  import org.opentrafficsim.core.dsol.OTSModelInterface;
28  import org.opentrafficsim.core.dsol.OTSSimulationException;
29  import org.opentrafficsim.core.dsol.OTSSimulatorInterface;
30  import org.opentrafficsim.core.geometry.OTSGeometryException;
31  import org.opentrafficsim.core.gtu.GTUException;
32  import org.opentrafficsim.core.gtu.GTUType;
33  import org.opentrafficsim.core.network.NetworkException;
34  import org.opentrafficsim.draw.core.OTSDrawingException;
35  import org.opentrafficsim.road.network.OTSRoadNetwork;
36  import org.opentrafficsim.road.network.factory.xml.XmlParserException;
37  import org.opentrafficsim.road.network.factory.xml.parser.XmlNetworkLaneParser;
38  import org.opentrafficsim.road.network.lane.CrossSectionLink;
39  import org.opentrafficsim.road.network.lane.conflict.ConflictBuilder;
40  import org.opentrafficsim.road.network.lane.conflict.LaneCombinationList;
41  import org.opentrafficsim.swing.gui.OTSAnimationPanel;
42  import org.opentrafficsim.swing.gui.OTSSimulationApplication;
43  import org.xml.sax.SAXException;
44  
45  import nl.tudelft.simulation.dsol.SimRuntimeException;
46  import nl.tudelft.simulation.dsol.model.inputparameters.InputParameterException;
47  import nl.tudelft.simulation.jstats.streams.MersenneTwister;
48  import nl.tudelft.simulation.jstats.streams.StreamInterface;
49  import nl.tudelft.simulation.language.DSOLException;
50  
51  /**
52   * Select a OTS-network XML file, load it and run it.
53   * <p>
54   * Copyright (c) 2013-2020 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
55   * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
56   * <p>
57   * @version $Revision$, $LastChangedDate$, by $Author$, initial version Apr 21, 2017 <br>
58   * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
59   * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
60   * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
61   */
62  public class LoadXML extends OTSSimulationApplication<OTSModelInterface>
63  {
64      /** */
65      private static final long serialVersionUID = 20170421L;
66  
67      /**
68       * @param model OTSModelInterface; the model
69       * @param animationPanel OTSAnimationPanel; the animation panel
70       * @throws OTSDrawingException on drawing error
71       */
72      public LoadXML(final OTSModelInterface model, final OTSAnimationPanel animationPanel) throws OTSDrawingException
73      {
74          super(model, animationPanel);
75      }
76  
77      /**
78       * Load a network from an XML file; program entry point.
79       * @param args String[]; the command line arguments; optional name of file to load
80       * @throws IOException when the file could not be read
81       * @throws InputParameterException should never happen
82       * @throws OTSSimulationException when an error occurs during simulation
83       * @throws NamingException when a name collision is detected
84       * @throws SimRuntimeException should never happen
85       * @throws DSOLException when simulator does not implement AnimatorInterface
86       */
87      public static void main(final String[] args) throws IOException, SimRuntimeException, NamingException,
88              OTSSimulationException, InputParameterException, DSOLException
89      {
90          String fileName;
91          String xml;
92          if (0 == args.length)
93          {
94              JFileChooser fileChooser = new JFileChooser();
95              fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
96              fileChooser.addChoosableFileFilter(new FileFilter()
97              {
98  
99                  @Override
100                 public boolean accept(final File f)
101                 {
102                     if (f.isDirectory())
103                     {
104                         return true;
105                     }
106                     String name = f.getName();
107                     int length = name.length();
108                     if (length < 5)
109                     {
110                         return false;
111                     }
112                     String type = name.substring(length - 4);
113                     return type.equalsIgnoreCase(".xml");
114                 }
115 
116                 @Override
117                 public String getDescription()
118                 {
119                     return "XML files";
120                 }
121             });
122             fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
123             if (JFileChooser.APPROVE_OPTION != fileChooser.showOpenDialog(null))
124             {
125                 System.out.println("No file chosen; exiting");
126                 System.exit(0);
127             }
128             fileName = fileChooser.getSelectedFile().getAbsolutePath();
129         }
130         else
131         {
132             fileName = args[0];
133         }
134         xml = new String(Files.readAllBytes(Paths.get(fileName)));
135         try
136         {
137             OTSAnimator simulator = new OTSAnimator("LoadXML");
138             XMLModel xmlModel = new XMLModel(simulator, "XML model", "Model built from XML file " + fileName, xml);
139             Map<String, StreamInterface> map = new LinkedHashMap<>();
140             // TODO: This seed is Aimsun specific.
141             map.put("generation", new MersenneTwister(6L));
142             simulator.initialize(Time.ZERO, Duration.ZERO, Duration.instantiateSI(3600.0), xmlModel, map);
143             OTSAnimationPanel animationPanel = new OTSAnimationPanel(xmlModel.getNetwork().getExtent(), new Dimension(800, 600),
144                     simulator, xmlModel, DEFAULT_COLORER, xmlModel.getNetwork());
145             new LoadXML(xmlModel, animationPanel);
146         }
147         catch (SimRuntimeException | OTSDrawingException sre)
148         {
149             JOptionPane.showMessageDialog(null, sre.getMessage(), "Exception occured", JOptionPane.ERROR_MESSAGE);
150             System.exit(1);
151         }
152     }
153 
154     /**
155      * The Model.
156      */
157     static class XMLModel extends AbstractOTSModel
158     {
159         /** */
160         private static final long serialVersionUID = 20170421L;
161 
162         /** The network. */
163         private OTSRoadNetwork network;
164 
165         /** The XML. */
166         private final String xml;
167 
168         /**
169          * @param simulator OTSSimulatorInterface; the simulator
170          * @param shortName String; name of the model
171          * @param description String; description of the model
172          * @param xml String; the XML string
173          */
174         XMLModel(final OTSSimulatorInterface simulator, final String shortName, final String description, final String xml)
175         {
176             super(simulator, shortName, description);
177             this.xml = xml;
178         }
179 
180         /** {@inheritDoc} */
181         @Override
182         public void constructModel() throws SimRuntimeException
183         {
184             this.network = new OTSRoadNetwork(getShortName(), true);
185             try
186             {
187                 XmlNetworkLaneParser.build(new ByteArrayInputStream(this.xml.getBytes(StandardCharsets.UTF_8)), this.network,
188                         getSimulator(), false);
189                 LaneCombinationList ignoreList = new LaneCombinationList();
190                 try
191                 {
192                     // TODO: These links are Aimsun Barcelona network specific.
193                     ignoreList.addLinkCombination((CrossSectionLink) this.network.getLink("928_J5"),
194                             (CrossSectionLink) this.network.getLink("928_J6"));
195                     ignoreList.addLinkCombination((CrossSectionLink) this.network.getLink("925_J1"),
196                             (CrossSectionLink) this.network.getLink("925_J2"));
197                 }
198                 catch (NullPointerException npe)
199                 {
200                     // Ignore exception that is expected to happen when the network is NOT the Barcelona test network
201                 }
202                 LaneCombinationList permittedList = new LaneCombinationList();
203                 ConflictBuilder.buildConflicts(this.network, this.network.getGtuType(GTUType.DEFAULTS.VEHICLE), getSimulator(),
204                         new ConflictBuilder.FixedWidthGenerator(Length.instantiateSI(2.0)), ignoreList, permittedList);
205             }
206             catch (NetworkException | OTSGeometryException | JAXBException | URISyntaxException | XmlParserException
207                     | SAXException | ParserConfigurationException | GTUException exception)
208             {
209                 exception.printStackTrace();
210                 // Abusing the SimRuntimeException to propagate the message to the main method (the problem could actually be a
211                 // parsing problem)
212                 throw new SimRuntimeException(exception.getMessage());
213             }
214         }
215 
216         /** {@inheritDoc} */
217         @Override
218         public OTSRoadNetwork getNetwork()
219         {
220             return this.network;
221         }
222 
223         /** {@inheritDoc} */
224         @Override
225         public Serializable getSourceId()
226         {
227             return "LoadXML.Model";
228         }
229 
230     }
231 
232 }