View Javadoc
1   /*
2    * Copyright (C) 2022 B3Partners B.V.
3    *
4    * SPDX-License-Identifier: MIT
5    */
6   package org.tailormap.api.controller;
7   
8   import static org.springframework.web.bind.annotation.RequestMethod.GET;
9   import static org.springframework.web.bind.annotation.RequestMethod.POST;
10  import static org.tailormap.api.persistence.helper.TMAttributeTypeHelper.isGeometry;
11  import static org.tailormap.api.persistence.helper.TMFeatureTypeHelper.getConfiguredAttributes;
12  
13  import io.micrometer.core.annotation.Timed;
14  import jakarta.validation.constraints.NotNull;
15  import java.io.IOException;
16  import java.io.Serializable;
17  import java.lang.invoke.MethodHandles;
18  import java.time.Duration;
19  import java.util.ArrayList;
20  import java.util.List;
21  import java.util.Locale;
22  import java.util.Map;
23  import java.util.stream.Collectors;
24  import org.geotools.api.data.Query;
25  import org.geotools.api.data.SimpleFeatureSource;
26  import org.geotools.api.feature.simple.SimpleFeature;
27  import org.geotools.api.filter.Filter;
28  import org.geotools.api.filter.FilterFactory;
29  import org.geotools.api.filter.sort.SortOrder;
30  import org.geotools.api.referencing.FactoryException;
31  import org.geotools.api.referencing.operation.MathTransform;
32  import org.geotools.api.referencing.operation.TransformException;
33  import org.geotools.data.simple.SimpleFeatureIterator;
34  import org.geotools.data.wfs.WFSDataStore;
35  import org.geotools.factory.CommonFactoryFinder;
36  import org.geotools.filter.text.cql2.CQLException;
37  import org.geotools.geometry.jts.JTS;
38  import org.geotools.util.factory.GeoTools;
39  import org.locationtech.jts.geom.Coordinate;
40  import org.locationtech.jts.geom.Geometry;
41  import org.locationtech.jts.util.GeometricShapeFactory;
42  import org.slf4j.Logger;
43  import org.slf4j.LoggerFactory;
44  import org.springframework.beans.factory.annotation.Value;
45  import org.springframework.http.HttpStatus;
46  import org.springframework.http.MediaType;
47  import org.springframework.http.ResponseEntity;
48  import org.springframework.transaction.annotation.Transactional;
49  import org.springframework.validation.annotation.Validated;
50  import org.springframework.web.bind.annotation.ModelAttribute;
51  import org.springframework.web.bind.annotation.RequestMapping;
52  import org.springframework.web.bind.annotation.RequestParam;
53  import org.springframework.web.server.ResponseStatusException;
54  import org.tailormap.api.annotation.AppRestController;
55  import org.tailormap.api.geotools.FilterUtil;
56  import org.tailormap.api.geotools.TransformationUtil;
57  import org.tailormap.api.geotools.featuresources.AttachmentsHelper;
58  import org.tailormap.api.geotools.featuresources.FeatureSourceFactoryHelper;
59  import org.tailormap.api.geotools.featuresources.WFSFeatureSourceHelper;
60  import org.tailormap.api.geotools.processing.GeometryProcessor;
61  import org.tailormap.api.geotools.wfs.WFSCountDefaultUtil;
62  import org.tailormap.api.geotools.wfs.WFSHitsCountUtil;
63  import org.tailormap.api.persistence.Application;
64  import org.tailormap.api.persistence.GeoService;
65  import org.tailormap.api.persistence.TMFeatureSource;
66  import org.tailormap.api.persistence.TMFeatureType;
67  import org.tailormap.api.persistence.helper.TMFeatureTypeHelper;
68  import org.tailormap.api.persistence.json.AppLayerSettings;
69  import org.tailormap.api.persistence.json.AppTreeLayerNode;
70  import org.tailormap.api.persistence.json.FeatureTypeTemplate;
71  import org.tailormap.api.persistence.json.GeoServiceLayer;
72  import org.tailormap.api.persistence.json.TMAttributeDescriptor;
73  import org.tailormap.api.persistence.json.TMAttributeType;
74  import org.tailormap.api.repository.FeatureSourceRepository;
75  import org.tailormap.api.util.Constants;
76  import org.tailormap.api.viewer.model.AttachmentMetadata;
77  import org.tailormap.api.viewer.model.ColumnMetadata;
78  import org.tailormap.api.viewer.model.Feature;
79  import org.tailormap.api.viewer.model.FeaturesResponse;
80  
81  @AppRestController
82  @Validated
83  @RequestMapping(
84      path = "${tailormap-api.base-path}/{viewerKind}/{viewerName}/layer/{appLayerId}/features",
85      produces = MediaType.APPLICATION_JSON_VALUE)
86  public class FeaturesController implements Constants {
87    private static final Logger logger =
88        LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
89  
90    private final FeatureSourceFactoryHelper featureSourceFactoryHelper;
91    private final TMFeatureTypeHelper featureTypeHelper;
92    private final FeatureSourceRepository featureSourceRepository;
93    private final FilterFactory ff = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
94  
95    @Value("${tailormap-api.default-page-size:100}")
96    private int defaultPageSize;
97  
98    @Value("${tailormap-api.max-page-size:500}")
99    private int maxPageSize;
100 
101   @Value("${tailormap-api.feature.info.maxitems:30}")
102   private int maxFeatures;
103 
104   @Value("${tailormap-api.features.wfs-hits-timeout:3s}")
105   private Duration wfsHitsTimeout;
106 
107   @Value("${tailormap-api.features.wfs-slow-hits-ttl:4h}")
108   private Duration wfsSlowHitsTtl;
109 
110   public FeaturesController(
111       FeatureSourceFactoryHelper featureSourceFactoryHelper,
112       TMFeatureTypeHelper featureTypeHelper,
113       FeatureSourceRepository featureSourceRepository) {
114     this.featureSourceFactoryHelper = featureSourceFactoryHelper;
115     this.featureTypeHelper = featureTypeHelper;
116     this.featureSourceRepository = featureSourceRepository;
117   }
118 
119   @Transactional
120   @RequestMapping(method = {GET, POST})
121   @Timed(value = "get_features", description = "time spent to process get features call")
122   public ResponseEntity<Serializable> getFeatures(
123       @ModelAttribute AppTreeLayerNode appTreeLayerNode,
124       @ModelAttribute GeoService service,
125       @ModelAttribute GeoServiceLayer layer,
126       @ModelAttribute Application application,
127       @RequestParam(required = false) Double x,
128       @RequestParam(required = false) Double y,
129       @RequestParam(defaultValue = "4") Double distance,
130       @RequestParam(required = false) String __fid,
131       @RequestParam(defaultValue = "false") Boolean simplify,
132       @RequestParam(required = false) String filter,
133       @RequestParam(required = false) Integer page,
134       @RequestParam(required = false) Integer pageSize,
135       @RequestParam(required = false) String sortBy,
136       @RequestParam(required = false, defaultValue = "asc") String sortOrder,
137       @RequestParam(defaultValue = "false") boolean onlyGeometries,
138       @RequestParam(defaultValue = "false") boolean geometryInAttributes,
139       @RequestParam(defaultValue = "false") boolean withAttachments) {
140 
141     if (layer == null) {
142       throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Can't find layer " + appTreeLayerNode);
143     }
144 
145     TMFeatureType tmft = service.findFeatureTypeForLayer(layer, featureSourceRepository);
146     if (tmft == null) {
147       throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Layer does not have feature type");
148     }
149     AppLayerSettings appLayerSettings = application.getAppLayerSettings(appTreeLayerNode);
150 
151     if (onlyGeometries) {
152       geometryInAttributes = true;
153     }
154 
155     FeaturesResponse featuresResponse;
156 
157     if (null != __fid) {
158       featuresResponse =
159           getFeatureByFID(tmft, appLayerSettings, __fid, application, !geometryInAttributes, withAttachments);
160     } else if (null != x && null != y) {
161       featuresResponse = getFeaturesByXY(
162           tmft,
163           appLayerSettings,
164           filter,
165           x,
166           y,
167           application,
168           distance,
169           simplify,
170           !geometryInAttributes,
171           withAttachments);
172     } else if (null != page && page > 0) {
173       featuresResponse = getAllFeatures(
174           tmft,
175           application,
176           appLayerSettings,
177           page,
178           pageSize,
179           filter,
180           sortBy,
181           sortOrder,
182           simplify,
183           onlyGeometries,
184           !geometryInAttributes,
185           withAttachments);
186     } else {
187       throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Unsupported combination of request parameters");
188     }
189 
190     return ResponseEntity.status(HttpStatus.OK).body(featuresResponse);
191   }
192 
193   @NotNull private FeaturesResponse getAllFeatures(
194       @NotNull TMFeatureType tmft,
195       @NotNull Application application,
196       @NotNull AppLayerSettings appLayerSettings,
197       Integer page,
198       Integer pageSize,
199       String filterECQL,
200       String sortBy,
201       String sortOrder,
202       boolean simplifyGeometry,
203       boolean onlyGeometries,
204       boolean skipGeometryOutput,
205       boolean withAttachments) {
206     int requestedPageSize = pageSize != null ? pageSize : defaultPageSize;
207     requestedPageSize = Math.max(1, requestedPageSize);
208     int requestPageSize = Math.min(maxPageSize, requestedPageSize);
209     FeaturesResponse featuresResponse = new FeaturesResponse().page(page).pageSize(requestPageSize);
210 
211     SimpleFeatureSource fs = null;
212     try {
213       fs = featureSourceFactoryHelper.openGeoToolsFeatureSource(tmft);
214 
215       // A WFS 1.x has no offset: GeoTools only sends MAXFEATURES and skips the start index in memory, so a
216       // next page would silently be empty. Use WFS 2.0.0 for paging.
217       if (page > 1
218           && fs.getDataStore() instanceof WFSDataStore wfsDataStore
219           && !wfsDataStore.getWfsClient().canOffset()) {
220         throw new ResponseStatusException(
221             HttpStatus.BAD_REQUEST,
222             "Paging is not supported for this WFS version, only the first page can be retrieved. Use WFS 2.0.0");
223       }
224 
225       // A WFS returns at most its CountDefault features. Use that as the page size (returned in the response so
226       // the client uses it too), otherwise the start index of the next page would skip features, and a client
227       // that does not know the total would think a page with fewer features than the page size is the last page.
228       Integer wfsCountDefault = WFSCountDefaultUtil.getCountDefault(fs.getDataStore());
229       if (wfsCountDefault != null && wfsCountDefault < requestPageSize) {
230         requestPageSize = wfsCountDefault;
231         featuresResponse.setPageSize(requestPageSize);
232       }
233 
234       // Property names for sorting: only non-geometry attributes that aren't hidden
235       List<String> propNames = getConfiguredAttributes(tmft, appLayerSettings).values().stream()
236           .map(TMFeatureTypeHelper.AttributeWithSettings::attributeDescriptor)
237           .filter(a -> !isGeometry(a.getType()))
238           .map(TMAttributeDescriptor::getName)
239           .collect(Collectors.toList());
240 
241       String sortAttrName;
242       if (onlyGeometries) {
243         propNames = List.of(tmft.getDefaultGeometryAttribute());
244         // do not try to sort by geometry
245         sortAttrName = null;
246       } else {
247         if (propNames.isEmpty()) {
248           return featuresResponse;
249         }
250         // Default sorting attribute if sortBy not specified or not a configured attribute
251         if (tmft.getPrimaryKeyAttribute() != null && propNames.contains(tmft.getPrimaryKeyAttribute())) {
252           // There is a primary key and it is known, use that for sorting
253           sortAttrName = tmft.getPrimaryKeyAttribute();
254         } else if (tmft.getFeatureSource().getProtocol() == TMFeatureSource.Protocol.WFS
255             && "2.0.0"
256                 .equals(WFSFeatureSourceHelper.getWFSVersion(
257                     tmft.getFeatureSource().getUrl()))) {
258           // A WFS has no known primary key (only detected for JDBC) and the first attribute need not be
259           // unique, so use the natural order of the server. WFS 2.0 (ISO 19142) 7.9.2.5.4.4 requires a server
260           // to keep the order of a query without a sorting clause the same across executions, so it is stable
261           // across pages (MapServer with PostGIS doesn't strictly do this: no ORDER BY with LIMIT/OFFSET).
262           // Sorting on gml:id is not possible (PDOK and GeoServer reject it).
263           // Not for WFS 1.x: GeoTools then sends the NATURAL_ORDER it adds when paging as a SortProperty
264           // without a PropertyName, which GeoServer rejects.
265           sortAttrName = null;
266         } else {
267           // A database has no guaranteed order without ORDER BY. For WFS 1.x, sort on the first attribute
268           sortAttrName = propNames.getFirst();
269         }
270 
271         if (null != sortBy) {
272           // Only use sortBy attribute if it is in the list of configured attributes and not a
273           // geometry type (propNames does not contain geometry attributes, see above)
274           if (propNames.contains(sortBy)) {
275             sortAttrName = sortBy;
276           } else {
277             logger.warn(
278                 "Requested sortBy attribute {} was not found in configured attributes or is a geometry attribute",
279                 sortBy);
280           }
281         }
282       }
283 
284       SortOrder _sortOrder = SortOrder.ASCENDING;
285       if (null != sortOrder && (sortOrder.equalsIgnoreCase("desc") || sortOrder.equalsIgnoreCase("asc"))) {
286         _sortOrder = SortOrder.valueOf(sortOrder.toUpperCase(Locale.ROOT));
287       }
288 
289       // setup query, attributes and filter
290       Query q = new Query(fs.getName().toString());
291 
292       // add default geometry attribute to the property names for query
293       if (!skipGeometryOutput && !onlyGeometries) {
294         propNames.add(tmft.getDefaultGeometryAttribute());
295       }
296       q.setPropertyNames(propNames);
297 
298       // count can be -1 if too costly or unknown, eg. some WFS, or a WFS which counts slowly
299       int featureCount;
300       if (null != filterECQL) {
301         Filter filter = parseFilter(filterECQL, application, fs);
302         q.setFilter(filter);
303         featureCount = WFSHitsCountUtil.getCount(fs, q, wfsHitsTimeout, wfsSlowHitsTtl);
304       } else {
305         featureCount = WFSHitsCountUtil.getCount(fs, Query.ALL, wfsHitsTimeout, wfsSlowHitsTtl);
306       }
307       featuresResponse.setTotal(featureCount);
308 
309       // setup page query
310       if (sortAttrName != null) {
311         q.setSortBy(ff.sort(sortAttrName, _sortOrder));
312       }
313       q.setMaxFeatures(requestPageSize);
314       // Only set a start index for pages after the first. With a start index and no sort order, GeoTools adds
315       // SortBy.NATURAL_ORDER, which a WFS 1.1.0 client sends to the server as a SortProperty without a
316       // PropertyName that GeoServer and MapServer reject. Without a sort order this happens for onlyGeometries.
317       if (page > 1) {
318         q.setStartIndex((page - 1) * requestPageSize);
319       }
320       logger.debug("Attribute query: {}", q);
321 
322       executeQueryOnFeatureSourceAndClose(
323           simplifyGeometry,
324           featuresResponse,
325           tmft,
326           appLayerSettings,
327           onlyGeometries,
328           fs,
329           q,
330           application,
331           skipGeometryOutput,
332           withAttachments);
333     } catch (ResponseStatusException e) {
334       throw e;
335     } catch (IOException | RuntimeException e) {
336       throw featuresReadError(tmft, e);
337     } finally {
338       if (fs != null) {
339         fs.getDataStore().dispose();
340       }
341     }
342 
343     return featuresResponse;
344   }
345 
346   /**
347    * Parse an ECQL filter from the request.
348    *
349    * @throws ResponseStatusException with status 400 if the filter is invalid
350    */
351   private static Filter parseFilter(String filterECQL, Application application, SimpleFeatureSource fs) {
352     try {
353       return FilterUtil.parseFilter(filterECQL, application, fs);
354     } catch (CQLException | FactoryException | UnsupportedOperationException e) {
355       throw new ResponseStatusException(
356           HttpStatus.BAD_REQUEST, "Could not parse requested filter: " + e.getMessage(), e);
357     }
358   }
359 
360   /**
361    * Log an error that occurred while reading features and create an exception to report it to the client, instead of
362    * returning an empty response or a server error without a message.
363    */
364   private static ResponseStatusException featuresReadError(TMFeatureType tmFeatureType, Exception e) {
365     logger.error("Error reading features of feature type {}", tmFeatureType.getName(), e);
366     return new ResponseStatusException(
367         HttpStatus.INTERNAL_SERVER_ERROR,
368         "Error reading features of feature type \"%s\": %s"
369             .formatted(
370                 tmFeatureType.getName(),
371                 e.getMessage() != null
372                     ? e.getMessage()
373                     : e.getClass().getName()),
374         e);
375   }
376 
377   @NotNull private FeaturesResponse getFeatureByFID(
378       @NotNull TMFeatureType tmFeatureType,
379       @NotNull AppLayerSettings appLayerSettings,
380       @NotNull String fid,
381       @NotNull Application application,
382       boolean skipGeometryOutput,
383       boolean withAttachments) {
384     FeaturesResponse featuresResponse = new FeaturesResponse();
385 
386     SimpleFeatureSource fs = null;
387     try {
388       fs = featureSourceFactoryHelper.openGeoToolsFeatureSource(tmFeatureType);
389       Query q = new Query(fs.getName().toString());
390       q.setFilter(ff.id(ff.featureId(fid)));
391       q.setMaxFeatures(1);
392       logger.debug("FID query: {}", q);
393 
394       executeQueryOnFeatureSourceAndClose(
395           false,
396           featuresResponse,
397           tmFeatureType,
398           appLayerSettings,
399           false,
400           fs,
401           q,
402           application,
403           skipGeometryOutput,
404           withAttachments);
405     } catch (ResponseStatusException e) {
406       throw e;
407     } catch (IOException | RuntimeException e) {
408       throw featuresReadError(tmFeatureType, e);
409     } finally {
410       if (fs != null) {
411         fs.getDataStore().dispose();
412       }
413     }
414 
415     return featuresResponse;
416   }
417 
418   @NotNull private FeaturesResponse getFeaturesByXY(
419       @NotNull TMFeatureType tmFeatureType,
420       @NotNull AppLayerSettings appLayerSettings,
421       String filterECQL,
422       @NotNull Double x,
423       @NotNull Double y,
424       @NotNull Application application,
425       @NotNull Double distance,
426       @NotNull Boolean simplifyGeometry,
427       boolean skipGeometryOutput,
428       boolean withAttachments) {
429 
430     if (null != distance && 0d >= distance) {
431       throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Buffer distance must be greater than 0");
432     }
433 
434     FeaturesResponse featuresResponse = new FeaturesResponse();
435 
436     SimpleFeatureSource fs = null;
437     try {
438       GeometricShapeFactory shapeFact = new GeometricShapeFactory();
439       shapeFact.setNumPoints(32);
440       shapeFact.setCentre(new Coordinate(x, y));
441       //noinspection ConstantConditions
442       shapeFact.setSize(distance * 2d);
443       Geometry p = shapeFact.createCircle();
444       logger.trace("created selection geometry: {}", p);
445 
446       MathTransform transform = null;
447       fs = featureSourceFactoryHelper.openGeoToolsFeatureSource(tmFeatureType);
448       try {
449         transform = TransformationUtil.getTransformationToDataSource(application, fs);
450       } catch (FactoryException e) {
451         logger.warn("Unable to find transformation from query geometry to desired datasource", e);
452       }
453       if (null != transform) {
454         try {
455           p = JTS.transform(p, transform);
456           logger.trace("reprojected selection geometry to: {}", p);
457         } catch (TransformException e) {
458           logger.warn("Unable to transform query geometry to desired CRS, trying with original CRS");
459         }
460       }
461       logger.trace("using selection geometry: {}", p);
462       Filter spatialFilter =
463           ff.intersects(ff.property(tmFeatureType.getDefaultGeometryAttribute()), ff.literal(p));
464 
465       Filter finalFilter = spatialFilter;
466       if (null != filterECQL) {
467         Filter filter = parseFilter(filterECQL, application, fs);
468         finalFilter = ff.and(spatialFilter, filter);
469       }
470       Query q = new Query(fs.getName().toString());
471       q.setFilter(finalFilter);
472       q.setMaxFeatures(maxFeatures);
473 
474       executeQueryOnFeatureSourceAndClose(
475           simplifyGeometry,
476           featuresResponse,
477           tmFeatureType,
478           appLayerSettings,
479           false,
480           fs,
481           q,
482           application,
483           skipGeometryOutput,
484           withAttachments);
485     } catch (ResponseStatusException e) {
486       throw e;
487     } catch (IOException | RuntimeException e) {
488       throw featuresReadError(tmFeatureType, e);
489     } finally {
490       if (fs != null) {
491         // Normally executeQueryOnFeatureSourceAndClose() will close the datastore, but when filterECQL is
492         // invalid the datastore will be left open, so close here to make sure (disposing twice won't hurt)
493         fs.getDataStore().dispose();
494       }
495     }
496     return featuresResponse;
497   }
498 
499   private void executeQueryOnFeatureSourceAndClose(
500       boolean simplifyGeometry,
501       @NotNull FeaturesResponse featuresResponse,
502       @NotNull TMFeatureType tmFeatureType,
503       @NotNull AppLayerSettings appLayerSettings,
504       boolean onlyGeometries,
505       @NotNull SimpleFeatureSource featureSource,
506       @NotNull Query selectQuery,
507       @NotNull Application application,
508       boolean skipGeometryOutput,
509       boolean withAttachments)
510       throws IOException {
511     boolean addFields = false;
512 
513     MathTransform transform = null;
514     try {
515       transform = TransformationUtil.getTransformationToApplication(application, featureSource);
516     } catch (FactoryException e) {
517       logger.error("Can not transform geometry to desired CRS", e);
518     }
519 
520     boolean ftSupportsAttachments = tmFeatureType.getSettings().getAttachmentAttributes() != null
521         && !tmFeatureType.getSettings().getAttachmentAttributes().isEmpty();
522 
523     List<Object> featurePKs = new ArrayList<>();
524     Map<String, TMFeatureTypeHelper.AttributeWithSettings> configuredAttributes =
525         getConfiguredAttributes(tmFeatureType, appLayerSettings);
526 
527     // send request to attribute source
528     try (SimpleFeatureIterator feats =
529         featureSource.getFeatures(selectQuery).features()) {
530       while (feats.hasNext()) {
531         addFields = true;
532         // transform found simplefeatures to list of Feature
533         SimpleFeature feature = feats.next();
534 
535         // processedGeometry can be null
536         String processedGeometry = GeometryProcessor.processGeometry(
537             feature.getAttribute(tmFeatureType.getDefaultGeometryAttribute()),
538             simplifyGeometry,
539             true,
540             transform);
541         Feature newFeat = new Feature().fid(feature.getID()).geometry(processedGeometry);
542 
543         if (!onlyGeometries) {
544           for (String attName : configuredAttributes.keySet()) {
545             Object value = feature.getAttribute(attName);
546             if (value instanceof Geometry geometry) {
547               if (skipGeometryOutput) {
548                 value = null;
549               } else {
550                 value = GeometryProcessor.geometryToWKT(geometry);
551               }
552             }
553             newFeat.putAttributesItem(attName, value);
554           }
555           if (withAttachments && ftSupportsAttachments) {
556             // Just add the PK as is, no conversion needed
557             featurePKs.add(feature.getAttribute(tmFeatureType.getPrimaryKeyAttribute()));
558           }
559         }
560         featuresResponse.addFeaturesItem(newFeat);
561       }
562     } finally {
563       featureSource.getDataStore().dispose();
564     }
565     FeatureTypeTemplate ftt = tmFeatureType.getSettings().getTemplate();
566     if (ftt != null) {
567       featuresResponse.setTemplate(ftt.getTemplate());
568     }
569     if (addFields) {
570       configuredAttributes.values().stream()
571           .map(attributeWithSettings -> {
572             TMAttributeType type =
573                 attributeWithSettings.attributeDescriptor().getType();
574             return new ColumnMetadata()
575                 .name(attributeWithSettings
576                     .attributeDescriptor()
577                     .getName())
578                 .alias(attributeWithSettings.settings().getTitle())
579                 .type(isGeometry(type) ? TMAttributeType.GEOMETRY : type);
580           })
581           .forEach(featuresResponse::addColumnMetadataItem);
582     }
583     if (ftSupportsAttachments) {
584       //  add attachment metadata
585       featuresResponse.setAttachmentMetadata(
586           featureTypeHelper.getAttachmentAttributesWithMaxFileUploadSize(tmFeatureType));
587 
588       if (withAttachments) {
589         //  fetch all attachments for all features, grouped by feature fid
590         Map<String, List<AttachmentMetadata>> attachmentsByFeatureId =
591             AttachmentsHelper.listAttachmentsForFeaturesByFeatureId(tmFeatureType, featurePKs);
592         //  add attachment data to features using the feature FID to match
593         for (Feature feature : featuresResponse.getFeatures()) {
594           String primaryKey = feature.getFid();
595           List<AttachmentMetadata> attachments = attachmentsByFeatureId.get(primaryKey);
596           if (attachments != null) {
597             feature.setAttachments(attachments);
598           }
599         }
600       }
601     }
602   }
603 }