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