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

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

Sonar - various performance improvements

  • Property svn:eol-style set to native
File size: 15.7 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("://").append(serviceUrl.getHost());
84 if (serviceUrl.getPort() != -1) {
85 a.append(':').append(serviceUrl.getPort());
86 }
87 a.append(serviceUrl.getPath()).append('?');
88 if (serviceUrl.getQuery() != null) {
89 a.append(serviceUrl.getQuery());
90 if (!serviceUrl.getQuery().isEmpty() && !serviceUrl.getQuery().endsWith("&")) {
91 a.append('&');
92 }
93 }
94 return a.toString();
95 }
96
97 public String buildGetMapUrl(Collection<LayerDetails> selectedLayers) {
98 return buildGetMapUrl(selectedLayers, "image/jpeg");
99 }
100
101 public String buildGetMapUrl(Collection<LayerDetails> selectedLayers, String format) {
102 return buildRootUrl()
103 + "FORMAT=" + format + (imageFormatHasTransparency(format) ? "&TRANSPARENT=TRUE" : "")
104 + "&VERSION=1.1.1&SERVICE=WMS&REQUEST=GetMap&LAYERS="
105 + Utils.join(",", Utils.transform(selectedLayers, new Utils.Function<LayerDetails, String>() {
106 @Override
107 public String apply(LayerDetails x) {
108 return x.ident;
109 }
110 }))
111 + "&STYLES=&SRS={proj}&WIDTH={width}&HEIGHT={height}&BBOX={bbox}";
112 }
113
114 public void attemptGetCapabilities(String serviceUrlStr) throws MalformedURLException, IOException, WMSGetCapabilitiesException {
115 URL getCapabilitiesUrl = null;
116 try {
117 if (!Pattern.compile(".*GetCapabilities.*", Pattern.CASE_INSENSITIVE).matcher(serviceUrlStr).matches()) {
118 // If the url doesn't already have GetCapabilities, add it in
119 getCapabilitiesUrl = new URL(serviceUrlStr);
120 final String getCapabilitiesQuery = "VERSION=1.1.1&SERVICE=WMS&REQUEST=GetCapabilities";
121 if (getCapabilitiesUrl.getQuery() == null) {
122 getCapabilitiesUrl = new URL(serviceUrlStr + "?" + getCapabilitiesQuery);
123 } else if (!getCapabilitiesUrl.getQuery().isEmpty() && !getCapabilitiesUrl.getQuery().endsWith("&")) {
124 getCapabilitiesUrl = new URL(serviceUrlStr + "&" + getCapabilitiesQuery);
125 } else {
126 getCapabilitiesUrl = new URL(serviceUrlStr + getCapabilitiesQuery);
127 }
128 } else {
129 // Otherwise assume it's a good URL and let the subsequent error
130 // handling systems deal with problems
131 getCapabilitiesUrl = new URL(serviceUrlStr);
132 }
133 serviceUrl = new URL(serviceUrlStr);
134 } catch (HeadlessException e) {
135 return;
136 }
137
138 Main.info("GET " + getCapabilitiesUrl);
139 URLConnection openConnection = Utils.openHttpConnection(getCapabilitiesUrl);
140 StringBuilder ba = new StringBuilder();
141
142 try (
143 InputStream inputStream = openConnection.getInputStream();
144 BufferedReader br = new BufferedReader(UTFInputStreamReader.create(inputStream))
145 ) {
146 String line;
147 while ((line = br.readLine()) != null) {
148 ba.append(line);
149 ba.append('\n');
150 }
151 }
152 String incomingData = ba.toString();
153 Main.debug("Server response to Capabilities request:");
154 Main.debug(incomingData);
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 static boolean imageFormatHasTransparency(final String format) {
225 return format != null && (format.startsWith("image/png") || format.startsWith("image/gif")
226 || format.startsWith("image/svg") || format.startsWith("image/tiff"));
227 }
228
229 public ImageryInfo toImageryInfo(String name, Collection<LayerDetails> selectedLayers) {
230 ImageryInfo i = new ImageryInfo(name, buildGetMapUrl(selectedLayers));
231 if (selectedLayers != null) {
232 Set<String> proj = new HashSet<>();
233 for (WMSImagery.LayerDetails l : selectedLayers) {
234 proj.addAll(l.getProjections());
235 }
236 i.setServerProjections(proj);
237 }
238 return i;
239 }
240
241 private List<LayerDetails> parseLayers(List<Element> children, Set<String> parentCrs) {
242 List<LayerDetails> details = new ArrayList<>(children.size());
243 for (Element element : children) {
244 details.add(parseLayer(element, parentCrs));
245 }
246 return details;
247 }
248
249 private LayerDetails parseLayer(Element element, Set<String> parentCrs) {
250 String name = getChildContent(element, "Title", null, null);
251 String ident = getChildContent(element, "Name", null, null);
252
253 // The set of supported CRS/SRS for this layer
254 Set<String> crsList = new HashSet<>();
255 // ...including this layer's already-parsed parent projections
256 crsList.addAll(parentCrs);
257
258 // Parse the CRS/SRS pulled out of this layer's XML element
259 // I think CRS and SRS are the same at this point
260 List<Element> crsChildren = getChildren(element, "CRS");
261 crsChildren.addAll(getChildren(element, "SRS"));
262 for (Element child : crsChildren) {
263 String crs = (String) getContent(child);
264 if (!crs.isEmpty()) {
265 String upperCase = crs.trim().toUpperCase();
266 crsList.add(upperCase);
267 }
268 }
269
270 // Check to see if any of the specified projections are supported by JOSM
271 boolean josmSupportsThisLayer = false;
272 for (String crs : crsList) {
273 josmSupportsThisLayer |= isProjSupported(crs);
274 }
275
276 Bounds bounds = null;
277 Element bboxElem = getChild(element, "EX_GeographicBoundingBox");
278 if (bboxElem != null) {
279 // Attempt to use EX_GeographicBoundingBox for bounding box
280 double left = Double.parseDouble(getChildContent(bboxElem, "westBoundLongitude", null, null));
281 double top = Double.parseDouble(getChildContent(bboxElem, "northBoundLatitude", null, null));
282 double right = Double.parseDouble(getChildContent(bboxElem, "eastBoundLongitude", null, null));
283 double bot = Double.parseDouble(getChildContent(bboxElem, "southBoundLatitude", null, null));
284 bounds = new Bounds(bot, left, top, right);
285 } else {
286 // If that's not available, try LatLonBoundingBox
287 bboxElem = getChild(element, "LatLonBoundingBox");
288 if (bboxElem != null) {
289 double left = Double.parseDouble(bboxElem.getAttribute("minx"));
290 double top = Double.parseDouble(bboxElem.getAttribute("maxy"));
291 double right = Double.parseDouble(bboxElem.getAttribute("maxx"));
292 double bot = Double.parseDouble(bboxElem.getAttribute("miny"));
293 bounds = new Bounds(bot, left, top, right);
294 }
295 }
296
297 List<Element> layerChildren = getChildren(element, "Layer");
298 List<LayerDetails> childLayers = parseLayers(layerChildren, crsList);
299
300 return new LayerDetails(name, ident, crsList, josmSupportsThisLayer, bounds, childLayers);
301 }
302
303 private boolean isProjSupported(String crs) {
304 for (ProjectionChoice pc : ProjectionPreference.getProjectionChoices()) {
305 if (pc.getPreferencesFromCode(crs) != null) return true;
306 }
307 return false;
308 }
309
310 private static String getChildContent(Element parent, String name, String missing, String empty) {
311 Element child = getChild(parent, name);
312 if (child == null)
313 return missing;
314 else {
315 String content = (String) getContent(child);
316 return (!content.isEmpty()) ? content : empty;
317 }
318 }
319
320 private static Object getContent(Element element) {
321 NodeList nl = element.getChildNodes();
322 StringBuilder content = new StringBuilder();
323 for (int i = 0; i < nl.getLength(); i++) {
324 Node node = nl.item(i);
325 switch (node.getNodeType()) {
326 case Node.ELEMENT_NODE:
327 return node;
328 case Node.CDATA_SECTION_NODE:
329 case Node.TEXT_NODE:
330 content.append(node.getNodeValue());
331 break;
332 }
333 }
334 return content.toString().trim();
335 }
336
337 private static List<Element> getChildren(Element parent, String name) {
338 List<Element> retVal = new ArrayList<>();
339 for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {
340 if (child instanceof Element && name.equals(child.getNodeName())) {
341 retVal.add((Element) child);
342 }
343 }
344 return retVal;
345 }
346
347 private static Element getChild(Element parent, String name) {
348 if (parent == null)
349 return null;
350 for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling()) {
351 if (child instanceof Element && name.equals(child.getNodeName()))
352 return (Element) child;
353 }
354 return null;
355 }
356
357 public static class LayerDetails {
358
359 public final String name;
360 public final String ident;
361 public final List<LayerDetails> children;
362 public final Bounds bounds;
363 public final Set<String> crsList;
364 public final boolean supported;
365
366 public LayerDetails(String name, String ident, Set<String> crsList,
367 boolean supportedLayer, Bounds bounds,
368 List<LayerDetails> childLayers) {
369 this.name = name;
370 this.ident = ident;
371 this.supported = supportedLayer;
372 this.children = childLayers;
373 this.bounds = bounds;
374 this.crsList = crsList;
375 }
376
377 public boolean isSupported() {
378 return this.supported;
379 }
380
381 public Set<String> getProjections() {
382 return crsList;
383 }
384
385 @Override
386 public String toString() {
387 if (this.name == null || this.name.isEmpty())
388 return this.ident;
389 else
390 return this.name;
391 }
392
393 }
394}
Note: See TracBrowser for help on using the repository browser.