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

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

WMTS: don't show layer selection dialog if there is only one layer with one tile matrix set that matches the current projection (see #10623)

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