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