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

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

see #8465 - global use of try-with-resources, according to

File size: 15.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.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 + "&VERSION=1.1.1&SERVICE=WMS&REQUEST=GetMap&LAYERS="
107 + Utils.join(",", Utils.transform(selectedLayers, new Utils.Function<LayerDetails, String>() {
108 @Override
109 public String apply(LayerDetails x) {
110 return x.ident;
111 }
112 }))
113 + "&STYLES=&SRS={proj}&WIDTH={width}&HEIGHT={height}&BBOX={bbox}";
114 }
115
116 public void attemptGetCapabilities(String serviceUrlStr) throws MalformedURLException, IOException, WMSGetCapabilitiesException {
117 URL getCapabilitiesUrl = null;
118 try {
119 if (!Pattern.compile(".*GetCapabilities.*", Pattern.CASE_INSENSITIVE).matcher(serviceUrlStr).matches()) {
120 // If the url doesn't already have GetCapabilities, add it in
121 getCapabilitiesUrl = new URL(serviceUrlStr);
122 final String getCapabilitiesQuery = "VERSION=1.1.1&SERVICE=WMS&REQUEST=GetCapabilities";
123 if (getCapabilitiesUrl.getQuery() == null) {
124 getCapabilitiesUrl = new URL(serviceUrlStr + "?" + getCapabilitiesQuery);
125 } else if (!getCapabilitiesUrl.getQuery().isEmpty() && !getCapabilitiesUrl.getQuery().endsWith("&")) {
126 getCapabilitiesUrl = new URL(serviceUrlStr + "&" + getCapabilitiesQuery);
127 } else {
128 getCapabilitiesUrl = new URL(serviceUrlStr + getCapabilitiesQuery);
129 }
130 } else {
131 // Otherwise assume it's a good URL and let the subsequent error
132 // handling systems deal with problems
133 getCapabilitiesUrl = new URL(serviceUrlStr);
134 }
135 serviceUrl = new URL(serviceUrlStr);
136 } catch (HeadlessException e) {
137 return;
138 }
139
140 Main.info("GET " + getCapabilitiesUrl.toString());
141 URLConnection openConnection = Utils.openHttpConnection(getCapabilitiesUrl);
142 StringBuilder ba = new StringBuilder();
143
144 try (
145 InputStream inputStream = openConnection.getInputStream();
146 BufferedReader br = new BufferedReader(UTFInputStreamReader.create(inputStream))
147 ) {
148 String line;
149 while ((line = br.readLine()) != null) {
150 ba.append(line);
151 ba.append("\n");
152 }
153 }
154 String incomingData = ba.toString();
155
156 try {
157 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
158 builderFactory.setValidating(false);
159 builderFactory.setNamespaceAware(true);
160 DocumentBuilder builder = null;
161 builder = builderFactory.newDocumentBuilder();
162 builder.setEntityResolver(new EntityResolver() {
163 @Override
164 public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
165 Main.info("Ignoring DTD " + publicId + ", " + systemId);
166 return new InputSource(new StringReader(""));
167 }
168 });
169 Document document = null;
170 document = builder.parse(new InputSource(new StringReader(incomingData)));
171
172 // Some WMS service URLs specify a different base URL for their GetMap service
173 Element child = getChild(document.getDocumentElement(), "Capability");
174 child = getChild(child, "Request");
175 child = getChild(child, "GetMap");
176
177 formats = new ArrayList<>(Utils.filter(Utils.transform(getChildren(child, "Format"),
178 new Utils.Function<Element, String>() {
179 @Override
180 public String apply(Element x) {
181 return x.getTextContent();
182 }
183 }),
184 new Predicate<String>() {
185 @Override
186 public boolean evaluate(String format) {
187 boolean isFormatSupported = isImageFormatSupported(format);
188 if (!isFormatSupported) {
189 Main.info("Skipping unsupported image format {0}", format);
190 }
191 return isFormatSupported;
192 }
193 }
194 ));
195
196 child = getChild(child, "DCPType");
197 child = getChild(child, "HTTP");
198 child = getChild(child, "Get");
199 child = getChild(child, "OnlineResource");
200 if (child != null) {
201 String baseURL = child.getAttribute("xlink:href");
202 if (baseURL != null && !baseURL.equals(serviceUrlStr)) {
203 Main.info("GetCapabilities specifies a different service URL: " + baseURL);
204 serviceUrl = new URL(baseURL);
205 }
206 }
207
208 Element capabilityElem = getChild(document.getDocumentElement(), "Capability");
209 List<Element> children = getChildren(capabilityElem, "Layer");
210 layers = parseLayers(children, new HashSet<String>());
211 } catch (Exception e) {
212 throw new WMSGetCapabilitiesException(e, incomingData);
213 }
214 }
215
216 static boolean isImageFormatSupported(final String format) {
217 return ImageIO.getImageReadersByMIMEType(format).hasNext()
218 || (format.startsWith("image/tiff") || format.startsWith("image/geotiff")) && ImageIO.getImageReadersBySuffix("tiff").hasNext() // handles image/tiff image/tiff8 image/geotiff image/geotiff8
219 || format.startsWith("image/png") && ImageIO.getImageReadersBySuffix("png").hasNext()
220 || format.startsWith("image/svg") && ImageIO.getImageReadersBySuffix("svg").hasNext()
221 || format.startsWith("image/bmp") && ImageIO.getImageReadersBySuffix("bmp").hasNext();
222 }
223
224 public ImageryInfo toImageryInfo(String name, Collection<LayerDetails> selectedLayers) {
225 ImageryInfo i = new ImageryInfo(name, buildGetMapUrl(selectedLayers));
226 if (selectedLayers != null) {
227 HashSet<String> proj = new HashSet<>();
228 for (WMSImagery.LayerDetails l : selectedLayers) {
229 proj.addAll(l.getProjections());
230 }
231 i.setServerProjections(proj);
232 }
233 return i;
234 }
235
236 private List<LayerDetails> parseLayers(List<Element> children, Set<String> parentCrs) {
237 List<LayerDetails> details = new ArrayList<>(children.size());
238 for (Element element : children) {
239 details.add(parseLayer(element, parentCrs));
240 }
241 return details;
242 }
243
244 private LayerDetails parseLayer(Element element, Set<String> parentCrs) {
245 String name = getChildContent(element, "Title", null, null);
246 String ident = getChildContent(element, "Name", null, null);
247
248 // The set of supported CRS/SRS for this layer
249 Set<String> crsList = new HashSet<>();
250 // ...including this layer's already-parsed parent projections
251 crsList.addAll(parentCrs);
252
253 // Parse the CRS/SRS pulled out of this layer's XML element
254 // I think CRS and SRS are the same at this point
255 List<Element> crsChildren = getChildren(element, "CRS");
256 crsChildren.addAll(getChildren(element, "SRS"));
257 for (Element child : crsChildren) {
258 String crs = (String) getContent(child);
259 if (!crs.isEmpty()) {
260 String upperCase = crs.trim().toUpperCase();
261 crsList.add(upperCase);
262 }
263 }
264
265 // Check to see if any of the specified projections are supported by JOSM
266 boolean josmSupportsThisLayer = false;
267 for (String crs : crsList) {
268 josmSupportsThisLayer |= isProjSupported(crs);
269 }
270
271 Bounds bounds = null;
272 Element bboxElem = getChild(element, "EX_GeographicBoundingBox");
273 if (bboxElem != null) {
274 // Attempt to use EX_GeographicBoundingBox for bounding box
275 double left = Double.parseDouble(getChildContent(bboxElem, "westBoundLongitude", null, null));
276 double top = Double.parseDouble(getChildContent(bboxElem, "northBoundLatitude", null, null));
277 double right = Double.parseDouble(getChildContent(bboxElem, "eastBoundLongitude", null, null));
278 double bot = Double.parseDouble(getChildContent(bboxElem, "southBoundLatitude", null, null));
279 bounds = new Bounds(bot, left, top, right);
280 } else {
281 // If that's not available, try LatLonBoundingBox
282 bboxElem = getChild(element, "LatLonBoundingBox");
283 if (bboxElem != null) {
284 double left = Double.parseDouble(bboxElem.getAttribute("minx"));
285 double top = Double.parseDouble(bboxElem.getAttribute("maxy"));
286 double right = Double.parseDouble(bboxElem.getAttribute("maxx"));
287 double bot = Double.parseDouble(bboxElem.getAttribute("miny"));
288 bounds = new Bounds(bot, left, top, right);
289 }
290 }
291
292 List<Element> layerChildren = getChildren(element, "Layer");
293 List<LayerDetails> childLayers = parseLayers(layerChildren, crsList);
294
295 return new LayerDetails(name, ident, crsList, josmSupportsThisLayer, bounds, childLayers);
296 }
297
298 private boolean isProjSupported(String crs) {
299 for (ProjectionChoice pc : ProjectionPreference.getProjectionChoices()) {
300 if (pc.getPreferencesFromCode(crs) != null) return true;
301 }
302 return false;
303 }
304
305 private static String getChildContent(Element parent, String name, String missing, String empty) {
306 Element child = getChild(parent, name);
307 if (child == null)
308 return missing;
309 else {
310 String content = (String) getContent(child);
311 return (!content.isEmpty()) ? content : empty;
312 }
313 }
314
315 private static Object getContent(Element element) {
316 NodeList nl = element.getChildNodes();
317 StringBuilder content = new StringBuilder();
318 for (int i = 0; i < nl.getLength(); i++) {
319 Node node = nl.item(i);
320 switch (node.getNodeType()) {
321 case Node.ELEMENT_NODE:
322 return node;
323 case Node.CDATA_SECTION_NODE:
324 case Node.TEXT_NODE:
325 content.append(node.getNodeValue());
326 break;
327 }
328 }
329 return content.toString().trim();
330 }
331
332 private static List<Element> getChildren(Element parent, String name) {
333 List<Element> retVal = new ArrayList<>();
334 for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {
335 if (child instanceof Element && name.equals(child.getNodeName())) {
336 retVal.add((Element) child);
337 }
338 }
339 return retVal;
340 }
341
342 private static Element getChild(Element parent, String name) {
343 if (parent == null)
344 return null;
345 for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {
346 if (child instanceof Element && name.equals(child.getNodeName()))
347 return (Element) child;
348 }
349 return null;
350 }
351
352 public static class LayerDetails {
353
354 public final String name;
355 public final String ident;
356 public final List<LayerDetails> children;
357 public final Bounds bounds;
358 public final Set<String> crsList;
359 public final boolean supported;
360
361 public LayerDetails(String name, String ident, Set<String> crsList,
362 boolean supportedLayer, Bounds bounds,
363 List<LayerDetails> childLayers) {
364 this.name = name;
365 this.ident = ident;
366 this.supported = supportedLayer;
367 this.children = childLayers;
368 this.bounds = bounds;
369 this.crsList = crsList;
370 }
371
372 public boolean isSupported() {
373 return this.supported;
374 }
375
376 public Set<String> getProjections() {
377 return crsList;
378 }
379
380 @Override
381 public String toString() {
382 if (this.name == null || this.name.isEmpty())
383 return this.ident;
384 else
385 return this.name;
386 }
387
388 }
389}
Note: See TracBrowser for help on using the repository browser.