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