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

Last change on this file since 15850 was 15850, checked in by stoecker, 6 years ago

allow three dots at the end of a ignore line to skip ever changing URLs, use like 'http...' at the end of entry

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