View Javadoc
1   package org.opentrafficsim.xml.bindings;
2   
3   import javax.xml.bind.annotation.adapters.XmlAdapter;
4   
5   import org.djutils.exceptions.Throw;
6   
7   /**
8    * FractionAdapter to convert fractions as a number between 0.0 and 1.0, or as a percentage between 0% and 100%. <br>
9    * <br>
10   * Copyright (c) 2003-2018 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See
11   * for project information <a href="https://www.simulation.tudelft.nl/" target="_blank">www.simulation.tudelft.nl</a>. The
12   * source code and binary code of this software is proprietary information of Delft University of Technology.
13   * @author <a href="https://www.tudelft.nl/averbraeck" target="_blank">Alexander Verbraeck</a>
14   */
15  public class FractionAdapter extends XmlAdapter<String, Double>
16  {
17      /** {@inheritDoc} */
18      @Override
19      public Double unmarshal(final String field) throws IllegalArgumentException
20      {
21          try
22          {
23              String clean = field.replaceAll("\\s", "");
24  
25              if (clean.endsWith("%"))
26              {
27                  double d = 0.01 * Double.parseDouble(clean.substring(0, clean.length() - 1).trim());
28                  Throw.when(d < 0.0 || d > 1.0, IllegalArgumentException.class,
29                          "fraction must be between 0.0 and 1.0 (inclusive)");
30                  return d;
31              }
32  
33              if (clean.matches("([0]?\\.?\\d+)|[1](\\.0*)"))
34              {
35                  return Double.parseDouble(clean);
36              }
37          }
38          catch (Exception exception)
39          {
40              throw new IllegalArgumentException("Error parsing fraction " + field, exception);
41          }
42          throw new IllegalArgumentException("Error parsing fraction " + field);
43      }
44  
45      /** {@inheritDoc} */
46      @Override
47      public String marshal(final Double fraction) throws IllegalArgumentException
48      {
49          Throw.when(fraction < 0.0 || fraction > 1.0, IllegalArgumentException.class,
50                  "fraction must be between 0.0 and 1.0 (inclusive)");
51          return "" + fraction;
52      }
53  
54  }