source: josm/trunk/scripts/SyncEditorLayerIndex.java@ 15874

Last change on this file since 15874 was 15851, checked in by Don-vip, 5 years ago

fix recent spotbugs/checkstyle/javadoc issues

  • Property svn:eol-style set to native
File size: 64.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2import static java.nio.charset.StandardCharsets.UTF_8;
3import static org.apache.commons.lang3.StringUtils.isBlank;
4import static org.apache.commons.lang3.StringUtils.isNotBlank;
5
6import java.io.BufferedReader;
7import java.io.IOException;
8import java.io.InputStreamReader;
9import java.io.OutputStream;
10import java.io.OutputStreamWriter;
11import java.lang.reflect.Field;
12import java.net.MalformedURLException;
13import java.net.URL;
14import java.nio.file.Files;
15import java.nio.file.Paths;
16import java.text.DecimalFormat;
17import java.text.ParseException;
18import java.text.SimpleDateFormat;
19import java.util.ArrayList;
20import java.util.Arrays;
21import java.util.Calendar;
22import java.util.Collection;
23import java.util.Collections;
24import java.util.Date;
25import java.util.HashMap;
26import java.util.LinkedList;
27import java.util.List;
28import java.util.Locale;
29import java.util.Map;
30import java.util.Map.Entry;
31import java.util.Objects;
32import java.util.Set;
33import java.util.function.BiConsumer;
34import java.util.function.Function;
35import java.util.regex.Matcher;
36import java.util.regex.Pattern;
37import java.util.stream.Collectors;
38
39import javax.json.Json;
40import javax.json.JsonArray;
41import javax.json.JsonNumber;
42import javax.json.JsonObject;
43import javax.json.JsonReader;
44import javax.json.JsonString;
45import javax.json.JsonValue;
46
47import org.openstreetmap.gui.jmapviewer.Coordinate;
48import org.openstreetmap.josm.data.Preferences;
49import org.openstreetmap.josm.data.imagery.ImageryInfo;
50import org.openstreetmap.josm.data.imagery.ImageryInfo.ImageryBounds;
51import org.openstreetmap.josm.data.imagery.Shape;
52import org.openstreetmap.josm.data.preferences.JosmBaseDirectories;
53import org.openstreetmap.josm.data.preferences.JosmUrls;
54import org.openstreetmap.josm.data.projection.Projections;
55import org.openstreetmap.josm.data.validation.routines.DomainValidator;
56import org.openstreetmap.josm.io.imagery.ImageryReader;
57import org.openstreetmap.josm.spi.preferences.Config;
58import org.openstreetmap.josm.tools.ImageProvider;
59import org.openstreetmap.josm.tools.JosmRuntimeException;
60import org.openstreetmap.josm.tools.Logging;
61import org.openstreetmap.josm.tools.OptionParser;
62import org.openstreetmap.josm.tools.OptionParser.OptionCount;
63import org.openstreetmap.josm.tools.ReflectionUtils;
64import org.xml.sax.SAXException;
65
66/**
67 * Compare and analyse the differences of the editor layer index and the JOSM imagery list.
68 * The goal is to keep both lists in sync.
69 *
70 * The editor layer index project (https://github.com/osmlab/editor-layer-index)
71 * provides also a version in the JOSM format, but the GEOJSON is the original source
72 * format, so we read that.
73 *
74 * How to run:
75 * -----------
76 *
77 * Main JOSM binary needs to be in classpath, e.g.
78 *
79 * $ java -cp ../dist/josm-custom.jar SyncEditorLayerIndex
80 *
81 * Add option "-h" to show the available command line flags.
82 */
83@SuppressWarnings("unchecked")
84public class SyncEditorLayerIndex {
85
86 private static final int MAXLEN = 140;
87
88 private List<ImageryInfo> josmEntries;
89 private JsonArray eliEntries;
90
91 private final Map<String, JsonObject> eliUrls = new HashMap<>();
92 private final Map<String, ImageryInfo> josmUrls = new HashMap<>();
93 private final Map<String, ImageryInfo> josmMirrors = new HashMap<>();
94 private static final Map<String, String> oldproj = new HashMap<>();
95 private static final List<String> ignoreproj = new LinkedList<>();
96
97 private static String eliInputFile = "imagery_eli.geojson";
98 private static String josmInputFile = "imagery_josm.imagery.xml";
99 private static String ignoreInputFile = "imagery_josm.ignores.txt";
100 private static OutputStream outputFile;
101 private static OutputStreamWriter outputStream;
102 private static String optionOutput;
103 private static boolean optionShorten;
104 private static boolean optionNoSkip;
105 private static boolean optionXhtmlBody;
106 private static boolean optionXhtml;
107 private static String optionEliXml;
108 private static String optionJosmXml;
109 private static String optionEncoding;
110 private static boolean optionNoEli;
111 private Map<String, String> skip = new HashMap<>();
112 private Map<String, String> skipStart = new HashMap<>();
113
114 /**
115 * Main method.
116 * @param args program arguments
117 * @throws IOException if any I/O error occurs
118 * @throws ReflectiveOperationException if any reflective operation error occurs
119 * @throws SAXException if any SAX error occurs
120 */
121 public static void main(String[] args) throws IOException, SAXException, ReflectiveOperationException {
122 Locale.setDefault(Locale.ROOT);
123 parseCommandLineArguments(args);
124 Config.setUrlsProvider(JosmUrls.getInstance());
125 Preferences pref = new Preferences(JosmBaseDirectories.getInstance());
126 Config.setPreferencesInstance(pref);
127 pref.init(false);
128 SyncEditorLayerIndex script = new SyncEditorLayerIndex();
129 script.setupProj();
130 script.loadSkip();
131 script.start();
132 script.loadJosmEntries();
133 if (optionJosmXml != null) {
134 try (OutputStreamWriter stream = new OutputStreamWriter(Files.newOutputStream(Paths.get(optionJosmXml)), UTF_8)) {
135 script.printentries(script.josmEntries, stream);
136 }
137 }
138 script.loadELIEntries();
139 if (optionEliXml != null) {
140 try (OutputStreamWriter stream = new OutputStreamWriter(Files.newOutputStream(Paths.get(optionEliXml)), UTF_8)) {
141 script.printentries(script.eliEntries, stream);
142 }
143 }
144 script.checkInOneButNotTheOther();
145 script.checkCommonEntries();
146 script.end();
147 if (outputStream != null) {
148 outputStream.close();
149 }
150 if (outputFile != null) {
151 outputFile.close();
152 }
153 }
154
155 /**
156 * Displays help on the console
157 */
158 private static void showHelp() {
159 System.out.println(getHelp());
160 System.exit(0);
161 }
162
163 static String getHelp() {
164 return "usage: java -cp build SyncEditorLayerIndex\n" +
165 "-c,--encoding <encoding> output encoding (defaults to UTF-8 or cp850 on Windows)\n" +
166 "-e,--eli_input <eli_input> Input file for the editor layer index (geojson). " +
167 "Default is imagery_eli.geojson (current directory).\n" +
168 "-h,--help show this help\n" +
169 "-i,--ignore_input <ignore_input> Input file for the ignore list. Default is imagery_josm.ignores.txt (current directory).\n" +
170 "-j,--josm_input <josm_input> Input file for the JOSM imagery list (xml). " +
171 "Default is imagery_josm.imagery.xml (current directory).\n" +
172 "-m,--noeli don't show output for ELI problems\n" +
173 "-n,--noskip don't skip known entries\n" +
174 "-o,--output <output> Output file, - prints to stdout (default: -)\n" +
175 "-p,--elixml <elixml> ELI entries for use in JOSM as XML file (incomplete)\n" +
176 "-q,--josmxml <josmxml> JOSM entries reoutput as XML file (incomplete)\n" +
177 "-s,--shorten shorten the output, so it is easier to read in a console window\n" +
178 "-x,--xhtmlbody create XHTML body for display in a web page\n" +
179 "-X,--xhtml create XHTML for display in a web page\n";
180 }
181
182 /**
183 * Parse command line arguments.
184 * @param args program arguments
185 * @throws IOException in case of I/O error
186 */
187 static void parseCommandLineArguments(String[] args) throws IOException {
188 new OptionParser("JOSM/ELI synchronization script")
189 .addFlagParameter("help", SyncEditorLayerIndex::showHelp)
190 .addShortAlias("help", "h")
191 .addArgumentParameter("output", OptionCount.OPTIONAL, x -> optionOutput = x)
192 .addShortAlias("output", "o")
193 .addArgumentParameter("eli_input", OptionCount.OPTIONAL, x -> eliInputFile = x)
194 .addShortAlias("eli_input", "e")
195 .addArgumentParameter("josm_input", OptionCount.OPTIONAL, x -> josmInputFile = x)
196 .addShortAlias("josm_input", "j")
197 .addArgumentParameter("ignore_input", OptionCount.OPTIONAL, x -> ignoreInputFile = x)
198 .addShortAlias("ignore_input", "i")
199 .addFlagParameter("shorten", () -> optionShorten = true)
200 .addShortAlias("shorten", "s")
201 .addFlagParameter("noskip", () -> optionNoSkip = true)
202 .addShortAlias("noskip", "n")
203 .addFlagParameter("xhtmlbody", () -> optionXhtmlBody = true)
204 .addShortAlias("xhtmlbody", "x")
205 .addFlagParameter("xhtml", () -> optionXhtml = true)
206 .addShortAlias("xhtml", "X")
207 .addArgumentParameter("elixml", OptionCount.OPTIONAL, x -> optionEliXml = x)
208 .addShortAlias("elixml", "p")
209 .addArgumentParameter("josmxml", OptionCount.OPTIONAL, x -> optionJosmXml = x)
210 .addShortAlias("josmxml", "q")
211 .addFlagParameter("noeli", () -> optionNoEli = true)
212 .addShortAlias("noeli", "m")
213 .addArgumentParameter("encoding", OptionCount.OPTIONAL, x -> optionEncoding = x)
214 .addShortAlias("encoding", "c")
215 .parseOptionsOrExit(Arrays.asList(args));
216
217 if (optionOutput != null && !"-".equals(optionOutput)) {
218 outputFile = Files.newOutputStream(Paths.get(optionOutput));
219 outputStream = new OutputStreamWriter(outputFile, optionEncoding != null ? optionEncoding : "UTF-8");
220 } else if (optionEncoding != null) {
221 outputStream = new OutputStreamWriter(System.out, optionEncoding);
222 }
223 }
224
225 void setupProj() {
226 oldproj.put("EPSG:3359", "EPSG:3404");
227 oldproj.put("EPSG:3785", "EPSG:3857");
228 oldproj.put("EPSG:31297", "EPGS:31287");
229 oldproj.put("EPSG:31464", "EPSG:31468");
230 oldproj.put("EPSG:54004", "EPSG:3857");
231 oldproj.put("EPSG:102100", "EPSG:3857");
232 oldproj.put("EPSG:102113", "EPSG:3857");
233 oldproj.put("EPSG:900913", "EPGS:3857");
234 ignoreproj.add("EPSG:4267");
235 ignoreproj.add("EPSG:5221");
236 ignoreproj.add("EPSG:5514");
237 ignoreproj.add("EPSG:32019");
238 ignoreproj.add("EPSG:102066");
239 ignoreproj.add("EPSG:102067");
240 ignoreproj.add("EPSG:102685");
241 ignoreproj.add("EPSG:102711");
242 }
243
244 void loadSkip() throws IOException {
245 final Pattern pattern = Pattern.compile("^\\|\\| *(ELI|Ignore) *\\|\\| *\\{\\{\\{(.+)\\}\\}\\} *\\|\\|");
246 try (BufferedReader fr = new BufferedReader(new InputStreamReader(Files.newInputStream(Paths.get(ignoreInputFile)), UTF_8))) {
247 String line;
248
249 while ((line = fr.readLine()) != null) {
250 Matcher res = pattern.matcher(line);
251 if (res.matches()) {
252 String s = res.group(2);
253 if (s.endsWith("...")) {
254 s = s.substring(0, s.length() - 3);
255 if ("Ignore".equals(res.group(1))) {
256 skipStart.put(s, "green");
257 } else {
258 skipStart.put(s, "darkgoldenrod");
259 }
260 } else {
261 if ("Ignore".equals(res.group(1))) {
262 skip.put(s, "green");
263 } else {
264 skip.put(s, "darkgoldenrod");
265 }
266 }
267 }
268 }
269 }
270 }
271
272 void myprintlnfinal(String s) {
273 if (outputStream != null) {
274 try {
275 outputStream.write(s + System.getProperty("line.separator"));
276 } catch (IOException e) {
277 throw new JosmRuntimeException(e);
278 }
279 } else {
280 System.out.println(s);
281 }
282 }
283
284 String isSkipString(String s) {
285 if (skip.containsKey(s))
286 return skip.get(s);
287 for (Entry<String, String> str : skipStart.entrySet()) {
288 if (s.startsWith(str.getKey()))
289 return str.getValue();
290 }
291 return null;
292 }
293
294 void myprintln(String s) {
295 String color;
296 if ((color = isSkipString(s)) != null) {
297 skip.remove(s);
298 if (optionXhtmlBody || optionXhtml) {
299 s = "<pre style=\"margin:3px;color:"+color+"\">"
300 + s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")+"</pre>";
301 }
302 if (!optionNoSkip) {
303 return;
304 }
305 } else if (optionXhtmlBody || optionXhtml) {
306 color =
307 s.startsWith("***") ? "black" :
308 ((s.startsWith("+ ") || s.startsWith("+++ ELI")) ? "blue" :
309 (s.startsWith("#") ? "indigo" :
310 (s.startsWith("!") ? "orange" : "red")));
311 s = "<pre style=\"margin:3px;color:"+color+"\">"+s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")+"</pre>";
312 }
313 if ((s.startsWith("+ ") || s.startsWith("+++ ELI") || s.startsWith("#")) && optionNoEli) {
314 return;
315 }
316 myprintlnfinal(s);
317 }
318
319 void start() {
320 if (optionXhtml) {
321 myprintlnfinal(
322 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n");
323 myprintlnfinal(
324 "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>"+
325 "<title>JOSM - ELI differences</title></head><body>\n");
326 }
327 }
328
329 void end() {
330 for (String s : skip.keySet()) {
331 myprintln("+++ Obsolete skip entry: " + s);
332 }
333 if (optionXhtml) {
334 myprintlnfinal("</body></html>\n");
335 }
336 }
337
338 void loadELIEntries() throws IOException {
339 try (JsonReader jr = Json.createReader(new InputStreamReader(Files.newInputStream(Paths.get(eliInputFile)), UTF_8))) {
340 eliEntries = jr.readObject().getJsonArray("features");
341 }
342
343 for (JsonValue e : eliEntries) {
344 String url = getUrlStripped(e);
345 if (url.contains("{z}")) {
346 myprintln("+++ ELI-URL uses {z} instead of {zoom}: "+url);
347 url = url.replace("{z}", "{zoom}");
348 }
349 if (eliUrls.containsKey(url)) {
350 myprintln("+++ ELI-URL is not unique: "+url);
351 } else {
352 eliUrls.put(url, e.asJsonObject());
353 }
354 JsonArray s = e.asJsonObject().get("properties").asJsonObject().getJsonArray("available_projections");
355 if (s != null) {
356 String urlLc = url.toLowerCase(Locale.ENGLISH);
357 List<String> old = new LinkedList<>();
358 for (JsonValue p : s) {
359 String proj = ((JsonString) p).getString();
360 if (oldproj.containsKey(proj) || ("CRS:84".equals(proj) && !urlLc.contains("version=1.3"))) {
361 old.add(proj);
362 }
363 }
364 if (!old.isEmpty()) {
365 myprintln("+ ELI Projections "+String.join(", ", old)+" not useful: "+getDescription(e));
366 }
367 }
368 }
369 myprintln("*** Loaded "+eliEntries.size()+" entries (ELI). ***");
370 }
371
372 String cdata(String s) {
373 return cdata(s, false);
374 }
375
376 String cdata(String s, boolean escape) {
377 if (escape) {
378 return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
379 } else if (s.matches(".*[<>&].*"))
380 return "<![CDATA["+s+"]]>";
381 return s;
382 }
383
384 String maininfo(Object entry, String offset) {
385 String t = getType(entry);
386 String res = offset + "<type>"+t+"</type>\n";
387 res += offset + "<url>"+cdata(getUrl(entry))+"</url>\n";
388 if (getMinZoom(entry) != null)
389 res += offset + "<min-zoom>"+getMinZoom(entry)+"</min-zoom>\n";
390 if (getMaxZoom(entry) != null)
391 res += offset + "<max-zoom>"+getMaxZoom(entry)+"</max-zoom>\n";
392 if ("wms".equals(t)) {
393 List<String> p = getProjections(entry);
394 if (p != null) {
395 res += offset + "<projections>\n";
396 for (String c : p) {
397 res += offset + " <code>"+c+"</code>\n";
398 }
399 res += offset + "</projections>\n";
400 }
401 }
402 return res;
403 }
404
405 void printentries(List<?> entries, OutputStreamWriter stream) throws IOException {
406 DecimalFormat df = new DecimalFormat("#.#######");
407 df.setRoundingMode(java.math.RoundingMode.CEILING);
408 stream.write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
409 stream.write("<imagery xmlns=\"http://josm.openstreetmap.de/maps-1.0\">\n");
410 for (Object e : entries) {
411 stream.write(" <entry"
412 + ("eli-best".equals(getQuality(e)) ? " eli-best=\"true\"" : "")
413 + (getOverlay(e) ? " overlay=\"true\"" : "")
414 + ">\n");
415 String t;
416 if (isNotBlank(t = getName(e)))
417 stream.write(" <name>"+cdata(t, true)+"</name>\n");
418 if (isNotBlank(t = getId(e)))
419 stream.write(" <id>"+t+"</id>\n");
420 if (isNotBlank(t = getCategory(e)))
421 stream.write(" <category>"+t+"</category>\n");
422 if (isNotBlank(t = getDate(e)))
423 stream.write(" <date>"+t+"</date>\n");
424 if (isNotBlank(t = getCountryCode(e)))
425 stream.write(" <country-code>"+t+"</country-code>\n");
426 if ((getDefault(e)))
427 stream.write(" <default>true</default>\n");
428 stream.write(maininfo(e, " "));
429 if (isNotBlank(t = getAttributionText(e)))
430 stream.write(" <attribution-text mandatory=\"true\">"+cdata(t, true)+"</attribution-text>\n");
431 if (isNotBlank(t = getAttributionUrl(e)))
432 stream.write(" <attribution-url>"+cdata(t)+"</attribution-url>\n");
433 if (isNotBlank(t = getLogoImage(e)))
434 stream.write(" <logo-image>"+cdata(t, true)+"</logo-image>\n");
435 if (isNotBlank(t = getLogoUrl(e)))
436 stream.write(" <logo-url>"+cdata(t)+"</logo-url>\n");
437 if (isNotBlank(t = getTermsOfUseText(e)))
438 stream.write(" <terms-of-use-text>"+cdata(t, true)+"</terms-of-use-text>\n");
439 if (isNotBlank(t = getTermsOfUseUrl(e)))
440 stream.write(" <terms-of-use-url>"+cdata(t)+"</terms-of-use-url>\n");
441 if (isNotBlank(t = getPermissionReferenceUrl(e)))
442 stream.write(" <permission-ref>"+cdata(t)+"</permission-ref>\n");
443 if ((getValidGeoreference(e)))
444 stream.write(" <valid-georeference>true</valid-georeference>\n");
445 if (isNotBlank(t = getIcon(e)))
446 stream.write(" <icon>"+cdata(t)+"</icon>\n");
447 for (Entry<String, String> d : getDescriptions(e).entrySet()) {
448 stream.write(" <description lang=\""+d.getKey()+"\">"+d.getValue()+"</description>\n");
449 }
450 for (ImageryInfo m : getMirrors(e)) {
451 stream.write(" <mirror>\n"+maininfo(m, " ")+" </mirror>\n");
452 }
453 double minlat = 1000;
454 double minlon = 1000;
455 double maxlat = -1000;
456 double maxlon = -1000;
457 String shapes = "";
458 String sep = "\n ";
459 try {
460 for (Shape s: getShapes(e)) {
461 shapes += " <shape>";
462 int i = 0;
463 for (Coordinate p: s.getPoints()) {
464 double lat = p.getLat();
465 double lon = p.getLon();
466 if (lat > maxlat) maxlat = lat;
467 if (lon > maxlon) maxlon = lon;
468 if (lat < minlat) minlat = lat;
469 if (lon < minlon) minlon = lon;
470 if ((i++ % 3) == 0) {
471 shapes += sep + " ";
472 }
473 shapes += "<point lat='"+df.format(lat)+"' lon='"+df.format(lon)+"'/>";
474 }
475 shapes += sep + "</shape>\n";
476 }
477 } catch (IllegalArgumentException ignored) {
478 Logging.trace(ignored);
479 }
480 if (!shapes.isEmpty()) {
481 stream.write(" <bounds min-lat='"+df.format(minlat)
482 +"' min-lon='"+df.format(minlon)
483 +"' max-lat='"+df.format(maxlat)
484 +"' max-lon='"+df.format(maxlon)+"'>\n");
485 stream.write(shapes + " </bounds>\n");
486 }
487 stream.write(" </entry>\n");
488 }
489 stream.write("</imagery>\n");
490 stream.close();
491 }
492
493 void loadJosmEntries() throws IOException, SAXException, ReflectiveOperationException {
494 try (ImageryReader reader = new ImageryReader(josmInputFile)) {
495 josmEntries = reader.parse();
496 }
497
498 for (ImageryInfo e : josmEntries) {
499 if (isBlank(getUrl(e))) {
500 myprintln("+++ JOSM-Entry without URL: " + getDescription(e));
501 continue;
502 }
503 if (isBlank(getName(e))) {
504 myprintln("+++ JOSM-Entry without Name: " + getDescription(e));
505 continue;
506 }
507 String url = getUrlStripped(e);
508 if (url.contains("{z}")) {
509 myprintln("+++ JOSM-URL uses {z} instead of {zoom}: "+url);
510 url = url.replace("{z}", "{zoom}");
511 }
512 if (josmUrls.containsKey(url)) {
513 myprintln("+++ JOSM-URL is not unique: "+url);
514 } else {
515 josmUrls.put(url, e);
516 }
517 for (ImageryInfo m : e.getMirrors()) {
518 url = getUrlStripped(m);
519 Field origNameField = ImageryInfo.class.getDeclaredField("origName");
520 ReflectionUtils.setObjectsAccessible(origNameField);
521 origNameField.set(m, m.getOriginalName().replaceAll(" mirror server( \\d+)?", ""));
522 if (josmUrls.containsKey(url)) {
523 myprintln("+++ JOSM-Mirror-URL is not unique: "+url);
524 } else {
525 josmUrls.put(url, m);
526 josmMirrors.put(url, m);
527 }
528 }
529 }
530 myprintln("*** Loaded "+josmEntries.size()+" entries (JOSM). ***");
531 }
532
533 void checkInOneButNotTheOther() {
534 List<String> le = new LinkedList<>(eliUrls.keySet());
535 List<String> lj = new LinkedList<>(josmUrls.keySet());
536
537 List<String> ke = new LinkedList<>(le);
538 for (String url : ke) {
539 if (lj.contains(url)) {
540 le.remove(url);
541 lj.remove(url);
542 }
543 }
544
545 if (!le.isEmpty() && !lj.isEmpty()) {
546 ke = new LinkedList<>(le);
547 for (String urle : ke) {
548 JsonObject e = eliUrls.get(urle);
549 String ide = getId(e);
550 String urlhttps = urle.replace("http:", "https:");
551 if (lj.contains(urlhttps)) {
552 myprintln("+ Missing https: "+getDescription(e));
553 eliUrls.put(urlhttps, eliUrls.get(urle));
554 eliUrls.remove(urle);
555 le.remove(urle);
556 lj.remove(urlhttps);
557 } else if (isNotBlank(ide)) {
558 List<String> kj = new LinkedList<>(lj);
559 for (String urlj : kj) {
560 ImageryInfo j = josmUrls.get(urlj);
561 String idj = getId(j);
562
563 if (ide.equals(idj) && Objects.equals(getType(j), getType(e))) {
564 myprintln("* URL for id "+idj+" differs ("+urle+"): "+getDescription(j));
565 le.remove(urle);
566 lj.remove(urlj);
567 // replace key for this entry with JOSM URL
568 eliUrls.remove(urle);
569 eliUrls.put(urlj, e);
570 break;
571 }
572 }
573 }
574 }
575 }
576
577 myprintln("*** URLs found in ELI but not in JOSM ("+le.size()+"): ***");
578 Collections.sort(le);
579 if (!le.isEmpty()) {
580 for (String l : le) {
581 myprintln("- " + getDescription(eliUrls.get(l)));
582 }
583 }
584 myprintln("*** URLs found in JOSM but not in ELI ("+lj.size()+"): ***");
585 Collections.sort(lj);
586 if (!lj.isEmpty()) {
587 for (String l : lj) {
588 myprintln("+ " + getDescription(josmUrls.get(l)));
589 }
590 }
591 }
592
593 void checkCommonEntries() {
594 doSameUrlButDifferentName();
595 doSameUrlButDifferentId();
596 doSameUrlButDifferentType();
597 doSameUrlButDifferentZoomBounds();
598 doSameUrlButDifferentCountryCode();
599 doSameUrlButDifferentQuality();
600 doSameUrlButDifferentDates();
601 doSameUrlButDifferentInformation();
602 doMismatchingShapes();
603 doMismatchingIcons();
604 doMismatchingCategories();
605 doMiscellaneousChecks();
606 }
607
608 void doSameUrlButDifferentName() {
609 myprintln("*** Same URL, but different name: ***");
610 for (String url : eliUrls.keySet()) {
611 JsonObject e = eliUrls.get(url);
612 if (!josmUrls.containsKey(url)) continue;
613 ImageryInfo j = josmUrls.get(url);
614 String ename = getName(e).replace("'", "\u2019");
615 String jname = getName(j).replace("'", "\u2019");
616 if (!ename.equals(jname)) {
617 myprintln("* Name differs ('"+getName(e)+"' != '"+getName(j)+"'): "+getUrl(j));
618 }
619 }
620 }
621
622 void doSameUrlButDifferentId() {
623 myprintln("*** Same URL, but different Id: ***");
624 for (String url : eliUrls.keySet()) {
625 JsonObject e = eliUrls.get(url);
626 if (!josmUrls.containsKey(url)) continue;
627 ImageryInfo j = josmUrls.get(url);
628 String ename = getId(e);
629 String jname = getId(j);
630 if (!Objects.equals(ename, jname)) {
631 myprintln("# Id differs ('"+getId(e)+"' != '"+getId(j)+"'): "+getUrl(j));
632 }
633 }
634 }
635
636 void doSameUrlButDifferentType() {
637 myprintln("*** Same URL, but different type: ***");
638 for (String url : eliUrls.keySet()) {
639 JsonObject e = eliUrls.get(url);
640 if (!josmUrls.containsKey(url)) continue;
641 ImageryInfo j = josmUrls.get(url);
642 if (!Objects.equals(getType(e), getType(j))) {
643 myprintln("* Type differs ("+getType(e)+" != "+getType(j)+"): "+getName(j)+" - "+getUrl(j));
644 }
645 }
646 }
647
648 void doSameUrlButDifferentZoomBounds() {
649 myprintln("*** Same URL, but different zoom bounds: ***");
650 for (String url : eliUrls.keySet()) {
651 JsonObject e = eliUrls.get(url);
652 if (!josmUrls.containsKey(url)) continue;
653 ImageryInfo j = josmUrls.get(url);
654
655 Integer eMinZoom = getMinZoom(e);
656 Integer jMinZoom = getMinZoom(j);
657 /* dont warn for entries copied from the base of the mirror */
658 if (eMinZoom == null && "wms".equals(getType(j)) && j.getName().contains(" mirror"))
659 jMinZoom = null;
660 if (!Objects.equals(eMinZoom, jMinZoom) && !(Objects.equals(eMinZoom, 0) && jMinZoom == null)) {
661 myprintln("* Minzoom differs ("+eMinZoom+" != "+jMinZoom+"): "+getDescription(j));
662 }
663 Integer eMaxZoom = getMaxZoom(e);
664 Integer jMaxZoom = getMaxZoom(j);
665 /* dont warn for entries copied from the base of the mirror */
666 if (eMaxZoom == null && "wms".equals(getType(j)) && j.getName().contains(" mirror"))
667 jMaxZoom = null;
668 if (!Objects.equals(eMaxZoom, jMaxZoom)) {
669 myprintln("* Maxzoom differs ("+eMaxZoom+" != "+jMaxZoom+"): "+getDescription(j));
670 }
671 }
672 }
673
674 void doSameUrlButDifferentCountryCode() {
675 myprintln("*** Same URL, but different country code: ***");
676 for (String url : eliUrls.keySet()) {
677 JsonObject e = eliUrls.get(url);
678 if (!josmUrls.containsKey(url)) continue;
679 ImageryInfo j = josmUrls.get(url);
680 String cce = getCountryCode(e);
681 if ("ZZ".equals(cce)) { /* special ELI country code */
682 cce = null;
683 }
684 if (cce != null && !cce.equals(getCountryCode(j))) {
685 myprintln("* Country code differs ("+getCountryCode(e)+" != "+getCountryCode(j)+"): "+getDescription(j));
686 }
687 }
688 }
689
690 void doSameUrlButDifferentQuality() {
691 myprintln("*** Same URL, but different quality: ***");
692 for (String url : eliUrls.keySet()) {
693 JsonObject e = eliUrls.get(url);
694 if (!josmUrls.containsKey(url)) {
695 String q = getQuality(e);
696 if ("eli-best".equals(q)) {
697 myprintln("- Quality best entry not in JOSM for "+getDescription(e));
698 }
699 continue;
700 }
701 ImageryInfo j = josmUrls.get(url);
702 if (!Objects.equals(getQuality(e), getQuality(j))) {
703 myprintln("* Quality differs ("+getQuality(e)+" != "+getQuality(j)+"): "+getDescription(j));
704 }
705 }
706 }
707
708 void doSameUrlButDifferentDates() {
709 myprintln("*** Same URL, but different dates: ***");
710 Pattern pattern = Pattern.compile("^(.*;)(\\d\\d\\d\\d)(-(\\d\\d)(-(\\d\\d))?)?$");
711 for (String url : eliUrls.keySet()) {
712 String ed = getDate(eliUrls.get(url));
713 if (!josmUrls.containsKey(url)) continue;
714 ImageryInfo j = josmUrls.get(url);
715 String jd = getDate(j);
716 // The forms 2015;- or -;2015 or 2015;2015 are handled equal to 2015
717 String ef = ed.replaceAll("\\A-;", "").replaceAll(";-\\z", "").replaceAll("\\A([0-9-]+);\\1\\z", "$1");
718 // ELI has a strange and inconsistent used end_date definition, so we try again with subtraction by one
719 String ed2 = ed;
720 Matcher m = pattern.matcher(ed);
721 if (m.matches()) {
722 Calendar cal = Calendar.getInstance();
723 cal.set(Integer.valueOf(m.group(2)),
724 m.group(4) == null ? 0 : Integer.valueOf(m.group(4))-1,
725 m.group(6) == null ? 1 : Integer.valueOf(m.group(6)));
726 cal.add(Calendar.DAY_OF_MONTH, -1);
727 ed2 = m.group(1) + cal.get(Calendar.YEAR);
728 if (m.group(4) != null)
729 ed2 += "-" + String.format("%02d", cal.get(Calendar.MONTH)+1);
730 if (m.group(6) != null)
731 ed2 += "-" + String.format("%02d", cal.get(Calendar.DAY_OF_MONTH));
732 }
733 String ef2 = ed2.replaceAll("\\A-;", "").replaceAll(";-\\z", "").replaceAll("\\A([0-9-]+);\\1\\z", "$1");
734 if (!ed.equals(jd) && !ef.equals(jd) && !ed2.equals(jd) && !ef2.equals(jd)) {
735 String t = "'"+ed+"'";
736 if (!ed.equals(ef)) {
737 t += " or '"+ef+"'";
738 }
739 if (jd.isEmpty()) {
740 myprintln("- Missing JOSM date ("+t+"): "+getDescription(j));
741 } else if (!ed.isEmpty()) {
742 myprintln("* Date differs ('"+t+"' != '"+jd+"'): "+getDescription(j));
743 } else if (!optionNoEli) {
744 myprintln("+ Missing ELI date ('"+jd+"'): "+getDescription(j));
745 }
746 }
747 }
748 }
749
750 void doSameUrlButDifferentInformation() {
751 myprintln("*** Same URL, but different information: ***");
752 for (String url : eliUrls.keySet()) {
753 if (!josmUrls.containsKey(url)) continue;
754 JsonObject e = eliUrls.get(url);
755 ImageryInfo j = josmUrls.get(url);
756
757 compareDescriptions(e, j);
758 comparePermissionReferenceUrls(e, j);
759 compareAttributionUrls(e, j);
760 compareAttributionTexts(e, j);
761 compareProjections(e, j);
762 compareDefaults(e, j);
763 compareOverlays(e, j);
764 compareNoTileHeaders(e, j);
765 }
766 }
767
768 void compareDescriptions(JsonObject e, ImageryInfo j) {
769 String et = getDescriptions(e).getOrDefault("en", "");
770 String jt = getDescriptions(j).getOrDefault("en", "");
771 if (!et.equals(jt)) {
772 if (jt.isEmpty()) {
773 myprintln("- Missing JOSM description ("+et+"): "+getDescription(j));
774 } else if (!et.isEmpty()) {
775 myprintln("* Description differs ('"+et+"' != '"+jt+"'): "+getDescription(j));
776 } else if (!optionNoEli) {
777 myprintln("+ Missing ELI description ('"+jt+"'): "+getDescription(j));
778 }
779 }
780 }
781
782 void comparePermissionReferenceUrls(JsonObject e, ImageryInfo j) {
783 String et = getPermissionReferenceUrl(e);
784 String jt = getPermissionReferenceUrl(j);
785 String jt2 = getTermsOfUseUrl(j);
786 if (isBlank(jt)) jt = jt2;
787 if (!Objects.equals(et, jt)) {
788 if (isBlank(jt)) {
789 myprintln("- Missing JOSM license URL ("+et+"): "+getDescription(j));
790 } else if (isNotBlank(et)) {
791 String ethttps = et.replace("http:", "https:");
792 if (isBlank(jt2) || !(jt2.equals(ethttps) || jt2.equals(et+"/") || jt2.equals(ethttps+"/"))) {
793 if (jt.equals(ethttps) || jt.equals(et+"/") || jt.equals(ethttps+"/")) {
794 myprintln("+ License URL differs ('"+et+"' != '"+jt+"'): "+getDescription(j));
795 } else {
796 String ja = getAttributionUrl(j);
797 if (ja != null && (ja.equals(et) || ja.equals(ethttps) || ja.equals(et+"/") || ja.equals(ethttps+"/"))) {
798 myprintln("+ ELI License URL in JOSM Attribution: "+getDescription(j));
799 } else {
800 myprintln("* License URL differs ('"+et+"' != '"+jt+"'): "+getDescription(j));
801 }
802 }
803 }
804 } else if (!optionNoEli) {
805 myprintln("+ Missing ELI license URL ('"+jt+"'): "+getDescription(j));
806 }
807 }
808 }
809
810 void compareAttributionUrls(JsonObject e, ImageryInfo j) {
811 String et = getAttributionUrl(e);
812 String jt = getAttributionUrl(j);
813 if (!Objects.equals(et, jt)) {
814 if (isBlank(jt)) {
815 myprintln("- Missing JOSM attribution URL ("+et+"): "+getDescription(j));
816 } else if (isNotBlank(et)) {
817 String ethttps = et.replace("http:", "https:");
818 if (jt.equals(ethttps) || jt.equals(et+"/") || jt.equals(ethttps+"/")) {
819 myprintln("+ Attribution URL differs ('"+et+"' != '"+jt+"'): "+getDescription(j));
820 } else {
821 myprintln("* Attribution URL differs ('"+et+"' != '"+jt+"'): "+getDescription(j));
822 }
823 } else if (!optionNoEli) {
824 myprintln("+ Missing ELI attribution URL ('"+jt+"'): "+getDescription(j));
825 }
826 }
827 }
828
829 void compareAttributionTexts(JsonObject e, ImageryInfo j) {
830 String et = getAttributionText(e);
831 String jt = getAttributionText(j);
832 if (!Objects.equals(et, jt)) {
833 if (isBlank(jt)) {
834 myprintln("- Missing JOSM attribution text ("+et+"): "+getDescription(j));
835 } else if (isNotBlank(et)) {
836 myprintln("* Attribution text differs ('"+et+"' != '"+jt+"'): "+getDescription(j));
837 } else if (!optionNoEli) {
838 myprintln("+ Missing ELI attribution text ('"+jt+"'): "+getDescription(j));
839 }
840 }
841 }
842
843 void compareProjections(JsonObject e, ImageryInfo j) {
844 String et = getProjections(e).stream().sorted().collect(Collectors.joining(" "));
845 String jt = getProjections(j).stream().sorted().collect(Collectors.joining(" "));
846 if (!Objects.equals(et, jt)) {
847 if (isBlank(jt)) {
848 String t = getType(e);
849 if ("wms_endpoint".equals(t) || "tms".equals(t)) {
850 myprintln("+ ELI projections for type "+t+": "+getDescription(j));
851 } else {
852 myprintln("- Missing JOSM projections ("+et+"): "+getDescription(j));
853 }
854 } else if (isNotBlank(et)) {
855 if ("EPSG:3857 EPSG:4326".equals(et) || "EPSG:3857".equals(et) || "EPSG:4326".equals(et)) {
856 myprintln("+ ELI has minimal projections ('"+et+"' != '"+jt+"'): "+getDescription(j));
857 } else {
858 myprintln("* Projections differ ('"+et+"' != '"+jt+"'): "+getDescription(j));
859 }
860 } else if (!optionNoEli && !"tms".equals(getType(e))) {
861 myprintln("+ Missing ELI projections ('"+jt+"'): "+getDescription(j));
862 }
863 }
864 }
865
866 void compareDefaults(JsonObject e, ImageryInfo j) {
867 boolean ed = getDefault(e);
868 boolean jd = getDefault(j);
869 if (ed != jd) {
870 if (!jd) {
871 myprintln("- Missing JOSM default: "+getDescription(j));
872 } else if (!optionNoEli) {
873 myprintln("+ Missing ELI default: "+getDescription(j));
874 }
875 }
876 }
877
878 void compareOverlays(JsonObject e, ImageryInfo j) {
879 boolean eo = getOverlay(e);
880 boolean jo = getOverlay(j);
881 if (eo != jo) {
882 if (!jo) {
883 myprintln("- Missing JOSM overlay flag: "+getDescription(j));
884 } else if (!optionNoEli) {
885 myprintln("+ Missing ELI overlay flag: "+getDescription(j));
886 }
887 }
888 }
889
890 void compareNoTileHeaders(JsonObject e, ImageryInfo j) {
891 Map<String, Set<String>> eh = getNoTileHeader(e);
892 Map<String, Set<String>> jh = getNoTileHeader(j);
893 if (!Objects.equals(eh, jh)) {
894 if (jh == null || jh.isEmpty()) {
895 myprintln("- Missing JOSM no tile headers ("+eh+"): "+getDescription(j));
896 } else if (eh != null && !eh.isEmpty()) {
897 myprintln("* No tile headers differ ('"+eh+"' != '"+jh+"'): "+getDescription(j));
898 } else if (!optionNoEli) {
899 myprintln("+ Missing ELI no tile headers ('"+jh+"'): "+getDescription(j));
900 }
901 }
902 }
903
904 void doMismatchingShapes() {
905 myprintln("*** Mismatching shapes: ***");
906 for (String url : josmUrls.keySet()) {
907 ImageryInfo j = josmUrls.get(url);
908 int num = 1;
909 for (Shape shape : getShapes(j)) {
910 List<Coordinate> p = shape.getPoints();
911 if (!p.get(0).equals(p.get(p.size()-1))) {
912 myprintln("+++ JOSM shape "+num+" unclosed: "+getDescription(j));
913 }
914 for (int nump = 1; nump < p.size(); ++nump) {
915 if (Objects.equals(p.get(nump-1), p.get(nump))) {
916 myprintln("+++ JOSM shape "+num+" double point at "+(nump-1)+": "+getDescription(j));
917 }
918 }
919 ++num;
920 }
921 }
922 for (String url : eliUrls.keySet()) {
923 JsonObject e = eliUrls.get(url);
924 int num = 1;
925 List<Shape> s = null;
926 try {
927 s = getShapes(e);
928 for (Shape shape : s) {
929 List<Coordinate> p = shape.getPoints();
930 if (!p.get(0).equals(p.get(p.size()-1)) && !optionNoEli) {
931 myprintln("+++ ELI shape "+num+" unclosed: "+getDescription(e));
932 }
933 for (int nump = 1; nump < p.size(); ++nump) {
934 if (Objects.equals(p.get(nump-1), p.get(nump))) {
935 myprintln("+++ ELI shape "+num+" double point at "+(nump-1)+": "+getDescription(e));
936 }
937 }
938 ++num;
939 }
940 } catch (IllegalArgumentException err) {
941 String desc = getDescription(e);
942 myprintln("* Invalid data in ELI geometry for "+desc+": "+err.getMessage());
943 }
944 if (s == null || !josmUrls.containsKey(url)) {
945 continue;
946 }
947 ImageryInfo j = josmUrls.get(url);
948 List<Shape> js = getShapes(j);
949 if (s.isEmpty() && !js.isEmpty()) {
950 if (!optionNoEli) {
951 myprintln("+ No ELI shape: "+getDescription(j));
952 }
953 } else if (js.isEmpty() && !s.isEmpty()) {
954 // don't report boundary like 5 point shapes as difference
955 if (s.size() != 1 || s.get(0).getPoints().size() != 5) {
956 myprintln("- No JOSM shape: "+getDescription(j));
957 }
958 } else if (s.size() != js.size()) {
959 myprintln("* Different number of shapes ("+s.size()+" != "+js.size()+"): "+getDescription(j));
960 } else {
961 boolean[] edone = new boolean[s.size()];
962 boolean[] jdone = new boolean[js.size()];
963 for (int enums = 0; enums < s.size(); ++enums) {
964 List<Coordinate> ep = s.get(enums).getPoints();
965 for (int jnums = 0; jnums < js.size() && !edone[enums]; ++jnums) {
966 List<Coordinate> jp = js.get(jnums).getPoints();
967 if (ep.size() == jp.size() && !jdone[jnums]) {
968 boolean err = false;
969 for (int nump = 0; nump < ep.size() && !err; ++nump) {
970 Coordinate ept = ep.get(nump);
971 Coordinate jpt = jp.get(nump);
972 if (Math.abs(ept.getLat()-jpt.getLat()) > 0.00001 || Math.abs(ept.getLon()-jpt.getLon()) > 0.00001)
973 err = true;
974 }
975 if (!err) {
976 edone[enums] = true;
977 jdone[jnums] = true;
978 break;
979 }
980 }
981 }
982 }
983 for (int enums = 0; enums < s.size(); ++enums) {
984 List<Coordinate> ep = s.get(enums).getPoints();
985 for (int jnums = 0; jnums < js.size() && !edone[enums]; ++jnums) {
986 List<Coordinate> jp = js.get(jnums).getPoints();
987 if (ep.size() == jp.size() && !jdone[jnums]) {
988 boolean err = false;
989 for (int nump = 0; nump < ep.size() && !err; ++nump) {
990 Coordinate ept = ep.get(nump);
991 Coordinate jpt = jp.get(nump);
992 if (Math.abs(ept.getLat()-jpt.getLat()) > 0.00001 || Math.abs(ept.getLon()-jpt.getLon()) > 0.00001) {
993 String numtxt = Integer.toString(enums+1);
994 if (enums != jnums) {
995 numtxt += '/' + Integer.toString(jnums+1);
996 }
997 myprintln("* Different coordinate for point "+(nump+1)+" of shape "+numtxt+": "+getDescription(j));
998 break;
999 }
1000 }
1001 edone[enums] = true;
1002 jdone[jnums] = true;
1003 break;
1004 }
1005 }
1006 }
1007 for (int enums = 0; enums < s.size(); ++enums) {
1008 List<Coordinate> ep = s.get(enums).getPoints();
1009 for (int jnums = 0; jnums < js.size() && !edone[enums]; ++jnums) {
1010 List<Coordinate> jp = js.get(jnums).getPoints();
1011 if (!jdone[jnums]) {
1012 String numtxt = Integer.toString(enums+1);
1013 if (enums != jnums) {
1014 numtxt += '/' + Integer.toString(jnums+1);
1015 }
1016 myprintln("* Different number of points for shape "+numtxt+" ("+ep.size()+" ! = "+jp.size()+"): "
1017 + getDescription(j));
1018 edone[enums] = true;
1019 jdone[jnums] = true;
1020 break;
1021 }
1022 }
1023 }
1024 }
1025 }
1026 }
1027
1028 void doMismatchingIcons() {
1029 myprintln("*** Mismatching icons: ***");
1030 doMismatching(this::compareIcons);
1031 }
1032
1033 void doMismatchingCategories() {
1034 myprintln("*** Mismatching categories: ***");
1035 doMismatching(this::compareCategories);
1036 }
1037
1038 void doMismatching(BiConsumer<ImageryInfo, JsonObject> comparator) {
1039 for (String url : eliUrls.keySet()) {
1040 if (josmUrls.containsKey(url)) {
1041 comparator.accept(josmUrls.get(url), eliUrls.get(url));
1042 }
1043 }
1044 }
1045
1046 void compareIcons(ImageryInfo j, JsonObject e) {
1047 String ij = getIcon(j);
1048 String ie = getIcon(e);
1049 boolean ijok = isNotBlank(ij);
1050 boolean ieok = isNotBlank(ie);
1051 if (ijok && !ieok) {
1052 if (!optionNoEli) {
1053 myprintln("+ No ELI icon: "+getDescription(j));
1054 }
1055 } else if (!ijok && ieok) {
1056 myprintln("- No JOSM icon: "+getDescription(j));
1057 } else if (ijok && ieok && !Objects.equals(ij, ie) && !(
1058 (ie.startsWith("https://osmlab.github.io/editor-layer-index/")
1059 || ie.startsWith("https://raw.githubusercontent.com/osmlab/editor-layer-index/")) &&
1060 ij.startsWith("data:"))) {
1061 String iehttps = ie.replace("http:", "https:");
1062 if (ij.equals(iehttps)) {
1063 myprintln("+ Different icons: "+getDescription(j));
1064 } else {
1065 myprintln("* Different icons: "+getDescription(j));
1066 }
1067 }
1068 }
1069
1070 void compareCategories(ImageryInfo j, JsonObject e) {
1071 String cj = getCategory(j);
1072 String ce = getCategory(e);
1073 boolean cjok = isNotBlank(cj);
1074 boolean ceok = isNotBlank(ce);
1075 if (cjok && !ceok) {
1076 if (!optionNoEli) {
1077 myprintln("+ No ELI category: "+getDescription(j));
1078 }
1079 } else if (!cjok && ceok) {
1080 myprintln("- No JOSM category: "+getDescription(j));
1081 } else if (cjok && ceok && !Objects.equals(cj, ce)) {
1082 myprintln("* Different categories ('"+ce+"' != '"+cj+"'): "+getDescription(j));
1083 }
1084 }
1085
1086 void doMiscellaneousChecks() {
1087 myprintln("*** Miscellaneous checks: ***");
1088 Map<String, ImageryInfo> josmIds = new HashMap<>();
1089 Collection<String> all = Projections.getAllProjectionCodes();
1090 DomainValidator dv = DomainValidator.getInstance();
1091 for (String url : josmUrls.keySet()) {
1092 ImageryInfo j = josmUrls.get(url);
1093 String id = getId(j);
1094 if ("wms".equals(getType(j))) {
1095 String urlLc = url.toLowerCase(Locale.ENGLISH);
1096 if (getProjections(j).isEmpty()) {
1097 myprintln("* WMS without projections: "+getDescription(j));
1098 } else {
1099 List<String> unsupported = new LinkedList<>();
1100 List<String> old = new LinkedList<>();
1101 for (String p : getProjectionsUnstripped(j)) {
1102 if ("CRS:84".equals(p)) {
1103 if (!urlLc.contains("version=1.3")) {
1104 myprintln("* CRS:84 without WMS 1.3: "+getDescription(j));
1105 }
1106 } else if (oldproj.containsKey(p)) {
1107 old.add(p);
1108 } else if (!all.contains(p) && !ignoreproj.contains(p)) {
1109 unsupported.add(p);
1110 }
1111 }
1112 if (!unsupported.isEmpty()) {
1113 myprintln("* Projections "+String.join(", ", unsupported)+" not supported by JOSM: "+getDescription(j));
1114 }
1115 for (String o : old) {
1116 myprintln("* Projection "+o+" is an old unsupported code and has been replaced by "+oldproj.get(o)+": "
1117 + getDescription(j));
1118 }
1119 }
1120 if (urlLc.contains("version=1.3") && !urlLc.contains("crs={proj}")) {
1121 myprintln("* WMS 1.3 with strange CRS specification: "+getDescription(j));
1122 } else if (urlLc.contains("version=1.1") && !urlLc.contains("srs={proj}")) {
1123 myprintln("* WMS 1.1 with strange SRS specification: "+getDescription(j));
1124 }
1125 }
1126 List<String> urls = new LinkedList<>();
1127 if (!"scanex".equals(getType(j))) {
1128 urls.add(url);
1129 }
1130 String jt = getPermissionReferenceUrl(j);
1131 if (isNotBlank(jt) && !"Public Domain".equalsIgnoreCase(jt))
1132 urls.add(jt);
1133 jt = getTermsOfUseUrl(j);
1134 if (isNotBlank(jt))
1135 urls.add(jt);
1136 jt = getAttributionUrl(j);
1137 if (isNotBlank(jt))
1138 urls.add(jt);
1139 jt = getIcon(j);
1140 if (isNotBlank(jt)) {
1141 if (!jt.startsWith("data:image/"))
1142 urls.add(jt);
1143 else {
1144 try {
1145 new ImageProvider(jt).get();
1146 } catch (RuntimeException e) {
1147 myprintln("* Strange Icon: "+getDescription(j));
1148 }
1149 }
1150 }
1151 Pattern patternU = Pattern.compile("^https?://([^/]+?)(:\\d+)?(/.*)?");
1152 for (String u : urls) {
1153 if (!patternU.matcher(u).matches() || u.matches(".*[ \t]+$")) {
1154 myprintln("* Strange URL '"+u+"': "+getDescription(j));
1155 } else {
1156 try {
1157 URL jurl = new URL(u.replaceAll("\\{switch:[^\\}]*\\}", "x"));
1158 String domain = jurl.getHost();
1159 int port = jurl.getPort();
1160 if (!(domain.matches("^\\d+\\.\\d+\\.\\d+\\.\\d+$")) && !dv.isValid(domain))
1161 myprintln("* Strange Domain '"+domain+"': "+getDescription(j));
1162 else if (80 == port || 443 == port) {
1163 myprintln("* Useless port '"+port+"': "+getDescription(j));
1164 }
1165 } catch (MalformedURLException e) {
1166 myprintln("* Malformed URL '"+u+"': "+getDescription(j)+" => "+e.getMessage());
1167 }
1168 }
1169 }
1170
1171 if (josmMirrors.containsKey(url)) {
1172 continue;
1173 }
1174 if (isBlank(id)) {
1175 myprintln("* No JOSM-ID: "+getDescription(j));
1176 } else if (josmIds.containsKey(id)) {
1177 myprintln("* JOSM-ID "+id+" not unique: "+getDescription(j));
1178 } else {
1179 josmIds.put(id, j);
1180 }
1181 String d = getDate(j);
1182 if (isNotBlank(d)) {
1183 Pattern patternD = Pattern.compile("^(-|(\\d\\d\\d\\d)(-(\\d\\d)(-(\\d\\d))?)?)(;(-|(\\d\\d\\d\\d)(-(\\d\\d)(-(\\d\\d))?)?))?$");
1184 Matcher m = patternD.matcher(d);
1185 if (!m.matches()) {
1186 myprintln("* JOSM-Date '"+d+"' is strange: "+getDescription(j));
1187 } else {
1188 try {
1189 Date first = verifyDate(m.group(2), m.group(4), m.group(6));
1190 Date second = verifyDate(m.group(9), m.group(11), m.group(13));
1191 if (second.compareTo(first) < 0) {
1192 myprintln("* JOSM-Date '"+d+"' is strange (second earlier than first): "+getDescription(j));
1193 }
1194 } catch (Exception e) {
1195 myprintln("* JOSM-Date '"+d+"' is strange ("+e.getMessage()+"): "+getDescription(j));
1196 }
1197 }
1198 }
1199 if (isNotBlank(getAttributionUrl(j)) && isBlank(getAttributionText(j))) {
1200 myprintln("* Attribution link without text: "+getDescription(j));
1201 }
1202 if (isNotBlank(getLogoUrl(j)) && isBlank(getLogoImage(j))) {
1203 myprintln("* Logo link without image: "+getDescription(j));
1204 }
1205 if (isNotBlank(getTermsOfUseText(j)) && isBlank(getTermsOfUseUrl(j))) {
1206 myprintln("* Terms of Use text without link: "+getDescription(j));
1207 }
1208 List<Shape> js = getShapes(j);
1209 if (!js.isEmpty()) {
1210 double minlat = 1000;
1211 double minlon = 1000;
1212 double maxlat = -1000;
1213 double maxlon = -1000;
1214 for (Shape s: js) {
1215 for (Coordinate p: s.getPoints()) {
1216 double lat = p.getLat();
1217 double lon = p.getLon();
1218 if (lat > maxlat) maxlat = lat;
1219 if (lon > maxlon) maxlon = lon;
1220 if (lat < minlat) minlat = lat;
1221 if (lon < minlon) minlon = lon;
1222 }
1223 }
1224 ImageryBounds b = j.getBounds();
1225 if (b.getMinLat() != minlat || b.getMinLon() != minlon || b.getMaxLat() != maxlat || b.getMaxLon() != maxlon) {
1226 myprintln("* Bounds do not match shape (is "+b.getMinLat()+","+b.getMinLon()+","+b.getMaxLat()+","+b.getMaxLon()
1227 + ", calculated <bounds min-lat='"+minlat+"' min-lon='"+minlon+"' max-lat='"+maxlat+"' max-lon='"+maxlon+"'>): "
1228 + getDescription(j));
1229 }
1230 }
1231 List<String> knownCategories = Arrays.asList(
1232 "photo", "elevation", "map", "historicmap", "osmbasedmap", "historicphoto", "qa", "other");
1233 String cat = getCategory(j);
1234 if (isBlank(cat)) {
1235 myprintln("* No category: "+getDescription(j));
1236 } else if (!knownCategories.contains(cat)) {
1237 myprintln("* Strange category "+cat+": "+getDescription(j));
1238 }
1239 }
1240 }
1241
1242 /*
1243 * Utility functions that allow uniform access for both ImageryInfo and JsonObject.
1244 */
1245
1246 static String getUrl(Object e) {
1247 if (e instanceof ImageryInfo) return ((ImageryInfo) e).getUrl();
1248 return ((Map<String, JsonObject>) e).get("properties").getString("url");
1249 }
1250
1251 static String getUrlStripped(Object e) {
1252 return getUrl(e).replaceAll("\\?(apikey|access_token)=.*", "");
1253 }
1254
1255 static String getDate(Object e) {
1256 if (e instanceof ImageryInfo) return ((ImageryInfo) e).getDate() != null ? ((ImageryInfo) e).getDate() : "";
1257 JsonObject p = ((Map<String, JsonObject>) e).get("properties");
1258 String start = p.containsKey("start_date") ? p.getString("start_date") : "";
1259 String end = p.containsKey("end_date") ? p.getString("end_date") : "";
1260 if (!start.isEmpty() && !end.isEmpty())
1261 return start+";"+end;
1262 else if (!start.isEmpty())
1263 return start+";-";
1264 else if (!end.isEmpty())
1265 return "-;"+end;
1266 return "";
1267 }
1268
1269 static Date verifyDate(String year, String month, String day) throws ParseException {
1270 String date;
1271 if (year == null) {
1272 date = "3000-01-01";
1273 } else {
1274 date = year + "-" + (month == null ? "01" : month) + "-" + (day == null ? "01" : day);
1275 }
1276 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
1277 df.setLenient(false);
1278 return df.parse(date);
1279 }
1280
1281 static String getId(Object e) {
1282 if (e instanceof ImageryInfo) return ((ImageryInfo) e).getId();
1283 return ((Map<String, JsonObject>) e).get("properties").getString("id");
1284 }
1285
1286 static String getName(Object e) {
1287 if (e instanceof ImageryInfo) return ((ImageryInfo) e).getOriginalName();
1288 return ((Map<String, JsonObject>) e).get("properties").getString("name");
1289 }
1290
1291 static List<ImageryInfo> getMirrors(Object e) {
1292 if (e instanceof ImageryInfo) return ((ImageryInfo) e).getMirrors();
1293 return Collections.emptyList();
1294 }
1295
1296 static List<String> getProjections(Object e) {
1297 List<String> r = new ArrayList<>();
1298 List<String> u = getProjectionsUnstripped(e);
1299 if (u != null) {
1300 for (String p : u) {
1301 if (!oldproj.containsKey(p) && !("CRS:84".equals(p) && !(getUrlStripped(e).matches("(?i)version=1\\.3")))) {
1302 r.add(p);
1303 }
1304 }
1305 }
1306 return r;
1307 }
1308
1309 static List<String> getProjectionsUnstripped(Object e) {
1310 List<String> r = null;
1311 if (e instanceof ImageryInfo) {
1312 r = ((ImageryInfo) e).getServerProjections();
1313 } else {
1314 JsonValue s = ((Map<String, JsonObject>) e).get("properties").get("available_projections");
1315 if (s != null) {
1316 r = new ArrayList<>();
1317 for (JsonValue p : s.asJsonArray()) {
1318 r.add(((JsonString) p).getString());
1319 }
1320 }
1321 }
1322 return r != null ? r : Collections.emptyList();
1323 }
1324
1325 static List<Shape> getShapes(Object e) {
1326 if (e instanceof ImageryInfo) {
1327 ImageryBounds bounds = ((ImageryInfo) e).getBounds();
1328 if (bounds != null) {
1329 return bounds.getShapes();
1330 }
1331 return Collections.emptyList();
1332 }
1333 JsonValue ex = ((Map<String, JsonValue>) e).get("geometry");
1334 if (ex != null && !JsonValue.NULL.equals(ex) && !ex.asJsonObject().isNull("coordinates")) {
1335 JsonArray poly = ex.asJsonObject().getJsonArray("coordinates");
1336 List<Shape> l = new ArrayList<>();
1337 for (JsonValue shapes: poly) {
1338 Shape s = new Shape();
1339 for (JsonValue point: shapes.asJsonArray()) {
1340 String lon = point.asJsonArray().getJsonNumber(0).toString();
1341 String lat = point.asJsonArray().getJsonNumber(1).toString();
1342 s.addPoint(lat, lon);
1343 }
1344 l.add(s);
1345 }
1346 return l;
1347 }
1348 return Collections.emptyList();
1349 }
1350
1351 static String getType(Object e) {
1352 if (e instanceof ImageryInfo) return ((ImageryInfo) e).getImageryType().getTypeString();
1353 return ((Map<String, JsonObject>) e).get("properties").getString("type");
1354 }
1355
1356 static Integer getMinZoom(Object e) {
1357 if (e instanceof ImageryInfo) {
1358 int mz = ((ImageryInfo) e).getMinZoom();
1359 return mz == 0 ? null : mz;
1360 } else {
1361 JsonNumber num = ((Map<String, JsonObject>) e).get("properties").getJsonNumber("min_zoom");
1362 if (num == null) return null;
1363 return num.intValue();
1364 }
1365 }
1366
1367 static Integer getMaxZoom(Object e) {
1368 if (e instanceof ImageryInfo) {
1369 int mz = ((ImageryInfo) e).getMaxZoom();
1370 return mz == 0 ? null : mz;
1371 } else {
1372 JsonNumber num = ((Map<String, JsonObject>) e).get("properties").getJsonNumber("max_zoom");
1373 if (num == null) return null;
1374 return num.intValue();
1375 }
1376 }
1377
1378 static String getCountryCode(Object e) {
1379 if (e instanceof ImageryInfo) return "".equals(((ImageryInfo) e).getCountryCode()) ? null : ((ImageryInfo) e).getCountryCode();
1380 return ((Map<String, JsonObject>) e).get("properties").getString("country_code", null);
1381 }
1382
1383 static String getQuality(Object e) {
1384 if (e instanceof ImageryInfo) return ((ImageryInfo) e).isBestMarked() ? "eli-best" : null;
1385 return (((Map<String, JsonObject>) e).get("properties").containsKey("best")
1386 && ((Map<String, JsonObject>) e).get("properties").getBoolean("best")) ? "eli-best" : null;
1387 }
1388
1389 static boolean getOverlay(Object e) {
1390 if (e instanceof ImageryInfo) return ((ImageryInfo) e).isOverlay();
1391 return (((Map<String, JsonObject>) e).get("properties").containsKey("overlay")
1392 && ((Map<String, JsonObject>) e).get("properties").getBoolean("overlay"));
1393 }
1394
1395 static String getIcon(Object e) {
1396 if (e instanceof ImageryInfo) return ((ImageryInfo) e).getIcon();
1397 return ((Map<String, JsonObject>) e).get("properties").getString("icon", null);
1398 }
1399
1400 static String getAttributionText(Object e) {
1401 if (e instanceof ImageryInfo) return ((ImageryInfo) e).getAttributionText(0, null, null);
1402 try {
1403 return ((Map<String, JsonObject>) e).get("properties").getJsonObject("attribution").getString("text", null);
1404 } catch (NullPointerException ex) {
1405 return null;
1406 }
1407 }
1408
1409 static String getAttributionUrl(Object e) {
1410 if (e instanceof ImageryInfo) return ((ImageryInfo) e).getAttributionLinkURL();
1411 try {
1412 return ((Map<String, JsonObject>) e).get("properties").getJsonObject("attribution").getString("url", null);
1413 } catch (NullPointerException ex) {
1414 return null;
1415 }
1416 }
1417
1418 static String getTermsOfUseText(Object e) {
1419 if (e instanceof ImageryInfo) return ((ImageryInfo) e).getTermsOfUseText();
1420 return null;
1421 }
1422
1423 static String getTermsOfUseUrl(Object e) {
1424 if (e instanceof ImageryInfo) return ((ImageryInfo) e).getTermsOfUseURL();
1425 return null;
1426 }
1427
1428 static String getCategory(Object e) {
1429 if (e instanceof ImageryInfo) {
1430 return ((ImageryInfo) e).getImageryCategoryOriginalString();
1431 }
1432 return ((Map<String, JsonObject>) e).get("properties").getString("category", null);
1433 }
1434
1435 static String getLogoImage(Object e) {
1436 if (e instanceof ImageryInfo) return ((ImageryInfo) e).getAttributionImageRaw();
1437 return null;
1438 }
1439
1440 static String getLogoUrl(Object e) {
1441 if (e instanceof ImageryInfo) return ((ImageryInfo) e).getAttributionImageURL();
1442 return null;
1443 }
1444
1445 static String getPermissionReferenceUrl(Object e) {
1446 if (e instanceof ImageryInfo) return ((ImageryInfo) e).getPermissionReferenceURL();
1447 return ((Map<String, JsonObject>) e).get("properties").getString("license_url", null);
1448 }
1449
1450 static Map<String, Set<String>> getNoTileHeader(Object e) {
1451 if (e instanceof ImageryInfo) return ((ImageryInfo) e).getNoTileHeaders();
1452 JsonObject nth = ((Map<String, JsonObject>) e).get("properties").getJsonObject("no_tile_header");
1453 return nth == null ? null : nth.keySet().stream().collect(Collectors.toMap(
1454 Function.identity(),
1455 k -> nth.getJsonArray(k).stream().map(x -> ((JsonString) x).getString()).collect(Collectors.toSet())));
1456 }
1457
1458 static Map<String, String> getDescriptions(Object e) {
1459 Map<String, String> res = new HashMap<>();
1460 if (e instanceof ImageryInfo) {
1461 String a = ((ImageryInfo) e).getDescription();
1462 if (a != null) res.put("en", a);
1463 } else {
1464 String a = ((Map<String, JsonObject>) e).get("properties").getString("description", null);
1465 if (a != null) res.put("en", a.replaceAll("''", "'"));
1466 }
1467 return res;
1468 }
1469
1470 static boolean getValidGeoreference(Object e) {
1471 if (e instanceof ImageryInfo) return ((ImageryInfo) e).isGeoreferenceValid();
1472 return false;
1473 }
1474
1475 static boolean getDefault(Object e) {
1476 if (e instanceof ImageryInfo) return ((ImageryInfo) e).isDefaultEntry();
1477 return ((Map<String, JsonObject>) e).get("properties").getBoolean("default", false);
1478 }
1479
1480 String getDescription(Object o) {
1481 String url = getUrl(o);
1482 String cc = getCountryCode(o);
1483 if (cc == null) {
1484 ImageryInfo j = josmUrls.get(url);
1485 if (j != null) cc = getCountryCode(j);
1486 if (cc == null) {
1487 JsonObject e = eliUrls.get(url);
1488 if (e != null) cc = getCountryCode(e);
1489 }
1490 }
1491 if (cc == null) {
1492 cc = "";
1493 } else {
1494 cc = "["+cc+"] ";
1495 }
1496 String d = cc + getName(o) + " - " + getUrl(o);
1497 if (optionShorten) {
1498 if (d.length() > MAXLEN) d = d.substring(0, MAXLEN-1) + "...";
1499 }
1500 return d;
1501 }
1502}
Note: See TracBrowser for help on using the repository browser.