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