1 package org.opentrafficsim.xml.bindings;
2
3
4 import javax.xml.bind.annotation.adapters.XmlAdapter;
5
6 import org.djutils.draw.point.Point3d;
7 import org.djutils.exceptions.Throw;
8 import org.djutils.logger.CategoryLogger;
9
10
11
12
13
14
15
16
17
18
19
20 public class CoordinateAdapter extends XmlAdapter<String, Point3d>
21 {
22
23 @Override
24 public Point3d unmarshal(final String field) throws IllegalArgumentException
25 {
26 try
27 {
28 String clean = field.replaceAll("\\s", "");
29 Throw.when(!clean.startsWith("("), IllegalArgumentException.class, "Coordinate must start with '(': " + field);
30 Throw.when(!clean.endsWith(")"), IllegalArgumentException.class, "Coordinate must end with ')': " + field);
31 clean = clean.substring(1, clean.length() - 1);
32 String[] digits = clean.split(",");
33 Throw.when(digits.length < 2, IllegalArgumentException.class, "Coordinate must have at least x and y: " + field);
34 Throw.when(digits.length > 3, IllegalArgumentException.class,
35 "Coordinate must have at most 3 dimensions: " + field);
36
37 double x = Double.parseDouble(digits[0]);
38 double y = Double.parseDouble(digits[1]);
39 double z = digits.length == 2 ? 0.0 : Double.parseDouble(digits[2]);
40 return new Point3d(x, y, z);
41 }
42 catch (Exception exception)
43 {
44 CategoryLogger.always().error(exception, "Problem parsing coordinate '" + field + "'");
45 throw new IllegalArgumentException("Error parsing coordinate" + field, exception);
46 }
47 }
48
49
50 @Override
51 public String marshal(final Point3d point) throws IllegalArgumentException
52 {
53 if (point.z == 0.0)
54 return "(" + point.x + ", " + point.y + ")";
55 return "(" + point.x + ", " + point.y + ", " + point.z + ")";
56 }
57
58 }