FractionAdapter.java

  1. package org.opentrafficsim.xml.bindings;

  2. import javax.xml.bind.annotation.adapters.XmlAdapter;

  3. import org.djutils.exceptions.Throw;
  4. import org.djutils.logger.CategoryLogger;

  5. /**
  6.  * FractionAdapter to convert fractions as a number between 0.0 and 1.0, or as a percentage between 0% and 100%. <br>
  7.  * <br>
  8.  * Copyright (c) 2003-2018 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See
  9.  * for project information <a href="https://www.simulation.tudelft.nl/" target="_blank">www.simulation.tudelft.nl</a>. The
  10.  * source code and binary code of this software is proprietary information of Delft University of Technology.
  11.  * @author <a href="https://www.tudelft.nl/averbraeck" target="_blank">Alexander Verbraeck</a>
  12.  */
  13. public class FractionAdapter extends XmlAdapter<String, Double>
  14. {
  15.     /** {@inheritDoc} */
  16.     @Override
  17.     public Double unmarshal(final String field) throws IllegalArgumentException
  18.     {
  19.         try
  20.         {
  21.             String clean = field.replaceAll("\\s", "");

  22.             if (clean.endsWith("%"))
  23.             {
  24.                 double d = 0.01 * Double.parseDouble(clean.substring(0, clean.length() - 1).trim());
  25.                 Throw.when(d < 0.0 || d > 1.0, IllegalArgumentException.class,
  26.                         "fraction must be between 0.0 and 1.0 (inclusive)");
  27.                 return d;
  28.             }

  29.             if (clean.matches("([0]?\\.?\\d+)|[1](\\.0*)"))
  30.             {
  31.                 return Double.parseDouble(clean);
  32.             }
  33.         }
  34.         catch (Exception exception)
  35.         {
  36.             CategoryLogger.always().error(exception, "Problem parsing fraction '" + field + "'");
  37.             throw new IllegalArgumentException("Error parsing fraction " + field, exception);
  38.         }
  39.         CategoryLogger.always().error("Problem parsing fraction '" + field + "'");
  40.         throw new IllegalArgumentException("Error parsing fraction " + field);
  41.     }

  42.     /** {@inheritDoc} */
  43.     @Override
  44.     public String marshal(final Double fraction) throws IllegalArgumentException
  45.     {
  46.         Throw.when(fraction < 0.0 || fraction > 1.0, IllegalArgumentException.class,
  47.                 "fraction must be between 0.0 and 1.0 (inclusive)");
  48.         return "" + fraction;
  49.     }

  50. }