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

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

make it possible to switch between 2 supported projections for a given WMTS layer (see #7427)

  • Property svn:eol-style set to native
File size: 36.9 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 Layer l = parseLayer(reader);
359 if (l != null) {
360 layers.add(l);
361 }
362 }
363 if (QN_TILEMATRIXSET.equals(reader.getName())) {
364 TileMatrixSet entry = parseTileMatrixSet(reader);
365 matrixSetById.put(entry.identifier, entry);
366 }
367 }
368 }
369 Collection<Layer> ret = new ArrayList<>();
370 // link layers to matrix sets
371 for (Layer l: layers) {
372 for (String tileMatrixId: l.tileMatrixSetLinks) {
373 Layer newLayer = new Layer(l); // create a new layer object for each tile matrix set supported
374 newLayer.tileMatrixSet = matrixSetById.get(tileMatrixId);
375 ret.add(newLayer);
376 }
377 }
378 return ret;
379 }
380
381 /**
382 * Parse Layer tag. Returns when reader will reach Layer closing tag
383 *
384 * @param reader StAX reader instance
385 * @return Layer object, with tileMatrixSetLinks and no tileMatrixSet attribute set.
386 * @throws XMLStreamException See {@link XMLStreamReader}
387 */
388 private static Layer parseLayer(XMLStreamReader reader) throws XMLStreamException {
389 Layer layer = new Layer();
390 Stack<QName> tagStack = new Stack<>();
391 List<String> supportedMimeTypes = Arrays.asList(ImageIO.getReaderMIMETypes());
392 Collection<String> unsupportedFormats = new ArrayList<>();
393
394 for (int event = reader.getEventType();
395 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && QN_LAYER.equals(reader.getName()));
396 event = reader.next()) {
397 if (event == XMLStreamReader.START_ELEMENT) {
398 tagStack.push(reader.getName());
399 if (tagStack.size() == 2) {
400 if (QN_FORMAT.equals(reader.getName())) {
401 String format = reader.getElementText();
402 if (supportedMimeTypes.contains(format)) {
403 layer.format = format;
404 } else {
405 unsupportedFormats.add(format);
406 }
407 } else if (GetCapabilitiesParseHelper.QN_OWS_IDENTIFIER.equals(reader.getName())) {
408 layer.name = reader.getElementText();
409 } else if (QN_RESOURCE_URL.equals(reader.getName()) &&
410 "tile".equals(reader.getAttributeValue("", "resourceType"))) {
411 layer.baseUrl = reader.getAttributeValue("", "template");
412 } else if (QN_STYLE.equals(reader.getName()) &&
413 "true".equals(reader.getAttributeValue("", "isDefault"))) {
414 if (GetCapabilitiesParseHelper.moveReaderToTag(reader, new QName[] {GetCapabilitiesParseHelper.QN_OWS_IDENTIFIER})) {
415 layer.style = reader.getElementText();
416 tagStack.push(reader.getName()); // keep tagStack in sync
417 }
418 } else if (QN_TILEMATRIX_SET_LINK.equals(reader.getName())) {
419 layer.tileMatrixSetLinks.add(praseTileMatrixSetLink(reader));
420 } else {
421 GetCapabilitiesParseHelper.moveReaderToEndCurrentTag(reader);
422 }
423 }
424 }
425 // need to get event type from reader, as parsing might have change position of reader
426 if (reader.getEventType() == XMLStreamReader.END_ELEMENT) {
427 QName start = tagStack.pop();
428 if (!start.equals(reader.getName())) {
429 throw new IllegalStateException(tr("WMTS Parser error - start element {0} has different name than end element {2}",
430 start, reader.getName()));
431 }
432 }
433 }
434 if (layer.style == null) {
435 layer.style = "";
436 }
437 if (layer.format == null) {
438 // no format found - it's mandatory parameter - can't use this layer
439 Main.warn(tr("Can''t use layer {0} because no supported formats where found. Layer is available in formats: {1}",
440 layer.name,
441 String.join(", ", unsupportedFormats)));
442 return null;
443 }
444 return layer;
445 }
446
447 /**
448 * Gets TileMatrixSetLink value. Returns when reader is on TileMatrixSetLink closing tag
449 *
450 * @param reader StAX reader instance
451 * @return TileMatrixSetLink identifier
452 * @throws XMLStreamException See {@link XMLStreamReader}
453 */
454 private static String praseTileMatrixSetLink(XMLStreamReader reader) throws XMLStreamException {
455 String ret = null;
456 for (int event = reader.getEventType();
457 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT &&
458 QN_TILEMATRIX_SET_LINK.equals(reader.getName()));
459 event = reader.next()) {
460 if (event == XMLStreamReader.START_ELEMENT && QN_TILEMATRIXSET.equals(reader.getName())) {
461 ret = reader.getElementText();
462 }
463 }
464 return ret;
465 }
466
467 /**
468 * Parses TileMatrixSet section. Returns when reader is on TileMatrixSet closing tag
469 * @param reader StAX reader instance
470 * @return TileMatrixSet object
471 * @throws XMLStreamException See {@link XMLStreamReader}
472 */
473 private static TileMatrixSet parseTileMatrixSet(XMLStreamReader reader) throws XMLStreamException {
474 TileMatrixSetBuilder matrixSet = new TileMatrixSetBuilder();
475 for (int event = reader.getEventType();
476 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && QN_TILEMATRIXSET.equals(reader.getName()));
477 event = reader.next()) {
478 if (event == XMLStreamReader.START_ELEMENT) {
479 if (GetCapabilitiesParseHelper.QN_OWS_IDENTIFIER.equals(reader.getName())) {
480 matrixSet.identifier = reader.getElementText();
481 }
482 if (GetCapabilitiesParseHelper.QN_OWS_SUPPORTED_CRS.equals(reader.getName())) {
483 matrixSet.crs = GetCapabilitiesParseHelper.crsToCode(reader.getElementText());
484 }
485 if (QN_TILEMATRIX.equals(reader.getName())) {
486 matrixSet.tileMatrix.add(parseTileMatrix(reader, matrixSet.crs));
487 }
488 }
489 }
490 return matrixSet.build();
491 }
492
493 /**
494 * Parses TileMatrix section. Returns when reader is on TileMatrix closing tag.
495 * @param reader StAX reader instance
496 * @param matrixCrs projection used by this matrix
497 * @return TileMatrix object
498 * @throws XMLStreamException See {@link XMLStreamReader}
499 */
500 private static TileMatrix parseTileMatrix(XMLStreamReader reader, String matrixCrs) throws XMLStreamException {
501 Projection matrixProj = Optional.ofNullable(Projections.getProjectionByCode(matrixCrs))
502 .orElseGet(Main::getProjection); // use current projection if none found. Maybe user is using custom string
503 TileMatrix ret = new TileMatrix();
504 for (int event = reader.getEventType();
505 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT && QN_TILEMATRIX.equals(reader.getName()));
506 event = reader.next()) {
507 if (event == XMLStreamReader.START_ELEMENT) {
508 if (GetCapabilitiesParseHelper.QN_OWS_IDENTIFIER.equals(reader.getName())) {
509 ret.identifier = reader.getElementText();
510 }
511 if (QN_SCALE_DENOMINATOR.equals(reader.getName())) {
512 ret.scaleDenominator = Double.parseDouble(reader.getElementText());
513 }
514 if (QN_TOPLEFT_CORNER.equals(reader.getName())) {
515 String[] topLeftCorner = reader.getElementText().split(" ");
516 if (matrixProj.switchXY()) {
517 ret.topLeftCorner = new EastNorth(Double.parseDouble(topLeftCorner[1]), Double.parseDouble(topLeftCorner[0]));
518 } else {
519 ret.topLeftCorner = new EastNorth(Double.parseDouble(topLeftCorner[0]), Double.parseDouble(topLeftCorner[1]));
520 }
521 }
522 if (QN_TILE_HEIGHT.equals(reader.getName())) {
523 ret.tileHeight = Integer.parseInt(reader.getElementText());
524 }
525 if (QN_TILE_WIDTH.equals(reader.getName())) {
526 ret.tileWidth = Integer.parseInt(reader.getElementText());
527 }
528 if (QN_MATRIX_HEIGHT.equals(reader.getName())) {
529 ret.matrixHeight = Integer.parseInt(reader.getElementText());
530 }
531 if (QN_MATRIX_WIDTH.equals(reader.getName())) {
532 ret.matrixWidth = Integer.parseInt(reader.getElementText());
533 }
534 }
535 }
536 if (ret.tileHeight != ret.tileWidth) {
537 throw new AssertionError(tr("Only square tiles are supported. {0}x{1} returned by server for TileMatrix identifier {2}",
538 ret.tileHeight, ret.tileWidth, ret.identifier));
539 }
540 return ret;
541 }
542
543 /**
544 * Parses OperationMetadata section. Returns when reader is on OperationsMetadata closing tag.
545 * Sets this.baseUrl and this.transferMode
546 *
547 * @param reader StAX reader instance
548 * @throws XMLStreamException See {@link XMLStreamReader}
549 */
550 private void parseOperationMetadata(XMLStreamReader reader) throws XMLStreamException {
551 for (int event = reader.getEventType();
552 reader.hasNext() && !(event == XMLStreamReader.END_ELEMENT &&
553 GetCapabilitiesParseHelper.QN_OWS_OPERATIONS_METADATA.equals(reader.getName()));
554 event = reader.next()) {
555 if (event == XMLStreamReader.START_ELEMENT &&
556 GetCapabilitiesParseHelper.QN_OWS_OPERATION.equals(reader.getName()) &&
557 "GetTile".equals(reader.getAttributeValue("", "name")) &&
558 GetCapabilitiesParseHelper.moveReaderToTag(reader, new QName[] {
559 GetCapabilitiesParseHelper.QN_OWS_DCP,
560 GetCapabilitiesParseHelper.QN_OWS_HTTP,
561 GetCapabilitiesParseHelper.QN_OWS_GET,
562 })) {
563 this.baseUrl = reader.getAttributeValue(GetCapabilitiesParseHelper.XLINK_NS_URL, "href");
564 this.transferMode = GetCapabilitiesParseHelper.getTransferMode(reader);
565 }
566 }
567 }
568
569 /**
570 * Initializes projection for this TileSource with projection
571 * @param proj projection to be used by this TileSource
572 */
573 public void initProjection(Projection proj) {
574 // getLayers will return only layers matching the name, if the user already choose the layer
575 // so we will not ask the user again to chose the layer, if he just changes projection
576 Collection<Layer> candidates = getLayers(
577 currentLayer != null ? new WMTSDefaultLayer(currentLayer.name, currentLayer.tileMatrixSet.identifier) : defaultLayer,
578 proj.toCode());
579
580 if (candidates.size() == 1) {
581 Layer newLayer = candidates.iterator().next();
582 if (newLayer != null) {
583 this.currentTileMatrixSet = newLayer.tileMatrixSet;
584 this.currentLayer = newLayer;
585 Collection<Double> scales = new ArrayList<>(currentTileMatrixSet.tileMatrix.size());
586 for (TileMatrix tileMatrix : currentTileMatrixSet.tileMatrix) {
587 scales.add(tileMatrix.scaleDenominator * 0.28e-03);
588 }
589 this.nativeScaleList = new ScaleList(scales);
590 }
591 } else if (candidates.size() > 1) {
592 Main.warn("More than one layer WMTS available: {0} for projection {1} and name {2}. Do not know which to process",
593 candidates.stream().map(x -> x.name + ": " + x.tileMatrixSet.identifier).collect(Collectors.joining(", ")),
594 proj.toCode(),
595 currentLayer != null ? currentLayer.name : defaultLayer
596 );
597 }
598 this.crsScale = getTileSize() * 0.28e-03 / proj.getMetersPerUnit();
599 }
600
601 /**
602 *
603 * @param searchLayer which layer do we look for
604 * @param projectionCode projection code to match
605 * @return Collection of layers matching the name of the layer and projection, or only projection if name is not provided
606 */
607 private Collection<Layer> getLayers(WMTSDefaultLayer searchLayer, String projectionCode) {
608 Collection<Layer> ret = new ArrayList<>();
609 if (this.layers != null) {
610 for (Layer layer: this.layers) {
611 if ((searchLayer == null || (// if it's null, then accept all layers
612 searchLayer.getLayerName().equals(layer.name)))
613 && (projectionCode == null || // if it's null, then accept any projection
614 projectionCode.equals(layer.tileMatrixSet.crs))) {
615 ret.add(layer);
616 }
617 }
618 }
619 return ret;
620 }
621
622 @Override
623 public int getTileSize() {
624 // no support for non-square tiles (tileHeight != tileWidth)
625 // and for different tile sizes at different zoom levels
626 Collection<Layer> projLayers = getLayers(null, Main.getProjection().toCode());
627 if (!projLayers.isEmpty()) {
628 return projLayers.iterator().next().tileMatrixSet.tileMatrix.get(0).tileHeight;
629 }
630 // if no layers is found, fallback to default mercator tile size. Maybe it will work
631 Main.warn("WMTS: Could not determine tile size. Using default tile size of: {0}", getDefaultTileSize());
632 return getDefaultTileSize();
633 }
634
635 @Override
636 public String getTileUrl(int zoom, int tilex, int tiley) {
637 if (currentLayer == null) {
638 return "";
639 }
640
641 String url;
642 if (currentLayer.baseUrl != null && transferMode == null) {
643 url = currentLayer.baseUrl;
644 } else {
645 switch (transferMode) {
646 case KVP:
647 url = baseUrl + URL_GET_ENCODING_PARAMS;
648 break;
649 case REST:
650 url = currentLayer.baseUrl;
651 break;
652 default:
653 url = "";
654 break;
655 }
656 }
657
658 TileMatrix tileMatrix = getTileMatrix(zoom);
659
660 if (tileMatrix == null) {
661 return ""; // no matrix, probably unsupported CRS selected.
662 }
663
664 return url.replaceAll("\\{layer\\}", this.currentLayer.name)
665 .replaceAll("\\{format\\}", this.currentLayer.format)
666 .replaceAll("\\{TileMatrixSet\\}", this.currentTileMatrixSet.identifier)
667 .replaceAll("\\{TileMatrix\\}", tileMatrix.identifier)
668 .replaceAll("\\{TileRow\\}", Integer.toString(tiley))
669 .replaceAll("\\{TileCol\\}", Integer.toString(tilex))
670 .replaceAll("(?i)\\{style\\}", this.currentLayer.style);
671 }
672
673 /**
674 *
675 * @param zoom zoom level
676 * @return TileMatrix that's working on this zoom level
677 */
678 private TileMatrix getTileMatrix(int zoom) {
679 if (zoom > getMaxZoom()) {
680 return null;
681 }
682 if (zoom < 0) {
683 return null;
684 }
685 return this.currentTileMatrixSet.tileMatrix.get(zoom);
686 }
687
688 @Override
689 public double getDistance(double lat1, double lon1, double lat2, double lon2) {
690 throw new UnsupportedOperationException("Not implemented");
691 }
692
693 @Override
694 public ICoordinate tileXYToLatLon(Tile tile) {
695 return tileXYToLatLon(tile.getXtile(), tile.getYtile(), tile.getZoom());
696 }
697
698 @Override
699 public ICoordinate tileXYToLatLon(TileXY xy, int zoom) {
700 return tileXYToLatLon(xy.getXIndex(), xy.getYIndex(), zoom);
701 }
702
703 @Override
704 public ICoordinate tileXYToLatLon(int x, int y, int zoom) {
705 TileMatrix matrix = getTileMatrix(zoom);
706 if (matrix == null) {
707 return Main.getProjection().getWorldBoundsLatLon().getCenter().toCoordinate();
708 }
709 double scale = matrix.scaleDenominator * this.crsScale;
710 EastNorth ret = new EastNorth(matrix.topLeftCorner.east() + x * scale, matrix.topLeftCorner.north() - y * scale);
711 return Main.getProjection().eastNorth2latlon(ret).toCoordinate();
712 }
713
714 @Override
715 public TileXY latLonToTileXY(double lat, double lon, int zoom) {
716 TileMatrix matrix = getTileMatrix(zoom);
717 if (matrix == null) {
718 return new TileXY(0, 0);
719 }
720
721 Projection proj = Main.getProjection();
722 EastNorth enPoint = proj.latlon2eastNorth(new LatLon(lat, lon));
723 double scale = matrix.scaleDenominator * this.crsScale;
724 return new TileXY(
725 (enPoint.east() - matrix.topLeftCorner.east()) / scale,
726 (matrix.topLeftCorner.north() - enPoint.north()) / scale
727 );
728 }
729
730 @Override
731 public TileXY latLonToTileXY(ICoordinate point, int zoom) {
732 return latLonToTileXY(point.getLat(), point.getLon(), zoom);
733 }
734
735 @Override
736 public int getTileXMax(int zoom) {
737 return getTileXMax(zoom, Main.getProjection());
738 }
739
740 @Override
741 public int getTileYMax(int zoom) {
742 return getTileYMax(zoom, Main.getProjection());
743 }
744
745 @Override
746 public Point latLonToXY(double lat, double lon, int zoom) {
747 TileMatrix matrix = getTileMatrix(zoom);
748 if (matrix == null) {
749 return new Point(0, 0);
750 }
751 double scale = matrix.scaleDenominator * this.crsScale;
752 EastNorth point = Main.getProjection().latlon2eastNorth(new LatLon(lat, lon));
753 return new Point(
754 (int) Math.round((point.east() - matrix.topLeftCorner.east()) / scale),
755 (int) Math.round((matrix.topLeftCorner.north() - point.north()) / scale)
756 );
757 }
758
759 @Override
760 public Point latLonToXY(ICoordinate point, int zoom) {
761 return latLonToXY(point.getLat(), point.getLon(), zoom);
762 }
763
764 @Override
765 public Coordinate xyToLatLon(Point point, int zoom) {
766 return xyToLatLon(point.x, point.y, zoom);
767 }
768
769 @Override
770 public Coordinate xyToLatLon(int x, int y, int zoom) {
771 TileMatrix matrix = getTileMatrix(zoom);
772 if (matrix == null) {
773 return new Coordinate(0, 0);
774 }
775 double scale = matrix.scaleDenominator * this.crsScale;
776 Projection proj = Main.getProjection();
777 EastNorth ret = new EastNorth(
778 matrix.topLeftCorner.east() + x * scale,
779 matrix.topLeftCorner.north() - y * scale
780 );
781 LatLon ll = proj.eastNorth2latlon(ret);
782 return new Coordinate(ll.lat(), ll.lon());
783 }
784
785 @Override
786 public Map<String, String> getHeaders() {
787 return headers;
788 }
789
790 @Override
791 public int getMaxZoom() {
792 if (this.currentTileMatrixSet != null) {
793 return this.currentTileMatrixSet.tileMatrix.size()-1;
794 }
795 return 0;
796 }
797
798 @Override
799 public String getTileId(int zoom, int tilex, int tiley) {
800 return getTileUrl(zoom, tilex, tiley);
801 }
802
803 /**
804 * Checks if url is acceptable by this Tile Source
805 * @param url URL to check
806 */
807 public static void checkUrl(String url) {
808 CheckParameterUtil.ensureParameterNotNull(url, "url");
809 Matcher m = Pattern.compile("\\{[^}]*\\}").matcher(url);
810 while (m.find()) {
811 boolean isSupportedPattern = false;
812 for (String pattern : ALL_PATTERNS) {
813 if (m.group().matches(pattern)) {
814 isSupportedPattern = true;
815 break;
816 }
817 }
818 if (!isSupportedPattern) {
819 throw new IllegalArgumentException(
820 tr("{0} is not a valid WMS argument. Please check this server URL:\n{1}", m.group(), url));
821 }
822 }
823 }
824
825 /**
826 * @return set of projection codes that this TileSource supports
827 */
828 public Set<String> getSupportedProjections() {
829 Set<String> ret = new HashSet<>();
830 if (currentLayer == null) {
831 for (Layer layer: this.layers) {
832 ret.add(layer.tileMatrixSet.crs);
833 }
834 } else {
835 for (Layer layer: this.layers) {
836 if (currentLayer.name.equals(layer.name)) {
837 ret.add(layer.tileMatrixSet.crs);
838 }
839 }
840 }
841 return ret;
842 }
843
844 private int getTileYMax(int zoom, Projection proj) {
845 TileMatrix matrix = getTileMatrix(zoom);
846 if (matrix == null) {
847 return 0;
848 }
849
850 if (matrix.matrixHeight != -1) {
851 return matrix.matrixHeight;
852 }
853
854 double scale = matrix.scaleDenominator * this.crsScale;
855 EastNorth min = matrix.topLeftCorner;
856 EastNorth max = proj.latlon2eastNorth(proj.getWorldBoundsLatLon().getMax());
857 return (int) Math.ceil(Math.abs(max.north() - min.north()) / scale);
858 }
859
860 private int getTileXMax(int zoom, Projection proj) {
861 TileMatrix matrix = getTileMatrix(zoom);
862 if (matrix == null) {
863 return 0;
864 }
865 if (matrix.matrixWidth != -1) {
866 return matrix.matrixWidth;
867 }
868
869 double scale = matrix.scaleDenominator * this.crsScale;
870 EastNorth min = matrix.topLeftCorner;
871 EastNorth max = proj.latlon2eastNorth(proj.getWorldBoundsLatLon().getMax());
872 return (int) Math.ceil(Math.abs(max.east() - min.east()) / scale);
873 }
874
875 /**
876 * Get native scales of tile source.
877 * @return {@link ScaleList} of native scales
878 */
879 public ScaleList getNativeScales() {
880 return nativeScaleList;
881 }
882
883}
Note: See TracBrowser for help on using the repository browser.