/
AbstractMappingStore.java
573 lines (497 loc) · 21.1 KB
/
AbstractMappingStore.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
/* (c) 2017 Open Source Geospatial Foundation - all rights reserved
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.opensearch.eo.store;
import static org.geoserver.opensearch.eo.store.JDBCOpenSearchAccess.FF;
import static org.geoserver.opensearch.eo.store.OpenSearchAccess.METADATA_PROPERTY_NAME;
import static org.geoserver.opensearch.eo.store.OpenSearchAccess.OGC_LINKS_PROPERTY_NAME;
import java.awt.RenderingHints.Key;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Stream;
import org.geotools.data.DataAccess;
import org.geotools.data.DataSourceException;
import org.geotools.data.DataStore;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultResourceInfo;
import org.geotools.data.FeatureListener;
import org.geotools.data.FeatureReader;
import org.geotools.data.FeatureStore;
import org.geotools.data.Join;
import org.geotools.data.Join.Type;
import org.geotools.data.Query;
import org.geotools.data.QueryCapabilities;
import org.geotools.data.ResourceInfo;
import org.geotools.data.Transaction;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.data.store.EmptyFeatureCollection;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.AttributeBuilder;
import org.geotools.feature.ComplexFeatureBuilder;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.util.logging.Logging;
import org.opengis.feature.Attribute;
import org.opengis.feature.Feature;
import org.opengis.feature.FeatureFactory;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.feature.type.FeatureType;
import org.opengis.feature.type.Name;
import org.opengis.feature.type.PropertyDescriptor;
import org.opengis.filter.Filter;
import org.opengis.filter.expression.PropertyName;
import org.opengis.filter.identity.FeatureId;
import org.opengis.filter.sort.SortBy;
import org.opengis.filter.sort.SortOrder;
/**
* Base class for the collection and product specific feature source wrappers
*
* @author Andrea Aime - GeoSolutions
*/
public abstract class AbstractMappingStore implements FeatureStore<FeatureType, Feature> {
static final FeatureFactory FEATURE_FACTORY = CommonFactoryFinder.getFeatureFactory(null);
static final Logger LOGGER = Logging.getLogger(AbstractMappingStore.class);
protected JDBCOpenSearchAccess openSearchAccess;
protected FeatureType schema;
protected SourcePropertyMapper propertyMapper;
protected SortBy[] defaultSort;
private SimpleFeatureType linkFeatureType;
private Transaction transaction;
public AbstractMappingStore(JDBCOpenSearchAccess openSearchAccess,
FeatureType collectionFeatureType) throws IOException {
this.openSearchAccess = openSearchAccess;
this.schema = collectionFeatureType;
this.propertyMapper = new SourcePropertyMapper(schema);
this.defaultSort = buildDefaultSort(schema);
this.linkFeatureType = buildLinkFeatureType();
}
protected SimpleFeatureType buildLinkFeatureType() throws IOException {
SimpleFeatureType source = openSearchAccess.getDelegateStore().getSchema(getLinkTable());
try {
SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
b.init(source);
b.setName(openSearchAccess.OGC_LINKS_PROPERTY_NAME);
return b.buildFeatureType();
} catch (Exception e) {
throw new DataSourceException("Could not build the renamed feature type.", e);
}
}
/**
* Builds the default sort for the underlying feature source query
*
* @param schema
* @return
*/
protected SortBy[] buildDefaultSort(FeatureType schema) {
String timeStart = propertyMapper.getSourceName("timeStart");
String identifier = propertyMapper.getSourceName("identifier");
return new SortBy[] { FF.sort(timeStart, SortOrder.DESCENDING),
FF.sort(identifier, SortOrder.ASCENDING) };
}
@Override
public Name getName() {
return schema.getName();
}
@Override
public ResourceInfo getInfo() {
try {
SimpleFeatureSource featureSource = getDelegateCollectionSource();
ResourceInfo delegateInfo = featureSource.getInfo();
DefaultResourceInfo result = new DefaultResourceInfo(delegateInfo);
result.setSchema(new URI(schema.getName().getNamespaceURI()));
return result;
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/*
* Returns the underlying delegate source
*/
protected abstract SimpleFeatureSource getDelegateCollectionSource() throws IOException;
protected SimpleFeatureStore getDelegateCollectionStore() throws IOException {
SimpleFeatureStore fs = (SimpleFeatureStore) getDelegateCollectionSource();
return fs;
}
@Override
public DataAccess<FeatureType, Feature> getDataStore() {
return openSearchAccess;
}
@Override
public QueryCapabilities getQueryCapabilities() {
QueryCapabilities result = new QueryCapabilities() {
@Override
public boolean isOffsetSupported() {
return true;
}
@Override
public boolean isReliableFIDSupported() {
// the delegate store should have a primary key on collections
return true;
}
};
return result;
}
@Override
public void addFeatureListener(FeatureListener listener) {
throw new UnsupportedOperationException();
}
@Override
public void removeFeatureListener(FeatureListener listener) {
throw new UnsupportedOperationException();
}
@Override
public FeatureCollection<FeatureType, Feature> getFeatures(Filter filter) throws IOException {
return getFeatures(new Query(getSchema().getName().getLocalPart(), filter));
}
@Override
public FeatureCollection<FeatureType, Feature> getFeatures() throws IOException {
return getFeatures(Query.ALL);
}
@Override
public FeatureType getSchema() {
return schema;
}
@Override
public ReferencedEnvelope getBounds() throws IOException {
return getDelegateCollectionSource().getBounds();
}
@Override
public ReferencedEnvelope getBounds(Query query) throws IOException {
Query mapped = mapToSimpleCollectionQuery(query, false);
return getDelegateCollectionSource().getBounds(mapped);
}
@Override
public Set<Key> getSupportedHints() {
try {
return getDelegateCollectionSource().getSupportedHints();
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Override
public int getCount(Query query) throws IOException {
final Query mappedQuery = mapToSimpleCollectionQuery(query, false);
return getDelegateCollectionSource().getCount(mappedQuery);
}
/**
* Maps query back the main underlying feature source
*
* @param query
* @return
* @throws IOException
*/
protected Query mapToSimpleCollectionQuery(Query query, boolean addJoins) throws IOException {
Query result = new Query(getDelegateCollectionSource().getSchema().getTypeName());
if (query.getFilter() != null) {
MappingFilterVisitor visitor = new MappingFilterVisitor(propertyMapper);
Filter mappedFilter = (Filter) query.getFilter().accept(visitor, null);
result.setFilter(mappedFilter);
}
if (query.getPropertyNames() != null && query.getPropertyNames().length > 0) {
String[] mappedPropertyNames = Arrays.stream(query.getPropertyNames())
.map(name -> propertyMapper.getSourceName(name)).filter(name -> name != null)
.toArray(size -> new String[size]);
if (mappedPropertyNames.length == 0) {
result.setPropertyNames(Query.ALL_NAMES);
} else {
result.setPropertyNames(mappedPropertyNames);
}
}
if (query.getSortBy() != null && query.getSortBy().length > 0) {
SortBy[] mappedSortBy = Arrays.stream(query.getSortBy()).map(sb -> {
if (sb == SortBy.NATURAL_ORDER || sb == SortBy.REVERSE_ORDER) {
return sb;
} else {
String name = sb.getPropertyName().getPropertyName();
String mappedName = propertyMapper.getSourceName(name);
if (mappedName == null) {
throw new IllegalArgumentException("Cannot sort on " + name);
}
return FF.sort(mappedName, sb.getSortOrder());
}
}).toArray(size -> new SortBy[size]);
result.setSortBy(mappedSortBy);
} else {
// get stable results for paging
result.setSortBy(defaultSort);
}
if(addJoins) {
// join to metadata table if necessary
if (hasOutputProperty(query, METADATA_PROPERTY_NAME, false)) {
Filter filter = FF.equal(FF.property("id"), FF.property("metadata.mid"), true);
final String metadataTable = getMetadataTable();
Join join = new Join(metadataTable, filter);
join.setAlias("metadata");
result.getJoins().add(join);
}
// same goes for OGC links (they might be missing, so outer join is used)
if (hasOutputProperty(query, OGC_LINKS_PROPERTY_NAME, true)) {
final String linkTable = getLinkTable();
final String linkForeignKey = getLinkForeignKey();
Filter filter = FF.equal(FF.property("id"), FF.property("link." + linkForeignKey), true);
Join join = new Join(linkTable, filter);
join.setAlias("link");
join.setType(Type.OUTER);
result.getJoins().add(join);
}
} else {
// only non joined requests are pageable
result.setStartIndex(query.getStartIndex());
result.setMaxFeatures(query.getMaxFeatures());
}
return result;
}
/**
* Name of the metadata table to join in case the {@link OpenSearchAccess#METADATA_PROPERTY_NAME} property is requested
*
* @return
*/
protected abstract String getMetadataTable();
/**
* Name of the link table to join in case the {@link OpenSearchAccess#OGC_LINKS_PROPERTY_NAME} property is requested
*
* @return
*/
protected abstract String getLinkTable();
/**
* Name of the field linking back to the main table in case the {@link OpenSearchAccess#OGC_LINKS_PROPERTY_NAME} property is requested
*
* @return
*/
protected abstract String getLinkForeignKey();
/**
* Searches for an optional property among the query attributes. Returns true only if the property is explicitly listed
*
* @param query
* @param property
* @return
*/
protected boolean hasOutputProperty(Query query, Name property, boolean includedByDefault) {
if (query.getProperties() == null) {
return includedByDefault;
}
final String localPart = property.getLocalPart();
final String namespaceURI = property.getNamespaceURI();
for (PropertyName pn : query.getProperties()) {
if (localPart.equals(pn.getPropertyName())
&& namespaceURI.equals(pn.getNamespaceContext().getURI(""))) {
return true;
}
}
return false;
}
@Override
public FeatureCollection<FeatureType, Feature> getFeatures(Query query) throws IOException {
// first get the ids of the features we are going to return, no joins to support paging
Query idsQuery = mapToSimpleCollectionQuery(query, false);
// idsQuery.setProperties(Query.NO_PROPERTIES); (no can do, there are mandatory fields)
SimpleFeatureCollection idFeatureCollection = getDelegateCollectionSource().getFeatures(idsQuery);
Set<FeatureId> ids = new LinkedHashSet<>();
idFeatureCollection.accepts(f -> ids.add(f.getIdentifier()), null);
// if no features, return immediately
SimpleFeatureCollection fc;
if(ids.isEmpty()) {
fc = new EmptyFeatureCollection(getDelegateCollectionSource().getSchema());
} else {
// the run a joined query with the specified ids
Query dataQuery = mapToSimpleCollectionQuery(query, true);
dataQuery.setFilter(FF.id(ids));
fc = getDelegateCollectionSource().getFeatures(dataQuery);
}
return new MappingFeatureCollection(schema, fc, this::mapToComplexFeature);
}
/**
* Maps the underlying features (eventually joined) to the output complex feature
*
* @param it
* @return
*/
protected Feature mapToComplexFeature(PushbackFeatureIterator<SimpleFeature> it) {
SimpleFeature fi = it.next();
ComplexFeatureBuilder builder = new ComplexFeatureBuilder(schema);
// allow subclasses to perform custom mappings while reusing the common ones
mapPropertiesToComplex(builder, fi);
// the OGC links can be more than one
Object link = fi.getAttribute("link");
while(link instanceof SimpleFeature) {
// retype the feature to have the right name
SimpleFeature linkFeature = SimpleFeatureBuilder.retype((SimpleFeature) link, linkFeatureType);
builder.append(OGC_LINKS_PROPERTY_NAME, linkFeature);
// see if there are more links
if(it.hasNext()) {
SimpleFeature next = it.next();
// same feature?
if(next.getID().equals(fi.getID())) {
link = next.getAttribute("link");
} else {
// moved to the next feature, push it back,
// we're done for the current one
it.pushBack();
break;
}
} else {
break;
}
}
//
Feature feature = builder.buildFeature(fi.getID());
return feature;
}
/**
* Performs the common mappings, subclasses can override to add more
*
* @param builder
* @param fi
*/
protected void mapPropertiesToComplex(ComplexFeatureBuilder builder, SimpleFeature fi) {
AttributeBuilder ab = new AttributeBuilder(FEATURE_FACTORY);
for (PropertyDescriptor pd : schema.getDescriptors()) {
if (!(pd instanceof AttributeDescriptor)) {
continue;
}
String localName = (String) pd.getUserData().get(JDBCOpenSearchAccess.SOURCE_ATTRIBUTE);
if (localName == null) {
continue;
}
Object value = fi.getAttribute(localName);
if (value == null) {
continue;
}
ab.setDescriptor((AttributeDescriptor) pd);
Attribute attribute = ab.buildSimple(null, value);
builder.append(pd.getName(), attribute);
}
// handle joined metadata
Object metadataValue = fi.getAttribute("metadata");
if (metadataValue instanceof SimpleFeature) {
SimpleFeature metadataFeature = (SimpleFeature) metadataValue;
ab.setDescriptor((AttributeDescriptor) schema
.getDescriptor(METADATA_PROPERTY_NAME));
Attribute attribute = ab.buildSimple(null, metadataFeature.getAttribute("metadata"));
builder.append(METADATA_PROPERTY_NAME, attribute);
}
}
/**
* Maps a complex feature back to one or more simple features
*
* @param it
* @return
* @throws IOException
*/
protected SimpleFeature mapToMainSimpleFeature(Feature feature) throws IOException {
// map the primary simple feature
final SimpleFeatureType simpleSchema = getDelegateCollectionSource().getSchema();
SimpleFeatureBuilder fb = new SimpleFeatureBuilder(simpleSchema);
for (PropertyDescriptor pd : schema.getDescriptors()) {
if (!(pd instanceof AttributeDescriptor)) {
continue;
}
String localName = (String) pd.getUserData().get(JDBCOpenSearchAccess.SOURCE_ATTRIBUTE);
if (localName == null) {
continue;
}
Property property = feature.getProperty(pd.getName());
if(property == null || property.getValue() == null) {
continue;
}
fb.set(localName, property.getValue());
}
SimpleFeature sf = fb.buildFeature(null);
return sf;
}
protected List<SimpleFeature> mapToSecondarySimpleFeatures(Feature feature) {
// TODO: handle OGC links, but for the moment the code uses modifyFeatures to add those
return Collections.emptyList();
}
@Override
public List<FeatureId> addFeatures(FeatureCollection<FeatureType, Feature> featureCollection)
throws IOException {
// silly implementation assuming there will be only one insert at a time (which is
// indeed the case for the current REST API), needs to be turned into a streaming
// approach in case we want to handle larger data volumes
final DataStore delegateStore = openSearchAccess.getDelegateStore();
List<FeatureId> result = new ArrayList<>();
try(FeatureIterator it = featureCollection.features()) {
Feature feature = it.next();
SimpleFeature simpleFeature = mapToMainSimpleFeature(feature);
SimpleFeatureStore store = getDelegateCollectionStore();
store.setTransaction(getTransaction());
List<FeatureId> ids = store.addFeatures(DataUtilities.collection(simpleFeature));
result.addAll(ids);
List<SimpleFeature> simpleFeatures = mapToSecondarySimpleFeatures(feature);
for (SimpleFeature sf : simpleFeatures) {
SimpleFeatureStore fs = (SimpleFeatureStore) delegateStore.getFeatureSource(sf.getType().getTypeName());
if(fs == null) {
throw new IOException("Could not find a delegate feature store for unmapped feature " + sf);
}
fs.setTransaction(getTransaction());
fs.addFeatures(DataUtilities.collection(sf));
}
}
return result;
}
@Override
public void removeFeatures(Filter filter) throws IOException {
MappingFilterVisitor visitor = new MappingFilterVisitor(propertyMapper);
Filter mappedFilter = (Filter) filter.accept(visitor, null);
SimpleFeatureStore store = getDelegateCollectionStore();
store.removeFeatures(mappedFilter);
}
@Override
public void modifyFeatures(AttributeDescriptor[] types, Object[] values, Filter filter)
throws IOException {
Name[] names = Stream.of(types).map(type -> type.getName()).toArray(size -> new Name[size]);
modifyFeatures(names, values, filter);
}
@Override
public void modifyFeatures(Name attributeName, Object attributeValue, Filter filter)
throws IOException {
modifyFeatures(new Name[] {attributeName}, new Object[] {attributeValue}, filter);
}
@Override
public void modifyFeatures(AttributeDescriptor type, Object value, Filter filter)
throws IOException {
modifyFeatures(type.getName(), value, filter);
}
@Override
public void modifyFeatures(Name[] attributeNames, Object[] attributeValues, Filter filter)
throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void setFeatures(FeatureReader<FeatureType, Feature> reader) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void setTransaction(Transaction transaction) {
this.transaction = transaction;
}
@Override
public Transaction getTransaction() {
if(transaction == null) {
return Transaction.AUTO_COMMIT;
} else {
return this.transaction;
}
}
}