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
Line 
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;
9import java.util.ArrayList;
10import java.util.Collection;
11import java.util.Collections;
12import java.util.HashSet;
13import java.util.Iterator;
14import java.util.List;
15import java.util.Locale;
16import java.util.NoSuchElementException;
17import java.util.Set;
18import java.util.regex.Pattern;
19import java.util.stream.Collectors;
20import java.util.stream.Stream;
21import java.util.stream.StreamSupport;
22
23import javax.imageio.ImageIO;
24import javax.xml.parsers.DocumentBuilder;
25import javax.xml.parsers.ParserConfigurationException;
26
27import org.openstreetmap.josm.Main;
28import org.openstreetmap.josm.data.Bounds;
29import org.openstreetmap.josm.data.imagery.ImageryInfo;
30import org.openstreetmap.josm.data.projection.Projections;
31import org.openstreetmap.josm.tools.HttpClient;
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
40/**
41 * This class represents the capabilites of a WMS imagery server.
42 */
43public class WMSImagery {
44
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 */
79 public static class WMSGetCapabilitiesException extends Exception {
80 private final String incomingData;
81
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 */
87 public WMSGetCapabilitiesException(Throwable cause, String incomingData) {
88 super(cause);
89 this.incomingData = incomingData;
90 }
91
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 /**
104 * The data that caused this exception.
105 * @return The server response to the capabilites request.
106 */
107 public String getIncomingData() {
108 return incomingData;
109 }
110 }
111
112 private List<LayerDetails> layers;
113 private URL serviceUrl;
114 private List<String> formats;
115
116 /**
117 * Returns the list of layers.
118 * @return the list of layers
119 */
120 public List<LayerDetails> getLayers() {
121 return Collections.unmodifiableList(layers);
122 }
123
124 /**
125 * Returns the service URL.
126 * @return the service URL
127 */
128 public URL getServiceUrl() {
129 return serviceUrl;
130 }
131
132 /**
133 * Returns the list of supported formats.
134 * @return the list of supported formats
135 */
136 public List<String> getFormats() {
137 return Collections.unmodifiableList(formats);
138 }
139
140 /**
141 * Gets the preffered format for this imagery layer.
142 * @return The preffered format as mime type.
143 */
144 public String getPreferredFormats() {
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 }
154 }
155
156 String buildRootUrl() {
157 if (serviceUrl == null) {
158 return null;
159 }
160 StringBuilder a = new StringBuilder(serviceUrl.getProtocol());
161 a.append("://").append(serviceUrl.getHost());
162 if (serviceUrl.getPort() != -1) {
163 a.append(':').append(serviceUrl.getPort());
164 }
165 a.append(serviceUrl.getPath()).append('?');
166 if (serviceUrl.getQuery() != null) {
167 a.append(serviceUrl.getQuery());
168 if (!serviceUrl.getQuery().isEmpty() && !serviceUrl.getQuery().endsWith("&")) {
169 a.append('&');
170 }
171 }
172 return a.toString();
173 }
174
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 */
180 public String buildGetMapUrl(Collection<LayerDetails> selectedLayers) {
181 return buildGetMapUrl(selectedLayers, "image/jpeg");
182 }
183
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 */
190 public String buildGetMapUrl(Collection<LayerDetails> selectedLayers, String format) {
191 return buildRootUrl() + "FORMAT=" + format + (imageFormatHasTransparency(format) ? "&TRANSPARENT=TRUE" : "")
192 + "&VERSION=1.1.1&SERVICE=WMS&REQUEST=GetMap&LAYERS="
193 + selectedLayers.stream().map(x -> x.ident).collect(Collectors.joining(","))
194 + "&STYLES=&SRS={proj}&WIDTH={width}&HEIGHT={height}&BBOX={bbox}";
195 }
196
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 */
203 public void attemptGetCapabilities(String serviceUrlStr) throws IOException, WMSGetCapabilitiesException {
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) {
211 getCapabilitiesUrl = new URL(serviceUrlStr + '?' + getCapabilitiesQuery);
212 } else if (!getCapabilitiesUrl.getQuery().isEmpty() && !getCapabilitiesUrl.getQuery().endsWith("&")) {
213 getCapabilitiesUrl = new URL(serviceUrlStr + '&' + getCapabilitiesQuery);
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) {
224 Main.warn(e);
225 return;
226 }
227
228 final String incomingData = HttpClient.create(getCapabilitiesUrl).connect().fetchContent();
229 Main.debug("Server response to Capabilities request:");
230 Main.debug(incomingData);
231
232 try {
233 DocumentBuilder builder = Utils.newSafeDOMBuilder();
234 builder.setEntityResolver((publicId, systemId) -> {
235 Main.info("Ignoring DTD " + publicId + ", " + systemId);
236 return new InputSource(new StringReader(""));
237 });
238 Document document = builder.parse(new InputSource(new StringReader(incomingData)));
239 Element root = document.getDocumentElement();
240
241 // Check if the request resulted in ServiceException
242 if ("ServiceException".equals(root.getTagName())) {
243 throw new WMSGetCapabilitiesException(root.getTextContent(), incomingData);
244 }
245
246 // Some WMS service URLs specify a different base URL for their GetMap service
247 Element child = getChild(root, "Capability");
248 child = getChild(child, "Request");
249 child = getChild(child, "GetMap");
250
251 formats = getChildrenStream(child, "Format")
252 .map(Node::getTextContent)
253 .filter(WMSImagery::isImageFormatSupportedWarn)
254 .collect(Collectors.toList());
255
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");
262 if (!baseURL.equals(serviceUrlStr)) {
263 Main.info("GetCapabilities specifies a different service URL: " + baseURL);
264 serviceUrl = new URL(baseURL);
265 }
266 }
267
268 Element capabilityElem = getChild(root, "Capability");
269 List<Element> children = getChildren(capabilityElem, "Layer");
270 layers = parseLayers(children, new HashSet<String>());
271 } catch (MalformedURLException | ParserConfigurationException | SAXException e) {
272 throw new WMSGetCapabilitiesException(e, incomingData);
273 }
274 }
275
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
284 static boolean isImageFormatSupported(final String format) {
285 return ImageIO.getImageReadersByMIMEType(format).hasNext()
286 // handles image/tiff image/tiff8 image/geotiff image/geotiff8
287 || isImageFormatSupported(format, "tiff", "geotiff")
288 || isImageFormatSupported(format, "png")
289 || isImageFormatSupported(format, "svg")
290 || isImageFormatSupported(format, "bmp");
291 }
292
293 static boolean isImageFormatSupported(String format, String... mimeFormats) {
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
302 static boolean imageFormatHasTransparency(final String format) {
303 return format != null && (format.startsWith("image/png") || format.startsWith("image/gif")
304 || format.startsWith("image/svg") || format.startsWith("image/tiff"));
305 }
306
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 */
313 public ImageryInfo toImageryInfo(String name, Collection<LayerDetails> selectedLayers) {
314 ImageryInfo i = new ImageryInfo(name, buildGetMapUrl(selectedLayers));
315 if (selectedLayers != null) {
316 Set<String> proj = new HashSet<>();
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) {
326 List<LayerDetails> details = new ArrayList<>(children.size());
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
338 Set<String> crsList = new HashSet<>();
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
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);
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) {
370 double left = getDecimalDegree(bboxElem, "minx");
371 double top = getDecimalDegree(bboxElem, "maxy");
372 double right = getDecimalDegree(bboxElem, "maxx");
373 double bot = getDecimalDegree(bboxElem, "miny");
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
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
389 private static boolean isProjSupported(String crs) {
390 return Projections.getProjectionByCode(crs) != null;
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);
399 return (!content.isEmpty()) ? content : empty;
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;
415 default: // Do nothing
416 }
417 }
418 return content.toString().trim();
419 }
420
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);
428 }
429 }
430
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
439 private static Element getChild(Element parent, String name) {
440 return getChildrenStream(parent, name).findFirst().orElse(null);
441 }
442
443 /**
444 * The details of a layer of this wms server.
445 */
446 public static class LayerDetails {
447
448 /**
449 * The layer name
450 */
451 public final String name;
452 public final String ident;
453 /**
454 * The child layers of this layer
455 */
456 public final List<LayerDetails> children;
457 /**
458 * The bounds this layer can be used for
459 */
460 public final Bounds bounds;
461 public final Set<String> crsList;
462 public final boolean supported;
463
464 public LayerDetails(String name, String ident, Set<String> crsList, boolean supportedLayer, Bounds bounds,
465 List<LayerDetails> childLayers) {
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.