View Javadoc
1   /*
2    * Copyright (C) 2026 B3Partners B.V.
3    *
4    * SPDX-License-Identifier: MIT
5    */
6   package org.tailormap.api.controller;
7   
8   import static org.springframework.http.HttpStatus.BAD_REQUEST;
9   import static org.springframework.http.HttpStatus.NOT_FOUND;
10  import static org.springframework.http.HttpStatus.NOT_MODIFIED;
11  import static org.tailormap.api.service.UploadsService.createUploadResponseEntity;
12  import static org.tailormap.api.util.TMStringUtils.nullIfEmpty;
13  
14  import jakarta.servlet.http.HttpServletRequest;
15  import java.util.Optional;
16  import java.util.UUID;
17  import java.util.regex.Pattern;
18  import org.apache.commons.lang3.ObjectUtils;
19  import org.gaul.modernizer_maven_annotations.SuppressModernizer;
20  import org.springframework.http.ResponseEntity;
21  import org.springframework.validation.annotation.Validated;
22  import org.springframework.web.bind.annotation.GetMapping;
23  import org.springframework.web.bind.annotation.ModelAttribute;
24  import org.springframework.web.bind.annotation.PathVariable;
25  import org.springframework.web.server.ResponseStatusException;
26  import org.tailormap.api.annotation.AppRestController;
27  import org.tailormap.api.persistence.Application;
28  import org.tailormap.api.persistence.GeoService;
29  import org.tailormap.api.persistence.Upload;
30  import org.tailormap.api.persistence.UploadCategory;
31  import org.tailormap.api.persistence.json.AppLayerSettings;
32  import org.tailormap.api.persistence.json.AppTreeLayerNode;
33  import org.tailormap.api.persistence.json.GeoServiceDefaultLayerSettings;
34  import org.tailormap.api.persistence.json.GeoServiceLayer;
35  import org.tailormap.api.persistence.json.GeoServiceLayerSettings;
36  import org.tailormap.api.repository.UploadRepository;
37  import org.tailormap.api.service.UploadsService;
38  
39  @AppRestController
40  @Validated
41  public class LayerAttachedUploadsController {
42    private final UploadsService uploadsService;
43    private final UploadRepository uploadRepository;
44    private final UploadsController uploadsController;
45  
46    public LayerAttachedUploadsController(
47        UploadsService uploadsService, UploadRepository uploadRepository, UploadsController uploadsController) {
48      this.uploadsService = uploadsService;
49      this.uploadRepository = uploadRepository;
50      this.uploadsController = uploadsController;
51    }
52  
53    @GetMapping(
54        path = {
55          /* Can't use ${tailormap-api.base-path} because linkTo() used in UploadHelper#getUrlForLayerAttachedImage() may not work */
56          "/api/app/{viewerName}/layer/{appLayerId}/uploads/{category}/{id}",
57          "/api/app/{viewerName}/layer/{appLayerId}/uploads/{category}/{id}/{filename}"
58        })
59    public ResponseEntity<byte[]> getLayerAttachedUpload(
60        @ModelAttribute AppTreeLayerNode appTreeLayerNode,
61        @ModelAttribute GeoService service,
62        @ModelAttribute GeoServiceLayer layer,
63        @ModelAttribute Application application,
64        HttpServletRequest request,
65        @PathVariable UploadCategory category,
66        @PathVariable(name = "id") UUID id,
67        @PathVariable(name = "filename", required = false) String filename) {
68  
69      if (!category.isRestricted()) {
70        // return from the normal '/uploads' endpoint if the category is not restricted while removing the
71        // application and layer from the path. This could happen for "unrestricted" categories like APP_LOGO,
72        // UNRESTRICTED, etc. that have been attached to a layer.
73        return uploadsController.getUpload(request, category, id, filename);
74      }
75  
76      if (layer == null) {
77        throw new ResponseStatusException(NOT_FOUND, "Can't find layer " + appTreeLayerNode);
78      }
79  
80      switch (category) {
81        case LAYER_ATTACHED_FILE ->
82          validateUploadIsInDescription(id, service, layer, application, appTreeLayerNode);
83        case LEGEND -> {
84          validateLegendIsAttached(id, service, layer, application, appTreeLayerNode);
85        }
86        default ->
87          throw new ResponseStatusException(
88              BAD_REQUEST, "Uploads for category " + category + " are not accessible via this endpoint");
89      }
90  
91      if (!uploadsService.checkIfModifiedSince(id, UploadsService.getIfModifiedSince(request))) {
92        return ResponseEntity.status(NOT_MODIFIED).build();
93      }
94      // TODO this would fail when we have added a LEGEND upload to a layer description, because the category would be
95      //  wrong, since the frontend generating the url does not know the category of the upload, so it is likely to
96      //  always use LAYER_ATTACHED_FILE.
97      Upload upload = uploadRepository
98          .findWithContentByIdAndCategory(id, category)
99          .orElseThrow(() -> new ResponseStatusException(NOT_FOUND));
100     return createUploadResponseEntity(upload);
101   }
102 
103   /**
104    * check that the upload is actually attached to the layer by checking the text of any of the descriptions of the
105    * layer
106    *
107    * @param id the upload id
108    * @param service the GeoService the layer belongs to
109    * @param layer the layer the upload is attached to
110    * @param application the application the layer belongs to
111    * @param appTreeLayerNode the application tree node for the layer
112    * @throws ResponseStatusException if the upload is not attached to the layer
113    */
114   private void validateUploadIsInDescription(
115       UUID id,
116       GeoService service,
117       GeoServiceLayer layer,
118       Application application,
119       AppTreeLayerNode appTreeLayerNode)
120       throws ResponseStatusException {
121 
122     Pattern pattern =
123         Pattern.compile(Pattern.quote(UploadsService.UPLOAD_MARKDOWN_SCHEME) + Pattern.quote(id.toString()));
124 
125     GeoServiceDefaultLayerSettings defaultLayerSettings = Optional.ofNullable(
126             service.getSettings().getDefaultLayerSettings())
127         .orElseGet(GeoServiceDefaultLayerSettings::new);
128     GeoServiceLayerSettings serviceLayerSettings = Optional.ofNullable(
129             service.getSettings().getLayerSettings().get(layer.getName()))
130         .orElseGet(GeoServiceLayerSettings::new);
131     AppLayerSettings appLayerSettings = application.getAppLayerSettings(appTreeLayerNode);
132 
133     @SuppressModernizer
134     // not using Objects.requireNonNullElse(arg1, arg2) because we have 3 options to check for null
135     String description = ObjectUtils.firstNonNull(
136         nullIfEmpty(appLayerSettings.getDescription()),
137         nullIfEmpty(serviceLayerSettings.getDescription()),
138         nullIfEmpty(defaultLayerSettings.getDescription()));
139 
140     if (description == null
141         || description.isBlank()
142         || !pattern.matcher(description).find()) {
143       throw new ResponseStatusException(
144           BAD_REQUEST, "Upload with id '" + id + "' is not attached to layer '" + layer.getName() + "'");
145     }
146   }
147   /**
148    * check that the legend is actually attached to the layer by checking the legend fields and the text of any of the
149    * descriptions of the layer.
150    *
151    * @param id the upload id
152    * @param service the GeoService the layer belongs to
153    * @param layer the layer the upload is attached to
154    * @param application the application the layer belongs to
155    * @param appTreeLayerNode the application tree node for the layer
156    * @throws ResponseStatusException if the legend is not attached to the layer
157    */
158   private void validateLegendIsAttached(
159       UUID id,
160       GeoService service,
161       GeoServiceLayer layer,
162       Application application,
163       AppTreeLayerNode appTreeLayerNode)
164       throws ResponseStatusException {
165 
166     GeoServiceDefaultLayerSettings defaultLayerSettings = Optional.ofNullable(
167             service.getSettings().getDefaultLayerSettings())
168         .orElseGet(GeoServiceDefaultLayerSettings::new);
169 
170     GeoServiceLayerSettings serviceLayerSettings = Optional.ofNullable(
171             service.getSettings().getLayerSettings().get(layer.getName()))
172         .orElseGet(GeoServiceLayerSettings::new);
173 
174     @SuppressModernizer
175     // not using Objects.requireNonNullElse(arg1, arg2) because we never want to throw an NPE here, we just want to
176     // check if the legendImageId is set in either the service layer settings or the default layer settings
177     String legendImageId = ObjectUtils.firstNonNull(
178         serviceLayerSettings.getLegendImageId(), defaultLayerSettings.getLegendImageId());
179 
180     UUID legendUuid = null;
181     if (legendImageId != null && !legendImageId.isBlank()) {
182       try {
183         legendUuid = UUID.fromString(legendImageId);
184       } catch (IllegalArgumentException ignored) {
185         // Invalid UUID configured; treat as "not attached" and fall back to the description check below.
186       }
187     }
188 
189     if (!id.equals(legendUuid)) {
190       // could be a bad request, but a legend could also be in the description, so check that as well
191       validateUploadIsInDescription(id, service, layer, application, appTreeLayerNode);
192     }
193   }
194 }