Fork me on GitHub

Tutorial 14

E14 Using a custom type conversion to modify KML coordinates

This tutorial demonstrates the usage of a custom made type converter. We implement a new Java List "CoordinateList" which will handle our user defined type Coordinate. So far this is not related to data projection, it's just the scenario build up to show how easy user defined typed may be integrated. The actual configuration of the projector is basically just one line of code.

Projection

public interface KML {
 
    @XBRead("/kml/Placemark/Polygon/outerBoundaryIs/LinearRing/coordinates")
    public CoordinateList getCoordinates();
     
    @XBWrite("/kml/Placemark/Polygon/outerBoundaryIs/LinearRing/coordinates")
    public KML setCoordinates(CoordinateList coordinates);
     
}

Example Code

public class TestCustomTypeConversion {
 
    /**
     * This Conversion defines how String data is converted to our target type and
     * what default is to be applied when no data is available.
     */
    private final class CoordinateListConversion extends DefaultTypeConverter.Conversion<CoordinateList> {
        private CoordinateListConversion() {
            super(new CoordinateList(""));
        }
 
        @Override
        public CoordinateList convert(final String data) {
            return new CoordinateList(data);
        }
    }
 
    @Test
    public void testApplyOffsetToCoordinates() throws IOException {
        XBProjector projector = new XBProjector(new DefaultXMLFactoriesConfig().setNamespacePhilosophy(NamespacePhilosophy.AGNOSTIC));
        DefaultTypeConverter converter = new DefaultTypeConverter(Locale.getDefault(),TimeZone.getDefault()).setConversionForType(CoordinateList.class, new CoordinateListConversion());
        projector.config().setTypeConverter(converter);
        KML kml = projector.io().fromURLAnnotation(KML.class);
 
        // Extract the list of coordinates
        CoordinateList coordinates = kml.getCoordinates();
 
        assertTrue(coordinates.iterator().hasNext());
 
        // Apply some offset
        for (Coordinate a:coordinates) {
            a.setX(a.getX()+10);
        }
 
        // Set the list again
        kml.setCoordinates(coordinates);
    }
 
}