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

Last change on this file since 18211 was 18211, checked in by Don-vip, 3 years ago

global use of !Utils.isEmpty/isBlank

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