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

Last change on this file since 8345 was 8338, checked in by Don-vip, 9 years ago

fix squid:S1319 - Declarations should use Java collection interfaces rather than specific implementation classes

  • Property svn:eol-style set to native
File size: 15.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.BufferedReader;
6import java.io.IOException;
7import java.io.InputStream;
8import java.io.StringReader;
9import java.net.MalformedURLException;
10import java.net.URL;
11import java.net.URLConnection;
12import java.util.ArrayList;
13import java.util.Collection;
14import java.util.Collections;
15import java.util.HashSet;
16import java.util.List;
17import java.util.Set;
18import java.util.regex.Pattern;
19
20import javax.imageio.ImageIO;
21import javax.xml.parsers.DocumentBuilder;
22import javax.xml.parsers.DocumentBuilderFactory;
23
24import org.openstreetmap.josm.Main;
25import org.openstreetmap.josm.data.Bounds;
26import org.openstreetmap.josm.data.imagery.ImageryInfo;
27import org.openstreetmap.josm.gui.preferences.projection.ProjectionChoice;
28import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
29import org.openstreetmap.josm.io.UTFInputStreamReader;
30import org.openstreetmap.josm.tools.Predicate;
31import org.openstreetmap.josm.tools.Utils;
32import org.w3c.dom.Document;
33import org.w3c.dom.Element;
34import org.w3c.dom.Node;
35import org.w3c.dom.NodeList;
36import org.xml.sax.EntityResolver;
37import org.xml.sax.InputSource;
38import org.xml.sax.SAXException;
39
40public class WMSImagery {
41
42 public static class WMSGetCapabilitiesException extends Exception {
43 private final String incomingData;
44
45 public WMSGetCapabilitiesException(Throwable cause, String incomingData) {
46 super(cause);
47 this.incomingData = incomingData;
48 }
49
50 public String getIncomingData() {
51 return incomingData;
52 }
53 }
54
55 private List<LayerDetails> layers;
56 private URL serviceUrl;
57 private List<String> formats;
58
59 public List<LayerDetails> getLayers() {
60 return layers;
61 }
62
63 public URL getServiceUrl() {
64 return serviceUrl;
65 }
66
67 public List<String> getFormats() {
68 return Collections.unmodifiableList(formats);
69 }
70
71 public String getPreferredFormats() {
72 return formats.contains("image/jpeg") ? "image/jpeg"
73 : formats.contains("image/png") ? "image/png"
74 : formats.isEmpty() ? null
75 : formats.get(0);
76 }
77
78 String buildRootUrl() {
79 if (serviceUrl == null) {
80 return null;
81 }
82 StringBuilder a = new StringBuilder(serviceUrl.getProtocol());
83 a.append("://");
84 a.append(serviceUrl.getHost());
85 if (serviceUrl.getPort() != -1) {
86 a.append(":");
87 a.append(serviceUrl.getPort());
88 }
89 a.append(serviceUrl.getPath());
90 a.append("?");
91 if (serviceUrl.getQuery() != null) {
92 a.append(serviceUrl.getQuery());
93 if (!serviceUrl.getQuery().isEmpty() && !serviceUrl.getQuery().endsWith("&")) {
94 a.append("&");
95 }
96 }
97 return a.toString();
98 }
99
100 public String buildGetMapUrl(Collection<LayerDetails> selectedLayers) {
101 return buildGetMapUrl(selectedLayers, "image/jpeg");
102 }
103
104 public String buildGetMapUrl(Collection<LayerDetails> selectedLayers, String format) {
105 return buildRootUrl()
106 + "FORMAT=" + format + (imageFormatHasTransparency(format) ? "&TRANSPARENT=TRUE" : "")
107 + "&VERSION=1.1.1&SERVICE=WMS&REQUEST=GetMap&LAYERS="
108 + Utils.join(",", Utils.transform(selectedLayers, new Utils.Function<LayerDetails, String>() {
109 @Override
110 public String apply(LayerDetails x) {
111 return x.ident;
112 }
113 }))
114 + "&STYLES=&SRS={proj}&WIDTH={width}&HEIGHT={height}&BBOX={bbox}";
115 }
116
117 public void attemptGetCapabilities(String serviceUrlStr) throws MalformedURLException, IOException, WMSGetCapabilitiesException {
118 URL getCapabilitiesUrl = null;
119 try {
120 if (!Pattern.compile(".*GetCapabilities.*", Pattern.CASE_INSENSITIVE).matcher(serviceUrlStr).matches()) {
121 // If the url doesn't already have GetCapabilities, add it in
122 getCapabilitiesUrl = new URL(serviceUrlStr);
123 final String getCapabilitiesQuery = "VERSION=1.1.1&SERVICE=WMS&REQUEST=GetCapabilities";
124 if (getCapabilitiesUrl.getQuery() == null) {
125 getCapabilitiesUrl = new URL(serviceUrlStr + "?" + getCapabilitiesQuery);
126 } else if (!getCapabilitiesUrl.getQuery().isEmpty() && !getCapabilitiesUrl.getQuery().endsWith("&")) {
127 getCapabilitiesUrl = new URL(serviceUrlStr + "&" + getCapabilitiesQuery);
128 } else {
129 getCapabilitiesUrl = new URL(serviceUrlStr + getCapabilitiesQuery);
130 }
131 } else {
132 // Otherwise assume it's a good URL and let the subsequent error
133 // handling systems deal with problems
134 getCapabilitiesUrl = new URL(serviceUrlStr);
135 }
136 serviceUrl = new URL(serviceUrlStr);
137 } catch (HeadlessException e) {
138 return;
139 }
140
141 Main.info("GET " + getCapabilitiesUrl.toString());
142 URLConnection openConnection = Utils.openHttpConnection(getCapabilitiesUrl);
143 StringBuilder ba = new StringBuilder();
144
145 try (
146 InputStream inputStream = openConnection.getInputStream();
147 BufferedReader br = new BufferedReader(UTFInputStreamReader.create(inputStream))
148 ) {
149 String line;
150 while ((line = br.readLine()) != null) {
151 ba.append(line);
152 ba.append("\n");
153 }
154 }
155 String incomingData = ba.toString();
156 Main.debug("Server response to Capabilities request:");
157 Main.debug(incomingData);
158
159 try {
160 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
161 builderFactory.setValidating(false);
162 builderFactory.setNamespaceAware(true);
163 DocumentBuilder builder = null;
164 builder = builderFactory.newDocumentBuilder();
165 builder.setEntityResolver(new EntityResolver() {
166 @Override
167 public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
168 Main.info("Ignoring DTD " + publicId + ", " + systemId);
169 return new InputSource(new StringReader(""));
170 }
171 });
172 Document document = null;
173 document = builder.parse(new InputSource(new StringReader(incomingData)));
174
175 // Some WMS service URLs specify a different base URL for their GetMap service
176 Element child = getChild(document.getDocumentElement(), "Capability");
177 child = getChild(child, "Request");
178 child = getChild(child, "GetMap");
179
180 formats = new ArrayList<>(Utils.filter(Utils.transform(getChildren(child, "Format"),
181 new Utils.Function<Element, String>() {
182 @Override
183 public String apply(Element x) {
184 return x.getTextContent();
185 }
186 }),
187 new Predicate<String>() {
188 @Override
189 public boolean evaluate(String format) {
190 boolean isFormatSupported = isImageFormatSupported(format);
191 if (!isFormatSupported) {
192 Main.info("Skipping unsupported image format {0}", format);
193 }
194 return isFormatSupported;
195 }
196 }
197 ));
198
199 child = getChild(child, "DCPType");
200 child = getChild(child, "HTTP");
201 child = getChild(child, "Get");
202 child = getChild(child, "OnlineResource");
203 if (child != null) {
204 String baseURL = child.getAttribute("xlink:href");
205 if (baseURL != null && !baseURL.equals(serviceUrlStr)) {
206 Main.info("GetCapabilities specifies a different service URL: " + baseURL);
207 serviceUrl = new URL(baseURL);
208 }
209 }
210
211 Element capabilityElem = getChild(document.getDocumentElement(), "Capability");
212 List<Element> children = getChildren(capabilityElem, "Layer");
213 layers = parseLayers(children, new HashSet<String>());
214 } catch (Exception e) {
215 throw new WMSGetCapabilitiesException(e, incomingData);
216 }
217 }
218
219 static boolean isImageFormatSupported(final String format) {
220 return ImageIO.getImageReadersByMIMEType(format).hasNext()
221 || (format.startsWith("image/tiff") || format.startsWith("image/geotiff")) && ImageIO.getImageReadersBySuffix("tiff").hasNext() // handles image/tiff image/tiff8 image/geotiff image/geotiff8
222 || format.startsWith("image/png") && ImageIO.getImageReadersBySuffix("png").hasNext()
223 || format.startsWith("image/svg") && ImageIO.getImageReadersBySuffix("svg").hasNext()
224 || format.startsWith("image/bmp") && ImageIO.getImageReadersBySuffix("bmp").hasNext();
225 }
226
227 static boolean imageFormatHasTransparency(final String format) {
228 return format != null && (format.startsWith("image/png") || format.startsWith("image/gif")
229 || format.startsWith("image/svg") || format.startsWith("image/tiff"));
230 }
231
232 public ImageryInfo toImageryInfo(String name, Collection<LayerDetails> selectedLayers) {
233 ImageryInfo i = new ImageryInfo(name, buildGetMapUrl(selectedLayers));
234 if (selectedLayers != null) {
235 Set<String> proj = new HashSet<>();
236 for (WMSImagery.LayerDetails l : selectedLayers) {
237 proj.addAll(l.getProjections());
238 }
239 i.setServerProjections(proj);
240 }
241 return i;
242 }
243
244 private List<LayerDetails> parseLayers(List<Element> children, Set<String> parentCrs) {
245 List<LayerDetails> details = new ArrayList<>(children.size());
246 for (Element element : children) {
247 details.add(parseLayer(element, parentCrs));
248 }
249 return details;
250 }
251
252 private LayerDetails parseLayer(Element element, Set<String> parentCrs) {
253 String name = getChildContent(element, "Title", null, null);
254 String ident = getChildContent(element, "Name", null, null);
255
256 // The set of supported CRS/SRS for this layer
257 Set<String> crsList = new HashSet<>();
258 // ...including this layer's already-parsed parent projections
259 crsList.addAll(parentCrs);
260
261 // Parse the CRS/SRS pulled out of this layer's XML element
262 // I think CRS and SRS are the same at this point
263 List<Element> crsChildren = getChildren(element, "CRS");
264 crsChildren.addAll(getChildren(element, "SRS"));
265 for (Element child : crsChildren) {
266 String crs = (String) getContent(child);
267 if (!crs.isEmpty()) {
268 String upperCase = crs.trim().toUpperCase();
269 crsList.add(upperCase);
270 }
271 }
272
273 // Check to see if any of the specified projections are supported by JOSM
274 boolean josmSupportsThisLayer = false;
275 for (String crs : crsList) {
276 josmSupportsThisLayer |= isProjSupported(crs);
277 }
278
279 Bounds bounds = null;
280 Element bboxElem = getChild(element, "EX_GeographicBoundingBox");
281 if (bboxElem != null) {
282 // Attempt to use EX_GeographicBoundingBox for bounding box
283 double left = Double.parseDouble(getChildContent(bboxElem, "westBoundLongitude", null, null));
284 double top = Double.parseDouble(getChildContent(bboxElem, "northBoundLatitude", null, null));
285 double right = Double.parseDouble(getChildContent(bboxElem, "eastBoundLongitude", null, null));
286 double bot = Double.parseDouble(getChildContent(bboxElem, "southBoundLatitude", null, null));
287 bounds = new Bounds(bot, left, top, right);
288 } else {
289 // If that's not available, try LatLonBoundingBox
290 bboxElem = getChild(element, "LatLonBoundingBox");
291 if (bboxElem != null) {
292 double left = Double.parseDouble(bboxElem.getAttribute("minx"));
293 double top = Double.parseDouble(bboxElem.getAttribute("maxy"));
294 double right = Double.parseDouble(bboxElem.getAttribute("maxx"));
295 double bot = Double.parseDouble(bboxElem.getAttribute("miny"));
296 bounds = new Bounds(bot, left, top, right);
297 }
298 }
299
300 List<Element> layerChildren = getChildren(element, "Layer");
301 List<LayerDetails> childLayers = parseLayers(layerChildren, crsList);
302
303 return new LayerDetails(name, ident, crsList, josmSupportsThisLayer, bounds, childLayers);
304 }
305
306 private boolean isProjSupported(String crs) {
307 for (ProjectionChoice pc : ProjectionPreference.getProjectionChoices()) {
308 if (pc.getPreferencesFromCode(crs) != null) return true;
309 }
310 return false;
311 }
312
313 private static String getChildContent(Element parent, String name, String missing, String empty) {
314 Element child = getChild(parent, name);
315 if (child == null)
316 return missing;
317 else {
318 String content = (String) getContent(child);
319 return (!content.isEmpty()) ? content : empty;
320 }
321 }
322
323 private static Object getContent(Element element) {
324 NodeList nl = element.getChildNodes();
325 StringBuilder content = new StringBuilder();
326 for (int i = 0; i < nl.getLength(); i++) {
327 Node node = nl.item(i);
328 switch (node.getNodeType()) {
329 case Node.ELEMENT_NODE:
330 return node;
331 case Node.CDATA_SECTION_NODE:
332 case Node.TEXT_NODE:
333 content.append(node.getNodeValue());
334 break;
335 }
336 }
337 return content.toString().trim();
338 }
339
340 private static List<Element> getChildren(Element parent, String name) {
341 List<Element> retVal = new ArrayList<>();
342 for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {
343 if (child instanceof Element && name.equals(child.getNodeName())) {
344 retVal.add((Element) child);
345 }
346 }
347 return retVal;
348 }
349
350 private static Element getChild(Element parent, String name) {
351 if (parent == null)
352 return null;
353 for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {
354 if (child instanceof Element && name.equals(child.getNodeName()))
355 return (Element) child;
356 }
357 return null;
358 }
359
360 public static class LayerDetails {
361
362 public final String name;
363 public final String ident;
364 public final List<LayerDetails> children;
365 public final Bounds bounds;
366 public final Set<String> crsList;
367 public final boolean supported;
368
369 public LayerDetails(String name, String ident, Set<String> crsList,
370 boolean supportedLayer, Bounds bounds,
371 List<LayerDetails> childLayers) {
372 this.name = name;
373 this.ident = ident;
374 this.supported = supportedLayer;
375 this.children = childLayers;
376 this.bounds = bounds;
377 this.crsList = crsList;
378 }
379
380 public boolean isSupported() {
381 return this.supported;
382 }
383
384 public Set<String> getProjections() {
385 return crsList;
386 }
387
388 @Override
389 public String toString() {
390 if (this.name == null || this.name.isEmpty())
391 return this.ident;
392 else
393 return this.name;
394 }
395
396 }
397}
Note: See TracBrowser for help on using the repository browser.