View Javadoc
1   package org.opentrafficsim.core.network.factory.xml.units;
2   
3   import java.util.HashMap;
4   import java.util.Map;
5   
6   import org.djunits.unit.SpeedUnit;
7   import org.djunits.unit.UNITS;
8   import org.djunits.value.vdouble.scalar.Speed;
9   import org.opentrafficsim.core.network.NetworkException;
10  
11  /**
12   * Parser for speed with unit.
13   * <p>
14   * Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
15   * BSD-style license. See <a href="http://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
16   * <p>
17   * $LastChangedDate: 2015-07-24 02:58:59 +0200 (Fri, 24 Jul 2015) $, @version $Revision: 1147 $, by $Author: averbraeck $,
18   * initial version Jul 23, 2015 <br>
19   * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
20   */
21  public final class SpeedUnits implements UNITS
22  {
23      /** The speed units. */
24      public static final Map<String, SpeedUnit> SPEED_UNITS = new HashMap<>();
25      static
26      {
27          SPEED_UNITS.put("km/h", KM_PER_HOUR);
28          SPEED_UNITS.put("mi/h", MILE_PER_HOUR);
29          SPEED_UNITS.put("m/s", METER_PER_SECOND);
30          SPEED_UNITS.put("ft/s", FOOT_PER_SECOND);
31      }
32  
33      /** Utility class. */
34      private SpeedUnits()
35      {
36          // do not instantiate
37      }
38  
39      /**
40       * @param s String; the string to parse
41       * @return the unit as a String in the Map.
42       * @throws NetworkException when parsing fails
43       */
44      public static String parseSpeedUnit(final String s) throws NetworkException
45      {
46          String u = null;
47          for (String us : SPEED_UNITS.keySet())
48          {
49              if (s.toString().contains(us))
50              {
51                  if (u == null || us.length() > u.length())
52                  {
53                      u = us;
54                  }
55              }
56          }
57          if (u == null)
58          {
59              throw new NetworkException("Parsing network: cannot instantiate speed unit in: " + s);
60          }
61          return u;
62      }
63  
64      /**
65       * @param s String; the string to parse
66       * @return the next value.
67       * @throws NetworkException when parsing fails
68       */
69      public static Speed parseSpeed(final String s) throws NetworkException
70      {
71          String us = parseSpeedUnit(s);
72          SpeedUnit u = SPEED_UNITS.get(us);
73          String sv = s.substring(0, s.indexOf(us));
74          try
75          {
76              double value = Double.parseDouble(sv);
77              return new Speed(value, u);
78          }
79          catch (NumberFormatException nfe)
80          {
81              throw new NetworkException("Parsing network: cannot instantiate scalar: " + s, nfe);
82          }
83      }
84  }