View Javadoc
1   package org.opentrafficsim.xml.bindings;
2   
3   import org.djunits.value.vdouble.scalar.Duration;
4   import org.djutils.exceptions.Throw;
5   import org.djutils.logger.CategoryLogger;
6   import org.opentrafficsim.xml.bindings.types.DurationType;
7   
8   /**
9    * DurationAdapter converts between the XML String for a Duration and the DJUnits Duration (positive).
10   * <p>
11   * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
12   * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
13   * </p>
14   * @author <a href="https://github.com/averbraeck" target="_blank">Alexander Verbraeck</a>
15   * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
16   */
17  public class PositiveDurationAdapter extends ScalarAdapter<Duration, DurationType>
18  {
19  
20      /** {@inheritDoc} */
21      @Override
22      public DurationType unmarshal(final String field)
23      {
24          if (isExpression(field))
25          {
26              return new DurationType(trimBrackets(field));
27          }
28          try
29          {
30              Duration value = Duration.valueOf(field);
31              Throw.when(value.lt0(), IllegalArgumentException.class, "PositiveDuration value %s is not a positive value.", value);
32              return new DurationType(value);
33          }
34          catch (Exception exception)
35          {
36              CategoryLogger.always().error(exception, "Problem parsing Duration '" + field + "'");
37              throw exception;
38          }
39      }
40  
41      /** {@inheritDoc} */
42      @Override
43      public String marshal(final DurationType value)
44      {
45          Throw.when(!value.isExpression() && value.getValue().lt0(), IllegalArgumentException.class,
46                  "PositiveDuration value %s is not a positive value.", value.getValue());
47          return super.marshal(value);
48      }
49  
50  }