source: josm/trunk/src/org/openstreetmap/josm/data/imagery/WMTSTileSource.java@ 11792

Last change on this file since 11792 was 11792, checked in by bastiK, 7 years ago

fixed #14590 - WMTS: Show layer title, not layer identifier in layer selection dialog

  • Property svn:eol-style set to native
File size: 38.2 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.imagery;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.GridBagLayout;
7import java.awt.Point;
8import java.io.ByteArrayInputStream;
9import java.io.IOException;
10import java.io.InputStream;
11import java.nio.charset.StandardCharsets;
12import java.util.ArrayList;
13import java.util.Arrays;
14import java.util.Collection;
15import java.util.Collections;
16import java.util.HashSet;
17import java.util.List;
18import java.util.Map;
19import java.util.Map.Entry;
20import java.util.Objects;
21import java.util.Optional;
22import java.util.Set;
23import java.util.SortedSet;
24import java.util.Stack;
25import java.util.TreeSet;
26import java.util.concurrent.ConcurrentHashMap;
27import java.util.regex.Matcher;
28import java.util.regex.Pattern;
29import java.util.stream.Collectors;
30
31import javax.imageio.ImageIO;
32import javax.swing.JPanel;
33import javax.swing.JScrollPane;
34import javax.swing.JTable;
35import javax.swing.ListSelectionModel;
36import javax.swing.table.AbstractTableModel;
37import javax.xml.namespace.QName;
38import javax.xml.stream.XMLStreamException;
39import javax.xml.stream.XMLStreamReader;
40
41import org.openstreetmap.gui.jmapviewer.Coordinate;
42import org.openstreetmap.gui.jmapviewer.Tile;
43import org.openstreetmap.gui.jmapviewer.TileXY;
44import org.openstreetmap.gui.jmapviewer.interfaces.ICoordinate;
45import org.openstreetmap.gui.jmapviewer.interfaces.TemplatedTileSource;
46import org.openstreetmap.gui.jmapviewer.tilesources.AbstractTMSTileSource;
47import org.openstreetmap.josm.Main;
48import org.openstreetmap.josm.data.coor.EastNorth;
49import org.openstreetmap.josm.data.coor.LatLon;
50import org.openstreetmap.josm.data.projection.Projection;
51import org.openstreetmap.josm.data.projection.Projections;
52import org.openstreetmap.josm.gui.ExtendedDialog;
53import org.openstreetmap.josm.gui.layer.NativeScaleLayer.ScaleList;
54import org.openstreetmap.josm.io.CachedFile;
55import org.openstreetmap.josm.tools.CheckParameterUtil;
56import org.openstreetmap.josm.tools.GBC;
57import org.openstreetmap.josm.tools.Utils;
58
59/**
60 * Tile Source handling WMS providers
61 *
62 * @author Wiktor Niesiobędzki
63 * @since 8526
64 */
65public class WMTSTileSource extends AbstractTMSTileSource implements TemplatedTileSource {
66 /**
67 * WMTS namespace address
68 */
69 public static final String WMTS_NS_URL = "http://www.opengis.net/wmts/1.0";
70
71 // CHECKSTYLE.OFF: SingleSpaceSeparator
72 private static final QName QN_CONTENTS = new QName(WMTSTileSource.WMTS_NS_URL, "Contents");
73 private static final QName QN_FORMAT = new QName(WMTSTileSource.WMTS_NS_URL, "Format");
74 private static final QName QN_LAYER = new QName(WMTSTileSource.WMTS_NS_URL, "Layer");
75 private static final QName QN_MATRIX_WIDTH = new QName(WMTSTileSource.WMTS_NS_URL, "MatrixWidth");
76 private static final QName QN_MATRIX_HEIGHT = new QName(WMTSTileSource.WMTS_NS_URL, "MatrixHeight");
77 private static final QName QN_RESOURCE_URL = new QName(WMTSTileSource.WMTS_NS_URL, "ResourceURL");
78 private static final QName QN_SCALE_DENOMINATOR = new QName(WMTSTileSource.WMTS_NS_URL, "ScaleDenominator");
79 private static final QName QN_STYLE = new QName(WMTSTileSource.WMTS_NS_URL, "Style");
80 private static final QName QN_TILEMATRIX = new QName(WMTSTileSource.WMTS_NS_URL, "TileMatrix");
81 private static final QName QN_TILEMATRIXSET = new QName(WMTSTileSource.WMTS_NS_URL, "TileMatrixSet");
82 private static final QName QN_TILEMATRIX_SET_LINK = new QName(WMTSTileSource.WMTS_NS_URL, "TileMatrixSetLink");
83 private static final QName QN_TILE_WIDTH = new QName(WMTSTileSource.WMTS_NS_URL, "TileWidth");
84 private static final QName QN_TILE_HEIGHT = new QName(WMTSTileSource.WMTS_NS_URL, "TileHeight");
85 private static final QName QN_TOPLEFT_CORNER = new QName(WMTSTileSource.WMTS_NS_URL, "TopLeftCorner");
86 // CHECKSTYLE.ON: SingleSpaceSeparator
87
88 private static final String PATTERN_HEADER = "\\{header\\(([^,]+),([^}]+)\\)\\}";
89
90 private static final String URL_GET_ENCODING_PARAMS = "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER={layer}&STYLE={style}&"
91 + "FORMAT={format}&tileMatrixSet={TileMatrixSet}&tileMatrix={TileMatrix}&tileRow={TileRow}&tileCol={TileCol}";
92
93 private static final String[] ALL_PATTERNS = {
94 PATTERN_HEADER,
95 };
96
97 private static class TileMatrix {
98 private String identifier;
99 private double scaleDenominator;
100 private EastNorth topLeftCorner;
101 private int tileWidth;
102 private int tileHeight;
103 private int matrixWidth = -1;
104 private int matrixHeight = -1;
105 }
106
107 private static class TileMatrixSetBuilder {
108 // sorted by zoom level
109 SortedSet<TileMatrix> tileMatrix = new TreeSet<>((o1, o2) -> -1 * Double.compare(o1.scaleDenominator, o2.scaleDenominator));
110 private String crs;
111 private String identifier;
112
113 TileMatrixSet build() {
114 return new TileMatrixSet(this);
115 }
116 }
117
118 private static class TileMatrixSet {
119
120 private final List<TileMatrix> tileMatrix;
121 private final String crs;
122 private final String identifier;
123
124 TileMatrixSet(TileMatrixSet tileMatrixSet) {
125 if (tileMatrixSet != null) {
126 tileMatrix = new ArrayList<>(tileMatrixSet.tileMatrix);
127 crs = tileMatrixSet.crs;
128 identifier = tileMatrixSet.identifier;
129 } else {
130 tileMatrix = Collections.emptyList();
131 crs = null;
132 identifier = null;
133 }
134 }
135
136 TileMatrixSet(TileMatrixSetBuilder builder) {
137 tileMatrix = new ArrayList<>(builder.tileMatrix);
138 crs = builder.crs;
139 identifier = builder.identifier;
140 }
141
142 }
143
144 private static class Layer {
145 private String format;
146 private String identifier;
147 private String title;
148 private TileMatrixSet tileMatrixSet;
149 private String baseUrl;
150 private String style;
151 private final Collection<String> tileMatrixSetLinks = new ArrayList<>();
152
153 Layer(Layer l) {
154 Objects.requireNonNull(l);
155 format = l.format;
156 identifier = l.identifier;
157 title = l.title;
158 baseUrl = l.baseUrl;
159 style = l.style;
160 tileMatrixSet = new TileMatrixSet(l.tileMatrixSet);
161 }
162
163 Layer() {
164 }
165
166 /**
167 * Get title of the layer for user display.
168 *
169 * This is either the content of the Title element (if available) or
170 * the layer identifier (as fallback)
171 * @return title of the layer for user display
172 */
173 public String getUserTitle() {
174 return title != null ? title : identifier;
175 }
176 }
177
178 private static final class SelectLayerDialog extends ExtendedDialog {
179 private final transient List<Entry<String, List<Layer>>> layers;
180 private final JTable list;
181
182 SelectLayerDialog(Collection<Layer> layers) {
183 super(Main.parent, tr("Select WMTS layer"), new String[]{tr("Add layers"), tr("Cancel")});
184 this.layers = groupLayersByNameAndTileMatrixSet(layers);
185 //getLayersTable(layers, Main.getProjection())
186 this.list = new JTable(
187 new AbstractTableModel() {
188 @Override
189 public Object getValueAt(int rowIndex, int columnIndex) {
190 switch (columnIndex) {
191 case 0:
192 return SelectLayerDialog.this.layers.get(rowIndex).getValue()
193 .stream()
194 .map(x -> x.getUserTitle())
195 .collect(Collectors.joining(", ")); //this should be only one
196 case 1:
197 return SelectLayerDialog.this.layers.get(rowIndex).getValue()
198 .stream()
199 .map(x -> x.tileMatrixSet.crs)
200 .collect(Collectors.joining(", "));
201 case 2:
202 return SelectLayerDialog.this.layers.get(rowIndex).getValue()
203 .stream()
204 .map(x -> x.tileMatrixSet.identifier)
205 .collect(Collectors.joining(", ")); //this should be only one
206 default:
207 throw new IllegalArgumentException();
208 }
209 }
210
211 @Override
212 public int getRowCount() {
213 return SelectLayerDialog.this.layers.size();
214 }
215
216 @Override
217 public int getColumnCount() {
218 return 3;
219 }
220
221 @Override
222 public String getColumnName(int column) {
223 switch (column) {
224 case 0: return tr("Layer name");
225 case 1: return tr("Projection");
226 case 2: return tr("Matrix set identifier");
227 default:
228 throw new IllegalArgumentException();
229 }
230 }
231 });
232 this.list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
233 this.list.setRowSelectionAllowed(true);
234 this.list.setColumnSelectionAllowed(false);
235 JPanel panel = new JPanel(new GridBagLayout());
236 panel.add(new JScrollPane(this.list), GBC.eol().fill());
237 setContent(panel);
238 }
239
240 public DefaultLayer getSelectedLayer() {
241 int index = list.getSelectedRow();
242 if (index < 0) {
243 return null; //nothing selected
244 }
245 Layer selectedLayer = layers.get(index).getValue().get(0);
246 return new WMTSDefaultLayer(selectedLayer.identifier, selectedLayer.tileMatrixSet.identifier);
247 }
248 }
249
250 private final Map<String, String> headers = new ConcurrentHashMap<>();
251 private final Collection<Layer> layers;
252 private Layer currentLayer;
253 private TileMatrixSet currentTileMatrixSet;
254 private double crsScale;
255 private GetCapabilitiesParseHelper.TransferMode transferMode;
256
257 private ScaleList nativeScaleList;
258
259 private final WMTSDefaultLayer defaultLayer;
260
261
262 /**
263 * Creates a tile source based on imagery info
264 * @param info imagery info
265 * @throws IOException if any I/O error occurs
266 * @throws IllegalArgumentException if any other error happens for the given imagery info
267 */
268 public WMTSTileSource(ImageryInfo info) throws IOException {
269 super(info);
270 CheckParameterUtil.ensureThat(info.getDefaultLayers().size() < 2, "At most 1 default layer for WMTS is supported");
271
272 this.baseUrl = GetCapabilitiesParseHelper.normalizeCapabilitiesUrl(handleTemplate(info.getUrl()));
273 this.layers = getCapabilities();
274 this.defaultLayer = info.getDefaultLayers().isEmpty() ? null : (WMTSDefaultLayer) info.getDefaultLayers().iterator().next();
275 if (this.layers.isEmpty())
276 throw new IllegalArgumentException(tr("No layers defined by getCapabilities document: {0}", info.getUrl()));
277 }
278
279 /**
280 * Creates a dialog based on this tile source with all available layers and returns the name of selected layer
281 * @return Name of selected layer
282 */
283 public DefaultLayer userSelectLayer() {
284 Map<String, List<Layer>> layerById = layers.stream().collect(
285 Collectors.groupingBy(x -> x.identifier));
286 if (layerById.size() == 1) { // only one layer
287 List<Layer> ls = layerById.entrySet().iterator().next().getValue()
288 .stream().filter(
289 u -> u.tileMatrixSet.crs.equals(Main.getProjection().toCode()))
290 .collect(Collectors.toList());
291 if (ls.size() == 1) {
292 // only one tile matrix set with matching projection - no point in asking
293 Layer selectedLayer = ls.get(0);
294 return new WMTSDefaultLayer(selectedLayer.identifier, selectedLayer.tileMatrixSet.identifier);
295 }
296 }
297
298 final SelectLayerDialog layerSelection = new SelectLayerDialog(layers);
299 if (layerSelection.showDialog().getValue() == 1) {
300 return layerSelection.getSelectedLayer();
301 }
302 return null;
303 }
304
305 private String handleTemplate(String url) {
306 Pattern pattern = Pattern.compile(PATTERN_HEADER);
307 StringBuffer output = new StringBuffer();
308 Matcher matcher = pattern.matcher(url);
309 while (matcher.find()) {
310 this.headers.put(matcher.group(1), matcher.group(2));
311 matcher.appendReplacement(output, "");
312 }
313 matcher.appendTail(output);
314 return output.toString();
315 }
316
317 private static List<Entry<String, List<Layer>>> groupLayersByNameAndTileMatrixSet(Collection<Layer> layers) {
318 Map<String, List<Layer>> layerByName = layers.stream().collect(
319 Collectors.groupingBy(x -> x.identifier + '\u001c' + x.tileMatrixSet.identifier));
320 return layerByName.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList());
321 }
322
323 /**
324 * @return capabilities
325 * @throws IOException in case of any I/O error
326 * @throws IllegalArgumentException in case of any other error
327 */
328 private Collection<Layer> getCapabilities() throws IOException {
329 try (CachedFile cf = new CachedFile(baseUrl); InputStream in = cf.setHttpHeaders(headers).
330 setMaxAge(7 * CachedFile.DAYS).
331 setCachingStrategy(CachedFile.CachingStrategy.IfModifiedSince).
332 getInputStream()) {
333 byte[] data = Utils.readBytesFromStream(in);
334 if (data.length == 0) {
335 cf.clear();
336 throw new IllegalArgumentException("Could not read data from: " + baseUrl);
337 }
338
339 try {
340 XMLStreamReader reader = GetCapabilitiesParseHelper.getReader(new ByteArrayInputStream(data));
341 Collection<Layer> ret = new ArrayList<>();
342 for (int event = reader.getEventType(); reader.hasNext(); event = reader.next()) {
343 if (event == XMLStreamReader.START_ELEMENT) {
344 if (GetCapabilitiesParseHelper.QN_OWS_OPERATIONS_METADATA.equals(reader.getName())) {
345 parseOperationMetadata(reader);
346 }
347
348 if (QN_CONTENTS.equals(reader.getName())) {
349 ret = parseContents(reader);
350 }
351 }
352 }
353 return ret;
354 } catch (XMLStreamException e) {
355 cf.clear();
356 Main.warn(new String(data, StandardCharsets.UTF_8));
357 throw new IllegalArgumentException(e);
358 }
359 }
360 }
361
362 /**
363 * Parse Contents tag. Returns when reader reaches Contents closing tag
364 *
365 * @param reader StAX reader instance
366 * @return collection of layers within contents with properly linked TileMatrixSets
367 * @throws XMLStreamException See {@link XMLStreamReader}
368 */
369 private static Collection<Layer> parseContents(XMLStreamReader reader) throws XMLStreamException {
370 Map<String, TileMatrixSet> matrixSetById = new ConcurrentHashMap<>();
371 Collection<Layer> layers = new ArrayList<>();
372 for (int event = reader.getEventType();
373 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && QN_CONTENTS.equals(reader.getName()));
374 event = reader.next()) {
375 if (event == XMLStreamReader.START_ELEMENT) {
376 if (QN_LAYER.equals(reader.getName())) {
377 Layer l = parseLayer(reader);
378 if (l != null) {
379 layers.add(l);
380 }
381 }
382 if (QN_TILEMATRIXSET.equals(reader.getName())) {
383 TileMatrixSet entry = parseTileMatrixSet(reader);
384 matrixSetById.put(entry.identifier, entry);
385 }
386 }
387 }
388 Collection<Layer> ret = new ArrayList<>();
389 // link layers to matrix sets
390 for (Layer l: layers) {
391 for (String tileMatrixId: l.tileMatrixSetLinks) {
392 Layer newLayer = new Layer(l); // create a new layer object for each tile matrix set supported
393 newLayer.tileMatrixSet = matrixSetById.get(tileMatrixId);
394 ret.add(newLayer);
395 }
396 }
397 return ret;
398 }
399
400 /**
401 * Parse Layer tag. Returns when reader will reach Layer closing tag
402 *
403 * @param reader StAX reader instance
404 * @return Layer object, with tileMatrixSetLinks and no tileMatrixSet attribute set.
405 * @throws XMLStreamException See {@link XMLStreamReader}
406 */
407 private static Layer parseLayer(XMLStreamReader reader) throws XMLStreamException {
408 Layer layer = new Layer();
409 Stack<QName> tagStack = new Stack<>();
410 List<String> supportedMimeTypes = Arrays.asList(ImageIO.getReaderMIMETypes());
411 Collection<String> unsupportedFormats = new ArrayList<>();
412
413 for (int event = reader.getEventType();
414 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && QN_LAYER.equals(reader.getName()));
415 event = reader.next()) {
416 if (event == XMLStreamReader.START_ELEMENT) {
417 tagStack.push(reader.getName());
418 if (tagStack.size() == 2) {
419 if (QN_FORMAT.equals(reader.getName())) {
420 String format = reader.getElementText();
421 if (supportedMimeTypes.contains(format)) {
422 layer.format = format;
423 } else {
424 unsupportedFormats.add(format);
425 }
426 } else if (GetCapabilitiesParseHelper.QN_OWS_IDENTIFIER.equals(reader.getName())) {
427 layer.identifier = reader.getElementText();
428 } else if (GetCapabilitiesParseHelper.QN_OWS_TITLE.equals(reader.getName())) {
429 layer.title = reader.getElementText();
430 } else if (QN_RESOURCE_URL.equals(reader.getName()) &&
431 "tile".equals(reader.getAttributeValue("", "resourceType"))) {
432 layer.baseUrl = reader.getAttributeValue("", "template");
433 } else if (QN_STYLE.equals(reader.getName()) &&
434 "true".equals(reader.getAttributeValue("", "isDefault"))) {
435 if (GetCapabilitiesParseHelper.moveReaderToTag(reader, new QName[] {GetCapabilitiesParseHelper.QN_OWS_IDENTIFIER})) {
436 layer.style = reader.getElementText();
437 tagStack.push(reader.getName()); // keep tagStack in sync
438 }
439 } else if (QN_TILEMATRIX_SET_LINK.equals(reader.getName())) {
440 layer.tileMatrixSetLinks.add(praseTileMatrixSetLink(reader));
441 } else {
442 GetCapabilitiesParseHelper.moveReaderToEndCurrentTag(reader);
443 }
444 }
445 }
446 // need to get event type from reader, as parsing might have change position of reader
447 if (reader.getEventType() == XMLStreamReader.END_ELEMENT) {
448 QName start = tagStack.pop();
449 if (!start.equals(reader.getName())) {
450 throw new IllegalStateException(tr("WMTS Parser error - start element {0} has different name than end element {2}",
451 start, reader.getName()));
452 }
453 }
454 }
455 if (layer.style == null) {
456 layer.style = "";
457 }
458 if (layer.format == null) {
459 // no format found - it's mandatory parameter - can't use this layer
460 Main.warn(tr("Can''t use layer {0} because no supported formats where found. Layer is available in formats: {1}",
461 layer.getUserTitle(),
462 String.join(", ", unsupportedFormats)));
463 return null;
464 }
465 return layer;
466 }
467
468 /**
469 * Gets TileMatrixSetLink value. Returns when reader is on TileMatrixSetLink closing tag
470 *
471 * @param reader StAX reader instance
472 * @return TileMatrixSetLink identifier
473 * @throws XMLStreamException See {@link XMLStreamReader}
474 */
475 private static String praseTileMatrixSetLink(XMLStreamReader reader) throws XMLStreamException {
476 String ret = null;
477 for (int event = reader.getEventType();
478 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT &&
479 QN_TILEMATRIX_SET_LINK.equals(reader.getName()));
480 event = reader.next()) {
481 if (event == XMLStreamReader.START_ELEMENT && QN_TILEMATRIXSET.equals(reader.getName())) {
482 ret = reader.getElementText();
483 }
484 }
485 return ret;
486 }
487
488 /**
489 * Parses TileMatrixSet section. Returns when reader is on TileMatrixSet closing tag
490 * @param reader StAX reader instance
491 * @return TileMatrixSet object
492 * @throws XMLStreamException See {@link XMLStreamReader}
493 */
494 private static TileMatrixSet parseTileMatrixSet(XMLStreamReader reader) throws XMLStreamException {
495 TileMatrixSetBuilder matrixSet = new TileMatrixSetBuilder();
496 for (int event = reader.getEventType();
497 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && QN_TILEMATRIXSET.equals(reader.getName()));
498 event = reader.next()) {
499 if (event == XMLStreamReader.START_ELEMENT) {
500 if (GetCapabilitiesParseHelper.QN_OWS_IDENTIFIER.equals(reader.getName())) {
501 matrixSet.identifier = reader.getElementText();
502 }
503 if (GetCapabilitiesParseHelper.QN_OWS_SUPPORTED_CRS.equals(reader.getName())) {
504 matrixSet.crs = GetCapabilitiesParseHelper.crsToCode(reader.getElementText());
505 }
506 if (QN_TILEMATRIX.equals(reader.getName())) {
507 matrixSet.tileMatrix.add(parseTileMatrix(reader, matrixSet.crs));
508 }
509 }
510 }
511 return matrixSet.build();
512 }
513
514 /**
515 * Parses TileMatrix section. Returns when reader is on TileMatrix closing tag.
516 * @param reader StAX reader instance
517 * @param matrixCrs projection used by this matrix
518 * @return TileMatrix object
519 * @throws XMLStreamException See {@link XMLStreamReader}
520 */
521 private static TileMatrix parseTileMatrix(XMLStreamReader reader, String matrixCrs) throws XMLStreamException {
522 Projection matrixProj = Optional.ofNullable(Projections.getProjectionByCode(matrixCrs))
523 .orElseGet(Main::getProjection); // use current projection if none found. Maybe user is using custom string
524 TileMatrix ret = new TileMatrix();
525 for (int event = reader.getEventType();
526 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && QN_TILEMATRIX.equals(reader.getName()));
527 event = reader.next()) {
528 if (event == XMLStreamReader.START_ELEMENT) {
529 if (GetCapabilitiesParseHelper.QN_OWS_IDENTIFIER.equals(reader.getName())) {
530 ret.identifier = reader.getElementText();
531 }
532 if (QN_SCALE_DENOMINATOR.equals(reader.getName())) {
533 ret.scaleDenominator = Double.parseDouble(reader.getElementText());
534 }
535 if (QN_TOPLEFT_CORNER.equals(reader.getName())) {
536 String[] topLeftCorner = reader.getElementText().split(" ");
537 if (matrixProj.switchXY()) {
538 ret.topLeftCorner = new EastNorth(Double.parseDouble(topLeftCorner[1]), Double.parseDouble(topLeftCorner[0]));
539 } else {
540 ret.topLeftCorner = new EastNorth(Double.parseDouble(topLeftCorner[0]), Double.parseDouble(topLeftCorner[1]));
541 }
542 }
543 if (QN_TILE_HEIGHT.equals(reader.getName())) {
544 ret.tileHeight = Integer.parseInt(reader.getElementText());
545 }
546 if (QN_TILE_WIDTH.equals(reader.getName())) {
547 ret.tileWidth = Integer.parseInt(reader.getElementText());
548 }
549 if (QN_MATRIX_HEIGHT.equals(reader.getName())) {
550 ret.matrixHeight = Integer.parseInt(reader.getElementText());
551 }
552 if (QN_MATRIX_WIDTH.equals(reader.getName())) {
553 ret.matrixWidth = Integer.parseInt(reader.getElementText());
554 }
555 }
556 }
557 if (ret.tileHeight != ret.tileWidth) {
558 throw new AssertionError(tr("Only square tiles are supported. {0}x{1} returned by server for TileMatrix identifier {2}",
559 ret.tileHeight, ret.tileWidth, ret.identifier));
560 }
561 return ret;
562 }
563
564 /**
565 * Parses OperationMetadata section. Returns when reader is on OperationsMetadata closing tag.
566 * Sets this.baseUrl and this.transferMode
567 *
568 * @param reader StAX reader instance
569 * @throws XMLStreamException See {@link XMLStreamReader}
570 */
571 private void parseOperationMetadata(XMLStreamReader reader) throws XMLStreamException {
572 for (int event = reader.getEventType();
573 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT &&
574 GetCapabilitiesParseHelper.QN_OWS_OPERATIONS_METADATA.equals(reader.getName()));
575 event = reader.next()) {
576 if (event == XMLStreamReader.START_ELEMENT &&
577 GetCapabilitiesParseHelper.QN_OWS_OPERATION.equals(reader.getName()) &&
578 "GetTile".equals(reader.getAttributeValue("", "name")) &&
579 GetCapabilitiesParseHelper.moveReaderToTag(reader, new QName[] {
580 GetCapabilitiesParseHelper.QN_OWS_DCP,
581 GetCapabilitiesParseHelper.QN_OWS_HTTP,
582 GetCapabilitiesParseHelper.QN_OWS_GET,
583 })) {
584 this.baseUrl = reader.getAttributeValue(GetCapabilitiesParseHelper.XLINK_NS_URL, "href");
585 this.transferMode = GetCapabilitiesParseHelper.getTransferMode(reader);
586 }
587 }
588 }
589
590 /**
591 * Initializes projection for this TileSource with projection
592 * @param proj projection to be used by this TileSource
593 */
594 public void initProjection(Projection proj) {
595 // getLayers will return only layers matching the name, if the user already choose the layer
596 // so we will not ask the user again to chose the layer, if he just changes projection
597 Collection<Layer> candidates = getLayers(
598 currentLayer != null ? new WMTSDefaultLayer(currentLayer.identifier, currentLayer.tileMatrixSet.identifier) : defaultLayer,
599 proj.toCode());
600
601 if (candidates.size() > 1 && defaultLayer != null) {
602 candidates = candidates.stream()
603 .filter(t -> t.tileMatrixSet.identifier.equals(defaultLayer.getTileMatrixSet()))
604 .collect(Collectors.toList());
605 }
606 if (candidates.size() == 1) {
607 Layer newLayer = candidates.iterator().next();
608 if (newLayer != null) {
609 this.currentTileMatrixSet = newLayer.tileMatrixSet;
610 this.currentLayer = newLayer;
611 Collection<Double> scales = new ArrayList<>(currentTileMatrixSet.tileMatrix.size());
612 for (TileMatrix tileMatrix : currentTileMatrixSet.tileMatrix) {
613 scales.add(tileMatrix.scaleDenominator * 0.28e-03);
614 }
615 this.nativeScaleList = new ScaleList(scales);
616 }
617 } else if (candidates.size() > 1) {
618 Main.warn("More than one layer WMTS available: {0} for projection {1} and name {2}. Do not know which to process",
619 candidates.stream().map(x -> x.getUserTitle() + ": " + x.tileMatrixSet.identifier).collect(Collectors.joining(", ")),
620 proj.toCode(),
621 currentLayer != null ? currentLayer.getUserTitle() : defaultLayer
622 );
623 }
624 this.crsScale = getTileSize() * 0.28e-03 / proj.getMetersPerUnit();
625 }
626
627 /**
628 *
629 * @param searchLayer which layer do we look for
630 * @param projectionCode projection code to match
631 * @return Collection of layers matching the name of the layer and projection, or only projection if name is not provided
632 */
633 private Collection<Layer> getLayers(WMTSDefaultLayer searchLayer, String projectionCode) {
634 Collection<Layer> ret = new ArrayList<>();
635 if (this.layers != null) {
636 for (Layer layer: this.layers) {
637 if ((searchLayer == null || (// if it's null, then accept all layers
638 searchLayer.getLayerName().equals(layer.identifier)))
639 && (projectionCode == null || // if it's null, then accept any projection
640 projectionCode.equals(layer.tileMatrixSet.crs))) {
641 ret.add(layer);
642 }
643 }
644 }
645 return ret;
646 }
647
648 @Override
649 public int getTileSize() {
650 // no support for non-square tiles (tileHeight != tileWidth)
651 // and for different tile sizes at different zoom levels
652 Collection<Layer> projLayers = getLayers(null, Main.getProjection().toCode());
653 if (!projLayers.isEmpty()) {
654 return projLayers.iterator().next().tileMatrixSet.tileMatrix.get(0).tileHeight;
655 }
656 // if no layers is found, fallback to default mercator tile size. Maybe it will work
657 Main.warn("WMTS: Could not determine tile size. Using default tile size of: {0}", getDefaultTileSize());
658 return getDefaultTileSize();
659 }
660
661 @Override
662 public String getTileUrl(int zoom, int tilex, int tiley) {
663 if (currentLayer == null) {
664 return "";
665 }
666
667 String url;
668 if (currentLayer.baseUrl != null && transferMode == null) {
669 url = currentLayer.baseUrl;
670 } else {
671 switch (transferMode) {
672 case KVP:
673 url = baseUrl + URL_GET_ENCODING_PARAMS;
674 break;
675 case REST:
676 url = currentLayer.baseUrl;
677 break;
678 default:
679 url = "";
680 break;
681 }
682 }
683
684 TileMatrix tileMatrix = getTileMatrix(zoom);
685
686 if (tileMatrix == null) {
687 return ""; // no matrix, probably unsupported CRS selected.
688 }
689
690 return url.replaceAll("\\{layer\\}", this.currentLayer.identifier)
691 .replaceAll("\\{format\\}", this.currentLayer.format)
692 .replaceAll("\\{TileMatrixSet\\}", this.currentTileMatrixSet.identifier)
693 .replaceAll("\\{TileMatrix\\}", tileMatrix.identifier)
694 .replaceAll("\\{TileRow\\}", Integer.toString(tiley))
695 .replaceAll("\\{TileCol\\}", Integer.toString(tilex))
696 .replaceAll("(?i)\\{style\\}", this.currentLayer.style);
697 }
698
699 /**
700 *
701 * @param zoom zoom level
702 * @return TileMatrix that's working on this zoom level
703 */
704 private TileMatrix getTileMatrix(int zoom) {
705 if (zoom > getMaxZoom()) {
706 return null;
707 }
708 if (zoom < 0) {
709 return null;
710 }
711 return this.currentTileMatrixSet.tileMatrix.get(zoom);
712 }
713
714 @Override
715 public double getDistance(double lat1, double lon1, double lat2, double lon2) {
716 throw new UnsupportedOperationException("Not implemented");
717 }
718
719 @Override
720 public ICoordinate tileXYToLatLon(Tile tile) {
721 return tileXYToLatLon(tile.getXtile(), tile.getYtile(), tile.getZoom());
722 }
723
724 @Override
725 public ICoordinate tileXYToLatLon(TileXY xy, int zoom) {
726 return tileXYToLatLon(xy.getXIndex(), xy.getYIndex(), zoom);
727 }
728
729 @Override
730 public ICoordinate tileXYToLatLon(int x, int y, int zoom) {
731 TileMatrix matrix = getTileMatrix(zoom);
732 if (matrix == null) {
733 return Main.getProjection().getWorldBoundsLatLon().getCenter().toCoordinate();
734 }
735 double scale = matrix.scaleDenominator * this.crsScale;
736 EastNorth ret = new EastNorth(matrix.topLeftCorner.east() + x * scale, matrix.topLeftCorner.north() - y * scale);
737 return Main.getProjection().eastNorth2latlon(ret).toCoordinate();
738 }
739
740 @Override
741 public TileXY latLonToTileXY(double lat, double lon, int zoom) {
742 TileMatrix matrix = getTileMatrix(zoom);
743 if (matrix == null) {
744 return new TileXY(0, 0);
745 }
746
747 Projection proj = Main.getProjection();
748 EastNorth enPoint = proj.latlon2eastNorth(new LatLon(lat, lon));
749 double scale = matrix.scaleDenominator * this.crsScale;
750 return new TileXY(
751 (enPoint.east() - matrix.topLeftCorner.east()) / scale,
752 (matrix.topLeftCorner.north() - enPoint.north()) / scale
753 );
754 }
755
756 @Override
757 public TileXY latLonToTileXY(ICoordinate point, int zoom) {
758 return latLonToTileXY(point.getLat(), point.getLon(), zoom);
759 }
760
761 @Override
762 public int getTileXMax(int zoom) {
763 return getTileXMax(zoom, Main.getProjection());
764 }
765
766 @Override
767 public int getTileYMax(int zoom) {
768 return getTileYMax(zoom, Main.getProjection());
769 }
770
771 @Override
772 public Point latLonToXY(double lat, double lon, int zoom) {
773 TileMatrix matrix = getTileMatrix(zoom);
774 if (matrix == null) {
775 return new Point(0, 0);
776 }
777 double scale = matrix.scaleDenominator * this.crsScale;
778 EastNorth point = Main.getProjection().latlon2eastNorth(new LatLon(lat, lon));
779 return new Point(
780 (int) Math.round((point.east() - matrix.topLeftCorner.east()) / scale),
781 (int) Math.round((matrix.topLeftCorner.north() - point.north()) / scale)
782 );
783 }
784
785 @Override
786 public Point latLonToXY(ICoordinate point, int zoom) {
787 return latLonToXY(point.getLat(), point.getLon(), zoom);
788 }
789
790 @Override
791 public Coordinate xyToLatLon(Point point, int zoom) {
792 return xyToLatLon(point.x, point.y, zoom);
793 }
794
795 @Override
796 public Coordinate xyToLatLon(int x, int y, int zoom) {
797 TileMatrix matrix = getTileMatrix(zoom);
798 if (matrix == null) {
799 return new Coordinate(0, 0);
800 }
801 double scale = matrix.scaleDenominator * this.crsScale;
802 Projection proj = Main.getProjection();
803 EastNorth ret = new EastNorth(
804 matrix.topLeftCorner.east() + x * scale,
805 matrix.topLeftCorner.north() - y * scale
806 );
807 LatLon ll = proj.eastNorth2latlon(ret);
808 return new Coordinate(ll.lat(), ll.lon());
809 }
810
811 @Override
812 public Map<String, String> getHeaders() {
813 return headers;
814 }
815
816 @Override
817 public int getMaxZoom() {
818 if (this.currentTileMatrixSet != null) {
819 return this.currentTileMatrixSet.tileMatrix.size()-1;
820 }
821 return 0;
822 }
823
824 @Override
825 public String getTileId(int zoom, int tilex, int tiley) {
826 return getTileUrl(zoom, tilex, tiley);
827 }
828
829 /**
830 * Checks if url is acceptable by this Tile Source
831 * @param url URL to check
832 */
833 public static void checkUrl(String url) {
834 CheckParameterUtil.ensureParameterNotNull(url, "url");
835 Matcher m = Pattern.compile("\\{[^}]*\\}").matcher(url);
836 while (m.find()) {
837 boolean isSupportedPattern = false;
838 for (String pattern : ALL_PATTERNS) {
839 if (m.group().matches(pattern)) {
840 isSupportedPattern = true;
841 break;
842 }
843 }
844 if (!isSupportedPattern) {
845 throw new IllegalArgumentException(
846 tr("{0} is not a valid WMS argument. Please check this server URL:\n{1}", m.group(), url));
847 }
848 }
849 }
850
851 /**
852 * @return set of projection codes that this TileSource supports
853 */
854 public Set<String> getSupportedProjections() {
855 Set<String> ret = new HashSet<>();
856 if (currentLayer == null) {
857 for (Layer layer: this.layers) {
858 ret.add(layer.tileMatrixSet.crs);
859 }
860 } else {
861 for (Layer layer: this.layers) {
862 if (currentLayer.identifier.equals(layer.identifier)) {
863 ret.add(layer.tileMatrixSet.crs);
864 }
865 }
866 }
867 return ret;
868 }
869
870 private int getTileYMax(int zoom, Projection proj) {
871 TileMatrix matrix = getTileMatrix(zoom);
872 if (matrix == null) {
873 return 0;
874 }
875
876 if (matrix.matrixHeight != -1) {
877 return matrix.matrixHeight;
878 }
879
880 double scale = matrix.scaleDenominator * this.crsScale;
881 EastNorth min = matrix.topLeftCorner;
882 EastNorth max = proj.latlon2eastNorth(proj.getWorldBoundsLatLon().getMax());
883 return (int) Math.ceil(Math.abs(max.north() - min.north()) / scale);
884 }
885
886 private int getTileXMax(int zoom, Projection proj) {
887 TileMatrix matrix = getTileMatrix(zoom);
888 if (matrix == null) {
889 return 0;
890 }
891 if (matrix.matrixWidth != -1) {
892 return matrix.matrixWidth;
893 }
894
895 double scale = matrix.scaleDenominator * this.crsScale;
896 EastNorth min = matrix.topLeftCorner;
897 EastNorth max = proj.latlon2eastNorth(proj.getWorldBoundsLatLon().getMax());
898 return (int) Math.ceil(Math.abs(max.east() - min.east()) / scale);
899 }
900
901 /**
902 * Get native scales of tile source.
903 * @return {@link ScaleList} of native scales
904 */
905 public ScaleList getNativeScales() {
906 return nativeScaleList;
907 }
908
909}
Note: See TracBrowser for help on using the repository browser.