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

Last change on this file since 17328 was 17328, checked in by stoecker, 5 years ago

special handling for recent ELI WMS_URL switches

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