1
2
3
4
5
6 package org.tailormap.api.persistence.helper;
7
8 import static java.util.stream.Collectors.toSet;
9 import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
10 import static org.tailormap.api.persistence.helper.GeoServiceHelper.getWmsRequest;
11 import static org.tailormap.api.persistence.json.GeoServiceProtocol.LEGEND;
12 import static org.tailormap.api.persistence.json.GeoServiceProtocol.QUANTIZEDMESH;
13 import static org.tailormap.api.persistence.json.GeoServiceProtocol.TILES3D;
14 import static org.tailormap.api.persistence.json.GeoServiceProtocol.XYZ;
15 import static org.tailormap.api.util.TMStringUtils.nullIfEmpty;
16
17 import jakarta.persistence.EntityManager;
18 import java.lang.invoke.MethodHandles;
19 import java.net.URI;
20 import java.nio.charset.StandardCharsets;
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Objects;
25 import java.util.Optional;
26 import java.util.Set;
27 import java.util.stream.Collectors;
28 import org.apache.commons.lang3.ObjectUtils;
29 import org.gaul.modernizer_maven_annotations.SuppressModernizer;
30 import org.geotools.api.referencing.crs.CoordinateReferenceSystem;
31 import org.geotools.referencing.util.CRSUtilities;
32 import org.geotools.referencing.wkt.Formattable;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.springframework.stereotype.Service;
36 import org.springframework.transaction.annotation.Transactional;
37 import org.springframework.web.util.UriComponentsBuilder;
38 import org.springframework.web.util.UriUtils;
39 import org.tailormap.api.controller.GeoServiceProxyController;
40 import org.tailormap.api.persistence.Application;
41 import org.tailormap.api.persistence.Configuration;
42 import org.tailormap.api.persistence.GeoService;
43 import org.tailormap.api.persistence.SearchIndex;
44 import org.tailormap.api.persistence.TMFeatureType;
45 import org.tailormap.api.persistence.json.AppContent;
46 import org.tailormap.api.persistence.json.AppLayerSettings;
47 import org.tailormap.api.persistence.json.AppTreeLayerNode;
48 import org.tailormap.api.persistence.json.AppTreeLevelNode;
49 import org.tailormap.api.persistence.json.AppTreeNode;
50 import org.tailormap.api.persistence.json.Bounds;
51 import org.tailormap.api.persistence.json.GeoServiceDefaultLayerSettings;
52 import org.tailormap.api.persistence.json.GeoServiceLayer;
53 import org.tailormap.api.persistence.json.GeoServiceLayerSettings;
54 import org.tailormap.api.persistence.json.ServicePublishingSettings;
55 import org.tailormap.api.persistence.json.TileLayerHiDpiMode;
56 import org.tailormap.api.persistence.json.WMSStyle;
57 import org.tailormap.api.repository.ApplicationRepository;
58 import org.tailormap.api.repository.ConfigurationRepository;
59 import org.tailormap.api.repository.FeatureSourceRepository;
60 import org.tailormap.api.repository.GeoServiceRepository;
61 import org.tailormap.api.repository.SearchIndexRepository;
62 import org.tailormap.api.security.AuthorisationService;
63 import org.tailormap.api.service.UploadsService;
64 import org.tailormap.api.viewer.model.AppLayer;
65 import org.tailormap.api.viewer.model.LayerSearchIndex;
66 import org.tailormap.api.viewer.model.LayerTreeNode;
67 import org.tailormap.api.viewer.model.MapResponse;
68 import org.tailormap.api.viewer.model.TMCoordinateReferenceSystem;
69
70 @Service
71 public class ApplicationHelper {
72 private static final Logger logger =
73 LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
74 private static final String DEFAULT_WEB_MERCATOR_CRS = "EPSG:3857";
75
76 private final GeoServiceHelper geoServiceHelper;
77 private final GeoServiceRepository geoServiceRepository;
78 private final ConfigurationRepository configurationRepository;
79 private final ApplicationRepository applicationRepository;
80 private final FeatureSourceRepository featureSourceRepository;
81 private final EntityManager entityManager;
82 private final AuthorisationService authorisationService;
83 private final SearchIndexRepository searchIndexRepository;
84 private final UploadsService uploadsService;
85
86 public ApplicationHelper(
87 GeoServiceHelper geoServiceHelper,
88 GeoServiceRepository geoServiceRepository,
89 ConfigurationRepository configurationRepository,
90 ApplicationRepository applicationRepository,
91 FeatureSourceRepository featureSourceRepository,
92 EntityManager entityManager,
93 AuthorisationService authorisationService,
94 SearchIndexRepository searchIndexRepository,
95 UploadsService uploadsService) {
96 this.geoServiceHelper = geoServiceHelper;
97 this.geoServiceRepository = geoServiceRepository;
98 this.configurationRepository = configurationRepository;
99 this.applicationRepository = applicationRepository;
100 this.featureSourceRepository = featureSourceRepository;
101 this.entityManager = entityManager;
102 this.authorisationService = authorisationService;
103 this.searchIndexRepository = searchIndexRepository;
104 this.uploadsService = uploadsService;
105 }
106
107 public Application getServiceApplication(String baseAppName, String projection, GeoService service) {
108 if (baseAppName == null) {
109 baseAppName = Optional.ofNullable(service.getSettings().getPublishing())
110 .map(ServicePublishingSettings::getBaseApp)
111 .orElseGet(() -> configurationRepository.get(Configuration.DEFAULT_BASE_APP));
112 }
113
114 Application baseApp = null;
115 if (baseAppName != null) {
116 baseApp = applicationRepository.findByName(baseAppName);
117 if (baseApp != null) {
118
119
120 entityManager.detach(baseApp);
121 }
122 }
123
124 Application app = baseApp != null ? baseApp : new Application().setContentRoot(new AppContent());
125
126 if (projection != null) {
127
128 throw new UnsupportedOperationException("Projection filtering not yet supported");
129 } else {
130 if (baseApp != null) {
131 projection = baseApp.getCrs();
132 } else {
133 projection = DEFAULT_WEB_MERCATOR_CRS;
134 }
135 }
136
137 app.setName(service.getId()).setTitle(service.getTitle()).setCrs(projection);
138
139 return app;
140 }
141
142 @Transactional
143 public MapResponse toMapResponse(Application app) {
144 MapResponse mapResponse = new MapResponse();
145 setCrsAndBounds(app, mapResponse);
146 setLayers(app, mapResponse);
147 return mapResponse;
148 }
149
150 public void setCrsAndBounds(Application a, MapResponse mapResponse) {
151 CoordinateReferenceSystem gtCrs = a.getGeoToolsCoordinateReferenceSystem();
152 if (gtCrs == null) {
153 throw new IllegalArgumentException("Invalid CRS: " + a.getCrs());
154 }
155
156 TMCoordinateReferenceSystem crs = new TMCoordinateReferenceSystem()
157 .code(a.getCrs())
158 .definition(((Formattable) gtCrs).toWKT(0))
159 .bounds(GeoToolsHelper.fromCRS(gtCrs))
160 .unit(Optional.ofNullable(CRSUtilities.getUnit(gtCrs.getCoordinateSystem()))
161 .map(Objects::toString)
162 .orElse(null));
163
164 Bounds maxExtent = a.getMaxExtent() != null ? a.getMaxExtent() : crs.getBounds();
165 Bounds initialExtent = a.getInitialExtent() != null ? a.getInitialExtent() : maxExtent;
166
167 mapResponse.crs(crs).maxExtent(maxExtent).initialExtent(initialExtent);
168 }
169
170 private void setLayers(Application app, MapResponse mr) {
171 new MapResponseLayerBuilder(app, mr).buildLayers();
172 }
173
174 private String getProxyUrl(GeoService geoService, Application application, AppTreeLayerNode appTreeLayerNode) {
175 String baseProxyUrl = linkTo(
176 GeoServiceProxyController.class,
177 Map.of(
178 "viewerKind", "app",
179 "viewerName", application.getName(),
180 "appLayerId", appTreeLayerNode.getId()))
181 .toString();
182
183 String protocolPath = "/" + geoService.getProtocol().getValue();
184
185 if (geoService.getProtocol() == TILES3D) {
186 return baseProxyUrl + protocolPath + "/" + GeoServiceProxyController.TILES3D_DESCRIPTION_PATH;
187 }
188 return baseProxyUrl + protocolPath;
189 }
190
191 private String getLegendProxyUrl(Application application, AppTreeLayerNode appTreeLayerNode) {
192 return linkTo(
193 GeoServiceProxyController.class,
194 Map.of(
195 "viewerKind",
196 "app",
197 "viewerName",
198 application.getName(),
199 "appLayerId",
200 appTreeLayerNode.getId()))
201 + "/" + LEGEND.getValue();
202 }
203
204 private List<WMSStyle> getProxiedLegendStyles(
205 Application application, AppTreeLayerNode appTreeLayerNode, List<WMSStyle> legendStyles) {
206 String legendProxyUrl = getLegendProxyUrl(application, appTreeLayerNode);
207 return legendStyles.stream()
208 .map(style -> {
209 try {
210
211 return new WMSStyle()
212 .name(style.getName())
213 .title(style.getTitle())
214 .abstractText(style.getAbstractText())
215 .legendUrl(UriComponentsBuilder.fromUriString(legendProxyUrl)
216 .queryParam("STYLE", UriUtils.encode(style.getName(), StandardCharsets.UTF_8))
217 .build(true)
218 .toUri());
219 } catch (Exception e) {
220 logger.warn(
221 "Failed to create proxied legend style for application {} layer {} style {}: {}",
222 application.getId(),
223 appTreeLayerNode.getId(),
224 style.getName(),
225 e.getMessage());
226 return null;
227 }
228 })
229 .filter(Objects::nonNull)
230 .toList();
231 }
232
233 private class MapResponseLayerBuilder {
234 private final Application app;
235 private final MapResponse mapResponse;
236
237 private final Map<GeoServiceLayer, String> serviceLayerServiceIds = new HashMap<>();
238
239 MapResponseLayerBuilder(Application app, MapResponse mapResponse) {
240 this.app = app;
241 this.mapResponse = mapResponse;
242 }
243
244 void buildLayers() {
245 if (app.getContentRoot() != null) {
246 buildBackgroundLayers();
247 buildOverlayLayers();
248 buildTerrainLayers();
249 }
250 }
251
252 private void buildBackgroundLayers() {
253 if (app.getContentRoot().getBaseLayerNodes() != null) {
254 for (AppTreeNode node : app.getContentRoot().getBaseLayerNodes()) {
255 addAppTreeNodeItem(node, mapResponse.getBaseLayerTreeNodes());
256 }
257
258 Set<String> validLayerIds =
259 mapResponse.getAppLayers().stream().map(AppLayer::getId).collect(toSet());
260 List<LayerTreeNode> initialLayerTreeNodes = mapResponse.getBaseLayerTreeNodes();
261
262 mapResponse.setBaseLayerTreeNodes(cleanLayerTreeNodes(validLayerIds, initialLayerTreeNodes));
263 }
264 }
265
266 private void buildOverlayLayers() {
267 if (app.getContentRoot().getLayerNodes() != null) {
268 for (AppTreeNode node : app.getContentRoot().getLayerNodes()) {
269 addAppTreeNodeItem(node, mapResponse.getLayerTreeNodes());
270 }
271 Set<String> validLayerIds =
272 mapResponse.getAppLayers().stream().map(AppLayer::getId).collect(toSet());
273 List<LayerTreeNode> initialLayerTreeNodes = mapResponse.getLayerTreeNodes();
274
275 mapResponse.setLayerTreeNodes(cleanLayerTreeNodes(validLayerIds, initialLayerTreeNodes));
276 }
277 }
278
279
280
281
282
283
284
285
286
287 private List<LayerTreeNode> cleanLayerTreeNodes(
288 Set<String> validLayerIds, List<LayerTreeNode> initialLayerTreeNodes) {
289 List<String> levelNodes = initialLayerTreeNodes.stream()
290 .filter(n -> n.getAppLayerId() == null)
291 .map(LayerTreeNode::getId)
292 .toList();
293
294 List<LayerTreeNode> newLayerTreeNodes = initialLayerTreeNodes.stream()
295 .peek(n -> {
296 n.getChildrenIds()
297 .removeIf(childId ->
298
299 !validLayerIds.contains(childId) && !levelNodes.contains(childId));
300 })
301 .filter(n ->
302
303 !(n.getAppLayerId() == null
304 && (n.getChildrenIds() != null
305 && n.getChildrenIds().isEmpty())))
306 .toList();
307
308 List<String> cleanLevelNodeIds = newLayerTreeNodes.stream()
309 .filter(n -> n.getAppLayerId() == null)
310 .map(LayerTreeNode::getId)
311 .toList();
312
313 return newLayerTreeNodes.stream()
314 .peek(n -> {
315 n.getChildrenIds()
316 .removeIf(childId ->
317
318 !cleanLevelNodeIds.contains(childId) && levelNodes.contains(childId));
319 })
320 .toList();
321 }
322
323 private void buildTerrainLayers() {
324 if (app.getContentRoot().getTerrainLayerNodes() != null) {
325 for (AppTreeNode node : app.getContentRoot().getTerrainLayerNodes()) {
326 addAppTreeNodeItem(node, mapResponse.getTerrainLayerTreeNodes());
327 }
328 }
329 }
330
331 private void addAppTreeNodeItem(AppTreeNode node, List<LayerTreeNode> layerTreeNodeList) {
332 LayerTreeNode layerTreeNode = new LayerTreeNode();
333 if ("AppTreeLayerNode".equals(node.getObjectType())) {
334 AppTreeLayerNode appTreeLayerNode = (AppTreeLayerNode) node;
335 layerTreeNode.setId(appTreeLayerNode.getId());
336 layerTreeNode.setAppLayerId(appTreeLayerNode.getId());
337 if (!addAppLayerItem(appTreeLayerNode)) {
338 return;
339 }
340
341 layerTreeNode.setName(appTreeLayerNode.getLayerName());
342 layerTreeNode.setDescription(appTreeLayerNode.getDescription());
343 } else if ("AppTreeLevelNode".equals(node.getObjectType())) {
344 AppTreeLevelNode appTreeLevelNode = (AppTreeLevelNode) node;
345 layerTreeNode.setId(appTreeLevelNode.getId());
346 layerTreeNode.setChildrenIds(appTreeLevelNode.getChildrenIds());
347 layerTreeNode.setRoot(Boolean.TRUE.equals(appTreeLevelNode.getRoot()));
348
349 layerTreeNode.setName(appTreeLevelNode.getTitle());
350 layerTreeNode.setDescription(appTreeLevelNode.getDescription());
351 layerTreeNode.setExpandOnStartup(appTreeLevelNode.getExpandOnStartup());
352 }
353 layerTreeNodeList.add(layerTreeNode);
354 }
355
356 private boolean addAppLayerItem(AppTreeLayerNode layerRef) {
357 ServiceLayerInfo layerInfo = findServiceLayer(layerRef);
358 if (layerInfo == null) {
359 return false;
360 }
361 GeoService service = layerInfo.service();
362 GeoServiceLayer serviceLayer = layerInfo.serviceLayer();
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378 GeoServiceDefaultLayerSettings defaultLayerSettings = Optional.ofNullable(
379 service.getSettings().getDefaultLayerSettings())
380 .orElseGet(GeoServiceDefaultLayerSettings::new);
381 GeoServiceLayerSettings serviceLayerSettings =
382 Optional.ofNullable(layerInfo.layerSettings()).orElseGet(GeoServiceLayerSettings::new);
383
384 AppLayerSettings appLayerSettings = app.getAppLayerSettings(layerRef);
385
386 String title = Objects.requireNonNullElse(
387 nullIfEmpty(appLayerSettings.getTitle()),
388
389
390 service.getTitleWithSettingsOverrides(layerRef.getLayerName()));
391
392
393 @SuppressModernizer
394 String description = ObjectUtils.firstNonNull(
395 nullIfEmpty(appLayerSettings.getDescription()),
396 nullIfEmpty(serviceLayerSettings.getDescription()),
397 nullIfEmpty(defaultLayerSettings.getDescription()),
398 nullIfEmpty(serviceLayer.getAbstractText()));
399 description = uploadsService.replaceUploadLinks(app, layerRef.getId(), description);
400
401 @SuppressModernizer
402 String attribution = ObjectUtils.firstNonNull(
403 nullIfEmpty(appLayerSettings.getAttribution()),
404 nullIfEmpty(serviceLayerSettings.getAttribution()),
405 nullIfEmpty(defaultLayerSettings.getAttribution()));
406
407
408
409 @SuppressModernizer
410 boolean tilingDisabled = ObjectUtils.firstNonNull(
411 serviceLayerSettings.getTilingDisabled(), defaultLayerSettings.getTilingDisabled(), true);
412 @SuppressModernizer
413 Integer tilingGutter = ObjectUtils.firstNonNull(
414 serviceLayerSettings.getTilingGutter(), defaultLayerSettings.getTilingGutter(), 0);
415 @SuppressModernizer
416 boolean hiDpiDisabled = ObjectUtils.firstNonNull(
417 serviceLayerSettings.getHiDpiDisabled(), defaultLayerSettings.getHiDpiDisabled(), true);
418 @SuppressModernizer
419 TileLayerHiDpiMode hiDpiMode = ObjectUtils.firstNonNull(
420 serviceLayerSettings.getHiDpiMode(), defaultLayerSettings.getHiDpiMode(), null);
421
422 String hiDpiSubstituteLayer = serviceLayerSettings.getHiDpiSubstituteLayer();
423
424 TMFeatureType tmft = service.findFeatureTypeForLayer(serviceLayer, featureSourceRepository);
425
426 boolean proxied = service.getSettings().getUseProxy();
427
428 String legendImageUrl = serviceLayerSettings.getLegendImageId();
429 AppLayer.LegendTypeEnum legendType = AppLayer.LegendTypeEnum.STATIC;
430
431 if (legendImageUrl == null && serviceLayer.getStyles() != null) {
432
433 legendImageUrl = Optional.ofNullable(
434 GeoServiceHelper.getLayerLegendUrlFromStyles(service, serviceLayer))
435 .map(URI::toString)
436 .orElse(null);
437
438 if (legendImageUrl != null) {
439
440
441 legendType = "GetLegendGraphic".equalsIgnoreCase(getWmsRequest(legendImageUrl))
442 ? AppLayer.LegendTypeEnum.DYNAMIC
443 : AppLayer.LegendTypeEnum.STATIC;
444
445 if (proxied) {
446
447 legendImageUrl = getLegendProxyUrl(app, layerRef);
448 }
449 }
450 }
451
452 List<WMSStyle> legendStyles = appLayerSettings.getSelectedStyles();
453 if (proxied && legendStyles != null) {
454
455
456 legendStyles = getProxiedLegendStyles(app, layerRef, legendStyles);
457 }
458
459 SearchIndex searchIndex = null;
460 if (appLayerSettings.getSearchIndexId() != null) {
461 searchIndex = searchIndexRepository
462 .findById(appLayerSettings.getSearchIndexId())
463 .orElse(null);
464 }
465
466 boolean webMercatorAvailable = this.isWebMercatorAvailable(service, serviceLayer, hiDpiSubstituteLayer);
467
468 Set<String> keywords = serviceLayer.getKeywords().stream()
469 .filter(k -> !serviceLayerSettings.getHiddenKeywords().contains(k))
470 .collect(Collectors.toSet());
471 keywords.addAll(serviceLayerSettings.getExtraKeywords());
472
473 mapResponse.addAppLayersItem(new AppLayer()
474 .id(layerRef.getId())
475 .serviceId(serviceLayerServiceIds.get(serviceLayer))
476 .layerName(layerRef.getLayerName())
477 .hasAttributes(tmft != null)
478 .editable(TMFeatureTypeHelper.isEditable(app, layerRef, tmft))
479 .url(proxied ? getProxyUrl(service, app, layerRef) : null)
480
481
482 .maxScale(serviceLayer.getMaxScale())
483 .minScale(serviceLayer.getMinScale())
484 .title(title)
485 .tilingDisabled(tilingDisabled)
486 .tilingGutter(tilingGutter)
487 .hiDpiDisabled(hiDpiDisabled)
488 .hiDpiMode(hiDpiMode)
489 .hiDpiSubstituteLayer(hiDpiSubstituteLayer)
490 .minZoom(serviceLayerSettings.getMinZoom())
491 .maxZoom(serviceLayerSettings.getMaxZoom())
492 .tileSize(serviceLayerSettings.getTileSize())
493 .tileGridExtent(serviceLayerSettings.getTileGridExtent())
494 .opacity(appLayerSettings.getOpacity())
495 .autoRefreshInSeconds(appLayerSettings.getAutoRefreshInSeconds())
496 .searchIndex(
497 searchIndex != null
498 ? new LayerSearchIndex()
499 .id(searchIndex.getId())
500 .name(searchIndex.getName())
501 : null)
502 .legendImageUrl(legendImageUrl)
503 .legendType(legendType)
504 .visible(layerRef.getVisible())
505 .attribution(attribution)
506 .description(description)
507 .keywords(keywords)
508 .webMercatorAvailable(webMercatorAvailable)
509 .tileset3dStyle(appLayerSettings.getTileset3dStyle())
510 .hiddenFunctionality(appLayerSettings.getHiddenFunctionality())
511 .styles(legendStyles));
512
513 return true;
514 }
515
516 private ServiceLayerInfo findServiceLayer(AppTreeLayerNode layerRef) {
517 GeoService service =
518 geoServiceRepository.findById(layerRef.getServiceId()).orElse(null);
519 if (service == null) {
520 logger.warn(
521 "App {} references layer \"{}\" of missing service {}",
522 app.getId(),
523 layerRef.getLayerName(),
524 layerRef.getServiceId());
525 return null;
526 }
527
528 if (!authorisationService.userAllowedToViewGeoService(service)) {
529 return null;
530 }
531
532 GeoServiceLayer serviceLayer = service.findLayer(layerRef.getLayerName());
533
534 if (serviceLayer == null) {
535 logger.warn(
536 "App {} references layer \"{}\" not found in capabilities of service {}",
537 app.getId(),
538 layerRef.getLayerName(),
539 service.getId());
540 return null;
541 }
542
543 if (!authorisationService.userAllowedToViewGeoServiceLayer(service, serviceLayer)) {
544 logger.debug(
545 "User not allowed to view layer {} of service {}", serviceLayer.getName(), service.getId());
546 return null;
547 }
548
549 serviceLayerServiceIds.put(serviceLayer, service.getId());
550
551 if (mapResponse.getServices().stream()
552 .filter(s -> s.getId().equals(service.getId()))
553 .findAny()
554 .isEmpty()) {
555 mapResponse.addServicesItem(service.toJsonPojo(geoServiceHelper));
556 }
557
558 GeoServiceLayerSettings layerSettings = service.getLayerSettings(layerRef.getLayerName());
559 return new ServiceLayerInfo(service, serviceLayer, layerSettings);
560 }
561
562 private boolean isWebMercatorAvailable(
563 GeoService service, GeoServiceLayer serviceLayer, String hiDpiSubstituteLayer) {
564 if (service.getProtocol() == XYZ) {
565 return DEFAULT_WEB_MERCATOR_CRS.equals(service.getSettings().getXyzCrs());
566 }
567 if (service.getProtocol() == TILES3D || service.getProtocol() == QUANTIZEDMESH) {
568 return false;
569 }
570 if (hiDpiSubstituteLayer != null) {
571 GeoServiceLayer hiDpiSubstituteServiceLayer = service.findLayer(hiDpiSubstituteLayer);
572 if (hiDpiSubstituteServiceLayer != null
573 && !this.isWebMercatorAvailable(service, hiDpiSubstituteServiceLayer, null)) {
574 return false;
575 }
576 }
577 while (serviceLayer != null) {
578 Set<String> layerCrs = serviceLayer.getCrs();
579 if (layerCrs.contains(DEFAULT_WEB_MERCATOR_CRS)) {
580 return true;
581 }
582 if (serviceLayer.getRoot()) {
583 break;
584 }
585 serviceLayer = service.getParentLayer(serviceLayer.getId());
586 }
587 return false;
588 }
589
590 record ServiceLayerInfo(
591 GeoService service, GeoServiceLayer serviceLayer, GeoServiceLayerSettings layerSettings) {}
592 }
593 }