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