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

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

fix #15012 - Support WMS endpoint in Imagery -> Rectified Image

  • Property svn:eol-style set to native
File size: 17.4 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 public String buildGetMapUrl(Collection<LayerDetails> selectedLayers) {
176 return buildGetMapUrl(selectedLayers, "image/jpeg");
177 }
178
179 public String buildGetMapUrl(Collection<LayerDetails> selectedLayers, String format) {
180 return buildRootUrl() + "FORMAT=" + format + (imageFormatHasTransparency(format) ? "&TRANSPARENT=TRUE" : "")
181 + "&VERSION=1.1.1&SERVICE=WMS&REQUEST=GetMap&LAYERS="
182 + selectedLayers.stream().map(x -> x.ident).collect(Collectors.joining(","))
183 + "&STYLES=&SRS={proj}&WIDTH={width}&HEIGHT={height}&BBOX={bbox}";
184 }
185
186 public void attemptGetCapabilities(String serviceUrlStr) throws IOException, WMSGetCapabilitiesException {
187 URL getCapabilitiesUrl = null;
188 try {
189 if (!Pattern.compile(".*GetCapabilities.*", Pattern.CASE_INSENSITIVE).matcher(serviceUrlStr).matches()) {
190 // If the url doesn't already have GetCapabilities, add it in
191 getCapabilitiesUrl = new URL(serviceUrlStr);
192 final String getCapabilitiesQuery = "VERSION=1.1.1&SERVICE=WMS&REQUEST=GetCapabilities";
193 if (getCapabilitiesUrl.getQuery() == null) {
194 getCapabilitiesUrl = new URL(serviceUrlStr + '?' + getCapabilitiesQuery);
195 } else if (!getCapabilitiesUrl.getQuery().isEmpty() && !getCapabilitiesUrl.getQuery().endsWith("&")) {
196 getCapabilitiesUrl = new URL(serviceUrlStr + '&' + getCapabilitiesQuery);
197 } else {
198 getCapabilitiesUrl = new URL(serviceUrlStr + getCapabilitiesQuery);
199 }
200 } else {
201 // Otherwise assume it's a good URL and let the subsequent error
202 // handling systems deal with problems
203 getCapabilitiesUrl = new URL(serviceUrlStr);
204 }
205 serviceUrl = new URL(serviceUrlStr);
206 } catch (HeadlessException e) {
207 Main.warn(e);
208 return;
209 }
210
211 final String incomingData = HttpClient.create(getCapabilitiesUrl).connect().fetchContent();
212 Main.debug("Server response to Capabilities request:");
213 Main.debug(incomingData);
214
215 try {
216 DocumentBuilder builder = Utils.newSafeDOMBuilder();
217 builder.setEntityResolver((publicId, systemId) -> {
218 Main.info("Ignoring DTD " + publicId + ", " + systemId);
219 return new InputSource(new StringReader(""));
220 });
221 Document document = builder.parse(new InputSource(new StringReader(incomingData)));
222 Element root = document.getDocumentElement();
223
224 // Check if the request resulted in ServiceException
225 if ("ServiceException".equals(root.getTagName())) {
226 throw new WMSGetCapabilitiesException(root.getTextContent(), incomingData);
227 }
228
229 // Some WMS service URLs specify a different base URL for their GetMap service
230 Element child = getChild(root, "Capability");
231 child = getChild(child, "Request");
232 child = getChild(child, "GetMap");
233
234 formats = getChildrenStream(child, "Format")
235 .map(Node::getTextContent)
236 .filter(WMSImagery::isImageFormatSupportedWarn)
237 .collect(Collectors.toList());
238
239 child = getChild(child, "DCPType");
240 child = getChild(child, "HTTP");
241 child = getChild(child, "Get");
242 child = getChild(child, "OnlineResource");
243 if (child != null) {
244 String baseURL = child.getAttribute("xlink:href");
245 if (!baseURL.equals(serviceUrlStr)) {
246 Main.info("GetCapabilities specifies a different service URL: " + baseURL);
247 serviceUrl = new URL(baseURL);
248 }
249 }
250
251 Element capabilityElem = getChild(root, "Capability");
252 List<Element> children = getChildren(capabilityElem, "Layer");
253 layers = parseLayers(children, new HashSet<String>());
254 } catch (MalformedURLException | ParserConfigurationException | SAXException e) {
255 throw new WMSGetCapabilitiesException(e, incomingData);
256 }
257 }
258
259 private static boolean isImageFormatSupportedWarn(String format) {
260 boolean isFormatSupported = isImageFormatSupported(format);
261 if (!isFormatSupported) {
262 Main.info("Skipping unsupported image format {0}", format);
263 }
264 return isFormatSupported;
265 }
266
267 static boolean isImageFormatSupported(final String format) {
268 return ImageIO.getImageReadersByMIMEType(format).hasNext()
269 // handles image/tiff image/tiff8 image/geotiff image/geotiff8
270 || isImageFormatSupported(format, "tiff", "geotiff")
271 || isImageFormatSupported(format, "png")
272 || isImageFormatSupported(format, "svg")
273 || isImageFormatSupported(format, "bmp");
274 }
275
276 static boolean isImageFormatSupported(String format, String... mimeFormats) {
277 for (String mime : mimeFormats) {
278 if (format.startsWith("image/" + mime)) {
279 return ImageIO.getImageReadersBySuffix(mimeFormats[0]).hasNext();
280 }
281 }
282 return false;
283 }
284
285 static boolean imageFormatHasTransparency(final String format) {
286 return format != null && (format.startsWith("image/png") || format.startsWith("image/gif")
287 || format.startsWith("image/svg") || format.startsWith("image/tiff"));
288 }
289
290 public ImageryInfo toImageryInfo(String name, Collection<LayerDetails> selectedLayers) {
291 ImageryInfo i = new ImageryInfo(name, buildGetMapUrl(selectedLayers));
292 if (selectedLayers != null) {
293 Set<String> proj = new HashSet<>();
294 for (WMSImagery.LayerDetails l : selectedLayers) {
295 proj.addAll(l.getProjections());
296 }
297 i.setServerProjections(proj);
298 }
299 return i;
300 }
301
302 private List<LayerDetails> parseLayers(List<Element> children, Set<String> parentCrs) {
303 List<LayerDetails> details = new ArrayList<>(children.size());
304 for (Element element : children) {
305 details.add(parseLayer(element, parentCrs));
306 }
307 return details;
308 }
309
310 private LayerDetails parseLayer(Element element, Set<String> parentCrs) {
311 String name = getChildContent(element, "Title", null, null);
312 String ident = getChildContent(element, "Name", null, null);
313
314 // The set of supported CRS/SRS for this layer
315 Set<String> crsList = new HashSet<>();
316 // ...including this layer's already-parsed parent projections
317 crsList.addAll(parentCrs);
318
319 // Parse the CRS/SRS pulled out of this layer's XML element
320 // I think CRS and SRS are the same at this point
321 getChildrenStream(element)
322 .filter(child -> "CRS".equals(child.getNodeName()) || "SRS".equals(child.getNodeName()))
323 .map(child -> (String) getContent(child))
324 .filter(crs -> !crs.isEmpty())
325 .map(crs -> crs.trim().toUpperCase(Locale.ENGLISH))
326 .forEach(crsList::add);
327
328 // Check to see if any of the specified projections are supported by JOSM
329 boolean josmSupportsThisLayer = false;
330 for (String crs : crsList) {
331 josmSupportsThisLayer |= isProjSupported(crs);
332 }
333
334 Bounds bounds = null;
335 Element bboxElem = getChild(element, "EX_GeographicBoundingBox");
336 if (bboxElem != null) {
337 // Attempt to use EX_GeographicBoundingBox for bounding box
338 double left = Double.parseDouble(getChildContent(bboxElem, "westBoundLongitude", null, null));
339 double top = Double.parseDouble(getChildContent(bboxElem, "northBoundLatitude", null, null));
340 double right = Double.parseDouble(getChildContent(bboxElem, "eastBoundLongitude", null, null));
341 double bot = Double.parseDouble(getChildContent(bboxElem, "southBoundLatitude", null, null));
342 bounds = new Bounds(bot, left, top, right);
343 } else {
344 // If that's not available, try LatLonBoundingBox
345 bboxElem = getChild(element, "LatLonBoundingBox");
346 if (bboxElem != null) {
347 double left = getDecimalDegree(bboxElem ,"minx");
348 double top = getDecimalDegree(bboxElem, "maxy");
349 double right = getDecimalDegree(bboxElem, "maxx");
350 double bot = getDecimalDegree(bboxElem, "miny");
351 bounds = new Bounds(bot, left, top, right);
352 }
353 }
354
355 List<Element> layerChildren = getChildren(element, "Layer");
356 List<LayerDetails> childLayers = parseLayers(layerChildren, crsList);
357
358 return new LayerDetails(name, ident, crsList, josmSupportsThisLayer, bounds, childLayers);
359 }
360
361 private static double getDecimalDegree(Element elem, String attr) {
362 // Some real-world WMS servers use a comma instead of a dot as decimal separator (seen in Polish WMS server)
363 return Double.parseDouble(elem.getAttribute(attr).replace(',', '.'));
364 }
365
366 private static boolean isProjSupported(String crs) {
367 return Projections.getProjectionByCode(crs) != null;
368 }
369
370 private static String getChildContent(Element parent, String name, String missing, String empty) {
371 Element child = getChild(parent, name);
372 if (child == null)
373 return missing;
374 else {
375 String content = (String) getContent(child);
376 return (!content.isEmpty()) ? content : empty;
377 }
378 }
379
380 private static Object getContent(Element element) {
381 NodeList nl = element.getChildNodes();
382 StringBuilder content = new StringBuilder();
383 for (int i = 0; i < nl.getLength(); i++) {
384 Node node = nl.item(i);
385 switch (node.getNodeType()) {
386 case Node.ELEMENT_NODE:
387 return node;
388 case Node.CDATA_SECTION_NODE:
389 case Node.TEXT_NODE:
390 content.append(node.getNodeValue());
391 break;
392 default: // Do nothing
393 }
394 }
395 return content.toString().trim();
396 }
397
398 private static Stream<Element> getChildrenStream(Element parent) {
399 if (parent == null) {
400 // ignore missing elements
401 return Stream.empty();
402 } else {
403 Iterable<Element> it = () -> new ChildIterator(parent);
404 return StreamSupport.stream(it.spliterator(), false);
405 }
406 }
407
408 private static Stream<Element> getChildrenStream(Element parent, String name) {
409 return getChildrenStream(parent).filter(child -> name.equals(child.getNodeName()));
410 }
411
412 private static List<Element> getChildren(Element parent, String name) {
413 return getChildrenStream(parent, name).collect(Collectors.toList());
414 }
415
416 private static Element getChild(Element parent, String name) {
417 return getChildrenStream(parent, name).findFirst().orElse(null);
418 }
419
420 /**
421 * The details of a layer of this wms server.
422 */
423 public static class LayerDetails {
424
425 /**
426 * The layer name
427 */
428 public final String name;
429 public final String ident;
430 /**
431 * The child layers of this layer
432 */
433 public final List<LayerDetails> children;
434 /**
435 * The bounds this layer can be used for
436 */
437 public final Bounds bounds;
438 public final Set<String> crsList;
439 public final boolean supported;
440
441 public LayerDetails(String name, String ident, Set<String> crsList, boolean supportedLayer, Bounds bounds,
442 List<LayerDetails> childLayers) {
443 this.name = name;
444 this.ident = ident;
445 this.supported = supportedLayer;
446 this.children = childLayers;
447 this.bounds = bounds;
448 this.crsList = crsList;
449 }
450
451 public boolean isSupported() {
452 return this.supported;
453 }
454
455 public Set<String> getProjections() {
456 return crsList;
457 }
458
459 @Override
460 public String toString() {
461 if (this.name == null || this.name.isEmpty())
462 return this.ident;
463 else
464 return this.name;
465 }
466 }
467}
Note: See TracBrowser for help on using the repository browser.