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

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

fix #14361 - WMTS: download only supported image formats

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