View Javadoc
1   package org.opentrafficsim.demo.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.net.URISyntaxException;
8   import java.nio.charset.StandardCharsets;
9   import java.nio.file.Files;
10  import java.nio.file.Paths;
11  import java.util.LinkedHashMap;
12  import java.util.Map;
13  
14  import javax.naming.NamingException;
15  import javax.swing.JFileChooser;
16  import javax.swing.JOptionPane;
17  import javax.swing.filechooser.FileFilter;
18  import javax.xml.bind.JAXBException;
19  import javax.xml.parsers.ParserConfigurationException;
20  
21  import org.djunits.value.vdouble.scalar.Duration;
22  import org.djunits.value.vdouble.scalar.Time;
23  import org.opentrafficsim.core.dsol.AbstractOtsModel;
24  import org.opentrafficsim.core.dsol.OtsAnimator;
25  import org.opentrafficsim.core.dsol.OtsModelInterface;
26  import org.opentrafficsim.core.dsol.OtsSimulationException;
27  import org.opentrafficsim.core.dsol.OtsSimulatorInterface;
28  import org.opentrafficsim.core.geometry.OtsGeometryException;
29  import org.opentrafficsim.core.gtu.GtuException;
30  import org.opentrafficsim.core.network.NetworkException;
31  import org.opentrafficsim.draw.OtsDrawingException;
32  import org.opentrafficsim.road.network.RoadNetwork;
33  import org.opentrafficsim.road.network.factory.xml.XmlParserException;
34  import org.opentrafficsim.road.network.factory.xml.parser.XmlParser;
35  import org.opentrafficsim.swing.gui.OtsAnimationPanel;
36  import org.opentrafficsim.swing.gui.OtsSimulationApplication;
37  import org.opentrafficsim.trafficcontrol.TrafficControlException;
38  import org.xml.sax.SAXException;
39  
40  import nl.tudelft.simulation.dsol.SimRuntimeException;
41  import nl.tudelft.simulation.dsol.model.inputparameters.InputParameterException;
42  import nl.tudelft.simulation.jstats.streams.MersenneTwister;
43  import nl.tudelft.simulation.jstats.streams.StreamInterface;
44  import nl.tudelft.simulation.language.DsolException;
45  
46  /**
47   * Select a OTS-network XML file, load it and run it.
48   * <p>
49   * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
50   * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
51   * </p>
52   * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
53   * @author <a href="https://tudelft.nl/staff/p.knoppers-1">Peter Knoppers</a>
54   * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
55   */
56  public class LoadXml extends OtsSimulationApplication<OtsModelInterface>
57  {
58      /** */
59      private static final long serialVersionUID = 20170421L;
60  
61      /**
62       * @param model OtsModelInterface; the model
63       * @param animationPanel OtsAnimationPanel; the animation panel
64       * @throws OtsDrawingException on drawing error
65       */
66      public LoadXml(final OtsModelInterface model, final OtsAnimationPanel animationPanel) throws OtsDrawingException
67      {
68          super(model, animationPanel);
69      }
70  
71      /**
72       * Load a network from an XML file; program entry point.
73       * @param args String[]; the command line arguments; optional name of file to load
74       * @throws IOException when the file could not be read
75       * @throws InputParameterException should never happen
76       * @throws OtsSimulationException when an error occurs during simulation
77       * @throws NamingException when a name collision is detected
78       * @throws SimRuntimeException should never happen
79       * @throws DsolException when simulator does not implement AnimatorInterface
80       */
81      public static void main(final String[] args) throws IOException, SimRuntimeException, NamingException,
82              OtsSimulationException, InputParameterException, DsolException
83      {
84          String fileName;
85          String xml;
86          if (0 == args.length)
87          {
88              JFileChooser fileChooser = new JFileChooser();
89              fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
90              fileChooser.addChoosableFileFilter(new FileFilter()
91              {
92  
93                  @Override
94                  public boolean accept(final File f)
95                  {
96                      if (f.isDirectory())
97                      {
98                          return true;
99                      }
100                     String name = f.getName();
101                     int length = name.length();
102                     if (length < 5)
103                     {
104                         return false;
105                     }
106                     String type = name.substring(length - 4);
107                     return type.equalsIgnoreCase(".xml");
108                 }
109 
110                 @Override
111                 public String getDescription()
112                 {
113                     return "XML files";
114                 }
115             });
116             fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
117             if (JFileChooser.APPROVE_OPTION != fileChooser.showOpenDialog(null))
118             {
119                 System.out.println("No file chosen; exiting");
120                 System.exit(0);
121             }
122             fileName = fileChooser.getSelectedFile().getAbsolutePath();
123         }
124         else
125         {
126             fileName = args[0];
127         }
128         xml = new String(Files.readAllBytes(Paths.get(fileName)));
129         try
130         {
131             OtsAnimator simulator = new OtsAnimator("LoadXML");
132             XmlModel xmlModel = new XmlModel(simulator, "XML model", "Model built from XML file " + fileName, xml);
133             Map<String, StreamInterface> map = new LinkedHashMap<>();
134             // TODO: This seed is Aimsun specific.
135             map.put("generation", new MersenneTwister(6L));
136             simulator.initialize(Time.ZERO, Duration.ZERO, Duration.instantiateSI(3600.0), xmlModel, map);
137             OtsAnimationPanel animationPanel = new OtsAnimationPanel(xmlModel.getNetwork().getExtent(), new Dimension(800, 600),
138                     simulator, xmlModel, DEFAULT_COLORER, xmlModel.getNetwork());
139             animationPanel.enableSimulationControlButtons();
140             LoadXml loadXml = new LoadXml(xmlModel, animationPanel);
141             // TODO: permabilityType (CAR above) can probably not be null, but we will move stripe type to stripe later
142             // (now StripeAnimation.TYPE is figured out from permebability)
143         }
144         catch (SimRuntimeException | OtsDrawingException sre)
145         {
146             JOptionPane.showMessageDialog(null, sre.getMessage(), "Exception occured", JOptionPane.ERROR_MESSAGE);
147             System.exit(1);
148         }
149     }
150 
151     /**
152      * The Model.
153      */
154     static class XmlModel extends AbstractOtsModel
155     {
156         /** */
157         private static final long serialVersionUID = 20170421L;
158 
159         /** The network. */
160         private RoadNetwork network;
161 
162         /** The XML. */
163         private final String xml;
164 
165         /**
166          * @param simulator OtsSimulatorInterface; the simulator
167          * @param shortName String; name of the model
168          * @param description String; description of the model
169          * @param xml String; the XML string
170          */
171         XmlModel(final OtsSimulatorInterface simulator, final String shortName, final String description, final String xml)
172         {
173             super(simulator, shortName, description);
174             this.xml = xml;
175         }
176 
177         /** {@inheritDoc} */
178         @Override
179         public void constructModel() throws SimRuntimeException
180         {
181             this.network = new RoadNetwork(getShortName(), getSimulator());
182             try
183             {
184                 new XmlParser(this.network).setStream(new ByteArrayInputStream(this.xml.getBytes(StandardCharsets.UTF_8)))
185                         .build();
186             }
187             catch (NetworkException | OtsGeometryException | JAXBException | URISyntaxException | XmlParserException
188                     | SAXException | ParserConfigurationException | GtuException | IOException
189                     | TrafficControlException exception)
190             {
191                 exception.printStackTrace();
192                 // Abusing the SimRuntimeException to propagate the message to the main method (the problem could actually be a
193                 // parsing problem)
194                 throw new SimRuntimeException(exception.getMessage());
195             }
196         }
197 
198         /** {@inheritDoc} */
199         @Override
200         public RoadNetwork getNetwork()
201         {
202             return this.network;
203         }
204 
205     }
206 
207 }