source: josm/trunk/scripts/SyncEditorLayerIndex.groovy@ 11947

Last change on this file since 11947 was 11854, checked in by Don-vip, 8 years ago

sonar - grvy:org.codenarc.rule.naming.ClassNameSameAsFilenameRule - Class Name Same As Filename

  • Property svn:eol-style set to native
File size: 23.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2/**
3 * Compare and analyse the differences of the editor layer index and the JOSM imagery list.
4 * The goal is to keep both lists in sync.
5 *
6 * The editor layer index project (https://github.com/osmlab/editor-layer-index)
7 * provides also a version in the JOSM format, but the GEOJSON is the original source
8 * format, so we read that.
9 *
10 * How to run:
11 * -----------
12 *
13 * Main JOSM binary needs to be in classpath, e.g.
14 *
15 * $ groovy -cp ../dist/josm-custom.jar SyncEditorLayerIndex.groovy
16 *
17 * Add option "-h" to show the available command line flags.
18 */
19import javax.json.Json
20import javax.json.JsonArray
21import javax.json.JsonObject
22import javax.json.JsonReader
23
24import org.openstreetmap.josm.data.imagery.ImageryInfo
25import org.openstreetmap.josm.data.imagery.Shape
26import org.openstreetmap.josm.io.imagery.ImageryReader
27
28class SyncEditorLayerIndex {
29
30 List<ImageryInfo> josmEntries;
31 JsonArray eliEntries;
32
33 def eliUrls = new HashMap<String, JsonObject>()
34 def josmUrls = new HashMap<String, ImageryInfo>()
35 def josmMirrors = new HashMap<String, ImageryInfo>()
36
37 static String eliInputFile = 'imagery.geojson'
38 static String josmInputFile = 'maps.xml'
39 static String ignoreInputFile = 'maps_ignores.txt'
40 static FileWriter outputFile = null
41 static BufferedWriter outputStream = null
42 def skip = [:]
43
44 static def options
45
46 /**
47 * Main method.
48 */
49 static main(def args) {
50 parse_command_line_arguments(args)
51 def script = new SyncEditorLayerIndex()
52 script.loadSkip()
53 script.start()
54 script.loadJosmEntries()
55 script.loadELIEntries()
56 script.checkInOneButNotTheOther()
57 script.checkCommonEntries()
58 script.end()
59 if(outputStream != null) {
60 outputStream.close();
61 }
62 if(outputFile != null) {
63 outputFile.close();
64 }
65 }
66
67 /**
68 * Parse command line arguments.
69 */
70 static void parse_command_line_arguments(args) {
71 def cli = new CliBuilder(width: 160)
72 cli.o(longOpt:'output', args:1, argName: "output", "Output file, - prints to stdout (default: -)")
73 cli.e(longOpt:'eli_input', args:1, argName:"eli_input", "Input file for the editor layer index (geojson). Default is $eliInputFile (current directory).")
74 cli.j(longOpt:'josm_input', args:1, argName:"josm_input", "Input file for the JOSM imagery list (xml). Default is $josmInputFile (current directory).")
75 cli.i(longOpt:'ignore_input', args:1, argName:"ignore_input", "Input file for the ignore list. Default is $ignoreInputFile (current directory).")
76 cli.s(longOpt:'shorten', "shorten the output, so it is easier to read in a console window")
77 cli.n(longOpt:'noskip', argName:"noskip", "don't skip known entries")
78 cli.x(longOpt:'xhtmlbody', argName:"xhtmlbody", "create XHTML body for display in a web page")
79 cli.X(longOpt:'xhtml', argName:"xhtml", "create XHTML for display in a web page")
80 cli.m(longOpt:'nomissingeli', argName:"nomissingeli", "don't show missing editor layer index entries")
81 cli.h(longOpt:'help', "show this help")
82 options = cli.parse(args)
83
84 if (options.h) {
85 cli.usage()
86 System.exit(0)
87 }
88 if (options.eli_input) {
89 eliInputFile = options.eli_input
90 }
91 if (options.josm_input) {
92 josmInputFile = options.josm_input
93 }
94 if (options.ignore_input) {
95 ignoreInputFile = options.ignore_input
96 }
97 if (options.output && options.output != "-") {
98 outputFile = new FileWriter(options.output)
99 outputStream = new BufferedWriter(outputFile)
100 }
101 }
102
103 void loadSkip() {
104 FileReader fr = new FileReader(ignoreInputFile)
105 def line
106
107 while((line = fr.readLine()) != null) {
108 def res = (line =~ /^\|\| *(ELI|Ignore) *\|\| *\{\{\{(.+)\}\}\} *\|\|/)
109 if(res.count)
110 {
111 if(res[0][1].equals("Ignore")) {
112 skip[res[0][2]] = "green"
113 } else {
114 skip[res[0][2]] = "darkgoldenrod"
115 }
116 }
117 }
118 }
119
120 void myprintlnfinal(String s) {
121 if(outputStream != null) {
122 outputStream.write(s);
123 outputStream.newLine();
124 } else {
125 println s;
126 }
127 }
128
129 void myprintln(String s) {
130 if(skip.containsKey(s)) {
131 String color = skip.get(s)
132 skip.remove(s)
133 if(options.xhtmlbody || options.xhtml) {
134 s = "<pre style=\"margin:3px;color:"+color+"\">"+s.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")+"</pre>"
135 }
136 if (!options.noskip) {
137 return;
138 }
139 } else if(options.xhtmlbody || options.xhtml) {
140 String color = s.startsWith("***") ? "black" : ((s.startsWith("+ ") || s.startsWith("+++ ELI")) ? "blue" : "red")
141 s = "<pre style=\"margin:3px;color:"+color+"\">"+s.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")+"</pre>"
142 }
143 myprintlnfinal(s)
144 }
145
146 void start() {
147 if (options.xhtml) {
148 myprintlnfinal "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"
149 myprintlnfinal "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/><title>JOSM - ELI differences</title></head><body>\n"
150 }
151 }
152
153 void end() {
154 for (def s: skip.keySet()) {
155 myprintln "+++ Obsolete skip entry: " + s
156 }
157 if (options.xhtml) {
158 myprintlnfinal "</body></html>\n"
159 }
160 }
161
162 void loadELIEntries() {
163 FileReader fr = new FileReader(eliInputFile)
164 JsonReader jr = Json.createReader(fr)
165 eliEntries = jr.readObject().get("features")
166 jr.close()
167
168 for (def e : eliEntries) {
169 def url = getUrl(e)
170 if (url.contains("{z}")) {
171 myprintln "+++ ELI-URL uses {z} instead of {zoom}: "+url
172 url = url.replace("{z}","{zoom}")
173 }
174 if (eliUrls.containsKey(url)) {
175 myprintln "+++ ELI-URL is not unique: "+url
176 } else {
177 eliUrls.put(url, e)
178 }
179 }
180 myprintln "*** Loaded ${eliEntries.size()} entries (ELI). ***"
181 }
182
183 void loadJosmEntries() {
184 def reader = new ImageryReader(josmInputFile)
185 josmEntries = reader.parse()
186
187 for (def e : josmEntries) {
188 def url = getUrl(e)
189 if (url.contains("{z}")) {
190 myprintln "+++ JOSM-URL uses {z} instead of {zoom}: "+url
191 url = url.replace("{z}","{zoom}")
192 }
193 if (josmUrls.containsKey(url)) {
194 myprintln "+++ JOSM-URL is not unique: "+url
195 } else {
196 josmUrls.put(url, e)
197 }
198 for (def m : e.getMirrors()) {
199 url = getUrl(m)
200 m.origName = m.getOriginalName().replaceAll(" mirror server( \\d+)?","")
201 if (josmUrls.containsKey(url)) {
202 myprintln "+++ JOSM-Mirror-URL is not unique: "+url
203 } else {
204 josmUrls.put(url, m)
205 josmMirrors.put(url, m)
206 }
207 }
208 }
209 myprintln "*** Loaded ${josmEntries.size()} entries (JOSM). ***"
210 }
211
212 List inOneButNotTheOther(Map m1, Map m2) {
213 def l = []
214 for (def url : m1.keySet()) {
215 if (!m2.containsKey(url)) {
216 def name = getName(m1.get(url))
217 l += " "+getDescription(m1.get(url))
218 }
219 }
220 l.sort()
221 }
222
223 void checkInOneButNotTheOther() {
224 def l1 = inOneButNotTheOther(eliUrls, josmUrls)
225 myprintln "*** URLs found in ELI but not in JOSM (${l1.size()}): ***"
226 if (!l1.isEmpty()) {
227 for (def l : l1) {
228 myprintln "-" + l
229 }
230 }
231
232 if (options.nomissingeli)
233 return
234 def l2 = inOneButNotTheOther(josmUrls, eliUrls)
235 myprintln "*** URLs found in JOSM but not in ELI (${l2.size()}): ***"
236 if (!l2.isEmpty()) {
237 for (def l : l2) {
238 myprintln "+" + l
239 }
240 }
241 }
242
243 void checkCommonEntries() {
244 myprintln "*** Same URL, but different name: ***"
245 for (def url : eliUrls.keySet()) {
246 def e = eliUrls.get(url)
247 if (!josmUrls.containsKey(url)) continue
248 def j = josmUrls.get(url)
249 if (!getName(e).equals(getName(j))) {
250 myprintln "* Name differs ('${getName(e)}' != '${getName(j)}'): $url"
251 }
252 }
253
254 myprintln "*** Same URL, but different type: ***"
255 for (def url : eliUrls.keySet()) {
256 def e = eliUrls.get(url)
257 if (!josmUrls.containsKey(url)) continue
258 def j = josmUrls.get(url)
259 if (!getType(e).equals(getType(j))) {
260 myprintln "* Type differs (${getType(e)} != ${getType(j)}): ${getName(j)} - $url"
261 }
262 }
263
264 myprintln "*** Same URL, but different zoom bounds: ***"
265 for (def url : eliUrls.keySet()) {
266 def e = eliUrls.get(url)
267 if (!josmUrls.containsKey(url)) continue
268 def j = josmUrls.get(url)
269
270 Integer eMinZoom = getMinZoom(e)
271 Integer jMinZoom = getMinZoom(j)
272 if (eMinZoom != jMinZoom && !(eMinZoom == 0 && jMinZoom == null)) {
273 myprintln "* Minzoom differs (${eMinZoom} != ${jMinZoom}): ${getDescription(j)}"
274 }
275 Integer eMaxZoom = getMaxZoom(e)
276 Integer jMaxZoom = getMaxZoom(j)
277 if (eMaxZoom != jMaxZoom) {
278 myprintln "* Maxzoom differs (${eMaxZoom} != ${jMaxZoom}): ${getDescription(j)}"
279 }
280 }
281
282 myprintln "*** Same URL, but different country code: ***"
283 for (def url : eliUrls.keySet()) {
284 def e = eliUrls.get(url)
285 if (!josmUrls.containsKey(url)) continue
286 def j = josmUrls.get(url)
287 if (!getCountryCode(e).equals(getCountryCode(j))) {
288 myprintln "* Country code differs (${getCountryCode(e)} != ${getCountryCode(j)}): ${getDescription(j)}"
289 }
290 }
291 myprintln "*** Same URL, but different quality: ***"
292 for (def url : eliUrls.keySet()) {
293 def e = eliUrls.get(url)
294 if (!josmUrls.containsKey(url)) {
295 def q = getQuality(e)
296 if("eli-best".equals(q)) {
297 myprintln "- Quality best entry not in JOSM for ${getDescription(e)}"
298 }
299 continue
300 }
301 def j = josmUrls.get(url)
302 if (!getQuality(e).equals(getQuality(j))) {
303 myprintln "* Quality differs (${getQuality(e)} != ${getQuality(j)}): ${getDescription(j)}"
304 }
305 }
306 myprintln "*** Same URL, but different dates: ***"
307 for (def url : eliUrls.keySet()) {
308 def ed = getDate(eliUrls.get(url))
309 if (!josmUrls.containsKey(url)) continue
310 def j = josmUrls.get(url)
311 def jd = getDate(j)
312 // The forms 2015;- or -;2015 or 2015;2015 are handled equal to 2015
313 String ef = ed.replaceAll("\\A-;","").replaceAll(";-\\z","").replaceAll("\\A([0-9-]+);\\1\\z","\$1");
314 // ELI has a strange and inconsistent used end_date definition, so we try again with subtraction by one
315 String ed2 = ed;
316 def reg = (ed =~ /^(.*;)(\d\d\d\d)(-(\d\d)(-(\d\d))?)?$/)
317 if(reg != null && reg.count == 1) {
318 Calendar cal = Calendar.getInstance();
319 cal.set(reg[0][2] as Integer, reg[0][4] == null ? 0 : (reg[0][4] as Integer)-1, reg[0][6] == null ? 1 : reg[0][6] as Integer)
320 cal.add(Calendar.DAY_OF_MONTH, -1)
321 ed2 = reg[0][1] + cal.get(Calendar.YEAR)
322 if (reg[0][4] != null)
323 ed2 += "-" + String.format("%02d", cal.get(Calendar.MONTH)+1)
324 if (reg[0][6] != null)
325 ed2 += "-" + String.format("%02d", cal.get(Calendar.DAY_OF_MONTH))
326 }
327 String ef2 = ed2.replaceAll("\\A-;","").replaceAll(";-\\z","").replaceAll("\\A([0-9-]+);\\1\\z","\$1");
328 if (!ed.equals(jd) && !ef.equals(jd) && !ed2.equals(jd) && !ef2.equals(jd)) {
329 String t = "'${ed}'";
330 if (!ed.equals(ef)) {
331 t += " or '${ef}'";
332 }
333 if (jd.isEmpty()) {
334 myprintln "- Missing JOSM date (${t}): ${getDescription(j)}"
335 } else if (!ed.isEmpty()) {
336 myprintln "* Date differs (${t} != '${jd}'): ${getDescription(j)}"
337 } else if (!options.nomissingeli) {
338 myprintln "+ Missing ELI date ('${jd}'): ${getDescription(j)}"
339 }
340 }
341 }
342 myprintln "*** Mismatching shapes: ***"
343 for (def url : josmUrls.keySet()) {
344 def j = josmUrls.get(url)
345 def num = 1
346 for (def shape : getShapes(j)) {
347 def p = shape.getPoints()
348 if(!p[0].equals(p[p.size()-1])) {
349 myprintln "+++ JOSM shape $num unclosed: ${getDescription(j)}"
350 }
351 ++num
352 }
353 }
354 for (def url : eliUrls.keySet()) {
355 def e = eliUrls.get(url)
356 def num = 1
357 def s = getShapes(e)
358 for (def shape : s) {
359 def p = shape.getPoints()
360 if(!p[0].equals(p[p.size()-1]) && !options.nomissingeli) {
361 myprintln "+++ ELI shape $num unclosed: ${getDescription(e)}"
362 }
363 ++num
364 }
365 if (!josmUrls.containsKey(url)) {
366 continue
367 }
368 def j = josmUrls.get(url)
369 def js = getShapes(j)
370 if(!s.size() && js.size()) {
371 if(!options.nomissingeli) {
372 myprintln "+ No ELI shape: ${getDescription(j)}"
373 }
374 } else if(!js.size() && s.size()) {
375 // don't report boundary like 5 point shapes as difference
376 if (s.size() != 1 || s[0].getPoints().size() != 5) {
377 myprintln "- No JOSM shape: ${getDescription(j)}"
378 }
379 } else if(s.size() != js.size()) {
380 myprintln "* Different number of shapes (${s.size()} != ${js.size()}): ${getDescription(j)}"
381 } else {
382 for(def nums = 0; nums < s.size(); ++nums) {
383 def ep = s[nums].getPoints()
384 def jp = js[nums].getPoints()
385 if(ep.size() != jp.size()) {
386 myprintln "* Different number of points for shape ${nums+1} (${ep.size()} ! = ${jp.size()})): ${getDescription(j)}"
387 } else {
388 for(def nump = 0; nump < ep.size(); ++nump) {
389 def ept = ep[nump]
390 def jpt = jp[nump]
391 if(Math.abs(ept.getLat()-jpt.getLat()) > 0.000001 || Math.abs(ept.getLon()-jpt.getLon()) > 0.000001) {
392 myprintln "* Different coordinate for point ${nump+1} of shape ${nums+1}: ${getDescription(j)}"
393 nump = ep.size()
394 num = s.size()
395 }
396 }
397 }
398 }
399 }
400 }
401 myprintln "*** Mismatching icons: ***"
402 for (def url : eliUrls.keySet()) {
403 def e = eliUrls.get(url)
404 if (!josmUrls.containsKey(url)) {
405 continue
406 }
407 def j = josmUrls.get(url)
408 def ij = getIcon(j)
409 def ie = getIcon(e)
410 if(ij != null && ie == null) {
411 if(!options.nomissingeli) {
412 myprintln "+ No ELI icon: ${getDescription(j)}"
413 }
414 } else if(ij == null && ie != null) {
415 myprintln "- No JOSM icon: ${getDescription(j)}"
416 } else if(!ij.equals(ie)) {
417 myprintln "* Different icons: ${getDescription(j)}"
418 }
419 }
420 myprintln "*** Miscellaneous checks: ***"
421 def josmIds = new HashMap<String, ImageryInfo>()
422 for (def url : josmUrls.keySet()) {
423 def j = josmUrls.get(url)
424 def id = getId(j)
425 if(josmMirrors.containsKey(url)) {
426 continue;
427 }
428 if(id == null) {
429 myprintln "* No JOSM-ID: ${getDescription(j)}"
430 } else if(josmIds.containsKey(id)) {
431 myprintln "* JOSM-ID ${id} not unique: ${getDescription(j)}"
432 } else {
433 josmIds.put(id, j);
434 }
435 def d = getDate(j)
436 if(!d.isEmpty()) {
437 def reg = (d =~ /^(-|(\d\d\d\d)(-(\d\d)(-(\d\d))?)?)(;(-|(\d\d\d\d)(-(\d\d)(-(\d\d))?)?))?$/)
438 if(reg == null || reg.count != 1) {
439 myprintln "* JOSM-Date '${d}' is strange: ${getDescription(j)}"
440 } else {
441 try {
442 def first = verifyDate(reg[0][2],reg[0][4],reg[0][6]);
443 def second = verifyDate(reg[0][9],reg[0][11],reg[0][13]);
444 if(second.compareTo(first) < 0) {
445 myprintln "* JOSM-Date '${d}' is strange (second earlier than first): ${getDescription(j)}"
446 }
447 }
448 catch (Exception e) {
449 myprintln "* JOSM-Date '${d}' is strange (${e.getMessage()}): ${getDescription(j)}"
450 }
451 }
452 }
453 def js = getShapes(j)
454 if(js.size()) {
455 def minlat = 1000;
456 def minlon = 1000;
457 def maxlat = -1000;
458 def maxlon = -1000;
459 for(def s: js) {
460 for(def p: s.getPoints()) {
461 def lat = p.getLat();
462 def lon = p.getLon();
463 if(lat > maxlat) maxlat = lat;
464 if(lon > maxlon) maxlon = lon;
465 if(lat < minlat) minlat = lat;
466 if(lon < minlon) minlon = lon;
467 }
468 }
469 def b = j.getBounds();
470 if(b.getMinLat() != minlat || b.getMinLon() != minlon || b.getMaxLat() != maxlat || b.getMaxLon() != maxlon) {
471 myprintln "* Bounds do not match shape (is ${b.getMinLat()},${b.getMinLon()},${b.getMaxLat()},${b.getMaxLon()}, calculated <bounds min-lat='${minlat}' min-lon='${minlon}' max-lat='${maxlat}' max-lon='${maxlon}'>): ${getDescription(j)}"
472 }
473 }
474 }
475 }
476
477 /**
478 * Utility functions that allow uniform access for both ImageryInfo and JsonObject.
479 */
480 static String getUrl(Object e) {
481 if (e instanceof ImageryInfo) return e.url
482 return e.get("properties").getString("url")
483 }
484 static String getDate(Object e) {
485 if (e instanceof ImageryInfo) return e.date ? e.date : ""
486 def p = e.get("properties")
487 def start = p.containsKey("start_date") ? p.getString("start_date") : ""
488 def end = p.containsKey("end_date") ? p.getString("end_date") : ""
489 if(!start.isEmpty() && !end.isEmpty())
490 return start+";"+end
491 else if(!start.isEmpty())
492 return start+";-"
493 else if(!end.isEmpty())
494 return "-;"+end
495 return "";
496 }
497 static Date verifyDate(String year, String month, String day) {
498 def date
499 if(year == null) {
500 date = "3000-01-01"
501 } else {
502 date = year + "-" + (month == null ? "01" : month) + "-" + (day == null ? "01" : day)
503 }
504 def df = new java.text.SimpleDateFormat("yyyy-MM-dd")
505 df.setLenient(false)
506 return df.parse(date)
507 }
508 static String getId(Object e) {
509 if (e instanceof ImageryInfo) return e.getId()
510 return e.get("properties").getString("id")
511 }
512 static String getName(Object e) {
513 if (e instanceof ImageryInfo) return e.getOriginalName()
514 return e.get("properties").getString("name")
515 }
516 static List<Shape> getShapes(Object e) {
517 if (e instanceof ImageryInfo) {
518 def bounds = e.getBounds();
519 if(bounds != null) {
520 return bounds.getShapes();
521 }
522 return []
523 }
524 if(!e.isNull("geometry")) {
525 def ex = e.get("geometry")
526 if(ex != null && !ex.isNull("coordinates")) {
527 def poly = ex.get("coordinates")
528 List<Shape> l = []
529 for(def shapes: poly) {
530 def s = new Shape()
531 for(def point: shapes) {
532 def lon = point[0].toString()
533 def lat = point[1].toString()
534 s.addPoint(lat, lon)
535 }
536 l.add(s)
537 }
538 return l
539 }
540 }
541 return []
542 }
543 static String getType(Object e) {
544 if (e instanceof ImageryInfo) return e.getImageryType().getTypeString()
545 return e.get("properties").getString("type")
546 }
547 static Integer getMinZoom(Object e) {
548 if (e instanceof ImageryInfo) {
549 int mz = e.getMinZoom()
550 return mz == 0 ? null : mz
551 } else {
552 def num = e.get("properties").getJsonNumber("min_zoom")
553 if (num == null) return null
554 return num.intValue()
555 }
556 }
557 static Integer getMaxZoom(Object e) {
558 if (e instanceof ImageryInfo) {
559 int mz = e.getMaxZoom()
560 return mz == 0 ? null : mz
561 } else {
562 def num = e.get("properties").getJsonNumber("max_zoom")
563 if (num == null) return null
564 return num.intValue()
565 }
566 }
567 static String getCountryCode(Object e) {
568 if (e instanceof ImageryInfo) return "".equals(e.getCountryCode()) ? null : e.getCountryCode()
569 return e.get("properties").getString("country_code", null)
570 }
571 static String getQuality(Object e) {
572 if (e instanceof ImageryInfo) return e.isBestMarked() ? "eli-best" : null
573 return (e.get("properties").containsKey("best")
574 && e.get("properties").getBoolean("best")) ? "eli-best" : null
575 }
576 static String getIcon(Object e) {
577 if (e instanceof ImageryInfo) return e.getIcon()
578 return e.get("properties").getString("icon", null)
579 }
580 String getDescription(Object o) {
581 def url = getUrl(o)
582 def cc = getCountryCode(o)
583 if (cc == null) {
584 def j = josmUrls.get(url)
585 if (j != null) cc = getCountryCode(j)
586 if (cc == null) {
587 def e = eliUrls.get(url)
588 if (e != null) cc = getCountryCode(e)
589 }
590 }
591 if (cc == null) {
592 cc = ''
593 } else {
594 cc = "[$cc] "
595 }
596 def d = cc + getName(o) + " - " + getUrl(o)
597 if (options.shorten) {
598 def MAXLEN = 140
599 if (d.length() > MAXLEN) d = d.substring(0, MAXLEN-1) + "..."
600 }
601 return d
602 }
603}
Note: See TracBrowser for help on using the repository browser.