source: josm/trunk/src/org/openstreetmap/josm/io/imagery/WMSImagery.java@ 18821

Last change on this file since 18821 was 18801, checked in by taylor.smock, 11 months ago

Fix #22832: Code cleanup and some simplification, documentation fixes (patch by gaben)

There should not be any functional changes in this patch; it is intended to do
the following:

  • Simplify and cleanup code (example: Arrays.asList(item) -> Collections.singletonList(item))
  • Fix typos in documentation (which also corrects the documentation to match what actually happens, in some cases)
  • Property svn:eol-style set to native
File size: 34.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io.imagery;
3
4import static java.nio.charset.StandardCharsets.UTF_8;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.io.File;
8import java.io.IOException;
9import java.io.InputStream;
10import java.net.MalformedURLException;
11import java.net.URL;
12import java.nio.file.InvalidPathException;
13import java.util.ArrayList;
14import java.util.Arrays;
15import java.util.Collection;
16import java.util.Collections;
17import java.util.HashSet;
18import java.util.List;
19import java.util.Map;
20import java.util.Set;
21import java.util.concurrent.ConcurrentHashMap;
22import java.util.function.UnaryOperator;
23import java.util.regex.Pattern;
24import java.util.stream.Collectors;
25
26import javax.imageio.ImageIO;
27import javax.xml.namespace.QName;
28import javax.xml.stream.XMLStreamException;
29import javax.xml.stream.XMLStreamReader;
30
31import org.openstreetmap.josm.data.Bounds;
32import org.openstreetmap.josm.data.coor.EastNorth;
33import org.openstreetmap.josm.data.imagery.DefaultLayer;
34import org.openstreetmap.josm.data.imagery.GetCapabilitiesParseHelper;
35import org.openstreetmap.josm.data.imagery.ImageryInfo;
36import org.openstreetmap.josm.data.imagery.LayerDetails;
37import org.openstreetmap.josm.data.projection.Projection;
38import org.openstreetmap.josm.data.projection.Projections;
39import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
40import org.openstreetmap.josm.gui.progress.ProgressMonitor;
41import org.openstreetmap.josm.io.CachedFile;
42import org.openstreetmap.josm.tools.Logging;
43import org.openstreetmap.josm.tools.Utils;
44
45/**
46 * This class represents the capabilities of a WMS imagery server.
47 */
48public class WMSImagery {
49
50 private static final String SERVICE_WMS = "SERVICE=WMS";
51 private static final String REQUEST_GET_CAPABILITIES = "REQUEST=GetCapabilities";
52 private static final String CAPABILITIES_QUERY_STRING = SERVICE_WMS + "&" + REQUEST_GET_CAPABILITIES;
53
54 /**
55 * WMS namespace address
56 */
57 public static final String WMS_NS_URL = "http://www.opengis.net/wms";
58
59 // CHECKSTYLE.OFF: SingleSpaceSeparator
60 // WMS 1.0 - 1.3.0
61 private static final QName CAPABILITIES_ROOT_130 = new QName(WMS_NS_URL, "WMS_Capabilities");
62 private static final QName QN_ABSTRACT = new QName(WMS_NS_URL, "Abstract");
63 private static final QName QN_CAPABILITY = new QName(WMS_NS_URL, "Capability");
64 private static final QName QN_CRS = new QName(WMS_NS_URL, "CRS");
65 private static final QName QN_DCPTYPE = new QName(WMS_NS_URL, "DCPType");
66 private static final QName QN_FORMAT = new QName(WMS_NS_URL, "Format");
67 private static final QName QN_GET = new QName(WMS_NS_URL, "Get");
68 private static final QName QN_GETMAP = new QName(WMS_NS_URL, "GetMap");
69 private static final QName QN_HTTP = new QName(WMS_NS_URL, "HTTP");
70 private static final QName QN_LAYER = new QName(WMS_NS_URL, "Layer");
71 private static final QName QN_NAME = new QName(WMS_NS_URL, "Name");
72 private static final QName QN_REQUEST = new QName(WMS_NS_URL, "Request");
73 private static final QName QN_SERVICE = new QName(WMS_NS_URL, "Service");
74 private static final QName QN_STYLE = new QName(WMS_NS_URL, "Style");
75 private static final QName QN_TITLE = new QName(WMS_NS_URL, "Title");
76 private static final QName QN_BOUNDINGBOX = new QName(WMS_NS_URL, "BoundingBox");
77 private static final QName QN_EX_GEOGRAPHIC_BBOX = new QName(WMS_NS_URL, "EX_GeographicBoundingBox");
78 private static final QName QN_WESTBOUNDLONGITUDE = new QName(WMS_NS_URL, "westBoundLongitude");
79 private static final QName QN_EASTBOUNDLONGITUDE = new QName(WMS_NS_URL, "eastBoundLongitude");
80 private static final QName QN_SOUTHBOUNDLATITUDE = new QName(WMS_NS_URL, "southBoundLatitude");
81 private static final QName QN_NORTHBOUNDLATITUDE = new QName(WMS_NS_URL, "northBoundLatitude");
82 private static final QName QN_ONLINE_RESOURCE = new QName(WMS_NS_URL, "OnlineResource");
83
84 // WMS 1.1 - 1.1.1
85 private static final QName CAPABILITIES_ROOT_111 = new QName("WMT_MS_Capabilities");
86 private static final QName QN_SRS = new QName("SRS");
87 private static final QName QN_LATLONBOUNDINGBOX = new QName("LatLonBoundingBox");
88
89 // CHECKSTYLE.ON: SingleSpaceSeparator
90
91 /**
92 * An exception that is thrown if there was an error while getting the capabilities of the WMS server.
93 */
94 public static class WMSGetCapabilitiesException extends Exception {
95 private final String incomingData;
96
97 /**
98 * Constructs a new {@code WMSGetCapabilitiesException}
99 * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method)
100 * @param incomingData the answer from WMS server
101 */
102 public WMSGetCapabilitiesException(Throwable cause, String incomingData) {
103 super(cause);
104 this.incomingData = incomingData;
105 }
106
107 /**
108 * Constructs a new {@code WMSGetCapabilitiesException}
109 * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method
110 * @param incomingData the answer from the server
111 * @since 10520
112 */
113 public WMSGetCapabilitiesException(String message, String incomingData) {
114 super(message);
115 this.incomingData = incomingData;
116 }
117
118 /**
119 * The data that caused this exception.
120 * @return The server response to the capabilities request.
121 */
122 public String getIncomingData() {
123 return incomingData;
124 }
125 }
126
127 private final Map<String, String> headers = new ConcurrentHashMap<>();
128 private String version = "1.1.1"; // default version
129 private String getMapUrl;
130 private URL capabilitiesUrl;
131 private final List<String> formats = new ArrayList<>();
132 private List<LayerDetails> layers = new ArrayList<>();
133
134 private String title;
135
136 /**
137 * Make getCapabilities request towards given URL
138 * @param url service url
139 * @throws IOException when connection error when fetching get capabilities document
140 * @throws WMSGetCapabilitiesException when there are errors when parsing get capabilities document
141 * @throws InvalidPathException if a Path object cannot be constructed for the capabilities cached file
142 */
143 public WMSImagery(String url) throws IOException, WMSGetCapabilitiesException {
144 this(url, null);
145 }
146
147 /**
148 * Make getCapabilities request towards given URL using headers
149 * @param url service url
150 * @param headers HTTP headers to be sent with request
151 * @throws IOException when connection error when fetching get capabilities document
152 * @throws WMSGetCapabilitiesException when there are errors when parsing get capabilities document
153 * @throws InvalidPathException if a Path object cannot be constructed for the capabilities cached file
154 */
155 public WMSImagery(String url, Map<String, String> headers) throws IOException, WMSGetCapabilitiesException {
156 this(url, headers, NullProgressMonitor.INSTANCE);
157 }
158
159 /**
160 * Make getCapabilities request towards given URL using headers
161 * @param url service url
162 * @param headers HTTP headers to be sent with request
163 * @param monitor Feedback for which URL we are currently trying, the integer is the <i>total number of urls</i> we are going to try
164 * @throws IOException when connection error when fetching get capabilities document
165 * @throws WMSGetCapabilitiesException when there are errors when parsing get capabilities document
166 * @throws InvalidPathException if a Path object cannot be constructed for the capabilities cached file
167 * @since xxx
168 */
169 public WMSImagery(String url, Map<String, String> headers, ProgressMonitor monitor)
170 throws IOException, WMSGetCapabilitiesException {
171 if (headers != null) {
172 this.headers.putAll(headers);
173 }
174
175 IOException savedExc = null;
176 String workingAddress = null;
177 final String[] baseAdditions = {
178 normalizeUrl(url),
179 url,
180 url + CAPABILITIES_QUERY_STRING,
181 };
182 final String[] versionAdditions = {"", "&VERSION=1.3.0", "&VERSION=1.1.1"};
183 final int totalNumberOfUrlsToTry = baseAdditions.length * versionAdditions.length;
184 monitor.setTicksCount(totalNumberOfUrlsToTry);
185 url_search:
186 for (String z : baseAdditions) {
187 for (String ver : versionAdditions) {
188 if (monitor.isCanceled()) {
189 break url_search;
190 }
191 try {
192 monitor.setCustomText(z + ver);
193 monitor.worked(1);
194 attemptGetCapabilities(z + ver);
195 workingAddress = z;
196 calculateChildren();
197 // clear saved exception - we've got something working
198 savedExc = null;
199 break url_search;
200 } catch (IOException e) {
201 savedExc = e;
202 Logging.warn(e);
203 }
204 }
205 }
206
207 if (workingAddress != null) {
208 try {
209 capabilitiesUrl = new URL(workingAddress);
210 } catch (MalformedURLException e) {
211 if (savedExc == null) {
212 savedExc = e;
213 }
214 try {
215 capabilitiesUrl = new File(workingAddress).toURI().toURL();
216 } catch (MalformedURLException e1) { // NOPMD
217 // do nothing, raise original exception
218 Logging.trace(e1);
219 }
220 }
221 }
222 if (savedExc != null) {
223 throw savedExc;
224 }
225 }
226
227 private void calculateChildren() {
228 Map<LayerDetails, List<LayerDetails>> layerChildren = layers.stream()
229 .filter(x -> x.getParent() != null) // exclude top-level elements
230 .collect(Collectors.groupingBy(LayerDetails::getParent));
231 for (LayerDetails ld: layers) {
232 if (layerChildren.containsKey(ld)) {
233 ld.setChildren(layerChildren.get(ld));
234 }
235 }
236 // leave only top-most elements in the list
237 layers = layers.stream().filter(x -> x.getParent() == null).collect(Collectors.toCollection(ArrayList::new));
238 }
239
240 /**
241 * Returns the list of top-level layers.
242 * @return the list of top-level layers
243 */
244 public List<LayerDetails> getLayers() {
245 return Collections.unmodifiableList(layers);
246 }
247
248 /**
249 * Returns the list of supported formats.
250 * @return the list of supported formats
251 */
252 public Collection<String> getFormats() {
253 return Collections.unmodifiableList(formats);
254 }
255
256 /**
257 * Gets the preferred format for this imagery layer.
258 * @return The preferred format as mime type.
259 */
260 public String getPreferredFormat() {
261 if (formats.contains("image/png")) {
262 return "image/png";
263 } else if (formats.contains("image/jpeg")) {
264 return "image/jpeg";
265 } else if (formats.isEmpty()) {
266 return null;
267 } else {
268 return formats.get(0);
269 }
270 }
271
272 /**
273 * Returns root URL of services in this GetCapabilities.
274 * @return root URL of services in this GetCapabilities
275 */
276 public String buildRootUrl() {
277 if (getMapUrl == null && capabilitiesUrl == null) {
278 return null;
279 }
280 if (getMapUrl != null) {
281 return getMapUrl;
282 }
283
284 URL serviceUrl = capabilitiesUrl;
285 StringBuilder a = new StringBuilder(serviceUrl.getProtocol());
286 a.append("://").append(serviceUrl.getHost());
287 if (serviceUrl.getPort() != -1) {
288 a.append(':').append(serviceUrl.getPort());
289 }
290 a.append(serviceUrl.getPath()).append('?');
291 if (serviceUrl.getQuery() != null) {
292 a.append(serviceUrl.getQuery());
293 if (!serviceUrl.getQuery().isEmpty() && !serviceUrl.getQuery().endsWith("&")) {
294 a.append('&');
295 }
296 }
297 return a.toString();
298 }
299
300 /**
301 * Returns root URL of services without the GetCapabilities call.
302 * @return root URL of services without the GetCapabilities call
303 * @since 15209
304 */
305 public String buildRootUrlWithoutCapabilities() {
306 return buildRootUrl()
307 .replace(CAPABILITIES_QUERY_STRING, "")
308 .replace(SERVICE_WMS, "")
309 .replace(REQUEST_GET_CAPABILITIES, "")
310 .replace("?&", "?");
311 }
312
313 /**
314 * Returns URL for accessing GetMap service. String will contain following parameters:
315 * * {proj} - that needs to be replaced with projection (one of {@link #getServerProjections(List)})
316 * * {width} - that needs to be replaced with width of the tile
317 * * {height} - that needs to be replaces with height of the tile
318 * * {bbox} - that needs to be replaced with area that should be fetched (in {proj} coordinates)
319 *
320 * Format of the response will be calculated using {@link #getPreferredFormat()}
321 *
322 * @param selectedLayers list of DefaultLayer selection of layers to be shown
323 * @param transparent whether returned images should contain transparent pixels (if supported by format)
324 * @return URL template for GetMap service containing
325 */
326 public String buildGetMapUrl(List<DefaultLayer> selectedLayers, boolean transparent) {
327 return buildGetMapUrl(
328 getLayers(selectedLayers),
329 selectedLayers.stream().map(DefaultLayer::getStyle).collect(Collectors.toList()),
330 transparent);
331 }
332
333 /**
334 * Returns URL for accessing GetMap service. String will contain following parameters:
335 * * {proj} - that needs to be replaced with projection (one of {@link #getServerProjections(List)})
336 * * {width} - that needs to be replaced with width of the tile
337 * * {height} - that needs to be replaces with height of the tile
338 * * {bbox} - that needs to be replaced with area that should be fetched (in {proj} coordinates)
339 *
340 * Format of the response will be calculated using {@link #getPreferredFormat()}
341 *
342 * @param selectedLayers selected layers as subset of the tree returned by {@link #getLayers()}
343 * @param selectedStyles selected styles for all selectedLayers
344 * @param transparent whether returned images should contain transparent pixels (if supported by format)
345 * @return URL template for GetMap service
346 * @see #buildGetMapUrl(List, boolean)
347 */
348 public String buildGetMapUrl(List<LayerDetails> selectedLayers, List<String> selectedStyles, boolean transparent) {
349 return buildGetMapUrl(selectedLayers, selectedStyles, getPreferredFormat(), transparent);
350 }
351
352 /**
353 * Returns URL for accessing GetMap service. String will contain following parameters:
354 * * {proj} - that needs to be replaced with projection (one of {@link #getServerProjections(List)})
355 * * {width} - that needs to be replaced with width of the tile
356 * * {height} - that needs to be replaces with height of the tile
357 * * {bbox} - that needs to be replaced with area that should be fetched (in {proj} coordinates)
358 *
359 * @param selectedLayers selected layers as subset of the tree returned by {@link #getLayers()}
360 * @param selectedStyles selected styles for all selectedLayers
361 * @param format format of the response - one of {@link #getFormats()}
362 * @param transparent whether returned images should contain transparent pixels (if supported by format)
363 * @return URL template for GetMap service
364 * @see #buildGetMapUrl(List, boolean)
365 * @since 15228
366 */
367 public String buildGetMapUrl(List<LayerDetails> selectedLayers, List<String> selectedStyles, String format, boolean transparent) {
368 return buildGetMapUrl(
369 selectedLayers.stream().map(LayerDetails::getName).collect(Collectors.toList()),
370 selectedStyles,
371 format,
372 transparent);
373 }
374
375 /**
376 * Returns URL for accessing GetMap service. String will contain following parameters:
377 * * {proj} - that needs to be replaced with projection (one of {@link #getServerProjections(List)})
378 * * {width} - that needs to be replaced with width of the tile
379 * * {height} - that needs to be replaces with height of the tile
380 * * {bbox} - that needs to be replaced with area that should be fetched (in {proj} coordinates)
381 *
382 * @param selectedLayers selected layers as list of strings
383 * @param selectedStyles selected styles of layers as list of strings
384 * @param format format of the response - one of {@link #getFormats()}
385 * @param transparent whether returned images should contain transparent pixels (if supported by format)
386 * @return URL template for GetMap service
387 * @see #buildGetMapUrl(List, boolean)
388 */
389 public String buildGetMapUrl(List<String> selectedLayers,
390 Collection<String> selectedStyles,
391 String format,
392 boolean transparent) {
393
394 Utils.ensure(selectedStyles == null || selectedLayers.size() == selectedStyles.size(),
395 tr("Styles size {0} does not match layers size {1}"),
396 selectedStyles == null ? 0 : selectedStyles.size(),
397 selectedLayers.size());
398
399 return buildRootUrlWithoutCapabilities()
400 + "FORMAT=" + format + ((imageFormatHasTransparency(format) && transparent) ? "&TRANSPARENT=TRUE" : "")
401 + "&VERSION=" + this.version + "&" + SERVICE_WMS + "&REQUEST=GetMap&LAYERS="
402 + String.join(",", selectedLayers)
403 + "&STYLES="
404 + (selectedStyles != null ? String.join(",", selectedStyles) : "")
405 + "&"
406 + (belowWMS130() ? "SRS" : "CRS")
407 + "={proj}&WIDTH={width}&HEIGHT={height}&BBOX={bbox}";
408 }
409
410 private boolean tagEquals(QName a, QName b) {
411 boolean ret = a.equals(b);
412 if (ret) {
413 return ret;
414 }
415
416 if (belowWMS130()) {
417 return a.getLocalPart().equals(b.getLocalPart());
418 }
419
420 return false;
421 }
422
423 private void attemptGetCapabilities(String url) throws IOException, WMSGetCapabilitiesException {
424 Logging.debug("Trying WMS GetCapabilities with url {0}", url);
425 try (CachedFile cf = new CachedFile(url); InputStream in = cf.setHttpHeaders(headers).
426 setMaxAge(7 * CachedFile.DAYS).
427 setCachingStrategy(CachedFile.CachingStrategy.IfModifiedSince).
428 getInputStream()) {
429
430 try {
431 XMLStreamReader reader = GetCapabilitiesParseHelper.getReader(in);
432 for (int event = reader.getEventType(); reader.hasNext(); event = reader.next()) {
433 if (event == XMLStreamReader.START_ELEMENT) {
434 if (tagEquals(CAPABILITIES_ROOT_111, reader.getName())) {
435 this.version = Utils.firstNotEmptyString("1.1.1",
436 reader.getAttributeValue(null, "version"));
437 }
438 if (tagEquals(CAPABILITIES_ROOT_130, reader.getName())) {
439 this.version = Utils.firstNotEmptyString("1.3.0",
440 reader.getAttributeValue(WMS_NS_URL, "version"),
441 reader.getAttributeValue(null, "version"));
442 }
443 if (tagEquals(QN_SERVICE, reader.getName())) {
444 parseService(reader);
445 }
446
447 if (tagEquals(QN_CAPABILITY, reader.getName())) {
448 parseCapability(reader);
449 }
450 }
451 }
452 } catch (XMLStreamException e) {
453 String content = new String(cf.getByteContent(), UTF_8);
454 cf.clear(); // if there is a problem with parsing of the file, remove it from the cache
455 throw new WMSGetCapabilitiesException(e, content);
456 }
457 }
458 }
459
460 private void parseService(XMLStreamReader reader) throws XMLStreamException {
461 if (GetCapabilitiesParseHelper.moveReaderToTag(reader, this::tagEquals, QN_TITLE)) {
462 this.title = reader.getElementText();
463 // CHECKSTYLE.OFF: EmptyBlock
464 for (int event = reader.getEventType();
465 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && tagEquals(QN_SERVICE, reader.getName()));
466 event = reader.next()) {
467 // empty loop, just move reader to the end of Service tag, if moveReaderToTag return false, it's already done
468 }
469 // CHECKSTYLE.ON: EmptyBlock
470 }
471 }
472
473 private void parseCapability(XMLStreamReader reader) throws XMLStreamException {
474 for (int event = reader.getEventType();
475 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && tagEquals(QN_CAPABILITY, reader.getName()));
476 event = reader.next()) {
477
478 if (event == XMLStreamReader.START_ELEMENT) {
479 if (tagEquals(QN_REQUEST, reader.getName())) {
480 parseRequest(reader);
481 }
482 if (tagEquals(QN_LAYER, reader.getName())) {
483 parseLayer(reader, null);
484 }
485 }
486 }
487 }
488
489 private void parseRequest(XMLStreamReader reader) throws XMLStreamException {
490 String mode = "";
491 String getMapUrl = "";
492 if (GetCapabilitiesParseHelper.moveReaderToTag(reader, this::tagEquals, QN_GETMAP)) {
493 for (int event = reader.getEventType();
494 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && tagEquals(QN_GETMAP, reader.getName()));
495 event = reader.next()) {
496
497 if (event == XMLStreamReader.START_ELEMENT) {
498 if (tagEquals(QN_FORMAT, reader.getName())) {
499 String value = reader.getElementText();
500 if (isImageFormatSupportedWarn(value) && !this.formats.contains(value)) {
501 this.formats.add(value);
502 }
503 }
504 if (tagEquals(QN_DCPTYPE, reader.getName()) && GetCapabilitiesParseHelper.moveReaderToTag(reader,
505 this::tagEquals, QN_HTTP, QN_GET)) {
506 mode = reader.getName().getLocalPart();
507 if (GetCapabilitiesParseHelper.moveReaderToTag(reader, this::tagEquals, QN_ONLINE_RESOURCE)) {
508 getMapUrl = reader.getAttributeValue(GetCapabilitiesParseHelper.XLINK_NS_URL, "href");
509 }
510 // TODO should we handle also POST?
511 if ("GET".equalsIgnoreCase(mode) && getMapUrl != null && !getMapUrl.isEmpty()) {
512 try {
513 String query = new URL(getMapUrl).getQuery();
514 if (query == null) {
515 this.getMapUrl = getMapUrl + "?";
516 } else {
517 this.getMapUrl = getMapUrl;
518 }
519 } catch (MalformedURLException e) {
520 throw new XMLStreamException(e);
521 }
522 }
523 }
524 }
525 }
526 }
527 }
528
529 private void parseLayer(XMLStreamReader reader, LayerDetails parentLayer) throws XMLStreamException {
530 LayerDetails ret = new LayerDetails(parentLayer);
531 for (int event = reader.next(); // start with advancing reader by one element to get the contents of the layer
532 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && tagEquals(QN_LAYER, reader.getName()));
533 event = reader.next()) {
534
535 if (event == XMLStreamReader.START_ELEMENT) {
536 if (tagEquals(QN_NAME, reader.getName())) {
537 ret.setName(reader.getElementText());
538 } else if (tagEquals(QN_ABSTRACT, reader.getName())) {
539 ret.setAbstract(GetCapabilitiesParseHelper.getElementTextWithSubtags(reader));
540 } else if (tagEquals(QN_TITLE, reader.getName())) {
541 ret.setTitle(reader.getElementText());
542 } else if (tagEquals(QN_CRS, reader.getName())) {
543 ret.addCrs(reader.getElementText());
544 } else if (tagEquals(QN_SRS, reader.getName()) && belowWMS130()) {
545 ret.addCrs(reader.getElementText());
546 } else if (tagEquals(QN_STYLE, reader.getName())) {
547 parseAndAddStyle(reader, ret);
548 } else if (tagEquals(QN_LAYER, reader.getName())) {
549 parseLayer(reader, ret);
550 } else if (tagEquals(QN_EX_GEOGRAPHIC_BBOX, reader.getName()) && ret.getBounds() == null) {
551 ret.setBounds(parseExGeographic(reader));
552 } else if (tagEquals(QN_BOUNDINGBOX, reader.getName())) {
553 Projection conv;
554 if (belowWMS130()) {
555 conv = Projections.getProjectionByCode(reader.getAttributeValue(WMS_NS_URL, "SRS"));
556 } else {
557 conv = Projections.getProjectionByCode(reader.getAttributeValue(WMS_NS_URL, "CRS"));
558 }
559 if (ret.getBounds() == null && conv != null) {
560 ret.setBounds(parseBoundingBox(reader, conv));
561 }
562 } else if (tagEquals(QN_LATLONBOUNDINGBOX, reader.getName()) && belowWMS130() && ret.getBounds() == null) {
563 ret.setBounds(parseBoundingBox(reader, null));
564 } else {
565 // unknown tag, move to its end as it may have child elements
566 GetCapabilitiesParseHelper.moveReaderToEndCurrentTag(reader);
567 }
568 }
569 }
570 this.layers.add(ret);
571 }
572
573 /**
574 * Determines if this service operates at protocol level below WMS 1.3.0
575 * @return if this service operates at protocol level below 1.3.0
576 */
577 public boolean belowWMS130() {
578 return "1.1.1".equals(version) || "1.1".equals(version) || "1.0".equals(version);
579 }
580
581 private void parseAndAddStyle(XMLStreamReader reader, LayerDetails ld) throws XMLStreamException {
582 String name = null;
583 String title = null;
584 for (int event = reader.getEventType();
585 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && tagEquals(QN_STYLE, reader.getName()));
586 event = reader.next()) {
587 if (event == XMLStreamReader.START_ELEMENT) {
588 if (tagEquals(QN_NAME, reader.getName())) {
589 name = reader.getElementText();
590 }
591 if (tagEquals(QN_TITLE, reader.getName())) {
592 title = reader.getElementText();
593 }
594 }
595 }
596 if (name == null) {
597 name = "";
598 }
599 ld.addStyle(name, title);
600 }
601
602 private Bounds parseExGeographic(XMLStreamReader reader) throws XMLStreamException {
603 String minx = null, maxx = null, maxy = null, miny = null;
604
605 for (int event = reader.getEventType();
606 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && tagEquals(QN_EX_GEOGRAPHIC_BBOX, reader.getName()));
607 event = reader.next()) {
608 if (event == XMLStreamReader.START_ELEMENT) {
609 if (tagEquals(QN_WESTBOUNDLONGITUDE, reader.getName())) {
610 minx = reader.getElementText();
611 }
612
613 if (tagEquals(QN_EASTBOUNDLONGITUDE, reader.getName())) {
614 maxx = reader.getElementText();
615 }
616
617 if (tagEquals(QN_SOUTHBOUNDLATITUDE, reader.getName())) {
618 miny = reader.getElementText();
619 }
620
621 if (tagEquals(QN_NORTHBOUNDLATITUDE, reader.getName())) {
622 maxy = reader.getElementText();
623 }
624 }
625 }
626 return parseBBox(null, miny, minx, maxy, maxx);
627 }
628
629 private Bounds parseBoundingBox(XMLStreamReader reader, Projection conv) {
630 UnaryOperator<String> attrGetter = tag -> belowWMS130() ?
631 reader.getAttributeValue(null, tag)
632 : reader.getAttributeValue(WMS_NS_URL, tag);
633
634 return parseBBox(
635 conv,
636 attrGetter.apply("miny"),
637 attrGetter.apply("minx"),
638 attrGetter.apply("maxy"),
639 attrGetter.apply("maxx")
640 );
641 }
642
643 private static Bounds parseBBox(Projection conv, String miny, String minx, String maxy, String maxx) {
644 if (miny == null || minx == null || maxy == null || maxx == null || Arrays.asList(miny, minx, maxy, maxx).contains("nan")) {
645 return null;
646 }
647 if (conv != null) {
648 return new Bounds(
649 conv.eastNorth2latlon(new EastNorth(getDecimalDegree(minx), getDecimalDegree(miny))),
650 conv.eastNorth2latlon(new EastNorth(getDecimalDegree(maxx), getDecimalDegree(maxy)))
651 );
652 }
653 return new Bounds(
654 getDecimalDegree(miny),
655 getDecimalDegree(minx),
656 getDecimalDegree(maxy),
657 getDecimalDegree(maxx)
658 );
659 }
660
661 private static double getDecimalDegree(String value) {
662 // Some real-world WMS servers use a comma instead of a dot as decimal separator (seen in Polish WMS server)
663 return Double.parseDouble(value.replace(',', '.'));
664 }
665
666 private static String normalizeUrl(String serviceUrlStr) throws MalformedURLException {
667 URL getCapabilitiesUrl = null;
668 String ret = null;
669
670 if (!Pattern.compile(".*GetCapabilities.*", Pattern.CASE_INSENSITIVE).matcher(serviceUrlStr).matches()) {
671 // If the url doesn't already have GetCapabilities, add it in
672 getCapabilitiesUrl = new URL(serviceUrlStr);
673 if (getCapabilitiesUrl.getQuery() == null) {
674 ret = serviceUrlStr + '?' + CAPABILITIES_QUERY_STRING;
675 } else if (!getCapabilitiesUrl.getQuery().isEmpty() && !getCapabilitiesUrl.getQuery().endsWith("&")) {
676 ret = serviceUrlStr + '&' + CAPABILITIES_QUERY_STRING;
677 } else {
678 ret = serviceUrlStr + CAPABILITIES_QUERY_STRING;
679 }
680 } else {
681 // Otherwise assume it's a good URL and let the subsequent error
682 // handling systems deal with problems
683 ret = serviceUrlStr;
684 }
685 return ret;
686 }
687
688 private static boolean isImageFormatSupportedWarn(String format) {
689 boolean isFormatSupported = isImageFormatSupported(format);
690 if (!isFormatSupported) {
691 Logging.info("Skipping unsupported image format {0}", format);
692 }
693 return isFormatSupported;
694 }
695
696 static boolean isImageFormatSupported(final String format) {
697 return ImageIO.getImageReadersByMIMEType(format).hasNext()
698 // handles image/tiff image/tiff8 image/geotiff image/geotiff8
699 || isImageFormatSupported(format, "tiff", "geotiff")
700 || isImageFormatSupported(format, "png")
701 || isImageFormatSupported(format, "svg")
702 || isImageFormatSupported(format, "bmp");
703 }
704
705 static boolean isImageFormatSupported(String format, String... mimeFormats) {
706 for (String mime : mimeFormats) {
707 if (format.startsWith("image/" + mime)) {
708 return ImageIO.getImageReadersBySuffix(mimeFormats[0]).hasNext();
709 }
710 }
711 return false;
712 }
713
714 static boolean imageFormatHasTransparency(final String format) {
715 return format != null && (format.startsWith("image/png") || format.startsWith("image/gif")
716 || format.startsWith("image/svg") || format.startsWith("image/tiff"));
717 }
718
719 /**
720 * Creates ImageryInfo object from this GetCapabilities document
721 *
722 * @param name name of imagery layer
723 * @param selectedLayers layers which are to be used by this imagery layer
724 * @param selectedStyles styles that should be used for selectedLayers
725 * @param format format of the response - one of {@link #getFormats()}
726 * @param transparent if layer should be transparent
727 * @return ImageryInfo object
728 * @since 15228
729 */
730 public ImageryInfo toImageryInfo(
731 String name, List<LayerDetails> selectedLayers, List<String> selectedStyles, String format, boolean transparent) {
732 ImageryInfo i = new ImageryInfo(name, buildGetMapUrl(selectedLayers, selectedStyles, format, transparent));
733 if (!selectedLayers.isEmpty()) {
734 i.setServerProjections(getServerProjections(selectedLayers));
735 }
736 return i;
737 }
738
739 /**
740 * Returns projections that server supports for provided list of layers. This will be intersection of projections
741 * defined for each layer
742 *
743 * @param selectedLayers list of layers
744 * @return projection code
745 */
746 public Collection<String> getServerProjections(List<LayerDetails> selectedLayers) {
747 if (selectedLayers.isEmpty()) {
748 return Collections.emptyList();
749 }
750 Set<String> proj = new HashSet<>(selectedLayers.get(0).getCrs());
751
752 // set intersect with all layers
753 for (LayerDetails ld: selectedLayers) {
754 proj.retainAll(ld.getCrs());
755 }
756 return proj;
757 }
758
759 /**
760 * Returns collection of LayerDetails specified by defaultLayers.
761 * @param defaultLayers default layers that should select layer object
762 * @return collection of LayerDetails specified by defaultLayers
763 */
764 public List<LayerDetails> getLayers(List<DefaultLayer> defaultLayers) {
765 Collection<String> layerNames = defaultLayers.stream().map(DefaultLayer::getLayerName).collect(Collectors.toList());
766 return layers.stream()
767 .flatMap(LayerDetails::flattened)
768 .filter(x -> layerNames.contains(x.getName()))
769 .collect(Collectors.toList());
770 }
771
772 /**
773 * Returns title of this service.
774 * @return title of this service
775 */
776 public String getTitle() {
777 return title;
778 }
779}
Note: See TracBrowser for help on using the repository browser.