1
2
3
4
5
6 package org.tailormap.api.controller;
7
8 import static org.tailormap.api.persistence.helper.TMAttributeTypeHelper.isGeometry;
9 import static org.tailormap.api.persistence.helper.TMFeatureTypeHelper.getConfiguredAttributes;
10
11 import io.micrometer.core.annotation.Counted;
12 import io.micrometer.core.annotation.Timed;
13 import jakarta.validation.Valid;
14 import java.io.IOException;
15 import java.lang.invoke.MethodHandles;
16 import java.net.MalformedURLException;
17 import java.nio.file.Files;
18 import java.nio.file.Path;
19 import java.util.HashSet;
20 import java.util.LinkedHashSet;
21 import java.util.List;
22 import java.util.Locale;
23 import java.util.Map;
24 import java.util.Set;
25 import java.util.regex.Pattern;
26 import org.apache.commons.lang3.StringUtils;
27 import org.geotools.api.data.Query;
28 import org.geotools.api.data.SimpleFeatureSource;
29 import org.geotools.api.filter.Filter;
30 import org.geotools.api.filter.sort.SortOrder;
31 import org.geotools.api.referencing.FactoryException;
32 import org.geotools.filter.text.cql2.CQLException;
33 import org.jspecify.annotations.Nullable;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.springframework.beans.factory.annotation.Value;
37 import org.springframework.core.io.Resource;
38 import org.springframework.core.io.UrlResource;
39 import org.springframework.http.HttpHeaders;
40 import org.springframework.http.HttpStatus;
41 import org.springframework.http.MediaType;
42 import org.springframework.http.ResponseEntity;
43 import org.springframework.transaction.annotation.Transactional;
44 import org.springframework.web.bind.annotation.GetMapping;
45 import org.springframework.web.bind.annotation.ModelAttribute;
46 import org.springframework.web.bind.annotation.PathVariable;
47 import org.springframework.web.bind.annotation.PostMapping;
48 import org.springframework.web.bind.annotation.RequestMapping;
49 import org.springframework.web.bind.annotation.RequestParam;
50 import org.springframework.web.server.ResponseStatusException;
51 import org.tailormap.api.annotation.AppRestController;
52 import org.tailormap.api.geotools.FilterUtil;
53 import org.tailormap.api.geotools.data.excel.ExcelDataStore;
54 import org.tailormap.api.geotools.featuresources.FeatureSourceFactoryHelper;
55 import org.tailormap.api.geotools.wfs.WFSHitsCountUtil;
56 import org.tailormap.api.persistence.Application;
57 import org.tailormap.api.persistence.GeoService;
58 import org.tailormap.api.persistence.TMFeatureType;
59 import org.tailormap.api.persistence.helper.TMFeatureTypeHelper;
60 import org.tailormap.api.persistence.json.AppLayerSettings;
61 import org.tailormap.api.persistence.json.AppTreeLayerNode;
62 import org.tailormap.api.persistence.json.GeoServiceLayer;
63 import org.tailormap.api.repository.FeatureSourceRepository;
64 import org.tailormap.api.service.CreateLayerExtractService;
65
66 @AppRestController
67 @RequestMapping(path = "${tailormap-api.base-path}/{viewerKind}/{viewerName}/layer/{appLayerId}/extract")
68 public class LayerExtractController {
69 private static final Logger logger =
70 LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
71 private static final Pattern SAFE_DOWNLOAD_ID = Pattern.compile("^[A-Za-z0-9._-]+$");
72 private final FeatureSourceRepository featureSourceRepository;
73 private final CreateLayerExtractService createLayerExtractService;
74 private final FeatureSourceFactoryHelper featureSourceFactoryHelper;
75
76 @Value("#{'${tailormap-api.extract.allowed-outputformats}'.split(',')}")
77 private List<ExtractOutputFormat> allowedExtractOutputFormats;
78
79 public LayerExtractController(
80 FeatureSourceRepository featureSourceRepository,
81 CreateLayerExtractService createLayerExtractService,
82 FeatureSourceFactoryHelper featureSourceFactoryHelper) {
83 this.featureSourceRepository = featureSourceRepository;
84 this.createLayerExtractService = createLayerExtractService;
85 this.featureSourceFactoryHelper = featureSourceFactoryHelper;
86 }
87
88
89
90
91
92 @GetMapping(path = "/download/{downloadId}")
93 @Counted(value = "tailormap_api_extract_download", description = "Count of layer extract downloads")
94 public ResponseEntity<?> download(
95 @ModelAttribute GeoService service,
96 @ModelAttribute GeoServiceLayer layer,
97 @ModelAttribute Application application,
98 @ModelAttribute AppTreeLayerNode appTreeLayerNode,
99 @PathVariable String downloadId)
100 throws MalformedURLException {
101
102 if (downloadId == null || !SAFE_DOWNLOAD_ID.matcher(downloadId).matches()) {
103 throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid downloadId");
104 }
105 Path exportRoot = Path.of(createLayerExtractService.getExportFilesLocation())
106 .toAbsolutePath()
107 .normalize();
108 Path filePath = exportRoot.resolve(downloadId).normalize();
109 if (!filePath.startsWith(exportRoot)) {
110 throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid downloadId");
111 }
112
113 Resource resource = new UrlResource(filePath.toUri());
114 if (!resource.exists() || !resource.isReadable() || !resource.isFile()) {
115 throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Download file not found");
116 }
117
118 String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
119 try {
120 String detectedContentType = Files.probeContentType(filePath);
121 if (detectedContentType != null) {
122 contentType = detectedContentType;
123 }
124 } catch (IOException e) {
125 logger.debug("Could not determine content type for {}", filePath, e);
126 }
127
128 return ResponseEntity.ok()
129 .contentType(MediaType.parseMediaType(contentType))
130 .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filePath.getFileName() + "\"")
131 .body(resource);
132 }
133
134 @GetMapping("/formats")
135 public ResponseEntity<?> formats(
136 @Valid @ModelAttribute GeoServiceLayer layer,
137 @ModelAttribute GeoService service,
138 @ModelAttribute Application application,
139 @ModelAttribute AppTreeLayerNode appTreeLayerNode) {
140 return ResponseEntity.ok(allowedExtractOutputFormats.stream()
141 .map(ExtractOutputFormat::getValue)
142 .toList());
143 }
144
145 @Transactional
146 @PostMapping("/{clientId}")
147 @Timed(value = "tailormap_api_extract", description = "Time taken to process a layer extract request")
148 public ResponseEntity<?> extract(
149 @Valid @ModelAttribute GeoServiceLayer layer,
150 @ModelAttribute GeoService service,
151 @ModelAttribute Application application,
152 @ModelAttribute AppTreeLayerNode appTreeLayerNode,
153 @PathVariable String clientId,
154 @RequestParam ExtractOutputFormat outputFormat,
155 @RequestParam(required = false) Set<String> attributes,
156 @RequestParam(required = false) String filter,
157 @RequestParam(required = false) String sortBy,
158 @RequestParam(required = false, defaultValue = "asc") String sortOrder) {
159
160 try {
161 createLayerExtractService.validateClientId(clientId);
162 } catch (IllegalArgumentException e) {
163 logger.warn("Invalid clientId for extract request: {}", clientId);
164 throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
165 }
166
167 if (!allowedExtractOutputFormats.contains(outputFormat)) {
168 logger.debug("Invalid output format requested: {}", outputFormat);
169 throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid output format");
170 }
171
172 if (layer == null) {
173 throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Can't find layer " + appTreeLayerNode);
174 }
175
176 TMFeatureType sourceFT = service.findFeatureTypeForLayer(layer, featureSourceRepository);
177 if (sourceFT == null) {
178 logger.debug("Layer export requested for layer without feature type");
179 throw new ResponseStatusException(HttpStatus.NOT_FOUND);
180 }
181 if (attributes == null) {
182 attributes = new HashSet<>();
183 }
184
185 AppLayerSettings appLayerSettings = application.getAppLayerSettings(appTreeLayerNode);
186
187 Set<String> nonHiddenAttributes =
188 getConfiguredAttributes(sourceFT, appLayerSettings).keySet();
189
190 if (!attributes.isEmpty()) {
191
192 if (!nonHiddenAttributes.containsAll(attributes)) {
193 throw new ResponseStatusException(
194 HttpStatus.BAD_REQUEST,
195 "One or more requested attributes are not available on the feature type");
196 }
197 } else {
198
199
200 if (nonHiddenAttributes.isEmpty()) {
201 throw new ResponseStatusException(
202 HttpStatus.BAD_REQUEST, "No attributes are available to export for this feature type");
203 }
204 attributes = new LinkedHashSet<>(nonHiddenAttributes);
205 }
206
207
208 if (StringUtils.isNotBlank(sortBy)
209 && getConfiguredAttributes(sourceFT, appLayerSettings).values().stream()
210 .map(TMFeatureTypeHelper.AttributeWithSettings::attributeDescriptor)
211 .filter(a -> !isGeometry(a.getType()))
212 .noneMatch(a -> a.getName().equals(sortBy))) {
213 throw new ResponseStatusException(
214 HttpStatus.BAD_REQUEST, "Requested sortBy attribute is not available on the feature type");
215 }
216
217
218
219
220 if (!attributes.isEmpty() && sourceFT.getDefaultGeometryAttribute() != null) {
221 attributes.add(sourceFT.getDefaultGeometryAttribute());
222 }
223
224
225 Filter parsedECQL = null;
226 SimpleFeatureSource simpleFeatureSource = null;
227 try {
228 if (!StringUtils.isBlank(filter)) {
229 simpleFeatureSource = featureSourceFactoryHelper.openGeoToolsFeatureSource(sourceFT);
230 parsedECQL =
231 FilterUtil.parseFilter(filter, application, simpleFeatureSource, sourceFT, appLayerSettings);
232 }
233 } catch (CQLException | FactoryException | UnsupportedOperationException e) {
234 throw new ResponseStatusException(
235 HttpStatus.BAD_REQUEST, "Could not parse requested filter: " + e.getMessage(), e);
236 } catch (IOException e) {
237 logger.error("Failed to connect to datasource of feature type {}", sourceFT.getName(), e);
238 throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Failed to connect to datasource", e);
239 } finally {
240 if (simpleFeatureSource != null) {
241 try {
242 simpleFeatureSource.getDataStore().dispose();
243 } catch (Exception e) {
244 logger.warn("Failed to dispose feature source", e);
245 }
246 }
247 }
248 if (ExtractOutputFormat.XLSX.equals(outputFormat)) {
249 validateExcelLimits(sourceFT, attributes, parsedECQL);
250 }
251
252 SortOrder sortingOrder = SortOrder.ASCENDING;
253 if (null != sortOrder && (sortOrder.equalsIgnoreCase("desc") || sortOrder.equalsIgnoreCase("asc"))) {
254 sortingOrder = SortOrder.valueOf(sortOrder.toUpperCase(Locale.ROOT));
255 }
256
257 final String outputFileName =
258 this.createLayerExtractService.createExtractFilename(clientId, sourceFT, outputFormat);
259 this.createLayerExtractService.emitProgress(clientId, outputFileName, 0, false, "Extract task received");
260
261
262 this.createLayerExtractService.createLayerExtract(
263 clientId, sourceFT, attributes, parsedECQL, sortBy, sortingOrder, outputFormat, outputFileName);
264
265
266 return ResponseEntity.accepted()
267 .body(Map.of("message", "Extract request accepted", "downloadId", outputFileName));
268 }
269
270
271
272
273
274
275
276
277
278
279 private void validateExcelLimits(TMFeatureType featureType, Set<String> attributes, @Nullable Filter filter) {
280 if (attributes.size() > ExcelDataStore.getMaxColumns()) {
281 throw new ResponseStatusException(
282 HttpStatus.BAD_REQUEST,
283 "Excel format does not support more than " + ExcelDataStore.getMaxColumns() + " columns");
284 }
285 SimpleFeatureSource inputFeatureSource = null;
286 try {
287
288
289 inputFeatureSource = featureSourceFactoryHelper.openGeoToolsFeatureSource(featureType);
290 Query q = new Query(inputFeatureSource.getName().toString());
291 if (!attributes.isEmpty()) {
292 q.setPropertyNames(attributes.toArray(new String[0]));
293 }
294
295 if (filter != null) {
296 q.setFilter(filter);
297 }
298 final int featCount = WFSHitsCountUtil.getCount(inputFeatureSource, q);
299 if (featCount >= ExcelDataStore.getMaxRows()) {
300 throw new ResponseStatusException(
301 HttpStatus.BAD_REQUEST,
302 "Excel format does not support more than " + ExcelDataStore.getMaxRows() + " rows");
303 }
304 } catch (IOException e) {
305 throw new ResponseStatusException(
306 HttpStatus.INTERNAL_SERVER_ERROR,
307 "Failed to count all features for Excel extract: " + e.getMessage());
308 } catch (IllegalArgumentException e) {
309 throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid filter");
310 } finally {
311 if (inputFeatureSource != null) {
312 inputFeatureSource.getDataStore().dispose();
313 }
314 }
315 }
316
317 public enum ExtractOutputFormat {
318 GEOPACKAGE("geopackage", ".gpkg"),
319 CSV("csv", ".csv"),
320 GEOJSON("geojson", ".geojson"),
321 XLSX("xlsx", ".xlsx"),
322 SHAPE("shape", ".zip");
323
324 private final String value;
325 private final String extension;
326
327 ExtractOutputFormat(String value, String extension) {
328 this.value = value;
329 this.extension = extension;
330 }
331
332 public static ExtractOutputFormat fromValue(String value) {
333 for (ExtractOutputFormat format : ExtractOutputFormat.values()) {
334 if (format.value.equalsIgnoreCase(value)) {
335 return format;
336 }
337 }
338 throw new IllegalArgumentException("Invalid output format: " + value);
339 }
340
341 public String getValue() {
342 return this.value;
343 }
344
345 public String getExtension() {
346 return this.extension;
347 }
348
349 @Override
350 public String toString() {
351 return String.valueOf(this.value);
352 }
353 }
354 }