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

Last change on this file since 12475 was 12475, checked in by Don-vip, 7 years ago

see #15012 - checkstyle + javadoc

  • Property svn:eol-style set to native
File size: 18.5 KB
RevLine 
[5617]1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io.imagery;
3
4import java.awt.HeadlessException;
5import java.io.IOException;
6import java.io.StringReader;
7import java.net.MalformedURLException;
8import java.net.URL;
[6000]9import java.util.ArrayList;
[5617]10import java.util.Collection;
[6930]11import java.util.Collections;
[5617]12import java.util.HashSet;
[10612]13import java.util.Iterator;
[5617]14import java.util.List;
[8404]15import java.util.Locale;
[10612]16import java.util.NoSuchElementException;
[5617]17import java.util.Set;
18import java.util.regex.Pattern;
[10612]19import java.util.stream.Collectors;
20import java.util.stream.Stream;
21import java.util.stream.StreamSupport;
[5731]22
[6930]23import javax.imageio.ImageIO;
[5617]24import javax.xml.parsers.DocumentBuilder;
[10212]25import javax.xml.parsers.ParserConfigurationException;
[5731]26
[6248]27import org.openstreetmap.josm.Main;
[5617]28import org.openstreetmap.josm.data.Bounds;
29import org.openstreetmap.josm.data.imagery.ImageryInfo;
[9107]30import org.openstreetmap.josm.data.projection.Projections;
[9171]31import org.openstreetmap.josm.tools.HttpClient;
[5617]32import org.openstreetmap.josm.tools.Utils;
33import org.w3c.dom.Document;
34import org.w3c.dom.Element;
35import org.w3c.dom.Node;
36import org.w3c.dom.NodeList;
37import org.xml.sax.InputSource;
38import org.xml.sax.SAXException;
39
[10612]40/**
41 * This class represents the capabilites of a WMS imagery server.
42 */
[5617]43public class WMSImagery {
44
[10612]45 private static final class ChildIterator implements Iterator<Element> {
46 private Element child;
47
48 ChildIterator(Element parent) {
49 child = advanceToElement(parent.getFirstChild());
50 }
51
52 private static Element advanceToElement(Node firstChild) {
53 Node node = firstChild;
54 while (node != null && !(node instanceof Element)) {
55 node = node.getNextSibling();
56 }
57 return (Element) node;
58 }
59
60 @Override
61 public boolean hasNext() {
62 return child != null;
63 }
64
65 @Override
66 public Element next() {
67 if (!hasNext()) {
68 throw new NoSuchElementException("No next sibling.");
69 }
70 Element next = child;
71 child = advanceToElement(child.getNextSibling());
72 return next;
73 }
74 }
75
76 /**
77 * An exception that is thrown if there was an error while getting the capabilities of the WMS server.
78 */
[5617]79 public static class WMSGetCapabilitiesException extends Exception {
80 private final String incomingData;
81
[10520]82 /**
83 * Constructs a new {@code WMSGetCapabilitiesException}
84 * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method)
85 * @param incomingData the answer from WMS server
86 */
[5617]87 public WMSGetCapabilitiesException(Throwable cause, String incomingData) {
88 super(cause);
89 this.incomingData = incomingData;
90 }
91
[10520]92 /**
93 * Constructs a new {@code WMSGetCapabilitiesException}
94 * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method
95 * @param incomingData the answer from the server
96 * @since 10520
97 */
98 public WMSGetCapabilitiesException(String message, String incomingData) {
99 super(message);
100 this.incomingData = incomingData;
101 }
102
103 /**
[10612]104 * The data that caused this exception.
105 * @return The server response to the capabilites request.
[10520]106 */
[5617]107 public String getIncomingData() {
108 return incomingData;
109 }
110 }
111
112 private List<LayerDetails> layers;
113 private URL serviceUrl;
[6000]114 private List<String> formats;
[5617]115
[10216]116 /**
117 * Returns the list of layers.
118 * @return the list of layers
119 */
[5617]120 public List<LayerDetails> getLayers() {
[10612]121 return Collections.unmodifiableList(layers);
[5617]122 }
123
[10216]124 /**
125 * Returns the service URL.
126 * @return the service URL
127 */
[5617]128 public URL getServiceUrl() {
129 return serviceUrl;
130 }
131
[10216]132 /**
133 * Returns the list of supported formats.
134 * @return the list of supported formats
135 */
[6000]136 public List<String> getFormats() {
[6930]137 return Collections.unmodifiableList(formats);
[6000]138 }
139
[10612]140 /**
141 * Gets the preffered format for this imagery layer.
142 * @return The preffered format as mime type.
143 */
[6930]144 public String getPreferredFormats() {
[10612]145 if (formats.contains("image/jpeg")) {
146 return "image/jpeg";
147 } else if (formats.contains("image/png")) {
148 return "image/png";
149 } else if (formats.isEmpty()) {
150 return null;
151 } else {
152 return formats.get(0);
153 }
[6930]154 }
155
[5617]156 String buildRootUrl() {
[5731]157 if (serviceUrl == null) {
[6070]158 return null;
[5731]159 }
[5617]160 StringBuilder a = new StringBuilder(serviceUrl.getProtocol());
[8390]161 a.append("://").append(serviceUrl.getHost());
[5617]162 if (serviceUrl.getPort() != -1) {
[8390]163 a.append(':').append(serviceUrl.getPort());
[5617]164 }
[8390]165 a.append(serviceUrl.getPath()).append('?');
[5617]166 if (serviceUrl.getQuery() != null) {
167 a.append(serviceUrl.getQuery());
168 if (!serviceUrl.getQuery().isEmpty() && !serviceUrl.getQuery().endsWith("&")) {
[8390]169 a.append('&');
[5617]170 }
171 }
172 return a.toString();
173 }
174
[12475]175 /**
176 * Returns the URL for the "GetMap" WMS request in JPEG format.
177 * @param selectedLayers the list of selected layers, matching the "LAYERS" WMS request argument
178 * @return the URL for the "GetMap" WMS request
179 */
[5617]180 public String buildGetMapUrl(Collection<LayerDetails> selectedLayers) {
[6000]181 return buildGetMapUrl(selectedLayers, "image/jpeg");
182 }
183
[12475]184 /**
185 * Returns the URL for the "GetMap" WMS request.
186 * @param selectedLayers the list of selected layers, matching the "LAYERS" WMS request argument
187 * @param format the requested image format, matching the "FORMAT" WMS request argument
188 * @return the URL for the "GetMap" WMS request
189 */
[6000]190 public String buildGetMapUrl(Collection<LayerDetails> selectedLayers, String format) {
[10612]191 return buildRootUrl() + "FORMAT=" + format + (imageFormatHasTransparency(format) ? "&TRANSPARENT=TRUE" : "")
[7175]192 + "&VERSION=1.1.1&SERVICE=WMS&REQUEST=GetMap&LAYERS="
[10638]193 + selectedLayers.stream().map(x -> x.ident).collect(Collectors.joining(","))
[5617]194 + "&STYLES=&SRS={proj}&WIDTH={width}&HEIGHT={height}&BBOX={bbox}";
195 }
196
[12475]197 /**
198 * Attempts WMS "GetCapabilities" request and initializes internal variables if successful.
199 * @param serviceUrlStr WMS service URL
200 * @throws IOException if any I/O errors occurs
201 * @throws WMSGetCapabilitiesException if the WMS server replies a ServiceException
202 */
[10612]203 public void attemptGetCapabilities(String serviceUrlStr) throws IOException, WMSGetCapabilitiesException {
[5617]204 URL getCapabilitiesUrl = null;
205 try {
206 if (!Pattern.compile(".*GetCapabilities.*", Pattern.CASE_INSENSITIVE).matcher(serviceUrlStr).matches()) {
207 // If the url doesn't already have GetCapabilities, add it in
208 getCapabilitiesUrl = new URL(serviceUrlStr);
209 final String getCapabilitiesQuery = "VERSION=1.1.1&SERVICE=WMS&REQUEST=GetCapabilities";
210 if (getCapabilitiesUrl.getQuery() == null) {
[8846]211 getCapabilitiesUrl = new URL(serviceUrlStr + '?' + getCapabilitiesQuery);
[5617]212 } else if (!getCapabilitiesUrl.getQuery().isEmpty() && !getCapabilitiesUrl.getQuery().endsWith("&")) {
[8846]213 getCapabilitiesUrl = new URL(serviceUrlStr + '&' + getCapabilitiesQuery);
[5617]214 } else {
215 getCapabilitiesUrl = new URL(serviceUrlStr + getCapabilitiesQuery);
216 }
217 } else {
218 // Otherwise assume it's a good URL and let the subsequent error
219 // handling systems deal with problems
220 getCapabilitiesUrl = new URL(serviceUrlStr);
221 }
222 serviceUrl = new URL(serviceUrlStr);
223 } catch (HeadlessException e) {
[10612]224 Main.warn(e);
[5617]225 return;
226 }
227
[9171]228 final String incomingData = HttpClient.create(getCapabilitiesUrl).connect().fetchContent();
[7175]229 Main.debug("Server response to Capabilities request:");
230 Main.debug(incomingData);
[5617]231
232 try {
[10404]233 DocumentBuilder builder = Utils.newSafeDOMBuilder();
[10615]234 builder.setEntityResolver((publicId, systemId) -> {
235 Main.info("Ignoring DTD " + publicId + ", " + systemId);
236 return new InputSource(new StringReader(""));
[5617]237 });
[10212]238 Document document = builder.parse(new InputSource(new StringReader(incomingData)));
[10520]239 Element root = document.getDocumentElement();
[5617]240
[10520]241 // Check if the request resulted in ServiceException
242 if ("ServiceException".equals(root.getTagName())) {
243 throw new WMSGetCapabilitiesException(root.getTextContent(), incomingData);
244 }
245
[5617]246 // Some WMS service URLs specify a different base URL for their GetMap service
[10520]247 Element child = getChild(root, "Capability");
[5617]248 child = getChild(child, "Request");
249 child = getChild(child, "GetMap");
[6000]250
[10612]251 formats = getChildrenStream(child, "Format")
[10717]252 .map(Node::getTextContent)
[10612]253 .filter(WMSImagery::isImageFormatSupportedWarn)
254 .collect(Collectors.toList());
[6000]255
[5617]256 child = getChild(child, "DCPType");
257 child = getChild(child, "HTTP");
258 child = getChild(child, "Get");
259 child = getChild(child, "OnlineResource");
260 if (child != null) {
261 String baseURL = child.getAttribute("xlink:href");
[11381]262 if (!baseURL.equals(serviceUrlStr)) {
[6248]263 Main.info("GetCapabilities specifies a different service URL: " + baseURL);
[5617]264 serviceUrl = new URL(baseURL);
265 }
266 }
267
[10520]268 Element capabilityElem = getChild(root, "Capability");
[5617]269 List<Element> children = getChildren(capabilityElem, "Layer");
270 layers = parseLayers(children, new HashSet<String>());
[10212]271 } catch (MalformedURLException | ParserConfigurationException | SAXException e) {
[5617]272 throw new WMSGetCapabilitiesException(e, incomingData);
273 }
274 }
275
[10612]276 private static boolean isImageFormatSupportedWarn(String format) {
277 boolean isFormatSupported = isImageFormatSupported(format);
278 if (!isFormatSupported) {
279 Main.info("Skipping unsupported image format {0}", format);
280 }
281 return isFormatSupported;
282 }
283
[6930]284 static boolean isImageFormatSupported(final String format) {
285 return ImageIO.getImageReadersByMIMEType(format).hasNext()
[8509]286 // handles image/tiff image/tiff8 image/geotiff image/geotiff8
[11587]287 || isImageFormatSupported(format, "tiff", "geotiff")
288 || isImageFormatSupported(format, "png")
289 || isImageFormatSupported(format, "svg")
290 || isImageFormatSupported(format, "bmp");
[6930]291 }
[7221]292
[11747]293 static boolean isImageFormatSupported(String format, String... mimeFormats) {
[11587]294 for (String mime : mimeFormats) {
295 if (format.startsWith("image/" + mime)) {
296 return ImageIO.getImageReadersBySuffix(mimeFormats[0]).hasNext();
297 }
298 }
299 return false;
300 }
301
[7175]302 static boolean imageFormatHasTransparency(final String format) {
[7221]303 return format != null && (format.startsWith("image/png") || format.startsWith("image/gif")
304 || format.startsWith("image/svg") || format.startsWith("image/tiff"));
[7175]305 }
[6930]306
[12475]307 /**
308 * Returns a new {@code ImageryInfo} describing the given service name and selected WMS layers.
309 * @param name service name
310 * @param selectedLayers selected WMS layers
311 * @return a new {@code ImageryInfo} describing the given service name and selected WMS layers
312 */
[5617]313 public ImageryInfo toImageryInfo(String name, Collection<LayerDetails> selectedLayers) {
314 ImageryInfo i = new ImageryInfo(name, buildGetMapUrl(selectedLayers));
315 if (selectedLayers != null) {
[8338]316 Set<String> proj = new HashSet<>();
[5617]317 for (WMSImagery.LayerDetails l : selectedLayers) {
318 proj.addAll(l.getProjections());
319 }
320 i.setServerProjections(proj);
321 }
322 return i;
323 }
324
325 private List<LayerDetails> parseLayers(List<Element> children, Set<String> parentCrs) {
[7005]326 List<LayerDetails> details = new ArrayList<>(children.size());
[5617]327 for (Element element : children) {
328 details.add(parseLayer(element, parentCrs));
329 }
330 return details;
331 }
332
333 private LayerDetails parseLayer(Element element, Set<String> parentCrs) {
334 String name = getChildContent(element, "Title", null, null);
335 String ident = getChildContent(element, "Name", null, null);
336
337 // The set of supported CRS/SRS for this layer
[7005]338 Set<String> crsList = new HashSet<>();
[5617]339 // ...including this layer's already-parsed parent projections
340 crsList.addAll(parentCrs);
341
342 // Parse the CRS/SRS pulled out of this layer's XML element
343 // I think CRS and SRS are the same at this point
[10612]344 getChildrenStream(element)
345 .filter(child -> "CRS".equals(child.getNodeName()) || "SRS".equals(child.getNodeName()))
346 .map(child -> (String) getContent(child))
347 .filter(crs -> !crs.isEmpty())
348 .map(crs -> crs.trim().toUpperCase(Locale.ENGLISH))
349 .forEach(crsList::add);
[5617]350
351 // Check to see if any of the specified projections are supported by JOSM
352 boolean josmSupportsThisLayer = false;
353 for (String crs : crsList) {
354 josmSupportsThisLayer |= isProjSupported(crs);
355 }
356
357 Bounds bounds = null;
358 Element bboxElem = getChild(element, "EX_GeographicBoundingBox");
359 if (bboxElem != null) {
360 // Attempt to use EX_GeographicBoundingBox for bounding box
361 double left = Double.parseDouble(getChildContent(bboxElem, "westBoundLongitude", null, null));
362 double top = Double.parseDouble(getChildContent(bboxElem, "northBoundLatitude", null, null));
363 double right = Double.parseDouble(getChildContent(bboxElem, "eastBoundLongitude", null, null));
364 double bot = Double.parseDouble(getChildContent(bboxElem, "southBoundLatitude", null, null));
365 bounds = new Bounds(bot, left, top, right);
366 } else {
367 // If that's not available, try LatLonBoundingBox
368 bboxElem = getChild(element, "LatLonBoundingBox");
369 if (bboxElem != null) {
[12475]370 double left = getDecimalDegree(bboxElem, "minx");
[12469]371 double top = getDecimalDegree(bboxElem, "maxy");
372 double right = getDecimalDegree(bboxElem, "maxx");
373 double bot = getDecimalDegree(bboxElem, "miny");
[5617]374 bounds = new Bounds(bot, left, top, right);
375 }
376 }
377
378 List<Element> layerChildren = getChildren(element, "Layer");
379 List<LayerDetails> childLayers = parseLayers(layerChildren, crsList);
380
381 return new LayerDetails(name, ident, crsList, josmSupportsThisLayer, bounds, childLayers);
382 }
383
[12469]384 private static double getDecimalDegree(Element elem, String attr) {
385 // Some real-world WMS servers use a comma instead of a dot as decimal separator (seen in Polish WMS server)
386 return Double.parseDouble(elem.getAttribute(attr).replace(',', '.'));
387 }
388
[8870]389 private static boolean isProjSupported(String crs) {
[9107]390 return Projections.getProjectionByCode(crs) != null;
[5617]391 }
392
393 private static String getChildContent(Element parent, String name, String missing, String empty) {
394 Element child = getChild(parent, name);
395 if (child == null)
396 return missing;
397 else {
398 String content = (String) getContent(child);
[6289]399 return (!content.isEmpty()) ? content : empty;
[5617]400 }
401 }
402
403 private static Object getContent(Element element) {
404 NodeList nl = element.getChildNodes();
405 StringBuilder content = new StringBuilder();
406 for (int i = 0; i < nl.getLength(); i++) {
407 Node node = nl.item(i);
408 switch (node.getNodeType()) {
409 case Node.ELEMENT_NODE:
410 return node;
411 case Node.CDATA_SECTION_NODE:
412 case Node.TEXT_NODE:
413 content.append(node.getNodeValue());
414 break;
[10216]415 default: // Do nothing
[5617]416 }
417 }
418 return content.toString().trim();
419 }
420
[10612]421 private static Stream<Element> getChildrenStream(Element parent) {
422 if (parent == null) {
423 // ignore missing elements
424 return Stream.empty();
425 } else {
426 Iterable<Element> it = () -> new ChildIterator(parent);
427 return StreamSupport.stream(it.spliterator(), false);
[5617]428 }
429 }
430
[10612]431 private static Stream<Element> getChildrenStream(Element parent, String name) {
432 return getChildrenStream(parent).filter(child -> name.equals(child.getNodeName()));
433 }
434
435 private static List<Element> getChildren(Element parent, String name) {
436 return getChildrenStream(parent, name).collect(Collectors.toList());
437 }
438
[5617]439 private static Element getChild(Element parent, String name) {
[10612]440 return getChildrenStream(parent, name).findFirst().orElse(null);
[5617]441 }
442
[10612]443 /**
444 * The details of a layer of this wms server.
445 */
[5617]446 public static class LayerDetails {
447
[10612]448 /**
449 * The layer name
450 */
[5617]451 public final String name;
452 public final String ident;
[10612]453 /**
454 * The child layers of this layer
455 */
[5617]456 public final List<LayerDetails> children;
[10612]457 /**
458 * The bounds this layer can be used for
459 */
[5617]460 public final Bounds bounds;
461 public final Set<String> crsList;
462 public final boolean supported;
463
[10612]464 public LayerDetails(String name, String ident, Set<String> crsList, boolean supportedLayer, Bounds bounds,
465 List<LayerDetails> childLayers) {
[5617]466 this.name = name;
467 this.ident = ident;
468 this.supported = supportedLayer;
469 this.children = childLayers;
470 this.bounds = bounds;
471 this.crsList = crsList;
472 }
473
474 public boolean isSupported() {
475 return this.supported;
476 }
477
478 public Set<String> getProjections() {
479 return crsList;
480 }
481
482 @Override
483 public String toString() {
484 if (this.name == null || this.name.isEmpty())
485 return this.ident;
486 else
487 return this.name;
488 }
489 }
490}
Note: See TracBrowser for help on using the repository browser.