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

Last change on this file since 13741 was 13741, checked in by wiktorn, 6 years ago

PMD fixes

  • Property svn:eol-style set to native
File size: 29.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io.imagery;
3
4import static java.nio.charset.StandardCharsets.UTF_8;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.io.File;
8import java.io.IOException;
9import java.io.InputStream;
10import java.net.MalformedURLException;
11import java.net.URL;
12import java.util.ArrayList;
13import java.util.Collection;
14import java.util.Collections;
15import java.util.HashSet;
16import java.util.List;
17import java.util.Map;
18import java.util.Set;
19import java.util.concurrent.ConcurrentHashMap;
20import java.util.function.Function;
21import java.util.regex.Pattern;
22import java.util.stream.Collectors;
23
24import javax.imageio.ImageIO;
25import javax.xml.namespace.QName;
26import javax.xml.stream.XMLStreamException;
27import javax.xml.stream.XMLStreamReader;
28
29import org.openstreetmap.josm.data.Bounds;
30import org.openstreetmap.josm.data.coor.EastNorth;
31import org.openstreetmap.josm.data.imagery.DefaultLayer;
32import org.openstreetmap.josm.data.imagery.GetCapabilitiesParseHelper;
33import org.openstreetmap.josm.data.imagery.ImageryInfo;
34import org.openstreetmap.josm.data.imagery.LayerDetails;
35import org.openstreetmap.josm.data.projection.Projection;
36import org.openstreetmap.josm.data.projection.Projections;
37import org.openstreetmap.josm.io.CachedFile;
38import org.openstreetmap.josm.tools.Logging;
39import org.openstreetmap.josm.tools.Utils;
40
41/**
42 * This class represents the capabilities of a WMS imagery server.
43 */
44public class WMSImagery {
45
46
47 private static final String CAPABILITIES_QUERY_STRING = "SERVICE=WMS&REQUEST=GetCapabilities";
48
49 /**
50 * WMS namespace address
51 */
52 public static final String WMS_NS_URL = "http://www.opengis.net/wms";
53
54 // CHECKSTYLE.OFF: SingleSpaceSeparator
55 // WMS 1.0 - 1.3.0
56 private static final QName CAPABILITITES_ROOT_130 = new QName("WMS_Capabilities", WMS_NS_URL);
57 private static final QName QN_ABSTRACT = new QName(WMS_NS_URL, "Abstract");
58 private static final QName QN_CAPABILITY = new QName(WMS_NS_URL, "Capability");
59 private static final QName QN_CRS = new QName(WMS_NS_URL, "CRS");
60 private static final QName QN_DCPTYPE = new QName(WMS_NS_URL, "DCPType");
61 private static final QName QN_FORMAT = new QName(WMS_NS_URL, "Format");
62 private static final QName QN_GET = new QName(WMS_NS_URL, "Get");
63 private static final QName QN_GETMAP = new QName(WMS_NS_URL, "GetMap");
64 private static final QName QN_HTTP = new QName(WMS_NS_URL, "HTTP");
65 private static final QName QN_LAYER = new QName(WMS_NS_URL, "Layer");
66 private static final QName QN_NAME = new QName(WMS_NS_URL, "Name");
67 private static final QName QN_REQUEST = new QName(WMS_NS_URL, "Request");
68 private static final QName QN_SERVICE = new QName(WMS_NS_URL, "Service");
69 private static final QName QN_STYLE = new QName(WMS_NS_URL, "Style");
70 private static final QName QN_TITLE = new QName(WMS_NS_URL, "Title");
71 private static final QName QN_BOUNDINGBOX = new QName(WMS_NS_URL, "BoundingBox");
72 private static final QName QN_EX_GEOGRAPHIC_BBOX = new QName(WMS_NS_URL, "EX_GeographicBoundingBox");
73 private static final QName QN_WESTBOUNDLONGITUDE = new QName(WMS_NS_URL, "westBoundLongitude");
74 private static final QName QN_EASTBOUNDLONGITUDE = new QName(WMS_NS_URL, "eastBoundLongitude");
75 private static final QName QN_SOUTHBOUNDLATITUDE = new QName(WMS_NS_URL, "southBoundLatitude");
76 private static final QName QN_NORTHBOUNDLATITUDE = new QName(WMS_NS_URL, "northBoundLatitude");
77 private static final QName QN_ONLINE_RESOURCE = new QName(WMS_NS_URL, "OnlineResource");
78
79 // WMS 1.1 - 1.1.1
80 private static final QName CAPABILITIES_ROOT_111 = new QName("WMT_MS_Capabilities");
81 private static final QName QN_SRS = new QName("SRS");
82 private static final QName QN_LATLONBOUNDINGBOX = new QName("LatLonBoundingBox");
83
84 // CHECKSTYLE.ON: SingleSpaceSeparator
85
86 /**
87 * An exception that is thrown if there was an error while getting the capabilities of the WMS server.
88 */
89 public static class WMSGetCapabilitiesException extends Exception {
90 private final String incomingData;
91
92 /**
93 * Constructs a new {@code WMSGetCapabilitiesException}
94 * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method)
95 * @param incomingData the answer from WMS server
96 */
97 public WMSGetCapabilitiesException(Throwable cause, String incomingData) {
98 super(cause);
99 this.incomingData = incomingData;
100 }
101
102 /**
103 * Constructs a new {@code WMSGetCapabilitiesException}
104 * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method
105 * @param incomingData the answer from the server
106 * @since 10520
107 */
108 public WMSGetCapabilitiesException(String message, String incomingData) {
109 super(message);
110 this.incomingData = incomingData;
111 }
112
113 /**
114 * The data that caused this exception.
115 * @return The server response to the capabilities request.
116 */
117 public String getIncomingData() {
118 return incomingData;
119 }
120 }
121
122 private Map<String, String> headers = new ConcurrentHashMap<>();
123 private String version = "1.1.1"; // default version
124 private String getMapUrl;
125 private URL capabilitiesUrl;
126 private List<String> formats = new ArrayList<>();
127 private List<LayerDetails> layers = new ArrayList<>();
128
129 private String title;
130
131 /**
132 * Make getCapabilities request towards given URL
133 * @param url service url
134 * @throws IOException
135 * @throws WMSGetCapabilitiesException
136 */
137 public WMSImagery(String url) throws IOException, WMSGetCapabilitiesException {
138 this(url, null);
139 }
140
141 /**
142 * Make getCapabilities request towards given URL using headers
143 * @param url service url
144 * @param headers HTTP headers to be sent with request
145 * @throws IOException
146 * @throws WMSGetCapabilitiesException
147 */
148 public WMSImagery(String url, Map<String, String> headers) throws IOException, WMSGetCapabilitiesException {
149 if (headers != null) {
150 this.headers.putAll(headers);
151 }
152
153 IOException savedExc = null;
154 String workingAddress = null;
155 url_search:
156 for (String z: new String[]{
157 normalizeUrl(url),
158 url,
159 url + CAPABILITIES_QUERY_STRING,
160 }) {
161 for (String ver: new String[]{"", "&VERSION=1.3.0", "&VERSION=1.1.1"}) {
162 try {
163 attemptGetCapabilities(z + ver);
164 workingAddress = z;
165 calculateChildren();
166 // clear saved exception - we've got something working
167 savedExc = null;
168 break url_search;
169 } catch (IOException e) {
170 savedExc = e;
171 Logging.warn(e);
172 }
173 }
174 }
175
176 if (workingAddress != null) {
177 try {
178 capabilitiesUrl = new URL(workingAddress);
179 } catch (MalformedURLException e) {
180 if (savedExc != null) {
181 savedExc = e;
182 }
183 try {
184 capabilitiesUrl = new File(workingAddress).toURI().toURL();
185 } catch (MalformedURLException e1) { // NOPMD
186 // do nothing, raise original exception
187 }
188 }
189 }
190
191 if (savedExc != null) {
192 throw savedExc;
193 }
194 }
195
196 private void calculateChildren() {
197 Map<LayerDetails, List<LayerDetails>> layerChildren = layers.stream()
198 .filter(x -> x.getParent() != null) // exclude top-level elements
199 .collect(Collectors.groupingBy(LayerDetails::getParent));
200 for (LayerDetails ld: layers) {
201 if (layerChildren.containsKey(ld)) {
202 ld.setChildren(layerChildren.get(ld));
203 }
204 }
205 // leave only top-most elements in the list
206 layers = layers.stream().filter(x -> x.getParent() == null).collect(Collectors.toCollection(ArrayList::new));
207 }
208
209 /**
210 * Returns the list of top-level layers.
211 * @return the list of top-level layers
212 */
213 public List<LayerDetails> getLayers() {
214 return Collections.unmodifiableList(layers);
215 }
216
217 /**
218 * Returns the list of supported formats.
219 * @return the list of supported formats
220 */
221 public Collection<String> getFormats() {
222 return Collections.unmodifiableList(formats);
223 }
224
225 /**
226 * Gets the preferred format for this imagery layer.
227 * @return The preferred format as mime type.
228 */
229 public String getPreferredFormat() {
230 if (formats.contains("image/png")) {
231 return "image/png";
232 } else if (formats.contains("image/jpeg")) {
233 return "image/jpeg";
234 } else if (formats.isEmpty()) {
235 return null;
236 } else {
237 return formats.get(0);
238 }
239 }
240
241 /**
242 * @return root URL of services in this GetCapabilities
243 */
244 public String buildRootUrl() {
245 if (getMapUrl == null && capabilitiesUrl == null) {
246 return null;
247 }
248 if (getMapUrl != null) {
249 return getMapUrl;
250 }
251
252 URL serviceUrl = capabilitiesUrl;
253 StringBuilder a = new StringBuilder(serviceUrl.getProtocol());
254 a.append("://").append(serviceUrl.getHost());
255 if (serviceUrl.getPort() != -1) {
256 a.append(':').append(serviceUrl.getPort());
257 }
258 a.append(serviceUrl.getPath()).append('?');
259 if (serviceUrl.getQuery() != null) {
260 a.append(serviceUrl.getQuery());
261 if (!serviceUrl.getQuery().isEmpty() && !serviceUrl.getQuery().endsWith("&")) {
262 a.append('&');
263 }
264 }
265 return a.toString();
266 }
267
268 /**
269 * Returns URL for accessing GetMap service. String will contain following parameters:
270 * * {proj} - that needs to be replaced with projection (one of {@link #getServerProjections(List)})
271 * * {width} - that needs to be replaced with width of the tile
272 * * {height} - that needs to be replaces with height of the tile
273 * * {bbox} - that needs to be replaced with area that should be fetched (in {proj} coordinates)
274 *
275 * Format of the response will be calculated using {@link #getPreferredFormat()}
276 *
277 * @param selectedLayers list of DefaultLayer selection of layers to be shown
278 * @param transparent whether returned images should contain transparent pixels (if supported by format)
279 * @return URL template for GetMap service containing
280 */
281 public String buildGetMapUrl(List<DefaultLayer> selectedLayers, boolean transparent) {
282 return buildGetMapUrl(
283 getLayers(selectedLayers),
284 selectedLayers.stream().map(x -> x.getStyle()).collect(Collectors.toList()),
285 transparent);
286 }
287
288 /**
289 * @see #buildGetMapUrl(List, boolean)
290 *
291 * @param selectedLayers selected layers as subset of the tree returned by {@link #getLayers()}
292 * @param selectedStyles selected styles for all selectedLayers
293 * @param transparent whether returned images should contain transparent pixels (if supported by format)
294 * @return URL template for GetMap service
295 */
296 public String buildGetMapUrl(List<LayerDetails> selectedLayers, List<String> selectedStyles, boolean transparent) {
297 return buildGetMapUrl(
298 selectedLayers.stream().map(x -> x.getName()).collect(Collectors.toList()),
299 selectedStyles,
300 getPreferredFormat(),
301 transparent);
302 }
303
304 /**
305 * @see #buildGetMapUrl(List, boolean)
306 *
307 * @param selectedLayers selected layers as list of strings
308 * @param selectedStyles selected styles of layers as list of strings
309 * @param format format of the response - one of {@link #getFormats()}
310 * @param transparent whether returned images should contain transparent pixels (if supported by format)
311 * @return URL template for GetMap service
312 */
313 public String buildGetMapUrl(List<String> selectedLayers,
314 Collection<String> selectedStyles,
315 String format,
316 boolean transparent) {
317
318 Utils.ensure(selectedStyles == null || selectedLayers.size() == selectedStyles.size(),
319 tr("Styles size {0} doesn't match layers size {1}"),
320 selectedStyles == null ? 0 : selectedStyles.size(),
321 selectedLayers.size());
322
323 return buildRootUrl() + "FORMAT=" + format + ((imageFormatHasTransparency(format) && transparent) ? "&TRANSPARENT=TRUE" : "")
324 + "&VERSION=" + this.version + "&SERVICE=WMS&REQUEST=GetMap&LAYERS="
325 + selectedLayers.stream().collect(Collectors.joining(","))
326 + "&STYLES="
327 + (selectedStyles != null ? Utils.join(",", selectedStyles) : "")
328 + "&"
329 + (belowWMS130() ? "SRS" : "CRS")
330 + "={proj}&WIDTH={width}&HEIGHT={height}&BBOX={bbox}";
331 }
332
333 private boolean tagEquals(QName a, QName b) {
334 boolean ret = a.equals(b);
335 if (ret) {
336 return ret;
337 }
338
339 if (belowWMS130()) {
340 return a.getLocalPart().equals(b.getLocalPart());
341 }
342
343 return false;
344 }
345
346 private void attemptGetCapabilities(String url) throws IOException, WMSGetCapabilitiesException {
347 Logging.debug("Trying WMS getcapabilities with url {0}", url);
348 try (CachedFile cf = new CachedFile(url); InputStream in = cf.setHttpHeaders(headers).
349 setMaxAge(7 * CachedFile.DAYS).
350 setCachingStrategy(CachedFile.CachingStrategy.IfModifiedSince).
351 getInputStream()) {
352
353 try {
354 XMLStreamReader reader = GetCapabilitiesParseHelper.getReader(in);
355 for (int event = reader.getEventType(); reader.hasNext(); event = reader.next()) {
356 if (event == XMLStreamReader.START_ELEMENT) {
357 if (tagEquals(CAPABILITIES_ROOT_111, reader.getName())) {
358 // version 1.1.1
359 this.version = reader.getAttributeValue(null, "version");
360 if (this.version == null) {
361 this.version = "1.1.1";
362 }
363 }
364 if (tagEquals(CAPABILITITES_ROOT_130, reader.getName())) {
365 this.version = reader.getAttributeValue(WMS_NS_URL, "version");
366 }
367 if (tagEquals(QN_SERVICE, reader.getName())) {
368 parseService(reader);
369 }
370
371 if (tagEquals(QN_CAPABILITY, reader.getName())) {
372 parseCapability(reader);
373 }
374 }
375 }
376 } catch (XMLStreamException e) {
377 String content = new String(cf.getByteContent(), UTF_8);
378 cf.clear(); // if there is a problem with parsing of the file, remove it from the cache
379 throw new WMSGetCapabilitiesException(e, content);
380 }
381 }
382 }
383
384 private void parseService(XMLStreamReader reader) throws XMLStreamException {
385 if (GetCapabilitiesParseHelper.moveReaderToTag(reader, this::tagEquals, QN_TITLE)) {
386 this.title = reader.getElementText();
387 for (int event = reader.getEventType();
388 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && tagEquals(QN_SERVICE, reader.getName()));
389 event = reader.next()) {
390 // empty loop, just move reader to the end of Service tag, if moveReaderToTag return false, it's already done
391 }
392 }
393 }
394
395 private void parseCapability(XMLStreamReader reader) throws XMLStreamException {
396 for (int event = reader.getEventType();
397 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && tagEquals(QN_CAPABILITY, reader.getName()));
398 event = reader.next()) {
399
400 if (event == XMLStreamReader.START_ELEMENT) {
401 if (tagEquals(QN_REQUEST, reader.getName())) {
402 parseRequest(reader);
403 }
404 if (tagEquals(QN_LAYER, reader.getName())) {
405 parseLayer(reader, null);
406 }
407 }
408 }
409 }
410
411 private void parseRequest(XMLStreamReader reader) throws XMLStreamException {
412 String mode = "";
413 String getMapUrl = "";
414 if (GetCapabilitiesParseHelper.moveReaderToTag(reader, this::tagEquals, QN_GETMAP)) {
415 for (int event = reader.getEventType();
416 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && tagEquals(QN_GETMAP, reader.getName()));
417 event = reader.next()) {
418
419 if (event == XMLStreamReader.START_ELEMENT) {
420 if (tagEquals(QN_FORMAT, reader.getName())) {
421 String value = reader.getElementText();
422 if (isImageFormatSupportedWarn(value) && !this.formats.contains(value)) {
423 this.formats.add(value);
424 }
425 }
426 if (tagEquals(QN_DCPTYPE, reader.getName()) && GetCapabilitiesParseHelper.moveReaderToTag(reader,
427 this::tagEquals, QN_HTTP, QN_GET)) {
428 mode = reader.getName().getLocalPart();
429 if (GetCapabilitiesParseHelper.moveReaderToTag(reader, this::tagEquals, QN_ONLINE_RESOURCE)) {
430 getMapUrl = reader.getAttributeValue(GetCapabilitiesParseHelper.XLINK_NS_URL, "href");
431 }
432 // TODO should we handle also POST?
433 if ("GET".equalsIgnoreCase(mode) && getMapUrl != null && !"".equals(getMapUrl)) {
434 this.getMapUrl = getMapUrl;
435 }
436 }
437 }
438 }
439 }
440 }
441
442 private void parseLayer(XMLStreamReader reader, LayerDetails parentLayer) throws XMLStreamException {
443 LayerDetails ret = new LayerDetails(parentLayer);
444 for (int event = reader.next(); // start with advancing reader by one element to get the contents of the layer
445 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && tagEquals(QN_LAYER, reader.getName()));
446 event = reader.next()) {
447
448 if (event == XMLStreamReader.START_ELEMENT) {
449 if (tagEquals(QN_NAME, reader.getName())) {
450 ret.setName(reader.getElementText());
451 }
452 if (tagEquals(QN_ABSTRACT, reader.getName())) {
453 ret.setAbstract(GetCapabilitiesParseHelper.getElementTextWithSubtags(reader));
454 }
455 if (tagEquals(QN_TITLE, reader.getName())) {
456 ret.setTitle(reader.getElementText());
457 }
458 if (tagEquals(QN_CRS, reader.getName())) {
459 ret.addCrs(reader.getElementText());
460 }
461 if (tagEquals(QN_SRS, reader.getName()) && belowWMS130()) {
462 ret.addCrs(reader.getElementText());
463 }
464 if (tagEquals(QN_STYLE, reader.getName())) {
465 parseAndAddStyle(reader, ret);
466 }
467 if (tagEquals(QN_LAYER, reader.getName())) {
468
469 parseLayer(reader, ret);
470 }
471 if (tagEquals(QN_EX_GEOGRAPHIC_BBOX, reader.getName())) {
472 if (ret.getBounds() == null) {
473 Bounds bbox = parseExGeographic(reader);
474 ret.setBounds(bbox);
475 }
476
477 }
478 if (tagEquals(QN_BOUNDINGBOX, reader.getName())) {
479 Projection conv;
480 if (belowWMS130()) {
481 conv = Projections.getProjectionByCode(reader.getAttributeValue(WMS_NS_URL, "SRS"));
482 } else {
483 conv = Projections.getProjectionByCode(reader.getAttributeValue(WMS_NS_URL, "CRS"));
484 }
485 if (ret.getBounds() == null && conv != null) {
486 Bounds bbox = parseBoundingBox(reader, conv);
487 ret.setBounds(bbox);
488 }
489 }
490 if (tagEquals(QN_LATLONBOUNDINGBOX, reader.getName()) && belowWMS130()) {
491 if (ret.getBounds() == null) {
492 Bounds bbox = parseBoundingBox(reader, null);
493 ret.setBounds(bbox);
494 }
495 }
496 }
497 }
498 this.layers.add(ret);
499 }
500
501 /**
502 * @return if this service operates at protocol level below 1.3.0
503 */
504 public boolean belowWMS130() {
505 return this.version.equals("1.1.1") || this.version.equals("1.1") || this.version.equals("1.0");
506 }
507
508 private void parseAndAddStyle(XMLStreamReader reader, LayerDetails ld) throws XMLStreamException {
509 String name = null;
510 String title = null;
511 for (int event = reader.getEventType();
512 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && tagEquals(QN_STYLE, reader.getName()));
513 event = reader.next()) {
514 if (event == XMLStreamReader.START_ELEMENT) {
515 if (tagEquals(QN_NAME, reader.getName())) {
516 name = reader.getElementText();
517 }
518 if (tagEquals(QN_TITLE, reader.getName())) {
519 title = reader.getElementText();
520 }
521 }
522 }
523 if (name == null) {
524 name = "";
525 }
526 ld.addStyle(name, title);
527 }
528
529 private Bounds parseExGeographic(XMLStreamReader reader) throws XMLStreamException {
530 String minx = null, maxx = null, maxy = null, miny = null;
531
532 for (int event = reader.getEventType();
533 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && tagEquals(QN_EX_GEOGRAPHIC_BBOX, reader.getName()));
534 event = reader.next()) {
535 if (event == XMLStreamReader.START_ELEMENT) {
536 if (tagEquals(QN_WESTBOUNDLONGITUDE, reader.getName())) {
537 minx = reader.getElementText();
538 }
539
540 if (tagEquals(QN_EASTBOUNDLONGITUDE, reader.getName())) {
541 maxx = reader.getElementText();
542 }
543
544 if (tagEquals(QN_SOUTHBOUNDLATITUDE, reader.getName())) {
545 miny = reader.getElementText();
546 }
547
548 if (tagEquals(QN_NORTHBOUNDLATITUDE, reader.getName())) {
549 maxy = reader.getElementText();
550 }
551 }
552 }
553 return parseBBox(null, miny, minx, maxy, maxx);
554 }
555
556 private Bounds parseBoundingBox(XMLStreamReader reader, Projection conv) {
557 Function<String, String> attrGetter = tag -> belowWMS130() ?
558 reader.getAttributeValue(null, tag)
559 : reader.getAttributeValue(WMS_NS_URL, tag);
560
561 return parseBBox(
562 conv,
563 attrGetter.apply("miny"),
564 attrGetter.apply("minx"),
565 attrGetter.apply("maxy"),
566 attrGetter.apply("maxx")
567 );
568 }
569
570 private Bounds parseBBox(Projection conv, String miny, String minx, String maxy, String maxx) {
571 if (miny == null || minx == null || maxy == null || maxx == null) {
572 return null;
573 }
574 if (conv != null) {
575 new Bounds(
576 conv.eastNorth2latlon(new EastNorth(getDecimalDegree(minx), getDecimalDegree(miny))),
577 conv.eastNorth2latlon(new EastNorth(getDecimalDegree(maxx), getDecimalDegree(maxy)))
578 );
579 }
580 return new Bounds(
581 getDecimalDegree(miny),
582 getDecimalDegree(minx),
583 getDecimalDegree(maxy),
584 getDecimalDegree(maxx)
585 );
586 }
587
588 private static double getDecimalDegree(String value) {
589 // Some real-world WMS servers use a comma instead of a dot as decimal separator (seen in Polish WMS server)
590 return Double.parseDouble(value.replace(',', '.'));
591 }
592
593
594 private String normalizeUrl(String serviceUrlStr) throws MalformedURLException {
595 URL getCapabilitiesUrl = null;
596 String ret = null;
597
598 if (!Pattern.compile(".*GetCapabilities.*", Pattern.CASE_INSENSITIVE).matcher(serviceUrlStr).matches()) {
599 // If the url doesn't already have GetCapabilities, add it in
600 getCapabilitiesUrl = new URL(serviceUrlStr);
601 ret = serviceUrlStr;
602 if (getCapabilitiesUrl.getQuery() == null) {
603 ret = serviceUrlStr + '?' + CAPABILITIES_QUERY_STRING;
604 } else if (!getCapabilitiesUrl.getQuery().isEmpty() && !getCapabilitiesUrl.getQuery().endsWith("&")) {
605 ret = serviceUrlStr + '&' + CAPABILITIES_QUERY_STRING;
606 } else {
607 ret = serviceUrlStr + CAPABILITIES_QUERY_STRING;
608 }
609 } else {
610 // Otherwise assume it's a good URL and let the subsequent error
611 // handling systems deal with problems
612 ret = serviceUrlStr;
613 }
614 return ret;
615 }
616
617 private static boolean isImageFormatSupportedWarn(String format) {
618 boolean isFormatSupported = isImageFormatSupported(format);
619 if (!isFormatSupported) {
620 Logging.info("Skipping unsupported image format {0}", format);
621 }
622 return isFormatSupported;
623 }
624
625 static boolean isImageFormatSupported(final String format) {
626 return ImageIO.getImageReadersByMIMEType(format).hasNext()
627 // handles image/tiff image/tiff8 image/geotiff image/geotiff8
628 || isImageFormatSupported(format, "tiff", "geotiff")
629 || isImageFormatSupported(format, "png")
630 || isImageFormatSupported(format, "svg")
631 || isImageFormatSupported(format, "bmp");
632 }
633
634 static boolean isImageFormatSupported(String format, String... mimeFormats) {
635 for (String mime : mimeFormats) {
636 if (format.startsWith("image/" + mime)) {
637 return ImageIO.getImageReadersBySuffix(mimeFormats[0]).hasNext();
638 }
639 }
640 return false;
641 }
642
643
644 static boolean imageFormatHasTransparency(final String format) {
645 return format != null && (format.startsWith("image/png") || format.startsWith("image/gif")
646 || format.startsWith("image/svg") || format.startsWith("image/tiff"));
647 }
648
649 /**
650 * Creates ImageryInfo object from this GetCapabilities document
651 *
652 * @param name name of imagery layer
653 * @param selectedLayers layers which are to be used by this imagery layer
654 * @param selectedStyles styles that should be used for selectedLayers
655 * @param transparent if layer should be transparent
656 * @return ImageryInfo object
657 */
658 public ImageryInfo toImageryInfo(String name, List<LayerDetails> selectedLayers, List<String> selectedStyles, boolean transparent) {
659 ImageryInfo i = new ImageryInfo(name, buildGetMapUrl(selectedLayers, selectedStyles, transparent));
660 if (selectedLayers != null && !selectedLayers.isEmpty()) {
661 i.setServerProjections(getServerProjections(selectedLayers));
662 }
663 return i;
664 }
665
666 /**
667 * Returns projections that server supports for provided list of layers. This will be intersection of projections
668 * defined for each layer
669 *
670 * @param selectedLayers list of layers
671 * @return projection code
672 */
673 public Collection<String> getServerProjections(List<LayerDetails> selectedLayers) {
674 if (selectedLayers.isEmpty()) {
675 return Collections.emptyList();
676 }
677 Set<String> proj = new HashSet<>(selectedLayers.get(0).getCrs());
678
679 // set intersect with all layers
680 for (LayerDetails ld: selectedLayers) {
681 proj.retainAll(ld.getCrs());
682 }
683 return proj;
684 }
685
686
687 /**
688 * @param defaultLayers
689 * @return collection of LayerDetails specified by DefaultLayers
690 */
691 public List<LayerDetails> getLayers(List<DefaultLayer> defaultLayers) {
692 Collection<String> layerNames = defaultLayers.stream().map(x -> x.getLayerName()).collect(Collectors.toList());
693 return layers.stream()
694 .flatMap(LayerDetails::flattened)
695 .filter(x -> layerNames.contains(x.getName()))
696 .collect(Collectors.toList());
697 }
698
699 /**
700 * @return title of this service
701 */
702 public String getTitle() {
703 return title;
704 }
705}
Note: See TracBrowser for help on using the repository browser.