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

Last change on this file since 11189 was 11189, checked in by wiktorn, 7 years ago

Log GetCapabilities document on parse error

See: #13861

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