1 package org.opentrafficsim.xml.bindings;
2
3 import javax.xml.bind.annotation.adapters.XmlAdapter;
4
5 import org.djunits.value.Scalar;
6 import org.djunits.value.vdouble.scalar.Length;
7 import org.djutils.exceptions.Throw;
8 import org.opentrafficsim.xml.bindings.types.LengthBeginEnd;
9
10
11
12
13
14
15
16
17
18 public class LengthBeginEndAdapter extends XmlAdapter<String, LengthBeginEnd>
19 {
20
21 @Override
22 public LengthBeginEnd unmarshal(final String field) throws IllegalArgumentException
23 {
24 String clean = field.replaceAll("\\s", "");
25
26 try
27 {
28 if (clean.trim().equals("BEGIN"))
29 {
30 return new LengthBeginEnd(true, Length.ZERO);
31 }
32
33 if (clean.trim().equals("END"))
34 {
35 return new LengthBeginEnd(false, Length.ZERO);
36 }
37
38 if (clean.endsWith("%"))
39 {
40 double d = 0.01 * Double.parseDouble(clean.substring(0, clean.length() - 1).trim());
41 Throw.when(d < 0.0 || d > 1.0, IllegalArgumentException.class,
42 "fraction must be between 0.0 and 1.0 (inclusive)");
43 return new LengthBeginEnd(d);
44 }
45
46 if (clean.matches("([0]?\\.?\\d+)|[1](\\.0*)"))
47 {
48 double d = Double.parseDouble(clean);
49 return new LengthBeginEnd(d);
50 }
51
52 boolean begin = true;
53 if (clean.startsWith("END-"))
54 {
55 begin = false;
56 clean = clean.substring(4);
57 }
58
59 Length length = Length.valueOf(clean);
60 return new LengthBeginEnd(begin, length);
61 }
62 catch (Exception exception)
63 {
64 throw new IllegalArgumentException("Error parsing LengthBeginEnd " + field, exception);
65 }
66 }
67
68
69 @Override
70 public String marshal(final LengthBeginEnd lbe) throws IllegalArgumentException
71 {
72 if (!lbe.isAbsolute())
73 {
74 Throw.when(lbe.getFraction() < 0.0 || lbe.getFraction() > 1.0, IllegalArgumentException.class,
75 "fraction must be between 0.0 and 1.0 (inclusive)");
76 return "" + lbe.getFraction();
77 }
78
79 if (lbe.getOffset().eq(Length.ZERO))
80 {
81 return lbe.isBegin() ? "BEGIN" : "END";
82 }
83
84 String prefix = lbe.isBegin() ? "" : "END-";
85 return prefix + Scalar.textualStringOfDefaultLocale(lbe.getOffset());
86 }
87
88 }