View Javadoc
1   package org.opentrafficsim.xml.bindings;
2   
3   import org.djutils.exceptions.Throw;
4   import org.djutils.logger.CategoryLogger;
5   import org.opentrafficsim.xml.bindings.types.DoubleType;
6   
7   /**
8    * FractionAdapter to convert fractions as a number between 0.0 and 1.0, or as a percentage between 0% and 100%.
9    * <p>
10   * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
11   * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
12   * </p>
13   * @author <a href="https://github.com/averbraeck" target="_blank">Alexander Verbraeck</a>
14   * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
15   */
16  public class FractionAdapter extends ExpressionAdapter<Double, DoubleType>
17  {
18      
19      /** {@inheritDoc} */
20      @Override
21      public DoubleType unmarshal(final String field) throws IllegalArgumentException
22      {
23          if (isExpression(field))
24          {
25              return new DoubleType(trimBrackets(field));
26          }
27          try
28          {
29              String clean = field.replaceAll("\\s", "");
30  
31              if (clean.endsWith("%"))
32              {
33                  double d = 0.01 * Double.parseDouble(clean.substring(0, clean.length() - 1).trim());
34                  Throw.when(d < 0.0 || d > 1.0, IllegalArgumentException.class,
35                          "fraction must be between 0.0 and 1.0 (inclusive)");
36                  return new DoubleType(d);
37              }
38  
39              if (clean.matches("([0]?\\.?\\d+)|[1](\\.0*)"))
40              {
41                  return new DoubleType(Double.parseDouble(clean));
42              }
43          }
44          catch (Exception exception)
45          {
46              CategoryLogger.always().error(exception, "Problem parsing fraction '" + field + "'");
47              throw new IllegalArgumentException("Error parsing fraction " + field, exception);
48          }
49          CategoryLogger.always().error("Problem parsing fraction '" + field + "'");
50          throw new IllegalArgumentException("Error parsing fraction " + field);
51      }
52  
53      /** {@inheritDoc} */
54      @Override
55      public String marshal(final DoubleType fraction) throws IllegalArgumentException
56      {
57          Throw.when(!fraction.isExpression() && fraction.getValue() < 0.0 || fraction.getValue() > 1.0,
58                  IllegalArgumentException.class, "fraction must be between 0.0 and 1.0 (inclusive)");
59          return super.marshal(fraction);
60      }
61  
62  }