1
2
3
4
5
6 package org.tailormap.api.geotools.featuresources;
7
8 import static org.geotools.jdbc.JDBCDataStore.JDBC_PRIMARY_KEY_COLUMN;
9 import static org.geotools.jdbc.JDBCDataStore.JDBC_READ_ONLY;
10 import static org.tailormap.api.persistence.helper.GeoToolsHelper.crsToString;
11
12 import java.io.IOException;
13 import java.lang.invoke.MethodHandles;
14 import java.util.Arrays;
15 import java.util.HashMap;
16 import java.util.List;
17 import java.util.Map;
18 import org.apache.commons.lang3.StringUtils;
19 import org.geotools.api.data.DataStore;
20 import org.geotools.api.data.DataStoreFactorySpi;
21 import org.geotools.api.data.DataStoreFinder;
22 import org.geotools.api.data.ResourceInfo;
23 import org.geotools.api.data.ServiceInfo;
24 import org.geotools.api.data.SimpleFeatureSource;
25 import org.geotools.api.feature.simple.SimpleFeatureType;
26 import org.geotools.api.feature.type.AttributeDescriptor;
27 import org.geotools.api.feature.type.AttributeType;
28 import org.geotools.jdbc.JDBCFeatureStore;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.tailormap.api.admin.model.CapabilitiesLoadingEvent;
32 import org.tailormap.api.persistence.TMFeatureSource;
33 import org.tailormap.api.persistence.TMFeatureType;
34 import org.tailormap.api.persistence.helper.CapabilitiesLoadingProgressReporting;
35 import org.tailormap.api.persistence.helper.GeoToolsHelper;
36 import org.tailormap.api.persistence.json.TMAttributeDescriptor;
37 import org.tailormap.api.persistence.json.TMAttributeType;
38 import org.tailormap.api.persistence.json.TMFeatureTypeInfo;
39 import org.tailormap.api.persistence.json.TMServiceCaps;
40 import org.tailormap.api.persistence.json.TMServiceInfo;
41
42 public abstract class FeatureSourceHelper {
43 private static final Logger logger =
44 LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
45
46 public DataStore createDataStore(TMFeatureSource tmfs) throws IOException {
47 return createDataStore(tmfs, null);
48 }
49
50
51
52
53
54
55
56
57
58
59 public abstract DataStore createDataStore(TMFeatureSource tmfs, Integer timeout) throws IOException;
60
61 public SimpleFeatureSource openGeoToolsFeatureSource(TMFeatureType tmft, Integer timeout) throws IOException {
62 DataStore ds = createDataStore(tmft.getFeatureSource(), timeout);
63 try {
64 return ds.getFeatureSource(tmft.getName());
65 } catch (IOException | RuntimeException e) {
66
67 ds.dispose();
68 throw e;
69 }
70 }
71
72 public DataStore openDatastore(Map<String, Object> params, String passwordKey) throws IOException {
73 return openDatastore(params, passwordKey, null);
74 }
75
76
77
78
79
80
81
82
83
84
85 public DataStore openDatastore(Map<String, Object> params, String passwordKey, DataStoreFactorySpi factory)
86 throws IOException {
87 Map<String, Object> logParams = new HashMap<>(params);
88 String passwd = (String) params.get(passwordKey);
89 if (passwd != null) {
90 logParams.put(passwordKey, String.valueOf(new char[passwd.length()]).replace("\0", "*"));
91 }
92 logger.debug("Opening datastore using parameters: {}", logParams);
93 DataStore ds;
94 try {
95 ds = factory != null ? factory.createDataStore(params) : DataStoreFinder.getDataStore(params);
96 } catch (IOException e) {
97 throw new IOException("Cannot open datastore using parameters: " + logParams, e);
98 }
99 if (ds == null) {
100 throw new IOException("No datastore found using parameters " + logParams);
101 }
102 return ds;
103 }
104
105 public void loadCapabilities(
106 TMFeatureSource tmfs,
107 Integer timeout,
108 CapabilitiesLoadingProgressReporting reporter,
109 CapabilitiesLoadingEvent event)
110 throws IOException {
111
112 reporter.reportCapabilitiesLoadingProgress(
113 event.message("Opening datastore for feature source " + tmfs.getTitle()));
114
115 DataStore ds = createDataStore(tmfs, timeout);
116 try {
117 if (StringUtils.isBlank(tmfs.getTitle())) {
118 tmfs.setTitle(ds.getInfo().getTitle());
119 }
120
121 ServiceInfo si = ds.getInfo();
122 tmfs.setServiceCapabilities(new TMServiceCaps()
123 .serviceInfo(new TMServiceInfo()
124 .title(si.getTitle())
125 .keywords(si.getKeywords())
126 .description(si.getDescription())
127 .publisher(si.getPublisher())
128 .schema(si.getSchema())
129 .source(si.getSource())));
130
131 List<String> typeNames = Arrays.asList(ds.getTypeNames());
132 int progress = 0;
133 reporter.reportCapabilitiesLoadingProgress(
134 event.message("Retrieved service information for feature source " + tmfs.getTitle())
135 .total(typeNames.size())
136 .progress(progress));
137 logger.debug(
138 "Type names for {} {}: {}",
139 tmfs.getProtocol().getValue(),
140 tmfs.getProtocol() == TMFeatureSource.Protocol.WFS ? tmfs.getUrl() : tmfs.getJdbcConnection(),
141 typeNames);
142
143 tmfs.getFeatureTypes().removeIf(tmft -> {
144 if (!typeNames.contains(tmft.getName())) {
145 logger.debug("Feature type removed: {}", tmft.getName());
146 return true;
147 } else {
148 return false;
149 }
150 });
151
152 for (String typeName : typeNames) {
153 TMFeatureType pft = tmfs.getFeatureTypes().stream()
154 .filter(ft -> ft.getName().equals(typeName))
155 .findFirst()
156 .orElseGet(() -> new TMFeatureType().setName(typeName).setFeatureSource(tmfs));
157 if (!tmfs.getFeatureTypes().contains(pft)) {
158 tmfs.getFeatureTypes().add(pft);
159 }
160 try {
161 logger.debug("Get feature source from GeoTools datastore for type \"{}\"", typeName);
162 SimpleFeatureSource gtFs = ds.getFeatureSource(typeName);
163 ResourceInfo info = gtFs.getInfo();
164 if (info != null) {
165 pft.setTitle(info.getTitle());
166 pft.setInfo(getFeatureTypeInfo(pft, info, gtFs));
167 pft.getAttributes().clear();
168
169 SimpleFeatureType gtFt = gtFs.getSchema();
170
171 reporter.reportCapabilitiesLoadingProgress(event.message("Retrieved feature type " + typeName)
172 .progress(++progress));
173
174 pft.setWriteable(gtFs instanceof JDBCFeatureStore
175 && !Boolean.TRUE.equals(gtFt.getUserData().get(JDBC_READ_ONLY)));
176 String primaryKeyName = null;
177 for (AttributeDescriptor gtAttr : gtFt.getAttributeDescriptors()) {
178 AttributeType type = gtAttr.getType();
179 if (Boolean.TRUE.equals(gtAttr.getUserData().get(JDBC_PRIMARY_KEY_COLUMN))) {
180 if (primaryKeyName == null) {
181 logger.debug(
182 "Found primary key attribute \"{}\" for type \"{}\"",
183 gtAttr.getLocalName(),
184 typeName);
185 primaryKeyName = gtAttr.getLocalName();
186 } else {
187 logger.warn(
188 "Multiple primary key attributes found for type \"{}\": \"{}\" and \"{}\". Composite primary keys are not supported for writing, setting as read-only.",
189 typeName,
190 primaryKeyName,
191 gtAttr.getLocalName());
192 pft.setWriteable(false);
193 }
194 }
195 TMAttributeDescriptor tmAttr = new TMAttributeDescriptor()
196 .name(gtAttr.getLocalName())
197 .type(GeoToolsHelper.toAttributeType(type))
198 .nullable(gtAttr.isNillable())
199 .defaultValue(
200 gtAttr.getDefaultValue() == null
201 ? null
202 : gtAttr.getDefaultValue().toString())
203 .description(
204 type.getDescription() == null
205 ? null
206 : type.getDescription().toString());
207 if (tmAttr.getType() == TMAttributeType.OBJECT) {
208 tmAttr.setUnknownTypeClassName(type.getBinding().getName());
209 }
210 pft.getAttributes().add(tmAttr);
211 }
212 pft.setPrimaryKeyAttribute(primaryKeyName);
213 pft.setDefaultGeometryAttribute(pft.findDefaultGeometryAttribute());
214 }
215 } catch (Exception e) {
216 logger.error("Exception reading feature type \"{}\"", typeName, e);
217 }
218 }
219 } finally {
220 ds.dispose();
221 }
222 }
223
224 protected TMFeatureTypeInfo getFeatureTypeInfo(TMFeatureType pft, ResourceInfo info, SimpleFeatureSource gtFs) {
225 return new TMFeatureTypeInfo()
226 .keywords(info.getKeywords())
227 .description(info.getDescription())
228 .bounds(GeoToolsHelper.fromEnvelope(info.getBounds()))
229 .crs(crsToString(info.getCRS()));
230 }
231 }