View Javadoc
1   /*
2    * Copyright (C) 2026 B3Partners B.V.
3    *
4    * SPDX-License-Identifier: MIT
5    */
6   package org.tailormap.api.service;
7   
8   import ch.rasc.sse.eventbus.SseEvent;
9   import ch.rasc.sse.eventbus.SseEventBus;
10  import jakarta.annotation.PostConstruct;
11  import java.io.File;
12  import java.io.IOException;
13  import java.io.UncheckedIOException;
14  import java.lang.invoke.MethodHandles;
15  import java.nio.charset.StandardCharsets;
16  import java.nio.file.Files;
17  import java.nio.file.Path;
18  import java.time.Instant;
19  import java.util.ArrayList;
20  import java.util.Comparator;
21  import java.util.List;
22  import java.util.Map;
23  import java.util.Objects;
24  import java.util.Set;
25  import java.util.concurrent.TimeUnit;
26  import java.util.concurrent.atomic.AtomicInteger;
27  import java.util.stream.Stream;
28  import org.apache.commons.lang3.StringUtils;
29  import org.geotools.api.data.FeatureEvent;
30  import org.geotools.api.data.FileDataStore;
31  import org.geotools.api.data.Query;
32  import org.geotools.api.data.SimpleFeatureSource;
33  import org.geotools.api.data.SimpleFeatureStore;
34  import org.geotools.api.data.Transaction;
35  import org.geotools.api.feature.simple.SimpleFeatureType;
36  import org.geotools.api.filter.Filter;
37  import org.geotools.api.filter.FilterFactory;
38  import org.geotools.api.filter.sort.SortOrder;
39  import org.geotools.data.DataUtilities;
40  import org.geotools.data.DefaultTransaction;
41  import org.geotools.data.csv.CSVDataStoreFactory;
42  import org.geotools.data.geojson.store.GeoJSONDataStoreFactory;
43  import org.geotools.data.shapefile.ShapefileDumper;
44  import org.geotools.factory.CommonFactoryFinder;
45  import org.geotools.geopkg.FeatureEntry;
46  import org.geotools.geopkg.GeoPackage;
47  import org.geotools.util.factory.GeoTools;
48  import org.jspecify.annotations.NonNull;
49  import org.jspecify.annotations.Nullable;
50  import org.slf4j.Logger;
51  import org.slf4j.LoggerFactory;
52  import org.springframework.beans.factory.annotation.Qualifier;
53  import org.springframework.beans.factory.annotation.Value;
54  import org.springframework.scheduling.annotation.Async;
55  import org.springframework.scheduling.annotation.Scheduled;
56  import org.springframework.stereotype.Service;
57  import org.springframework.transaction.annotation.Transactional;
58  import org.tailormap.api.controller.LayerExtractController;
59  import org.tailormap.api.geotools.collection.ProgressReportingFeatureCollection;
60  import org.tailormap.api.geotools.data.excel.ExcelDataStore;
61  import org.tailormap.api.geotools.data.excel.ExcelDataStoreFactory;
62  import org.tailormap.api.geotools.featuresources.FeatureSourceFactoryHelper;
63  import org.tailormap.api.geotools.wfs.WFSHitsCountUtil;
64  import org.tailormap.api.persistence.TMFeatureType;
65  import org.tailormap.api.util.UUIDv7;
66  import org.tailormap.api.viewer.model.ServerSentEventResponse;
67  import tools.jackson.databind.SerializationFeature;
68  import tools.jackson.databind.json.JsonMapper;
69  
70  @Service
71  public class CreateLayerExtractService {
72    private static final Logger logger =
73        LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
74    private final SseEventBus eventBus;
75    private final JsonMapper jsonMapper;
76    private final FeatureSourceFactoryHelper featureSourceFactoryHelper;
77    private final ZipService zipService;
78    private final FilterFactory ff = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
79  
80    private static final String EXTRACT_SUBDIRECTORY = "tm-extracts";
81    // we can safely use the tmp dir as a default here because we are running in a docker container without a shell so
82    // access is limited
83    // Base directory from config; actual export dir is <base>/tm-extracts
84    @Value("${tailormap-api.extract.location:#{systemProperties['java.io.tmpdir']}}")
85    private String exportFilesBaseLocation;
86  
87    private String exportFilesLocation;
88  
89    @Value("${tailormap-api.extract.cleanup-minutes:120}")
90    private int cleanupIntervalMinutes;
91  
92    @Value("#{T(java.lang.Math).max(1, ${tailormap-api.extract.progress-report-interval:100})}")
93    private int progressReportInterval;
94  
95    @PostConstruct
96    void initializeExtractDirectory() {
97      try {
98        Path exportRoot = Path.of(exportFilesBaseLocation, EXTRACT_SUBDIRECTORY);
99        Files.createDirectories(exportRoot);
100       this.exportFilesLocation = exportRoot.toRealPath().toString();
101       logger.info("Using extract output directory: {}", this.exportFilesLocation);
102     } catch (IOException e) {
103       throw new UncheckedIOException(
104           "Failed to initialize extract directory under base path: " + exportFilesBaseLocation, e);
105     }
106   }
107 
108   public CreateLayerExtractService(
109       @Qualifier("viewerSseEventBus") SseEventBus eventBus,
110       JsonMapper jsonMapper,
111       FeatureSourceFactoryHelper featureSourceFactoryHelper,
112       ZipService zipService) {
113     this.eventBus = eventBus;
114     this.featureSourceFactoryHelper = featureSourceFactoryHelper;
115     this.zipService = zipService;
116     // force unindented/single line output for SSE messages, because we may have set
117     // spring.jackson.serialization.indent_output=true for debugging/development/test
118     if (jsonMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
119       this.jsonMapper = jsonMapper
120           .rebuild()
121           .configure(SerializationFeature.INDENT_OUTPUT, false)
122           .build();
123     } else {
124       this.jsonMapper = jsonMapper;
125     }
126   }
127 
128   public String getExportFilesLocation() {
129     return exportFilesLocation;
130   }
131 
132   /**
133    * Log an exception that occurred while creating an extract and report it to the client. Any exception must be
134    * reported, because the extract is created asynchronously and the client would otherwise wait indefinitely.
135    */
136   private void emitExtractError(@NonNull String clientId, @NonNull TMFeatureType featureType, Exception e) {
137     logger.error("Creating extract of feature type {} failed", featureType.getName(), e);
138     emitError(
139         clientId, e.getMessage() != null ? e.getMessage() : e.getClass().getName());
140   }
141 
142   private void emitError(@NonNull String clientId, String details) {
143     eventBus.handleEvent(SseEvent.builder()
144         .addClientId(clientId)
145         .data(jsonMapper.writeValueAsString(new ServerSentEventResponse()
146             .eventType(ServerSentEventResponse.EventTypeEnum.EXTRACT_FAILED)
147             .id(UUIDv7.randomV7())
148             .details(Map.of(
149                 "message", "An error occurred during extract creation", "explanation", details))))
150         .build());
151   }
152 
153   public void emitProgress(
154       @NonNull String clientId,
155       @Nullable String fileId,
156       int progress,
157       boolean completed,
158       @Nullable String message) {
159     message = StringUtils.isBlank(message) ? "Extract task started" : message;
160     fileId = StringUtils.isBlank(fileId) ? "" : fileId;
161     logger.debug("Emitting progress {}% for client [{}], message: '{}'", progress, clientId, message);
162 
163     eventBus.handleEvent(SseEvent.builder()
164         .addClientId(clientId)
165         .data(jsonMapper.writeValueAsString(new ServerSentEventResponse()
166             .eventType(
167                 completed
168                     ? ServerSentEventResponse.EventTypeEnum.EXTRACT_COMPLETED
169                     : ServerSentEventResponse.EventTypeEnum.EXTRACT_PROGRESS)
170             .id(UUIDv7.randomV7())
171             .details(Map.of(
172                 "progress",
173                 progress,
174                 "message",
175                 completed ? "Extract task completed" : message,
176                 "downloadId",
177                 fileId))))
178         .build());
179   }
180 
181   /**
182    * Check that the sse client id is valid and exists.
183    *
184    * @param clientId the SSE client id
185    * @throws IllegalArgumentException when the SSE client id is invalid or not found on the event bus
186    */
187   public void validateClientId(@NonNull String clientId) throws IllegalArgumentException {
188     if (!clientId.matches("[A-Za-z0-9_-]+")) {
189       logger.warn("Invalid clientId for SSE connection: {}", clientId);
190       throw new IllegalArgumentException("Invalid clientId");
191     }
192 
193     // validate the given clientId is known on the event bus
194     this.eventBus.getAllClientIds().stream()
195         .filter(id -> Objects.equals(id, clientId))
196         .findFirst()
197         .ifPresentOrElse(id -> logger.debug("Validated clientId {}", id), () -> {
198           throw new IllegalArgumentException("No active subscription found for clientId " + clientId);
199         });
200   }
201 
202   /**
203    * Create a validated filename for an extract. The naming follows the pattern
204    * {@code "%s_%s_%s%s".formatted(sourceFT.getName(), clientId, UUIDv7.randomV7(), outputFormat.getExtension()) }
205    * where the first part is the source feature type name (this is cleaned from some characters), the second part is
206    * the SSE client id, the third part is a random UUIDv7 and the fourth part is the file extension based on the
207    * requested output format.
208    *
209    * @param clientId the SSE client id
210    * @param sourceFT the source featuretype for the extract
211    * @param outputFormat the required format of the extract
212    * @return the filename used to create an extract
213    * @throws IllegalArgumentException when the SSE clientId is invalid or not found on the event bus
214    */
215   public String createExtractFilename(
216       @NonNull String clientId,
217       @NonNull TMFeatureType sourceFT,
218       LayerExtractController.@NonNull ExtractOutputFormat outputFormat)
219       throws IllegalArgumentException {
220 
221     this.validateClientId(clientId);
222 
223     String cleanFTName = sourceFT.getName();
224     if (cleanFTName.contains(":")) {
225       // clip off the WFS namespace part
226       cleanFTName = cleanFTName.substring(cleanFTName.lastIndexOf(":") + 1);
227       // remove: '.' and '_' which are used as separators in the filename and could cause issues when parsing the
228       // filename later on
229       cleanFTName = cleanFTName.replaceAll("[._]", "");
230     }
231     return "%s_%s_%s%s".formatted(cleanFTName, clientId, UUIDv7.randomV7(), outputFormat.getExtension());
232   }
233 
234   @Async("extractTaskExecutor")
235   @Transactional
236   public void createLayerExtract(
237       @NonNull String clientId,
238       @NonNull TMFeatureType inputTmFeatureType,
239       @NonNull Set<String> attributes,
240       @Nullable Filter filter,
241       String sortBy,
242       SortOrder sortOrder,
243       LayerExtractController.@NonNull ExtractOutputFormat extractOutputFormat,
244       @NonNull String outputFileName) {
245 
246     this.emitProgress(clientId, outputFileName, 0, false, "Starting extract");
247 
248     switch (extractOutputFormat) {
249       case GEOPACKAGE ->
250         this.handleGeoPackage(
251             clientId, inputTmFeatureType, attributes, filter, sortBy, sortOrder, outputFileName);
252       case SHAPE ->
253         this.handleWithShapeDumper(
254             clientId, inputTmFeatureType, attributes, filter, sortBy, sortOrder, outputFileName);
255       case CSV, GEOJSON, XLSX ->
256         this.handleSingleFileFormats(
257             clientId,
258             inputTmFeatureType,
259             attributes,
260             filter,
261             sortBy,
262             sortOrder,
263             extractOutputFormat,
264             outputFileName);
265     }
266   }
267 
268   private void handleGeoPackage(
269       @NonNull String clientId,
270       @NonNull TMFeatureType inputTmFeatureType,
271       @NonNull Set<String> attributes,
272       Filter filter,
273       String sortBy,
274       SortOrder sortOrder,
275       @NonNull String outputFileName) {
276 
277     SimpleFeatureSource inputFeatureSource = null;
278     File outputFile;
279     try {
280       outputFile = getValidatedOutputFile(outputFileName);
281       if (!logger.isDebugEnabled()) {
282         // delete in production after JVM exit because the event bus will be reset when the JVM exits, and then
283         // we are unlikely to have a reference to the file anymore.
284         // In debug/development mode we want to keep the file for inspection.
285         outputFile.deleteOnExit();
286       }
287     } catch (IOException e) {
288       emitError(clientId, e.getMessage());
289       logger.error("Creating extract failed", e);
290       return;
291     }
292 
293     try (GeoPackage geopkg = new GeoPackage(outputFile)) {
294       geopkg.init();
295 
296       inputFeatureSource = featureSourceFactoryHelper.openGeoToolsFeatureSource(inputTmFeatureType);
297 
298       Query q = createQuery(inputFeatureSource, attributes, filter, sortBy, sortOrder);
299 
300       int featCount = getFeatureCount(inputFeatureSource, q);
301       if (featCount < 0) {
302         logger.warn("Could not determine feature count for extract, progress reporting will be inaccurate");
303       }
304       final boolean hasKnownFeatureCount = featCount > 0;
305 
306       SimpleFeatureType fType =
307           DataUtilities.createSubType(inputFeatureSource.getSchema(), attributes.toArray(new String[0]));
308 
309       FeatureEntry entry = new FeatureEntry();
310       entry.setTableName(fType.getTypeName());
311       entry.setDescription(fType.getTypeName());
312 
313       AtomicInteger lastProgress = new AtomicInteger(0);
314       geopkg.add(
315           entry,
316           new ProgressReportingFeatureCollection(
317               inputFeatureSource.getFeatures(q), progressReportInterval, processed -> {
318                 int progress = hasKnownFeatureCount ? (int) ((processed / (double) featCount) * 99) : 0;
319                 lastProgress.set(progress);
320                 String progressMessage = hasKnownFeatureCount
321                     ? "Extracting geopackage: %d/%d features processed"
322                         .formatted(processed, featCount)
323                     : "Extracting geopackage: %d features processed".formatted(processed);
324                 this.emitProgress(clientId, outputFileName, progress, false, progressMessage);
325               }));
326 
327       this.emitProgress(
328           clientId,
329           outputFileName,
330           Math.max(99, lastProgress.get()),
331           false,
332           "Extract geopackage created successfully");
333       geopkg.createSpatialIndex(entry);
334       geopkg.close();
335       this.emitProgress(clientId, outputFileName, 100, true, "Extract completed successfully");
336     } catch (Exception e) {
337       emitExtractError(clientId, inputTmFeatureType, e);
338     } finally {
339       if (inputFeatureSource != null) {
340         try {
341           inputFeatureSource.getDataStore().dispose();
342         } catch (Exception e) {
343           logger.warn("Error disposing datastore for feature source {}", inputFeatureSource.getName(), e);
344         }
345       }
346     }
347   }
348 
349   private void handleSingleFileFormats(
350       @NonNull String clientId,
351       @NonNull TMFeatureType inputTmFeatureType,
352       @NonNull Set<String> attributes,
353       Filter filter,
354       String sortBy,
355       SortOrder sortOrder,
356       LayerExtractController.@NonNull ExtractOutputFormat extractOutputFormat,
357       @NonNull String outputFileName) {
358 
359     SimpleFeatureSource inputFeatureSource = null;
360     FileDataStore outputDataStore = null;
361     try (Transaction outputTransaction = new DefaultTransaction("tailormap-extract-output")) {
362       inputFeatureSource = featureSourceFactoryHelper.openGeoToolsFeatureSource(inputTmFeatureType);
363 
364       Query q = createQuery(inputFeatureSource, attributes, filter, sortBy, sortOrder);
365 
366       int featCount = getFeatureCount(inputFeatureSource, q);
367 
368       if (extractOutputFormat == LayerExtractController.ExtractOutputFormat.XLSX
369           && featCount >= ExcelDataStore.getMaxRows()) {
370         this.emitError(
371             clientId,
372             "Extract result contains %d features, which exceeds the maximum of %d for Excel output format. Please refine your filter or choose a different output format."
373                 .formatted(featCount, ExcelDataStore.getMaxRows()));
374         logger.error(
375             "Extract result contains {} features, which exceeds the maximum of {} for Excel output format. Please refine your filter or choose a different output format.",
376             featCount,
377             ExcelDataStore.getMaxRows());
378         // nothing we can do now as we are in a background/async process, so we just return without creating an
379         // extract file.
380         // The client will receive no extract completed event, and we have already emitted an error message with
381         // details.
382         return;
383       }
384 
385       outputDataStore = this.getExtractDataStore(extractOutputFormat, outputFileName, clientId);
386       SimpleFeatureType fType =
387           DataUtilities.createSubType(inputFeatureSource.getSchema(), attributes.toArray(new String[0]));
388       outputDataStore.createSchema(fType);
389 
390       final AtomicInteger featsAdded = new AtomicInteger();
391       if (outputDataStore.getFeatureSource() instanceof SimpleFeatureStore featureStore) {
392         featureStore.setTransaction(outputTransaction);
393         featureStore.addFeatureListener(event -> {
394           if (event.getType().equals(FeatureEvent.Type.ADDED)) {
395             featsAdded.getAndIncrement();
396           }
397           if (featCount > 0) {
398             if (featsAdded.get() % progressReportInterval == 0) {
399               this.emitProgress(
400                   clientId,
401                   outputFileName,
402                   (int) ((featsAdded.doubleValue() / featCount) * 100),
403                   false,
404                   null);
405             }
406           }
407         });
408         featureStore.addFeatures(inputFeatureSource.getFeatures(q));
409         outputTransaction.commit();
410         outputDataStore.dispose();
411         this.emitProgress(clientId, outputFileName, 100, true, "Extract completed successfully");
412       } else {
413         outputDataStore.dispose();
414         this.emitError(clientId, "Output datastore is not a SimpleFeatureStore, cannot write features");
415         logger.error("Output datastore is not a SimpleFeatureStore, cannot write features");
416       }
417     } catch (Exception e) {
418       emitExtractError(clientId, inputTmFeatureType, e);
419     } finally {
420       if (outputDataStore != null) {
421         outputDataStore.dispose();
422       }
423       if (inputFeatureSource != null) {
424         try {
425           inputFeatureSource.getDataStore().dispose();
426         } catch (Exception e) {
427           logger.warn("Error disposing datastore for feature source {}", inputFeatureSource.getName(), e);
428         }
429       }
430     }
431   }
432 
433   private File getValidatedOutputFile(String outputFileName) throws IOException {
434     Path exportRoot = Path.of(exportFilesLocation).toRealPath();
435     Path outputPath = exportRoot.resolve(outputFileName).normalize();
436     if (!outputPath.startsWith(exportRoot)) {
437       throw new IOException("Invalid file path");
438     }
439     Path createdFilePath = Files.createFile(outputPath).toRealPath();
440     if (!createdFilePath.startsWith(exportRoot)) {
441       throw new IOException("Invalid file path");
442     }
443     return createdFilePath.toFile();
444   }
445 
446   /**
447    * Create a writable GeoTools {@link FileDataStore} for the requested extract format. The format must be must be
448    * supported by a {@link FileDataStore} implementation, for example CSV, Excel or GeoJSON. For unsupported formats
449    * (for example Shapefile) a custom handling is used in the calling method.
450    *
451    * <p>The output file is validated to ensure it is created under the configured extract location.
452    *
453    * @param extractOutputFormat the requested extract output format
454    * @param outputFileName the target output filename
455    * @param clientId the SSE client id, used for error reporting
456    * @return a newly created {@link FileDataStore} configured for the requested format
457    * @throws IOException when the output file path is invalid or the datastore cannot be created
458    */
459   private FileDataStore getExtractDataStore(
460       LayerExtractController.ExtractOutputFormat extractOutputFormat, String outputFileName, String clientId)
461       throws IOException {
462 
463     final File outputFile = getValidatedOutputFile(outputFileName);
464     if (!logger.isDebugEnabled()) {
465       outputFile.deleteOnExit();
466     }
467 
468     return switch (extractOutputFormat) {
469       case CSV ->
470         (FileDataStore) new CSVDataStoreFactory()
471             .createNewDataStore(Map.of(
472                 CSVDataStoreFactory.FILE_PARAM.key,
473                 outputFile,
474                 CSVDataStoreFactory.STRATEGYP.key,
475                 CSVDataStoreFactory.WKT_STRATEGY,
476                 CSVDataStoreFactory.WKTP.key,
477                 "the_geom_wkt",
478                 CSVDataStoreFactory.WRITEPRJ.key,
479                 false,
480                 CSVDataStoreFactory.QUOTEALL.key,
481                 true));
482       case XLSX ->
483         (FileDataStore) new ExcelDataStoreFactory()
484             .createNewDataStore(Map.of(ExcelDataStoreFactory.FILE_PARAM.key, outputFile));
485       case GEOJSON ->
486         (FileDataStore) new GeoJSONDataStoreFactory()
487             .createNewDataStore(Map.of(GeoJSONDataStoreFactory.FILE_PARAM.key, outputFile));
488       default -> {
489         emitError(clientId, "Unknown output format: " + extractOutputFormat);
490         logger.error("Unknown output format: {}", extractOutputFormat);
491         throw new IllegalArgumentException("Unknown output format: " + extractOutputFormat);
492       }
493     };
494   }
495 
496   private int getFeatureCount(SimpleFeatureSource source, Query query) throws IOException {
497     int count = WFSHitsCountUtil.getCount(source, query);
498     logger.debug("Filtered source counts {} features", count);
499     return count;
500   }
501 
502   private void handleWithShapeDumper(
503       @NonNull String clientId,
504       @NonNull TMFeatureType inputTmFeatureType,
505       @NonNull Set<String> attributes,
506       Filter filter,
507       String sortBy,
508       SortOrder sortOrder,
509       @NonNull String outputFileName) {
510     SimpleFeatureSource inputFeatureSource = null;
511     File outputDirectory = null;
512     try {
513       File outputFile = getValidatedOutputFile(outputFileName);
514       String baseName = outputFile
515           .getName()
516           .substring(
517               0,
518               outputFile
519                   .getName()
520                   .lastIndexOf(LayerExtractController.ExtractOutputFormat.SHAPE.getExtension()));
521       outputDirectory = outputFile
522           .getParentFile()
523           .toPath()
524           .resolve(baseName)
525           .toFile()
526           .getCanonicalFile();
527       if (!logger.isDebugEnabled()) {
528         // delete in production after JVM exit because the event bus will be reset when the JVM exits, and then
529         // we are unlikely to have a reference to the file anymore.
530         // In debug/development mode we want to keep the directory for inspection.
531         outputDirectory.deleteOnExit();
532       }
533       Files.createDirectories(outputDirectory.toPath());
534 
535       ShapefileDumper dumper = new ShapefileDumper(outputDirectory);
536       dumper.setCharset(StandardCharsets.UTF_8);
537       dumper.setEmptyShapefileAllowed(false);
538 
539       inputFeatureSource = featureSourceFactoryHelper.openGeoToolsFeatureSource(inputTmFeatureType);
540 
541       Query q = createQuery(inputFeatureSource, attributes, filter, sortBy, sortOrder);
542 
543       final int featCount = getFeatureCount(inputFeatureSource, q);
544       final boolean hasKnownFeatureCount = featCount > 0;
545 
546       AtomicInteger lastProgress = new AtomicInteger(0);
547 
548       dumper.dump(new ProgressReportingFeatureCollection(
549           inputFeatureSource.getFeatures(q), progressReportInterval, processed -> {
550             int progress = hasKnownFeatureCount ? (int) ((processed / (double) featCount) * 99) : 0;
551             lastProgress.set(progress);
552             String progressMessage = hasKnownFeatureCount
553                 ? "Extracting shapes: %d/%d features processed".formatted(processed, featCount)
554                 : "Extracting shapes: %d features processed".formatted(processed);
555             this.emitProgress(clientId, outputFileName, progress, false, progressMessage);
556           }));
557       this.emitProgress(
558           clientId,
559           outputFileName,
560           Math.max(99, lastProgress.get()),
561           false,
562           "Extract shapes dumped successfully");
563 
564       zipService.zipDirectory(outputDirectory.toPath(), outputFile.toPath());
565       this.emitProgress(clientId, outputFileName, 100, true, "Extract completed successfully");
566     } catch (Exception e) {
567       emitExtractError(clientId, inputTmFeatureType, e);
568     } finally {
569       if (outputDirectory != null) {
570         try {
571           deleteDirectoryRecursively(outputDirectory.toPath());
572         } catch (IOException e) {
573           logger.error("Failed to delete output directory {}", outputDirectory, e);
574         }
575       }
576       if (inputFeatureSource != null) {
577         try {
578           inputFeatureSource.getDataStore().dispose();
579         } catch (Exception e) {
580           logger.warn("Error disposing datastore for feature source {}", inputFeatureSource.getName(), e);
581         }
582       }
583     }
584   }
585 
586   private Query createQuery(
587       SimpleFeatureSource inputFeatureSource,
588       Set<String> attributes,
589       Filter filter,
590       String sortBy,
591       SortOrder sortOrder) {
592     Query q = new Query(inputFeatureSource.getName().toString());
593     if (!attributes.isEmpty()) {
594       q.setPropertyNames(attributes.toArray(new String[0]));
595     }
596 
597     if (filter != null) {
598       q.setFilter(filter);
599     }
600     if (!StringUtils.isBlank(sortBy)) {
601       q.setSortBy(ff.sort(sortBy, Objects.requireNonNullElse(sortOrder, SortOrder.ASCENDING)));
602     }
603     return q;
604   }
605 
606   /**
607    * Cleanup expired extract files. Filenames are created in {@link CreateLayerExtractService#createExtractFilename }
608    * and follow the pattern {@code "%s_%s_%s.%s".formatted(sourceFT.getName(), clientId, UUIDv7.randomV7(),
609    * outputFormat.getExtension()) }
610    */
611   @Scheduled(fixedDelay = 5, timeUnit = TimeUnit.MINUTES, initialDelay = 15)
612   public void cleanupExpiredExtracts() {
613     logger.debug("Running expired extracts cleanup in {}", exportFilesLocation);
614     List<FileWithAttributes> oldDownloadFilesOnDisk = new ArrayList<>();
615     Set<String> validClientIds = eventBus.getAllClientIds();
616 
617     // list download files in export location and delete those that are not bound to an active sse stream client
618     try (Stream<Path> stream = Files.walk(Path.of(exportFilesLocation))) {
619       stream.filter(Files::isRegularFile).forEach(path -> {
620         File file = path.toFile();
621         String filename = file.getName();
622         String[] parts = filename.split("[_.]", -1);
623         if (parts.length < 4) {
624           logger.warn("Unexpected file in extract location: {}", filename);
625           return;
626         }
627         String clientId = parts[1];
628         if (!validClientIds.contains(clientId)) {
629           if (!file.delete()) {
630             logger.error("Failed to delete unattached extract file {}", filename);
631           }
632         } else {
633           try {
634             Instant timestampPart = UUIDv7.timestampAsInstant(UUIDv7.fromString(parts[2]));
635             oldDownloadFilesOnDisk.add(new FileWithAttributes(file, timestampPart, clientId));
636           } catch (IllegalArgumentException ignored) {
637             // not a valid v7 uuid
638           }
639         }
640       });
641 
642       try (Stream<Path> paths = Files.walk(Path.of(exportFilesLocation))) {
643         paths.filter(Files::isDirectory)
644             .filter(path -> !path.equals(Path.of(exportFilesLocation)))
645             .forEach(path -> {
646               logger.debug("Checking directory {} for expired extracts", path);
647               File file = path.toFile();
648               String filename = file.getName();
649               String[] parts = filename.split("[_]", -1);
650               if (parts.length < 3) {
651                 logger.warn("Unexpected directory in extract location: {}", filename);
652                 return;
653               }
654               String clientId = parts[1];
655               if (!validClientIds.contains(clientId)) {
656                 try {
657                   deleteDirectoryRecursively(file.toPath());
658                 } catch (IOException e) {
659                   logger.error("Failed to delete unattached extract directory {}", filename);
660                 }
661               } else {
662                 try {
663                   Instant timestampPart = UUIDv7.timestampAsInstant(UUIDv7.fromString(parts[2]));
664                   oldDownloadFilesOnDisk.add(new FileWithAttributes(file, timestampPart, clientId));
665                 } catch (IllegalArgumentException ignored) {
666                   // not a valid v7 uuid
667                 }
668               }
669             });
670       }
671 
672       // delete any files/directories are older than the cutoff
673       oldDownloadFilesOnDisk.stream()
674           .filter(f -> f.timestamp()
675               .isBefore(Instant.now().minusSeconds(TimeUnit.MINUTES.toSeconds(cleanupIntervalMinutes))))
676           .forEach(f -> {
677             if (f.file.isDirectory()) {
678               try {
679                 deleteDirectoryRecursively(f.file().toPath());
680               } catch (IOException ignored) {
681                 logger.warn("Failed to delete directory {}", f.file());
682               }
683             } else {
684               if (!f.file().delete()) {
685                 logger.error(
686                     "Failed to delete expired extract file {}",
687                     f.file().getName());
688               }
689             }
690           });
691     } catch (IOException e) {
692       logger.error("Error while cleaning up expired extracts", e);
693     }
694   }
695 
696   private void deleteDirectoryRecursively(Path directory) throws IOException {
697     try (Stream<Path> paths = Files.walk(directory)) {
698       paths.sorted(Comparator.reverseOrder()).forEach(path -> {
699         try {
700           logger.debug("Deleting path {}", path);
701           Files.deleteIfExists(path);
702         } catch (IOException e) {
703           throw new RuntimeException("Failed to delete path: " + path, e);
704         }
705       });
706     } catch (RuntimeException e) {
707       if (e.getCause() instanceof IOException ioException) {
708         throw ioException;
709       }
710       throw e;
711     }
712   }
713 
714   private record FileWithAttributes(File file, Instant timestamp, String clientId) {}
715 }