View Javadoc
1   /*
2    * Copyright (C) 2023 B3Partners B.V.
3    *
4    * SPDX-License-Identifier: MIT
5    */
6   package org.tailormap.api.persistence.helper;
7   
8   import static ch.rasc.sse.eventbus.SseEvent.DEFAULT_EVENT;
9   
10  import ch.rasc.sse.eventbus.SseEvent;
11  import ch.rasc.sse.eventbus.SseEventBus;
12  import java.io.IOException;
13  import java.lang.invoke.MethodHandles;
14  import java.net.URI;
15  import java.net.URISyntaxException;
16  import java.nio.charset.StandardCharsets;
17  import java.time.Instant;
18  import java.time.OffsetDateTime;
19  import java.time.ZoneId;
20  import java.util.ArrayList;
21  import java.util.List;
22  import java.util.Map;
23  import java.util.Objects;
24  import java.util.Optional;
25  import java.util.Set;
26  import java.util.function.Predicate;
27  import java.util.stream.Collectors;
28  import org.apache.commons.lang3.StringUtils;
29  import org.geotools.api.data.ServiceInfo;
30  import org.geotools.data.ows.AbstractOpenWebService;
31  import org.geotools.data.ows.Capabilities;
32  import org.geotools.data.ows.OperationType;
33  import org.geotools.http.HTTPClientFinder;
34  import org.geotools.ows.ServiceException;
35  import org.geotools.ows.wms.Layer;
36  import org.geotools.ows.wms.WMSCapabilities;
37  import org.geotools.ows.wms.WebMapServer;
38  import org.geotools.ows.wmts.WebMapTileServer;
39  import org.geotools.ows.wmts.model.WMTSLayer;
40  import org.geotools.xml.DocumentFactory;
41  import org.slf4j.Logger;
42  import org.slf4j.LoggerFactory;
43  import org.springframework.http.MediaType;
44  import org.springframework.stereotype.Service;
45  import org.springframework.web.util.UriComponentsBuilder;
46  import org.tailormap.api.admin.model.CapabilitiesLoadingEvent;
47  import org.tailormap.api.admin.model.ServerSentEvent;
48  import org.tailormap.api.configuration.TailormapConfig;
49  import org.tailormap.api.geotools.ResponseTeeingHTTPClient;
50  import org.tailormap.api.geotools.WMSServiceExceptionUtil;
51  import org.tailormap.api.persistence.GeoService;
52  import org.tailormap.api.persistence.json.GeoServiceLayer;
53  import org.tailormap.api.persistence.json.GeoServiceProtocol;
54  import org.tailormap.api.persistence.json.ServiceAuthentication;
55  import org.tailormap.api.persistence.json.TMServiceCapabilitiesRequest;
56  import org.tailormap.api.persistence.json.TMServiceCapabilitiesRequestGetFeatureInfo;
57  import org.tailormap.api.persistence.json.TMServiceCapabilitiesRequestGetMap;
58  import org.tailormap.api.persistence.json.TMServiceCaps;
59  import org.tailormap.api.persistence.json.TMServiceCapsCapabilities;
60  import org.tailormap.api.persistence.json.TMServiceInfo;
61  import org.tailormap.api.persistence.json.WMSStyle;
62  import org.tailormap.api.viewer.model.Service.ServerTypeEnum;
63  import tools.jackson.core.JacksonException;
64  import tools.jackson.databind.json.JsonMapper;
65  
66  @Service
67  public class GeoServiceHelper implements CapabilitiesLoadingProgressReporting {
68    private static final Logger logger =
69        LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
70    private final TailormapConfig tailormapConfig;
71    private final SseEventBus eventBus;
72    private final JsonMapper mapper;
73  
74    public GeoServiceHelper(TailormapConfig tailormapConfig, SseEventBus eventBus, JsonMapper mapper) {
75      this.tailormapConfig = tailormapConfig;
76      this.eventBus = eventBus;
77      this.mapper = mapper;
78    }
79  
80    public static ServerTypeEnum guessServerTypeFromUrl(String url) {
81  
82      if (StringUtils.isBlank(url)) {
83        return org.tailormap.api.viewer.model.Service.ServerTypeEnum.GENERIC;
84      }
85      if (url.contains("/arcgis/")) {
86        return org.tailormap.api.viewer.model.Service.ServerTypeEnum.GENERIC;
87      }
88      if (url.contains("/geoserver/")) {
89        return org.tailormap.api.viewer.model.Service.ServerTypeEnum.GEOSERVER;
90      }
91      if (url.contains("/mapserv")) { // /cgi-bin/mapserv, /cgi-bin/mapserv.cgi, /cgi-bin/mapserv.fcgi
92        return org.tailormap.api.viewer.model.Service.ServerTypeEnum.MAPSERVER;
93      }
94      return org.tailormap.api.viewer.model.Service.ServerTypeEnum.GENERIC;
95    }
96  
97    public static String getWmsRequest(String uri) {
98      return getWmsRequest(uri == null ? null : URI.create(uri));
99    }
100 
101   /**
102    * Extracts the value of the WMS "REQUEST" parameter (case-insensitive) from the given URI.
103    *
104    * @param uri the URI to extract the request parameter from
105    * @return the value of the request parameter, or null if not found
106    */
107   public static String getWmsRequest(URI uri) {
108     if (uri == null || uri.getQuery() == null) {
109       return null;
110     }
111     return UriComponentsBuilder.fromUri(uri).build().getQueryParams().entrySet().stream()
112         .filter(entry -> "request".equalsIgnoreCase(entry.getKey()))
113         .map(entry -> entry.getValue().getFirst())
114         .findFirst()
115         .orElse(null);
116   }
117 
118   public GeoService loadServiceCapabilities(GeoService geoService)
119       throws IOException, IllegalArgumentException, URISyntaxException, ServiceException,
120           UnsupportedOperationException {
121 
122     final Instant startedAt = Instant.now();
123     final OffsetDateTime startedAtOffset =
124         startedAt.atOffset(ZoneId.systemDefault().getRules().getOffset(startedAt));
125     CapabilitiesLoadingEvent event = new CapabilitiesLoadingEvent()
126         .startedAt(startedAtOffset)
127         .title(StringUtils.isNotBlank(geoService.getTitle()) ? geoService.getTitle() : geoService.getUrl())
128         .id(geoService.getId() != null ? geoService.getId() : null);
129 
130     if (geoService.getProtocol() == GeoServiceProtocol.XYZ) {
131       setXyzCapabilities(geoService);
132       return geoService;
133     }
134 
135     if (geoService.getProtocol() == GeoServiceProtocol.TILES3D) {
136       set3DTilesCapabilities(geoService);
137       return geoService;
138     }
139 
140     if (geoService.getProtocol() == GeoServiceProtocol.QUANTIZEDMESH) {
141       setQuantizedMeshCapabilities(geoService);
142       return geoService;
143     }
144 
145     ResponseTeeingHTTPClient client = new ResponseTeeingHTTPClient(
146         HTTPClientFinder.createClient(), null, Set.of("Access-Control-Allow-Origin"));
147 
148     ServiceAuthentication auth = geoService.getAuthentication();
149     if (auth != null && auth.getMethod() == ServiceAuthentication.MethodEnum.PASSWORD) {
150       client.setUser(auth.getUsername());
151       client.setPassword(auth.getPassword());
152     }
153 
154     // tailormap-api.timeout is in milliseconds, the GeoTools HTTPClient timeouts are in seconds
155     int timeoutSeconds = Math.max(1, Math.round(this.tailormapConfig.getTimeout() / 1000f));
156     client.setReadTimeout(timeoutSeconds);
157     client.setConnectTimeout(timeoutSeconds);
158     client.setTryGzip(true);
159 
160     logger.info(
161         "Get capabilities for {} {} from URL {}",
162         geoService.getProtocol(),
163         geoService.getId() == null ? "(new)" : "id " + geoService.getId(),
164         geoService.getUrl());
165 
166     reportCapabilitiesLoadingProgress(event.message("Getting capabilities for " + event.getTitle()));
167     // TODO: micrometer met tags voor URL/id van service
168 
169     switch (geoService.getProtocol()) {
170       case WMS -> loadWMSCapabilities(geoService, client, event);
171       case WMTS -> loadWMTSCapabilities(geoService, client, event);
172       default ->
173         throw new UnsupportedOperationException(
174             "Unsupported geo service protocol: " + geoService.getProtocol());
175     }
176 
177     if (geoService.getTitle() == null) {
178       geoService.setTitle(Optional.ofNullable(geoService.getServiceCapabilities())
179           .map(TMServiceCaps::getServiceInfo)
180           .map(TMServiceInfo::getTitle)
181           .orElse(null));
182     }
183 
184     if (logger.isDebugEnabled()) {
185       logger.debug("Loaded service layers: {}", geoService.getLayers());
186     } else {
187       logger.info(
188           "Loaded service layers: {}",
189           geoService.getLayers().stream()
190               .filter(Predicate.not(GeoServiceLayer::getVirtual))
191               .map(GeoServiceLayer::getName)
192               .collect(Collectors.toList()));
193     }
194     this.reportCapabilitiesLoadingProgress(event.message("Finished loading geoservice capabilities in "
195             + (Instant.now().toEpochMilli() - startedAt.toEpochMilli()) + " ms")
196         // total is not set for WMS/WMTS capabilities loading,
197         // so we just set it to progress (or 1) to indicate that we are done
198         .progress(event.getProgress() == null ? 1 : event.getProgress()));
199     return geoService;
200   }
201 
202   private static void setXyzCapabilities(GeoService geoService) {
203     geoService.setLayers(List.of(new GeoServiceLayer()
204         .id("0")
205         .root(true)
206         .name("xyz")
207         .title(geoService.getTitle())
208         .crs(Set.of(geoService.getSettings().getXyzCrs()))
209         .virtual(false)
210         .queryable(false)));
211   }
212 
213   private static void set3DTilesCapabilities(GeoService geoService) {
214     geoService.setLayers(List.of(new GeoServiceLayer()
215         .id("0")
216         .root(true)
217         .name("tiles3d")
218         .title(geoService.getTitle())
219         .virtual(false)
220         .queryable(false)));
221   }
222 
223   private static void setQuantizedMeshCapabilities(GeoService geoService) {
224     geoService.setLayers(List.of(new GeoServiceLayer()
225         .id("0")
226         .root(true)
227         .name("quantizedmesh")
228         .title(geoService.getTitle())
229         .virtual(false)
230         .queryable(false)));
231   }
232 
233   private void setServiceInfo(
234       GeoService geoService,
235       ResponseTeeingHTTPClient client,
236       AbstractOpenWebService<? extends Capabilities, Layer> ows) {
237     geoService.setCapabilities(client.getLatestResponseCopy());
238     geoService.setCapabilitiesContentType(MediaType.APPLICATION_XML_VALUE);
239     geoService.setCapabilitiesFetched(Instant.now());
240 
241     ServiceInfo info = ows.getInfo();
242 
243     TMServiceCaps caps = new TMServiceCaps();
244     geoService.setServiceCapabilities(caps);
245 
246     caps.setCorsAllowOrigin(client.getLatestResponse().getResponseHeader("Access-Control-Allow-Origin"));
247 
248     if (info != null) {
249       if (StringUtils.isBlank(geoService.getTitle())) {
250         geoService.setTitle(info.getTitle());
251       }
252 
253       caps.serviceInfo(new TMServiceInfo()
254           .keywords(info.getKeywords())
255           .description(info.getDescription())
256           .title(info.getTitle())
257           .publisher(info.getPublisher())
258           .schema(info.getSchema())
259           .source(info.getSource()));
260 
261       geoService.setAdvertisedUrl(info.getSource().toString());
262     } else if (ows.getCapabilities() != null && ows.getCapabilities().getService() != null) {
263       org.geotools.data.ows.Service service = ows.getCapabilities().getService();
264 
265       if (StringUtils.isBlank(geoService.getTitle())) {
266         geoService.setTitle(service.getTitle());
267       }
268       caps.setServiceInfo(new TMServiceInfo().keywords(Set.copyOf(List.of(service.getKeywordList()))));
269     }
270   }
271 
272   private GeoServiceLayer toGeoServiceLayer(Layer l, List<? extends Layer> layers) {
273     return new GeoServiceLayer()
274         .id(String.valueOf(layers.indexOf(l)))
275         .name(l.getName())
276         .root(l.getParent() == null)
277         .title(l.getTitle())
278         .maxScale(Double.isNaN(l.getScaleDenominatorMax()) ? null : l.getScaleDenominatorMax())
279         .minScale(Double.isNaN(l.getScaleDenominatorMin()) ? null : l.getScaleDenominatorMin())
280         .virtual(l.getName() == null)
281         .crs(l.getSrs())
282         .latLonBoundingBox(GeoToolsHelper.boundsFromCRSEnvelope(l.getLatLonBoundingBox()))
283         .styles(l.getStyles().stream()
284             .map(gtStyle -> {
285               WMSStyle style = new WMSStyle()
286                   .name(gtStyle.getName())
287                   .title(Optional.ofNullable(gtStyle.getTitle())
288                       .map(Objects::toString)
289                       .orElse(null))
290                   .abstractText(Optional.ofNullable(gtStyle.getAbstract())
291                       .map(Objects::toString)
292                       .orElse(null));
293               try {
294                 List<?> legendUrls = gtStyle.getLegendURLs();
295                 // GeoTools will replace invalid URLs with null in legendURLs
296                 if (legendUrls != null && !legendUrls.isEmpty() && legendUrls.getFirst() != null) {
297                   style.legendUrl(new URI((String) legendUrls.getFirst()));
298                 }
299               } catch (URISyntaxException ignored) {
300                 // Won't occur because GeoTools would have already returned null on
301                 // invalid URL
302               }
303               return style;
304             })
305             .collect(Collectors.toList()))
306         .queryable(l.isQueryable())
307         .abstractText(l.get_abstract())
308         .keywords(l.getKeywords() == null ? Set.of() : Set.copyOf(List.of(l.getKeywords())))
309         .children(l.getLayerChildren().stream()
310             .map(layers::indexOf)
311             .map(String::valueOf)
312             .collect(Collectors.toList()));
313   }
314 
315   private void addLayerRecursive(
316       GeoService geoService, List<? extends Layer> layers, Layer layer, Set<String> parentCrs) {
317     GeoServiceLayer geoServiceLayer = toGeoServiceLayer(layer, layers);
318     // Crses are inherited from the parent and this is applied by GeoTools so Layer.getSrs() has all
319     // supported crses, but to save space we reverse that by only saving new crses for child layers
320     // -- just like the original WMS capabilities.
321     geoServiceLayer.getCrs().removeAll(parentCrs);
322     geoService.getLayers().add(geoServiceLayer);
323     for (Layer l : layer.getLayerChildren()) {
324       addLayerRecursive(geoService, layers, l, layer.getSrs());
325     }
326   }
327 
328   private void loadWMSCapabilities(
329       GeoService geoService, ResponseTeeingHTTPClient client, CapabilitiesLoadingEvent event)
330       throws IOException, IllegalArgumentException, URISyntaxException, ServiceException,
331           UnsupportedOperationException {
332     WebMapServer wms;
333     try {
334       reportCapabilitiesLoadingProgress(
335           event.message("Loading WMS capabilities").progress(0));
336       wms = new WebMapServer(
337           new URI(geoService.getUrl()).toURL(),
338           client,
339           Map.of(
340               // allow DTD for WMS 1.1.x
341               DocumentFactory.ENABLE_DTD, true));
342     } catch (ClassCastException | IllegalStateException e) {
343       // The gt-wms module tries to cast the XML unmarshalling result expecting capabilities, but a
344       // WMS 1.0.0/1.1.0 ServiceException may have been unmarshalled which leads to a
345       // ClassCastException.
346 
347       // A WMS 1.3.0 ServiceExceptionReport leads to an IllegalStateException because of a call to
348       // Throwable.initCause() on a SAXException that already has a cause.
349       // In these cases, try to extract a message from the HTTP response
350       String contentType = client.getLatestResponse().getContentType();
351       if (contentType != null && contentType.contains("text/xml")) {
352         String wmsException =
353             WMSServiceExceptionUtil.tryGetServiceExceptionMessage(client.getLatestResponseCopy());
354         throw new IOException("Error loading WMS capabilities: "
355             + (wmsException != null
356                 ? wmsException
357                 : new String(client.getLatestResponseCopy(), StandardCharsets.UTF_8)));
358       } else {
359         throw e;
360       }
361     } catch (IOException e) {
362       // This tries to match a HttpURLConnection (which the default GeoTools SimpleHTTPClient uses)
363       // exception message. In a container environment the JVM is always in English so never
364       // localized.
365       if (e.getMessage().contains("Server returned HTTP response code: 401 for URL:")) {
366         throw new IOException(
367             "Error loading WMS, got 401 unauthorized response (credentials may be required or invalid)");
368       } else {
369         throw e;
370       }
371     }
372 
373     OperationType getMap = wms.getCapabilities().getRequest().getGetMap();
374     OperationType getFeatureInfo = wms.getCapabilities().getRequest().getGetFeatureInfo();
375 
376     if (getMap == null) {
377       throw new UnsupportedOperationException("Service does not support GetMap");
378     }
379 
380     setServiceInfo(geoService, client, wms);
381 
382     WMSCapabilities wmsCapabilities = wms.getCapabilities();
383 
384     // TODO Jackson annotations op GeoTools classes of iets anders slims?
385 
386     geoService
387         .getServiceCapabilities()
388         .capabilities(new TMServiceCapsCapabilities()
389             .version(wmsCapabilities.getVersion())
390             .updateSequence(wmsCapabilities.getUpdateSequence())
391             .abstractText(wmsCapabilities.getService().get_abstract())
392             .request(new TMServiceCapabilitiesRequest()
393                 .getMap(new TMServiceCapabilitiesRequestGetMap()
394                     .formats(Set.copyOf(getMap.getFormats())))
395                 .getFeatureInfo(
396                     getFeatureInfo == null
397                         ? null
398                         : new TMServiceCapabilitiesRequestGetFeatureInfo()
399                             .formats(Set.copyOf(getFeatureInfo.getFormats())))
400                 .describeLayer(
401                     wms.getCapabilities().getRequest().getDescribeLayer() != null)));
402 
403     if (logger.isDebugEnabled()) {
404       logger.debug("Loaded capabilities, service capabilities: {}", geoService.getServiceCapabilities());
405     } else {
406       logger.info(
407           "Loaded capabilities from \"{}\", title: \"{}\"",
408           geoService.getUrl(),
409           geoService.getServiceCapabilities() != null
410                   && geoService.getServiceCapabilities().getServiceInfo() != null
411               ? geoService
412                   .getServiceCapabilities()
413                   .getServiceInfo()
414                   .getTitle()
415               : "(none)");
416     }
417     reportCapabilitiesLoadingProgress(
418         event.message("Loaded WMS capabilities").progress(1));
419     geoService.setLayers(new ArrayList<>());
420     addLayerRecursive(
421         geoService,
422         wms.getCapabilities().getLayerList(),
423         wms.getCapabilities().getLayer(),
424         Set.of());
425   }
426 
427   private void loadWMTSCapabilities(
428       GeoService geoService, ResponseTeeingHTTPClient client, CapabilitiesLoadingEvent event)
429       throws ServiceException, URISyntaxException, IOException {
430     reportCapabilitiesLoadingProgress(
431         event.message("Loading WMTS capabilities").progress(0));
432     WebMapTileServer wmts = new WebMapTileServer(new URI(geoService.getUrl()).toURL(), client);
433     setServiceInfo(geoService, client, wmts);
434 
435     // TODO set capabilities if we need something from it
436 
437     List<WMTSLayer> layers = wmts.getCapabilities().getLayerList();
438     geoService.setLayers(
439         layers.stream().map(l -> toGeoServiceLayer(l, layers)).collect(Collectors.toList()));
440   }
441 
442   /**
443    * Try to extract the legend url from the styles of the layer. This works by getting all styles for the layer and
444    * then removing any styles attached to other (parent) layers from the list of all styles. What remains is/are the
445    * legend url(s) for the layer. <i>NOTE: when a layer has more than one -not an inherited style- style the first
446    * style is used.</i>
447    *
448    * @param service the service that has the layer
449    * @param serviceLayer the layer to get the legend url for
450    * @return a URI to the legend image or null if not found
451    */
452   public static URI getLayerLegendUrlFromStyles(GeoService service, GeoServiceLayer serviceLayer) {
453     if (serviceLayer.getRoot()) {
454       // if this is a root layer, there are no parent layers, return the first style we find for
455       // this layer, if any
456       return serviceLayer.getStyles().stream()
457           .findFirst()
458           .map(WMSStyle::getLegendUrl)
459           .orElse(null);
460     }
461 
462     // Work on a copy: the styles list belongs to the (persistent) GeoService entity and must not be modified
463     final List<WMSStyle> allOurLayersStyles = new ArrayList<>(serviceLayer.getStyles());
464     if (allOurLayersStyles.size() == 1) {
465       return allOurLayersStyles.getFirst().getLegendUrl();
466     }
467     // remove the styles from all the other layer(s) from the list of all our layers styles
468     service.getLayers().stream()
469         .filter(layer -> !layer.equals(serviceLayer))
470         .forEach(layer -> allOurLayersStyles.removeAll(layer.getStyles()));
471 
472     return allOurLayersStyles.stream()
473         .findFirst()
474         .map(WMSStyle::getLegendUrl)
475         .orElse(null);
476   }
477 
478   @Override
479   public void reportCapabilitiesLoadingProgress(CapabilitiesLoadingEvent event) {
480     ServerSentEvent serverSentEvent = new ServerSentEvent()
481         .eventType(ServerSentEvent.EventTypeEnum.CAPABILITIES_LOADING)
482         .details(event);
483     try {
484       if (this.eventBus.countSubscribers(DEFAULT_EVENT) == 0) {
485         return;
486       }
487       this.eventBus.handleEvent(SseEvent.of(DEFAULT_EVENT, mapper.writeValueAsString(serverSentEvent)));
488     } catch (JacksonException e) {
489       logger.error("Error publishing geoservice capabilities loading progress event", e);
490     }
491   }
492 }