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.deserialization;
18  
19  import java.io.Serial;
20  import java.io.Serializable;
21  import java.util.List;
22  import java.util.Objects;
23  import org.locationtech.jts.geom.Coordinate;
24  
25  /**
26   * The object to coordinate converter.
27   *
28   * @author Christian Bremer
29   */
30  class ObjectToCoordinateConverter implements Serializable {
31  
32    @Serial
33    private static final long serialVersionUID = 1L;
34  
35    private final ObjectToDoubleConverter doubleConverter = new ObjectToDoubleConverter();
36  
37    /**
38     * Convert coordinate.
39     *
40     * @param source the source (must not be {@code null})
41     * @return the coordinate
42     */
43    Coordinate convert(Object source) {
44      if (Objects.isNull(source)) {
45        throw new IllegalArgumentException("Coordinate must be present.");
46      }
47      //noinspection unchecked
48      List<Object> list = (List<Object>) source;
49      Coordinate coordinate;
50      if (list.size() >= 3) {
51        coordinate = new Coordinate(
52            doubleConverter.convert(list.get(0)),
53            doubleConverter.convert(list.get(1)),
54            doubleConverter.convert(list.get(2)));
55      } else if (list.size() == 2) {
56        coordinate = new Coordinate(
57            doubleConverter.convert(list.get(0)),
58            doubleConverter.convert(list.get(1)));
59      } else if (list.size() == 1) {
60        coordinate = new Coordinate(
61            doubleConverter.convert(list.get(0)),
62            Double.NaN);
63      } else {
64        coordinate = null;
65      }
66      return coordinate;
67    }
68  
69  }