1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.bremersee.geojson.converter.serialization;
18
19 import static java.util.Collections.unmodifiableMap;
20 import static java.util.Objects.isNull;
21 import static java.util.Objects.requireNonNull;
22
23 import java.io.Serial;
24 import java.io.Serializable;
25 import java.util.Arrays;
26 import java.util.LinkedHashMap;
27 import java.util.Map;
28 import java.util.Optional;
29 import java.util.stream.Collectors;
30 import org.bremersee.geojson.GeoJsonConstants;
31 import org.bremersee.geojson.GeoJsonGeometryFactory;
32 import org.locationtech.jts.geom.Geometry;
33
34
35
36
37
38
39
40 abstract class AbstractGeometryToJsonConverter<S extends Geometry> implements Serializable {
41
42 @Serial
43 private static final long serialVersionUID = 1L;
44
45 private final boolean withBoundingBox;
46
47
48
49
50
51
52 AbstractGeometryToJsonConverter(boolean withBoundingBox) {
53 this.withBoundingBox = withBoundingBox;
54 }
55
56
57
58
59
60
61
62 Map<String, Object> convert(S source) {
63 if (isNull(source)) {
64 return null;
65 }
66 Map<String, Object> map = new LinkedHashMap<>();
67 map.put(GeoJsonConstants.TYPE, requireNonNull(getGeometryType()));
68 if (withBoundingBox) {
69 Optional.ofNullable(GeoJsonGeometryFactory.getBoundingBox(source))
70 .map(bbox -> Arrays.stream(bbox).boxed().toList())
71 .ifPresent(bbox -> map.put(GeoJsonConstants.BBOX, bbox));
72 }
73 map.put(GeoJsonConstants.COORDINATES, getGeometryJsonValue(source));
74 return unmodifiableMap(map);
75 }
76
77
78
79
80
81
82 abstract String getGeometryType();
83
84
85
86
87
88
89
90 abstract Object getGeometryJsonValue(S source);
91 }