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
9
10
11
12
13
14
15
16 public class FractionAdapter extends ExpressionAdapter<Double, DoubleType>
17 {
18
19
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
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 }