forked from geoserver/geoserver
-
Notifications
You must be signed in to change notification settings - Fork 1
/
FeatureTypeController.java
510 lines (450 loc) · 22 KB
/
FeatureTypeController.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
/* (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.rest.catalog;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import freemarker.template.ObjectWrapper;
import org.geoserver.catalog.*;
import org.geoserver.config.util.XStreamPersister;
import org.geoserver.rest.ObjectToMapWrapper;
import org.geoserver.rest.ResourceNotFoundException;
import org.geoserver.rest.RestBaseController;
import org.geoserver.rest.RestException;
import org.geoserver.rest.converters.XStreamMessageConverter;
import org.geoserver.rest.util.MediaTypeExtensions;
import org.geoserver.rest.wrapper.RestWrapper;
import org.geotools.data.DataAccess;
import org.geotools.data.DataStore;
import org.geotools.data.FeatureSource;
import org.geotools.feature.NameImpl;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.util.logging.Logging;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.FeatureType;
import org.opengis.feature.type.Name;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import freemarker.template.SimpleHash;
/**
* Feature type controller
*/
@RestController
@ControllerAdvice
@RequestMapping(path = {
RestBaseController.ROOT_PATH + "/workspaces/{workspaceName}/featuretypes",
RestBaseController.ROOT_PATH + "/workspaces/{workspaceName}/datastores/{storeName}/featuretypes"})
public class FeatureTypeController extends AbstractCatalogController {
private static final Logger LOGGER = Logging.getLogger(CoverageStoreController.class);
@Autowired
public FeatureTypeController(@Qualifier("catalog") Catalog catalog) {
super(catalog);
}
@GetMapping(produces = {
MediaType.TEXT_HTML_VALUE,
MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE })
public Object featureTypesGet(
@PathVariable String workspaceName,
@PathVariable(required = false) String storeName,
@RequestParam(defaultValue = "configured") String list) {
if ("available".equalsIgnoreCase(list) || "available_with_geom".equalsIgnoreCase(list)
|| "all".equalsIgnoreCase(list)) {
DataStoreInfo info = getExistingDataStore(workspaceName, storeName);
// flag to control whether to filter out types without geometry
boolean skipNoGeom = "available_with_geom".equalsIgnoreCase(list);
// list of available feature types
List<String> featureTypes = new ArrayList<>();
try {
DataStore ds = (DataStore) info.getDataStore(null);
String[] featureTypeNames = ds.getTypeNames();
for (String featureTypeName : featureTypeNames) {
FeatureTypeInfo ftinfo = catalog.getFeatureTypeByDataStore(info,
featureTypeName);
if (ftinfo == null) {
// The feature type is not in catalog, so add it to the return list.
// check whether to filter by geometry
if (skipNoGeom) {
try {
FeatureType featureType = ds.getSchema(featureTypeName);
if (featureType.getGeometryDescriptor() == null) {
// skip
continue;
}
} catch (IOException e) {
LOGGER.log(Level.WARNING,
"Unable to load schema for feature type " + featureTypeName,
e);
}
}
featureTypes.add(featureTypeName);
} else if ("all".equalsIgnoreCase(list)) {
// The feature type is already configured, but "all" was specified, so add it to the return list.
featureTypes.add(featureTypeName);
}
}
} catch (IOException e) {
throw new ResourceNotFoundException("Could not load datastore: " + storeName);
}
return new StringsList(featureTypes, "featureTypeName");
} else {
List<FeatureTypeInfo> fts;
if (storeName != null) {
DataStoreInfo dataStore = catalog.getDataStoreByName(workspaceName, storeName);
fts = catalog.getFeatureTypesByDataStore(dataStore);
} else {
NamespaceInfo ns = catalog.getNamespaceByPrefix(workspaceName);
fts = catalog.getFeatureTypesByNamespace(ns);
}
return wrapList(fts, FeatureTypeInfo.class);
}
}
@PostMapping(consumes = {
MediaTypeExtensions.TEXT_JSON_VALUE,
MediaType.APPLICATION_JSON_VALUE,
MediaType.TEXT_XML_VALUE,
MediaType.APPLICATION_XML_VALUE })
public ResponseEntity featureTypePost(
@PathVariable String workspaceName,
@PathVariable(required = false) String storeName,
@RequestBody FeatureTypeInfo ftInfo, UriComponentsBuilder builder) throws Exception {
DataStoreInfo dsInfo = getExistingDataStore(workspaceName, storeName);
// ensure the store matches up
if (ftInfo.getStore() != null && storeName != null) {
if (!storeName.equals(ftInfo.getStore().getName())) {
throw new RestException("Expected datastore " + storeName + " but client specified "
+ ftInfo.getStore().getName(), HttpStatus.FORBIDDEN);
}
dsInfo = ftInfo.getStore();
} else {
ftInfo.setStore(dsInfo);
}
// ensure workspace/namespace matches up
if (ftInfo.getNamespace() != null) {
if (!workspaceName.equals(ftInfo.getNamespace().getPrefix())) {
throw new RestException("Expected workspace " + workspaceName + " but client specified "
+ ftInfo.getNamespace().getPrefix(), HttpStatus.FORBIDDEN);
}
} else {
ftInfo.setNamespace(catalog.getNamespaceByPrefix(workspaceName));
}
ftInfo.setEnabled(true);
// now, does the feature type exist? If not, create it
DataAccess dataAccess = dsInfo.getDataStore(null);
if (dataAccess instanceof DataStore) {
String typeName = ftInfo.getName();
if (ftInfo.getNativeName() != null) {
typeName = ftInfo.getNativeName();
}
boolean typeExists = false;
DataStore dataStore = (DataStore) dataAccess;
for (String name : dataStore.getTypeNames()) {
if (name.equals(typeName)) {
typeExists = true;
break;
}
}
// check to see if this is a virtual JDBC feature type
MetadataMap mdm = ftInfo.getMetadata();
boolean virtual = mdm != null && mdm.containsKey(FeatureTypeInfo.JDBC_VIRTUAL_TABLE);
if (!virtual && !typeExists) {
dataStore.createSchema(buildFeatureType(ftInfo));
// the attributes created might not match up 1-1 with the actual spec due to
// limitations of the data store, have it re-compute them
ftInfo.getAttributes().clear();
List<String> typeNames = Arrays.asList(dataStore.getTypeNames());
// handle Oracle oddities
// TODO: use the incoming store capabilites API to better handle the name transformation
if (!typeNames.contains(typeName) && typeNames.contains(typeName.toUpperCase())) {
ftInfo.setNativeName(ftInfo.getName().toLowerCase());
}
}
}
CatalogBuilder cb = new CatalogBuilder(catalog);
cb.initFeatureType(ftInfo);
// attempt to fill in metadata from underlying feature source
try {
FeatureSource featureSource = dataAccess
.getFeatureSource(new NameImpl(ftInfo.getNativeName()));
if (featureSource != null) {
cb.setupMetadata(ftInfo, featureSource);
}
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Unable to fill in metadata from underlying feature source",
e);
}
if (ftInfo.getStore() == null) {
// get from requests
ftInfo.setStore(dsInfo);
}
NamespaceInfo ns = ftInfo.getNamespace();
if (ns != null && !ns.getPrefix().equals(workspaceName)) {
// TODO: change this once the two can be different and we untie namespace
// from workspace
LOGGER.warning("Namespace: " + ns.getPrefix() + " does not match workspace: "
+ workspaceName + ", overriding.");
ns = null;
}
if (ns == null) {
// infer from workspace
ns = catalog.getNamespaceByPrefix(workspaceName);
ftInfo.setNamespace(ns);
}
ftInfo.setEnabled(true);
catalog.validate(ftInfo, true).throwIfInvalid();
catalog.add(ftInfo);
// create a layer for the feature type
catalog.add(new CatalogBuilder(catalog).buildLayer(ftInfo));
LOGGER.info("POST feature type" + storeName + "," + ftInfo.getName());
UriComponents uriComponents;
if (storeName == null) {
uriComponents = builder.path("/workspaces/{workspaceName}/featuretypes/{featureTypeName}")
.buildAndExpand(workspaceName, ftInfo.getName());
} else {
uriComponents = builder.path("/workspaces/{workspaceName}/datastores/{storeName}/featuretypes/{featureTypeName}")
.buildAndExpand(workspaceName, storeName, ftInfo.getName());
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(uriComponents.toUri());
return new ResponseEntity<>("", headers, HttpStatus.CREATED);
}
@GetMapping(path = "/{featureTypeName}", produces = {
MediaType.TEXT_HTML_VALUE,
MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE })
public RestWrapper featureTypeGet(
@PathVariable String workspaceName,
@PathVariable(required = false) String storeName,
@PathVariable String featureTypeName,
@RequestParam(name = "quietOnNotFound", required = false, defaultValue = "false") Boolean quietOnNotFound) {
DataStoreInfo dsInfo = getExistingDataStore(workspaceName, storeName);
FeatureTypeInfo ftInfo = catalog.getFeatureTypeByDataStore(dsInfo, featureTypeName);
checkFeatureTypeExists(ftInfo, workspaceName, storeName, featureTypeName);
return wrapObject(ftInfo, FeatureTypeInfo.class);
}
@PutMapping(path = "/{featureTypeName}", produces = {
MediaType.TEXT_HTML_VALUE,
MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE })
public void featureTypePut(
@PathVariable String workspaceName,
@PathVariable(required = false) String storeName,
@PathVariable String featureTypeName,
@RequestBody FeatureTypeInfo featureTypeUpdate,
@RequestParam(name = "recalculate", required = false) String recalculate) {
DataStoreInfo dsInfo = getExistingDataStore(workspaceName, storeName);
FeatureTypeInfo ftInfo = catalog.getFeatureTypeByDataStore(dsInfo, featureTypeName);
checkFeatureTypeExists(ftInfo, workspaceName, storeName, featureTypeName);
Map<String, Serializable> parametersCheck = ftInfo.getStore()
.getConnectionParameters();
calculateOptionalFields(featureTypeUpdate, ftInfo, recalculate);
CatalogBuilder helper = new CatalogBuilder(catalog);
helper.updateFeatureType(ftInfo, featureTypeUpdate);
catalog.validate(ftInfo, false).throwIfInvalid();
catalog.save(ftInfo);
catalog.getResourcePool().clear(ftInfo);
Map<String, Serializable> parameters = ftInfo.getStore().getConnectionParameters();
MetadataMap mdm = ftInfo.getMetadata();
boolean virtual = mdm != null && mdm.containsKey(FeatureTypeInfo.JDBC_VIRTUAL_TABLE);
if (!virtual && parameters.equals(parametersCheck)) {
LOGGER.info("PUT FeatureType" + storeName + "," + featureTypeName
+ " updated metadata only");
} else {
LOGGER.info("PUT featureType" + storeName + "," + featureTypeName
+ " updated metadata and data access");
catalog.getResourcePool().clear(ftInfo.getStore());
}
}
@DeleteMapping(path = "{featureTypeName}", produces = {
MediaType.TEXT_HTML_VALUE,
MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE })
public void featureTypeDelete(
@PathVariable String workspaceName,
@PathVariable(required = false) String storeName,
@PathVariable String featureTypeName,
@RequestParam(name = "recurse", defaultValue = "false") Boolean recurse) {
DataStoreInfo dsInfo = getExistingDataStore(workspaceName, storeName);
FeatureTypeInfo ftInfo = catalog.getFeatureTypeByDataStore(dsInfo, featureTypeName);
checkFeatureTypeExists(ftInfo, workspaceName, storeName, featureTypeName);
List<LayerInfo> layers = catalog.getLayers(ftInfo);
if (recurse) {
// by recurse we clear out all the layers that public this resource
for (LayerInfo l : layers) {
catalog.remove(l);
LOGGER.info("DELETE layer " + l.getName());
}
} else {
if (!layers.isEmpty()) {
throw new RestException("feature type referenced by layer(s)",
HttpStatus.FORBIDDEN);
}
}
catalog.remove(ftInfo);
LOGGER.info("DELETE feature type" + storeName + "," + featureTypeName);
}
/**
* If the feature type doesn't exists throws a REST exception with HTTP 404 code.
*/
private void checkFeatureTypeExists(FeatureTypeInfo featureType, String workspaceName, String storeName, String featureTypeName) {
if (featureType == null && storeName == null) {
throw new ResourceNotFoundException(String.format(
"No such feature type: %s,%s", workspaceName, featureTypeName));
} else if (featureType == null) {
throw new ResourceNotFoundException(String.format(
"No such feature type: %s,%s,%s", workspaceName, storeName, featureTypeName));
}
}
/**
* Helper method that find a store based on the workspace name and store name.
*/
private DataStoreInfo getExistingDataStore(String workspaceName, String storeName) {
DataStoreInfo original = catalog.getDataStoreByName(workspaceName, storeName);
if (original == null) {
throw new ResourceNotFoundException(
"No such data store: " + workspaceName + "," + storeName);
}
return original;
}
SimpleFeatureType buildFeatureType(FeatureTypeInfo fti) {
// basic checks
if (fti.getName() == null) {
throw new RestException("Trying to create new feature type inside the store, "
+ "but no feature type name was specified", HttpStatus.BAD_REQUEST);
} else if (fti.getAttributes() == null || fti.getAttributes() == null) {
throw new RestException("Trying to create new feature type inside the store, "
+ "but no attributes were specified", HttpStatus.BAD_REQUEST);
}
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
if (fti.getNativeName() != null) {
builder.setName(fti.getNativeName());
} else {
builder.setName(fti.getName());
}
if (fti.getNativeCRS() != null) {
builder.setCRS(fti.getNativeCRS());
} else if (fti.getCRS() != null) {
builder.setCRS(fti.getCRS());
} else if (fti.getSRS() != null) {
builder.setSRS(fti.getSRS());
}
for (AttributeTypeInfo ati : fti.getAttributes()) {
if (ati.getLength() != null && ati.getLength() > 0) {
builder.length(ati.getLength());
}
builder.nillable(ati.isNillable());
builder.add(ati.getName(), ati.getBinding());
}
return builder.buildFeatureType();
}
@Override
public boolean supports(MethodParameter methodParameter, Type targetType,
Class<? extends HttpMessageConverter<?>> converterType) {
return FeatureTypeInfo.class.isAssignableFrom(methodParameter.getParameterType());
}
@Override
public void configurePersister(XStreamPersister persister, XStreamMessageConverter converter) {
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
String method = attrs.getRequest().getMethod();
if ("GET".equalsIgnoreCase(method)) {
persister.setHideFeatureTypeAttributes();
}
persister.setCallback(new XStreamPersister.Callback() {
@Override
protected Class<FeatureTypeInfo> getObjectClass() {
return FeatureTypeInfo.class;
}
@Override
protected CatalogInfo getCatalogObject() {
Map<String, String> uriTemplateVars = (Map<String, String>) RequestContextHolder
.getRequestAttributes()
.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE,
RequestAttributes.SCOPE_REQUEST);
String workspace = uriTemplateVars.get("workspaceName");
String featuretype = uriTemplateVars.get("featureTypeName");
String datastore = uriTemplateVars.get("storeName");
if (workspace == null || datastore == null || featuretype == null) {
return null;
}
DataStoreInfo ds = catalog.getDataStoreByName(workspace, datastore);
if (ds == null) {
return null;
}
return catalog.getFeatureTypeByDataStore(ds, featuretype);
}
@Override
protected void postEncodeReference(Object obj, String ref, String prefix,
HierarchicalStreamWriter writer, MarshallingContext context) {
if (obj instanceof NamespaceInfo) {
NamespaceInfo ns = (NamespaceInfo) obj;
converter.encodeLink("/namespaces/" + converter.encode(ns.getPrefix()), writer);
}
if (obj instanceof DataStoreInfo) {
DataStoreInfo ds = (DataStoreInfo) obj;
converter
.encodeLink(
"/workspaces/" + converter.encode(ds.getWorkspace().getName())
+ "/datastores/" + converter.encode(ds.getName()),
writer);
}
}
@Override
protected void postEncodeFeatureType(FeatureTypeInfo ft,
HierarchicalStreamWriter writer, MarshallingContext context) {
try {
writer.startNode("attributes");
context.convertAnother(ft.attributes());
writer.endNode();
} catch (IOException e) {
throw new RuntimeException("Could not get native attributes", e);
}
}
});
}
@Override
protected <T> ObjectWrapper createObjectWrapper(Class<T> clazz) {
return new ObjectToMapWrapper<FeatureTypeInfo>(FeatureTypeInfo.class) {
@Override
protected void wrapInternal(Map properties, SimpleHash model, FeatureTypeInfo object) {
try {
properties.put("boundingBox", object.boundingBox());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
}
}