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

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

sonar - squid:S3878 - Arrays should not be created for varargs parameters

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