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

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

see #15182 - deprecate all Main logging methods and introduce suitable replacements in Logging for most of them

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