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

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

Rework console output:

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