CoordinateAdapter.java

  1. package org.opentrafficsim.xml.bindings;

  2. import javax.vecmath.Point3d;
  3. import javax.xml.bind.annotation.adapters.XmlAdapter;

  4. import org.djutils.exceptions.Throw;
  5. import org.djutils.logger.CategoryLogger;

  6. /**
  7.  * CoordinateAdapter converts between the XML String for a coordinate and a Point3d. Because the ots-xsd project is not
  8.  * dependent on ots-core, Point3d is chosen instead of OTSPoint3D to store the (x, y, z) information. The marshal function
  9.  * returns a 2D-coordinate in case the z-value is zero. <br>
  10.  * <br>
  11.  * Copyright (c) 2003-2018 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See
  12.  * for project information <a href="https://www.simulation.tudelft.nl/" target="_blank">www.simulation.tudelft.nl</a>. The
  13.  * source code and binary code of this software is proprietary information of Delft University of Technology.
  14.  * @author <a href="https://www.tudelft.nl/averbraeck" target="_blank">Alexander Verbraeck</a>
  15.  */
  16. public class CoordinateAdapter extends XmlAdapter<String, Point3d>
  17. {
  18.     /** {@inheritDoc} */
  19.     @Override
  20.     public Point3d unmarshal(final String field) throws IllegalArgumentException
  21.     {
  22.         try
  23.         {
  24.             String clean = field.replaceAll("\\s", "");
  25.             Throw.when(!clean.startsWith("("), IllegalArgumentException.class, "Coordinate must start with '(': " + field);
  26.             Throw.when(!clean.endsWith(")"), IllegalArgumentException.class, "Coordinate must end with ')': " + field);
  27.             clean = clean.substring(1, clean.length() - 1);
  28.             String[] digits = clean.split(",");
  29.             Throw.when(digits.length < 2, IllegalArgumentException.class, "Coordinate must have at least x and y: " + field);
  30.             Throw.when(digits.length > 3, IllegalArgumentException.class,
  31.                     "Coordinate must have at most 3 dimensions: " + field);

  32.             double x = Double.parseDouble(digits[0]);
  33.             double y = Double.parseDouble(digits[1]);
  34.             double z = digits.length == 2 ? 0.0 : Double.parseDouble(digits[2]);
  35.             return new Point3d(x, y, z);
  36.         }
  37.         catch (Exception exception)
  38.         {
  39.             CategoryLogger.always().error(exception, "Problem parsing coordinate '" + field + "'");
  40.             throw new IllegalArgumentException("Error parsing coordinate" + field, exception);
  41.         }
  42.     }

  43.     /** {@inheritDoc} */
  44.     @Override
  45.     public String marshal(final Point3d point) throws IllegalArgumentException
  46.     {
  47.         if (point.z == 0.0)
  48.             return "(" + point.x + ", " + point.y + ")";
  49.         return "(" + point.x + ", " + point.y + ", " + point.z + ")";
  50.     }

  51. }