View Javadoc
1   /*
2    * Copyright 2022 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.bremersee.geojson.converter.serialization;
18  
19  import static java.util.Collections.unmodifiableList;
20  import static java.util.Objects.isNull;
21  import static org.bremersee.geojson.GeoJsonConstants.POLYGON;
22  
23  import java.io.Serial;
24  import java.util.ArrayList;
25  import java.util.List;
26  import org.locationtech.jts.geom.Polygon;
27  
28  /**
29   * The type Polygon to json converter.
30   *
31   * @author Christian Bremer
32   */
33  class PolygonToJsonConverter extends AbstractGeometryToJsonConverter<Polygon> {
34  
35    @Serial
36    private static final long serialVersionUID = 1L;
37  
38    /**
39     * The Coordinate sequence converter.
40     */
41    final CoordinateSequenceToListConverter coordinateSequenceConverter;
42  
43    /**
44     * Instantiates a new Polygon to json converter.
45     *
46     * @param coordinateSequenceConverter the coordinate sequence converter
47     * @param withBoundingBox the with bounding box
48     */
49    PolygonToJsonConverter(
50        CoordinateSequenceToListConverter coordinateSequenceConverter,
51        boolean withBoundingBox) {
52  
53      super(withBoundingBox);
54      if (isNull(coordinateSequenceConverter)) {
55        throw new IllegalArgumentException("Coordinate sequence converter must be present.");
56      }
57      this.coordinateSequenceConverter = coordinateSequenceConverter;
58    }
59  
60    @Override
61    String getGeometryType() {
62      return POLYGON;
63    }
64  
65    @Override
66    Object getGeometryJsonValue(Polygon source) {
67      List<List<List<Number>>> list = new ArrayList<>();
68      list.add(coordinateSequenceConverter
69          .convert(source.getExteriorRing().getCoordinateSequence()));
70      for (int i = 0; i < source.getNumInteriorRing(); i++) {
71        list.add(coordinateSequenceConverter
72            .convert(source.getInteriorRingN(i).getCoordinateSequence()));
73      }
74      return unmodifiableList(list);
75    }
76  }