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 import org.opentrafficsim.xml.bindings.types.Point3dList;
9
10
11
12
13
14
15
16
17
18
19
20
21 public class CoordinateListAdapter extends XmlAdapter<String, Point3dList>
22 {
23
24 @Override
25 public Point3dList unmarshal(final String field) throws IllegalArgumentException
26 {
27 try
28 {
29 Throw.when(!field.startsWith("("), IllegalArgumentException.class, "Coordinate list must start with '(': " + field);
30 Throw.when(!field.endsWith(")"), IllegalArgumentException.class, "Coordinate list must end with ')': " + field);
31 String clean = field.substring(1, field.length() - 2);
32 Point3dListPoint3dList.html#Point3dList">Point3dList coordinates = new Point3dList();
33 String[] coordinateFields = clean.split("\\(,\\)");
34 for (String coordinateField : coordinateFields)
35 {
36 String[] digits = coordinateField.split(",");
37 Throw.when(digits.length < 2, IllegalArgumentException.class,
38 "Coordinate must have at least x and y: " + coordinateField);
39 Throw.when(digits.length > 3, IllegalArgumentException.class,
40 "Coordinate must have at most 3 dimensions: " + coordinateField);
41 double x = Double.parseDouble(digits[0]);
42 double y = Double.parseDouble(digits[1]);
43 double z = digits.length == 2 ? 0.0 : Double.parseDouble(digits[2]);
44 coordinates.add(new Point3d(x, y, z));
45 }
46 return coordinates;
47 }
48 catch (Exception exception)
49 {
50 CategoryLogger.always().error(exception, "Problem parsing coordinate list: '" + field + "'");
51 throw new IllegalArgumentException("Error parsing coordinate list: " + field, exception);
52 }
53 }
54
55
56 @Override
57 public String marshal(final Point3dList points) throws IllegalArgumentException
58 {
59 String list = "";
60 for (Point3d point : points)
61 {
62 if (list.length() > 0)
63 list += ",";
64 if (point.z == 0.0)
65 list += "(" + point.x + "," + point.y + ")";
66 else
67 list += "(" + point.x + "," + point.y + "," + point.z + ")";
68 }
69 return list;
70 }
71
72 }