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