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

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

see #14655 - remove channels workaround

  • Property svn:eol-style set to native
File size: 34.7 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 java.text.DecimalFormat
20import javax.json.Json
21import javax.json.JsonArray
22import javax.json.JsonObject
23import javax.json.JsonReader
24
25import org.openstreetmap.josm.data.imagery.ImageryInfo
26import org.openstreetmap.josm.data.imagery.Shape
27import org.openstreetmap.josm.io.imagery.ImageryReader
28
29class SyncEditorLayerIndex {
30
31    List<ImageryInfo> josmEntries;
32    JsonArray eliEntries;
33
34    def eliUrls = new HashMap<String, JsonObject>()
35    def josmUrls = new HashMap<String, ImageryInfo>()
36    def josmMirrors = new HashMap<String, ImageryInfo>()
37
38    static String eliInputFile = 'imagery_eli.geojson'
39    static String josmInputFile = 'imagery_josm.imagery.xml'
40    static String ignoreInputFile = 'imagery_josm.ignores.txt'
41    static FileOutputStream outputFile = null
42    static OutputStreamWriter outputStream = null
43    def skip = [:]
44
45    static def options
46
47    /**
48     * Main method.
49     */
50    static main(def args) {
51        Locale.setDefault(Locale.ROOT);
52        parse_command_line_arguments(args)
53        def script = new SyncEditorLayerIndex()
54        script.loadSkip()
55        script.start()
56        script.loadJosmEntries()
57        if(options.josmxml) {
58            def file = new FileOutputStream(options.josmxml)
59            def stream = new OutputStreamWriter(file, "UTF-8")
60            script.printentries(script.josmEntries, stream)
61            stream.close();
62            file.close();
63        }
64        script.loadELIEntries()
65        if(options.elixml) {
66            def file = new FileOutputStream(options.elixml)
67            def stream = new OutputStreamWriter(file, "UTF-8")
68            script.printentries(script.eliEntries, stream)
69            stream.close();
70            file.close();
71        }
72        script.checkInOneButNotTheOther()
73        script.checkCommonEntries()
74        script.end()
75        if(outputStream != null) {
76            outputStream.close();
77        }
78        if(outputFile != null) {
79            outputFile.close();
80        }
81    }
82
83    /**
84     * Parse command line arguments.
85     */
86    static void parse_command_line_arguments(args) {
87        def cli = new CliBuilder(width: 160)
88        cli.o(longOpt:'output', args:1, argName: "output", "Output file, - prints to stdout (default: -)")
89        cli.e(longOpt:'eli_input', args:1, argName:"eli_input", "Input file for the editor layer index (geojson). Default is $eliInputFile (current directory).")
90        cli.j(longOpt:'josm_input', args:1, argName:"josm_input", "Input file for the JOSM imagery list (xml). Default is $josmInputFile (current directory).")
91        cli.i(longOpt:'ignore_input', args:1, argName:"ignore_input", "Input file for the ignore list. Default is $ignoreInputFile (current directory).")
92        cli.s(longOpt:'shorten', "shorten the output, so it is easier to read in a console window")
93        cli.n(longOpt:'noskip', argName:"noskip", "don't skip known entries")
94        cli.x(longOpt:'xhtmlbody', argName:"xhtmlbody", "create XHTML body for display in a web page")
95        cli.X(longOpt:'xhtml', argName:"xhtml", "create XHTML for display in a web page")
96        cli.p(longOpt:'elixml', args:1, argName:"elixml", "ELI entries for use in JOSM as XML file (incomplete)")
97        cli.q(longOpt:'josmxml', args:1, argName:"josmxml", "JOSM entries reoutput as XML file (incomplete)")
98        cli.m(longOpt:'noeli', argName:"noeli", "don't show output for ELI problems")
99        cli.h(longOpt:'help', "show this help")
100        options = cli.parse(args)
101
102        if (options.h) {
103            cli.usage()
104            System.exit(0)
105        }
106        if (options.eli_input) {
107            eliInputFile = options.eli_input
108        }
109        if (options.josm_input) {
110            josmInputFile = options.josm_input
111        }
112        if (options.ignore_input) {
113            ignoreInputFile = options.ignore_input
114        }
115        if (options.output && options.output != "-") {
116            outputFile = new FileOutputStream(options.output)
117            outputStream = new OutputStreamWriter(outputFile, "UTF-8")
118        }
119    }
120
121    void loadSkip() {
122        def fr = new InputStreamReader(new FileInputStream(ignoreInputFile), "UTF-8")
123        def line
124
125        while((line = fr.readLine()) != null) {
126            def res = (line =~ /^\|\| *(ELI|Ignore) *\|\| *\{\{\{(.+)\}\}\} *\|\|/)
127            if(res.count)
128            {
129                if(res[0][1].equals("Ignore")) {
130                    skip[res[0][2]] = "green"
131                } else {
132                    skip[res[0][2]] = "darkgoldenrod"
133                }
134            }
135        }
136    }
137
138    void myprintlnfinal(String s) {
139        if(outputStream != null) {
140            outputStream.write(s+System.getProperty("line.separator"))
141        } else {
142            println s
143        }
144    }
145
146    void myprintln(String s) {
147        if(skip.containsKey(s)) {
148            String color = skip.get(s)
149            skip.remove(s)
150            if(options.xhtmlbody || options.xhtml) {
151                s = "<pre style=\"margin:3px;color:"+color+"\">"+s.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")+"</pre>"
152            }
153            if (!options.noskip) {
154                return
155            }
156        } else if(options.xhtmlbody || options.xhtml) {
157            String color = s.startsWith("***") ? "black" : ((s.startsWith("+ ") || s.startsWith("+++ ELI")) ? "blue" : "red")
158            s = "<pre style=\"margin:3px;color:"+color+"\">"+s.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")+"</pre>"
159        }
160        if ((s.startsWith("+ ") || s.startsWith("+++ ELI")) && options.noeli) {
161            return
162        }
163        myprintlnfinal(s)
164    }
165
166    void start() {
167        if (options.xhtml) {
168            myprintlnfinal "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"
169            myprintlnfinal "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/><title>JOSM - ELI differences</title></head><body>\n"
170        }
171    }
172
173    void end() {
174        for (def s: skip.keySet()) {
175            myprintln "+++ Obsolete skip entry: " + s
176        }
177        if (options.xhtml) {
178            myprintlnfinal "</body></html>\n"
179        }
180    }
181
182    void loadELIEntries() {
183        FileReader fr = new FileReader(eliInputFile)
184        JsonReader jr = Json.createReader(fr)
185        eliEntries = jr.readObject().get("features")
186        jr.close()
187
188        for (def e : eliEntries) {
189            def url = getUrl(e)
190            if (url.contains("{z}")) {
191                myprintln "+++ ELI-URL uses {z} instead of {zoom}: "+url
192                url = url.replace("{z}","{zoom}")
193            }
194            if (eliUrls.containsKey(url)) {
195                myprintln "+++ ELI-URL is not unique: "+url
196            } else {
197                eliUrls.put(url, e)
198            }
199        }
200        myprintln "*** Loaded ${eliEntries.size()} entries (ELI). ***"
201    }
202    String cdata(def s, boolean escape = false) {
203        if(escape) {
204            return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
205        } else if(s =~ /[<>&]/)
206            return "<![CDATA[$s]]>"
207       return s
208    }
209
210    String maininfo(def entry, String offset) {
211        String t = getType(entry)
212        String res = offset + "<type>$t</type>\n"
213        res += offset + "<url>${cdata(getUrl(entry))}</url>\n"
214        if(t == "tms") {
215            if(getMinZoom(entry) != null)
216                res += offset + "<min-zoom>${getMinZoom(entry)}</min-zoom>\n"
217            if(getMaxZoom(entry) != null)
218                res += offset + "<max-zoom>${getMaxZoom(entry)}</max-zoom>\n"
219        } else if (t == "wms") {
220            def p = getProjections(entry)
221            if (p) {
222                res += offset + "<projections>\n"
223                for (def c : p)
224                    res += offset + "    <code>$c</code>\n"
225                res += offset + "</projections>\n"
226            }
227        }
228        return res
229    }
230
231    void printentries(def entries, def stream) {
232        DecimalFormat df = new DecimalFormat("#.#######")
233        df.setRoundingMode(java.math.RoundingMode.CEILING)
234        stream.write "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
235        stream.write "<imagery xmlns=\"http://josm.openstreetmap.de/maps-1.0\">\n"
236        for (def e : entries) {
237            def best = "eli-best".equals(getQuality(e))
238            stream.write "    <entry"+(best ? " eli-best=\"true\"" : "" )+">\n"
239            stream.write "        <name>${cdata(getName(e), true)}</name>\n"
240            stream.write "        <id>${getId(e)}</id>\n"
241            def t
242            if((t = getDate(e)))
243                stream.write "        <date>$t</date>\n"
244            if((t = getCountryCode(e)))
245                stream.write "        <country-code>$t</country-code>\n"
246            stream.write maininfo(e, "        ")
247            if((t = getAttributionText(e)))
248                stream.write "        <attribution-text mandatory=\"true\">${cdata(t, true)}</attribution-text>\n"
249            if((t = getAttributionUrl(e)))
250                stream.write "        <attribution-url>${cdata(t)}</attribution-url>\n"
251            if((t = getTermsOfUseText(e)))
252                stream.write "        <terms-of-use-text>${cdata(t, true)}</terms-of-use-text>\n"
253            if((t = getTermsOfUseUrl(e)))
254                stream.write "        <terms-of-use-url>${cdata(t)}</terms-of-use-url>\n"
255            if((t = getPermissionReferenceUrl(e)))
256                stream.write "        <permission-ref>${cdata(t)}</permission-ref>\n"
257            if((getValidGeoreference(e)))
258                stream.write "        <valid-georeference>true</valid-georeference>\n"
259            if((t = getIcon(e)))
260                stream.write "        <icon>${cdata(t)}</icon>\n"
261            for (def d : getDescriptions(e)) {
262                    stream.write "        <description lang=\"${d.getKey()}\">${d.getValue()}</description>\n"
263            }
264            for (def m : getMirrors(e)) {
265                    stream.write "        <mirror>\n"+maininfo(m, "            ")+"        </mirror>\n"
266            }
267            def minlat = 1000
268            def minlon = 1000
269            def maxlat = -1000
270            def maxlon = -1000
271            def shapes = ""
272            def sep = "\n            "
273            for(def s: getShapes(e)) {
274                shapes += "            <shape>"
275                def i = 0
276                for(def p: s.getPoints()) {
277                    def lat = p.getLat()
278                    def lon = p.getLon()
279                    if(lat > maxlat) maxlat = lat
280                    if(lon > maxlon) maxlon = lon
281                    if(lat < minlat) minlat = lat
282                    if(lon < minlon) minlon = lon
283                    if(!(i++%3)) {
284                        shapes += sep + "    "
285                    }
286                    shapes += "<point lat='${df.format(lat)}' lon='${df.format(lon)}'/>"
287                }
288                shapes += sep + "</shape>\n"
289            }
290            if(shapes) {
291                stream.write "        <bounds min-lat='${df.format(minlat)}' min-lon='${df.format(minlon)}' max-lat='${df.format(maxlat)}' max-lon='${df.format(maxlon)}'>\n"
292                stream.write shapes + "        </bounds>\n"
293            }
294            stream.write "    </entry>\n"
295        }
296        stream.write "</imagery>\n"
297        stream.close()
298    }
299
300    void loadJosmEntries() {
301        def reader = new ImageryReader(josmInputFile)
302        josmEntries = reader.parse()
303
304        for (def e : josmEntries) {
305            def url = getUrl(e)
306            if (url.contains("{z}")) {
307                myprintln "+++ JOSM-URL uses {z} instead of {zoom}: "+url
308                url = url.replace("{z}","{zoom}")
309            }
310            if (josmUrls.containsKey(url)) {
311                myprintln "+++ JOSM-URL is not unique: "+url
312            } else {
313                josmUrls.put(url, e)
314            }
315            for (def m : e.getMirrors()) {
316                url = getUrl(m)
317                m.origName = m.getOriginalName().replaceAll(" mirror server( \\d+)?","")
318                if (josmUrls.containsKey(url)) {
319                    myprintln "+++ JOSM-Mirror-URL is not unique: "+url
320                } else {
321                    josmUrls.put(url, m)
322                    josmMirrors.put(url, m)
323                }
324            }
325        }
326        myprintln "*** Loaded ${josmEntries.size()} entries (JOSM). ***"
327    }
328
329    List inOneButNotTheOther(Map m1, Map m2) {
330        def l = []
331        for (def url : m1.keySet()) {
332            if (!m2.containsKey(url)) {
333                def name = getName(m1.get(url))
334                l += "  "+getDescription(m1.get(url))
335            }
336        }
337        l.sort()
338    }
339
340    void checkInOneButNotTheOther() {
341        def l1 = inOneButNotTheOther(eliUrls, josmUrls)
342        myprintln "*** URLs found in ELI but not in JOSM (${l1.size()}): ***"
343        if (!l1.isEmpty()) {
344            for (def l : l1) {
345                myprintln "-" + l
346            }
347        }
348
349        def l2 = inOneButNotTheOther(josmUrls, eliUrls)
350        myprintln "*** URLs found in JOSM but not in ELI (${l2.size()}): ***"
351        if (!l2.isEmpty()) {
352            for (def l : l2) {
353                myprintln "+" + l
354            }
355        }
356    }
357
358    void checkCommonEntries() {
359        myprintln "*** Same URL, but different name: ***"
360        for (def url : eliUrls.keySet()) {
361            def e = eliUrls.get(url)
362            if (!josmUrls.containsKey(url)) continue
363            def j = josmUrls.get(url)
364            def ename = getName(e).replace("'","\u2019")
365            def jname = getName(j).replace("'","\u2019")
366            if (!ename.equals(jname)) {
367                myprintln "* Name differs ('${getName(e)}' != '${getName(j)}'): $url"
368            }
369        }
370
371        myprintln "*** Same URL, but different type: ***"
372        for (def url : eliUrls.keySet()) {
373            def e = eliUrls.get(url)
374            if (!josmUrls.containsKey(url)) continue
375            def j = josmUrls.get(url)
376            if (!getType(e).equals(getType(j))) {
377                myprintln "* Type differs (${getType(e)} != ${getType(j)}): ${getName(j)} - $url"
378            }
379        }
380
381        myprintln "*** Same URL, but different zoom bounds: ***"
382        for (def url : eliUrls.keySet()) {
383            def e = eliUrls.get(url)
384            if (!josmUrls.containsKey(url)) continue
385            def j = josmUrls.get(url)
386
387            Integer eMinZoom = getMinZoom(e)
388            Integer jMinZoom = getMinZoom(j)
389            if (eMinZoom != jMinZoom  && !(eMinZoom == 0 && jMinZoom == null)) {
390                myprintln "* Minzoom differs (${eMinZoom} != ${jMinZoom}): ${getDescription(j)}"
391            }
392            Integer eMaxZoom = getMaxZoom(e)
393            Integer jMaxZoom = getMaxZoom(j)
394            if (eMaxZoom != jMaxZoom) {
395                myprintln "* Maxzoom differs (${eMaxZoom} != ${jMaxZoom}): ${getDescription(j)}"
396            }
397        }
398
399        myprintln "*** Same URL, but different country code: ***"
400        for (def url : eliUrls.keySet()) {
401            def e = eliUrls.get(url)
402            if (!josmUrls.containsKey(url)) continue
403            def j = josmUrls.get(url)
404            if (!getCountryCode(e).equals(getCountryCode(j))) {
405                myprintln "* Country code differs (${getCountryCode(e)} != ${getCountryCode(j)}): ${getDescription(j)}"
406            }
407        }
408        myprintln "*** Same URL, but different quality: ***"
409        for (def url : eliUrls.keySet()) {
410            def e = eliUrls.get(url)
411            if (!josmUrls.containsKey(url)) {
412              def q = getQuality(e)
413              if("eli-best".equals(q)) {
414                myprintln "- Quality best entry not in JOSM for ${getDescription(e)}"
415              }
416              continue
417            }
418            def j = josmUrls.get(url)
419            if (!getQuality(e).equals(getQuality(j))) {
420                myprintln "* Quality differs (${getQuality(e)} != ${getQuality(j)}): ${getDescription(j)}"
421            }
422        }
423        myprintln "*** Same URL, but different dates: ***"
424        for (def url : eliUrls.keySet()) {
425            def ed = getDate(eliUrls.get(url))
426            if (!josmUrls.containsKey(url)) continue
427            def j = josmUrls.get(url)
428            def jd = getDate(j)
429            // The forms 2015;- or -;2015 or 2015;2015 are handled equal to 2015
430            String ef = ed.replaceAll("\\A-;","").replaceAll(";-\\z","").replaceAll("\\A([0-9-]+);\\1\\z","\$1")
431            // ELI has a strange and inconsistent used end_date definition, so we try again with subtraction by one
432            String ed2 = ed
433            def reg = (ed =~ /^(.*;)(\d\d\d\d)(-(\d\d)(-(\d\d))?)?$/)
434            if(reg != null && reg.count == 1) {
435                Calendar cal = Calendar.getInstance()
436                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)
437                cal.add(Calendar.DAY_OF_MONTH, -1)
438                ed2 = reg[0][1] + cal.get(Calendar.YEAR)
439                if (reg[0][4] != null)
440                    ed2 += "-" + String.format("%02d", cal.get(Calendar.MONTH)+1)
441                if (reg[0][6] != null)
442                    ed2 += "-" + String.format("%02d", cal.get(Calendar.DAY_OF_MONTH))
443            }
444            String ef2 = ed2.replaceAll("\\A-;","").replaceAll(";-\\z","").replaceAll("\\A([0-9-]+);\\1\\z","\$1")
445            if (!ed.equals(jd) && !ef.equals(jd) && !ed2.equals(jd) && !ef2.equals(jd)) {
446                String t = "'${ed}'"
447                if (!ed.equals(ef)) {
448                    t += " or '${ef}'"
449                }
450                if (jd.isEmpty()) {
451                    myprintln "- Missing JOSM date (${t}): ${getDescription(j)}"
452                } else if (!ed.isEmpty()) {
453                    myprintln "* Date differs (${t} != '${jd}'): ${getDescription(j)}"
454                } else if (!options.nomissingeli) {
455                    myprintln "+ Missing ELI date ('${jd}'): ${getDescription(j)}"
456                }
457            }
458        }
459        myprintln "*** Same URL, but different information: ***"
460        for (def url : eliUrls.keySet()) {
461            if (!josmUrls.containsKey(url)) continue
462            def e = eliUrls.get(url)
463            def j = josmUrls.get(url)
464
465            def et = getDescriptions(e)
466            def jt = getDescriptions(j)
467            et = (et.size() > 0) ? et["en"] : ""
468            jt = (jt.size() > 0) ? jt["en"] : ""
469            if (!et.equals(jt) && !(et && jt && et.endsWith(jt))) {
470                if (!jt) {
471                    myprintln "+ SKIP - Missing JOSM description (${et}): ${getDescription(j)}"
472                } else if (et) {
473                    myprintln "+ SKIP * Description differs (${et} != '${jt}'): ${getDescription(j)}"
474                } else if (!options.nomissingeli) {
475                    myprintln "+ Missing ELI description ('${jt}'): ${getDescription(j)}"
476                }
477            }
478
479            et = getPermissionReferenceUrl(e)
480            jt = getPermissionReferenceUrl(j)
481            if (!jt) jt = getTermsOfUseUrl(j)
482            if (!et.equals(jt)) {
483                if (!jt) {
484                    myprintln "+ SKIP - Missing JOSM license URL (${et}): ${getDescription(j)}"
485                } else if (et) {
486                    myprintln "+ SKIP * License URL differs (${et} != '${jt}'): ${getDescription(j)}"
487                } else if (!options.nomissingeli) {
488                    myprintln "+ Missing ELI license URL ('${jt}'): ${getDescription(j)}"
489                }
490            }
491
492            et = getAttributionUrl(e)
493            jt = getAttributionUrl(j)
494            if (!et.equals(jt)) {
495                if (!jt) {
496                    myprintln "+ SKIP - Missing JOSM attribution URL (${et}): ${getDescription(j)}"
497                } else if (et) {
498                    myprintln "+ SKIP * Attribution URL differs (${et} != '${jt}'): ${getDescription(j)}"
499                } else if (!options.nomissingeli) {
500                    myprintln "+ Missing ELI attribution URL ('${jt}'): ${getDescription(j)}"
501                }
502            }
503
504            et = getAttributionText(e)
505            jt = getAttributionText(j)
506            if (!et.equals(jt)) {
507                if (!jt) {
508                    myprintln "+ SKIP - Missing JOSM attribution text (${et}): ${getDescription(j)}"
509                } else if (et) {
510                    myprintln "+ SKIP * Attribution text differs (${et} != '${jt}'): ${getDescription(j)}"
511                } else if (!options.nomissingeli) {
512                    myprintln "+ Missing ELI attribution text ('${jt}'): ${getDescription(j)}"
513                }
514            }
515
516            et = getProjections(e)
517            jt = getProjections(j)
518            if (et) { et = new LinkedList(et); Collections.sort(et); et = String.join(" ", et) }
519            if (jt) { jt = new LinkedList(jt); Collections.sort(jt); jt = String.join(" ", jt) }
520            if (!et.equals(jt)) {
521                if (!jt) {
522                    myprintln "+ SKIP - Missing JOSM projections (${et}): ${getDescription(j)}"
523                } else if (et) {
524                    myprintln "+ SKIP * Projections differ (${et} != '${jt}'): ${getDescription(j)}"
525                } else if (!options.nomissingeli) {
526                    myprintln "+ Missing ELI projections ('${jt}'): ${getDescription(j)}"
527                }
528            }
529        }
530        myprintln "*** Mismatching shapes: ***"
531        for (def url : josmUrls.keySet()) {
532            def j = josmUrls.get(url)
533            def num = 1
534            for (def shape : getShapes(j)) {
535                def p = shape.getPoints()
536                if(!p[0].equals(p[p.size()-1])) {
537                    myprintln "+++ JOSM shape $num unclosed: ${getDescription(j)}"
538                }
539                for (def nump = 1; nump < p.size(); ++nump) {
540                    if (p[nump-1] == p[nump]) {
541                        myprintln "+++ JOSM shape $num double point at ${nump-1}: ${getDescription(j)}"
542                    }
543                }
544                ++num
545            }
546        }
547        for (def url : eliUrls.keySet()) {
548            def e = eliUrls.get(url)
549            def num = 1
550            def s = getShapes(e)
551            for (def shape : s) {
552                def p = shape.getPoints()
553                if(!p[0].equals(p[p.size()-1]) && !options.nomissingeli) {
554                    myprintln "+++ ELI shape $num unclosed: ${getDescription(e)}"
555                }
556                for (def nump = 1; nump < p.size(); ++nump) {
557                    if (p[nump-1] == p[nump]) {
558                        myprintln "+++ ELI shape $num double point at ${nump-1}: ${getDescription(e)}"
559                    }
560                }
561                ++num
562            }
563            if (!josmUrls.containsKey(url)) {
564                continue
565            }
566            def j = josmUrls.get(url)
567            def js = getShapes(j)
568            if(!s.size() && js.size()) {
569                if(!options.nomissingeli) {
570                    myprintln "+ No ELI shape: ${getDescription(j)}"
571                }
572            } else if(!js.size() && s.size()) {
573                // don't report boundary like 5 point shapes as difference
574                if (s.size() != 1 || s[0].getPoints().size() != 5) {
575                    myprintln "- No JOSM shape: ${getDescription(j)}"
576                }
577            } else if(s.size() != js.size()) {
578                myprintln "* Different number of shapes (${s.size()} != ${js.size()}): ${getDescription(j)}"
579            } else {
580                for(def nums = 0; nums < s.size(); ++nums) {
581                    def ep = s[nums].getPoints()
582                    def jp = js[nums].getPoints()
583                    if(ep.size() != jp.size()) {
584                        myprintln "* Different number of points for shape ${nums+1} (${ep.size()} ! = ${jp.size()})): ${getDescription(j)}"
585                    } else {
586                        for(def nump = 0; nump < ep.size(); ++nump) {
587                            def ept = ep[nump]
588                            def jpt = jp[nump]
589                            if(Math.abs(ept.getLat()-jpt.getLat()) > 0.000001 || Math.abs(ept.getLon()-jpt.getLon()) > 0.000001) {
590                                myprintln "* Different coordinate for point ${nump+1} of shape ${nums+1}: ${getDescription(j)}"
591                                nump = ep.size()
592                                num = s.size()
593                            }
594                        }
595                    }
596                }
597            }
598        }
599        myprintln "*** Mismatching icons: ***"
600        for (def url : eliUrls.keySet()) {
601            def e = eliUrls.get(url)
602            if (!josmUrls.containsKey(url)) {
603                continue
604            }
605            def j = josmUrls.get(url)
606            def ij = getIcon(j)
607            def ie = getIcon(e)
608            if(ij != null && ie == null) {
609                if(!options.nomissingeli) {
610                    myprintln "+ No ELI icon: ${getDescription(j)}"
611                }
612            } else if(ij == null && ie != null) {
613                myprintln "- No JOSM icon: ${getDescription(j)}"
614            } else if(!ij.equals(ie)) {
615                myprintln "* Different icons: ${getDescription(j)}"
616            }
617        }
618        myprintln "*** Miscellaneous checks: ***"
619        def josmIds = new HashMap<String, ImageryInfo>()
620        for (def url : josmUrls.keySet()) {
621            def j = josmUrls.get(url)
622            def id = getId(j)
623            if(josmMirrors.containsKey(url)) {
624                continue
625            }
626            if(id == null) {
627                myprintln "* No JOSM-ID: ${getDescription(j)}"
628            } else if(josmIds.containsKey(id)) {
629                myprintln "* JOSM-ID ${id} not unique: ${getDescription(j)}"
630            } else {
631                josmIds.put(id, j)
632            }
633            def d = getDate(j)
634            if(!d.isEmpty()) {
635                def reg = (d =~ /^(-|(\d\d\d\d)(-(\d\d)(-(\d\d))?)?)(;(-|(\d\d\d\d)(-(\d\d)(-(\d\d))?)?))?$/)
636                if(reg == null || reg.count != 1) {
637                    myprintln "* JOSM-Date '${d}' is strange: ${getDescription(j)}"
638                } else {
639                    try {
640                        def first = verifyDate(reg[0][2],reg[0][4],reg[0][6])
641                        def second = verifyDate(reg[0][9],reg[0][11],reg[0][13])
642                        if(second.compareTo(first) < 0) {
643                            myprintln "* JOSM-Date '${d}' is strange (second earlier than first): ${getDescription(j)}"
644                        }
645                    }
646                    catch (Exception e) {
647                        myprintln "* JOSM-Date '${d}' is strange (${e.getMessage()}): ${getDescription(j)}"
648                    }
649                }
650            }
651            def js = getShapes(j)
652            if(js.size()) {
653                def minlat = 1000
654                def minlon = 1000
655                def maxlat = -1000
656                def maxlon = -1000
657                for(def s: js) {
658                    for(def p: s.getPoints()) {
659                        def lat = p.getLat()
660                        def lon = p.getLon()
661                        if(lat > maxlat) maxlat = lat
662                        if(lon > maxlon) maxlon = lon
663                        if(lat < minlat) minlat = lat
664                        if(lon < minlon) minlon = lon
665                    }
666                }
667                def b = j.getBounds()
668                if(b.getMinLat() != minlat || b.getMinLon() != minlon || b.getMaxLat() != maxlat || b.getMaxLon() != maxlon) {
669                    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)}"
670                }
671            }
672        }
673    }
674
675    /**
676     * Utility functions that allow uniform access for both ImageryInfo and JsonObject.
677     */
678    static String getUrl(Object e) {
679        if (e instanceof ImageryInfo) return e.url
680        return e.get("properties").getString("url")
681    }
682    static String getDate(Object e) {
683        if (e instanceof ImageryInfo) return e.date ? e.date : ""
684        def p = e.get("properties")
685        def start = p.containsKey("start_date") ? p.getString("start_date") : ""
686        def end = p.containsKey("end_date") ? p.getString("end_date") : ""
687        if(!start.isEmpty() && !end.isEmpty())
688            return start+";"+end
689        else if(!start.isEmpty())
690            return start+";-"
691        else if(!end.isEmpty())
692            return "-;"+end
693        return ""
694    }
695    static Date verifyDate(String year, String month, String day) {
696        def date
697        if(year == null) {
698            date = "3000-01-01"
699        } else {
700            date = year + "-" + (month == null ? "01" : month) + "-" + (day == null ? "01" : day)
701        }
702        def df = new java.text.SimpleDateFormat("yyyy-MM-dd")
703        df.setLenient(false)
704        return df.parse(date)
705    }
706    static String getId(Object e) {
707        if (e instanceof ImageryInfo) return e.getId()
708        return e.get("properties").getString("id")
709    }
710    static String getName(Object e) {
711        if (e instanceof ImageryInfo) return e.getOriginalName()
712        return e.get("properties").getString("name")
713    }
714    static List<Object> getMirrors(Object e) {
715        if (e instanceof ImageryInfo) return e.getMirrors()
716        return []
717    }
718    static List<Object> getProjections(Object e) {
719        def r
720        if (e instanceof ImageryInfo) {
721            r = e.getServerProjections()
722        } else {
723            def s = e.get("properties").get("available_projections")
724            if (s) {
725                r = []
726                for (def p : s)
727                    r += p.getString()
728            }
729        }
730        return r ? r : []
731    }
732    static List<Shape> getShapes(Object e) {
733        if (e instanceof ImageryInfo) {
734            def bounds = e.getBounds()
735            if(bounds != null) {
736                return bounds.getShapes()
737            }
738            return []
739        }
740        if(!e.isNull("geometry")) {
741            def ex = e.get("geometry")
742            if(ex != null && !ex.isNull("coordinates")) {
743                def poly = ex.get("coordinates")
744                List<Shape> l = []
745                for(def shapes: poly) {
746                    def s = new Shape()
747                    for(def point: shapes) {
748                        def lon = point[0].toString()
749                        def lat = point[1].toString()
750                        s.addPoint(lat, lon)
751                    }
752                    l.add(s)
753                }
754                return l
755            }
756        }
757        return []
758    }
759    static String getType(Object e) {
760        if (e instanceof ImageryInfo) return e.getImageryType().getTypeString()
761        return e.get("properties").getString("type")
762    }
763    static Integer getMinZoom(Object e) {
764        if (e instanceof ImageryInfo) {
765            if("wms".equals(getType(e)) && e.getName() =~ / mirror/)
766                return null;
767            int mz = e.getMinZoom()
768            return mz == 0 ? null : mz
769        } else {
770            def num = e.get("properties").getJsonNumber("min_zoom")
771            if (num == null) return null
772            return num.intValue()
773        }
774    }
775    static Integer getMaxZoom(Object e) {
776        if (e instanceof ImageryInfo) {
777            if("wms".equals(getType(e)) && e.getName() =~ / mirror/)
778                return null;
779            int mz = e.getMaxZoom()
780            return mz == 0 ? null : mz
781        } else {
782            def num = e.get("properties").getJsonNumber("max_zoom")
783            if (num == null) return null
784            return num.intValue()
785        }
786    }
787    static String getCountryCode(Object e) {
788        if (e instanceof ImageryInfo) return "".equals(e.getCountryCode()) ? null : e.getCountryCode()
789        return e.get("properties").getString("country_code", null)
790    }
791    static String getQuality(Object e) {
792        if (e instanceof ImageryInfo) return e.isBestMarked() ? "eli-best" : null
793        return (e.get("properties").containsKey("best")
794            && e.get("properties").getBoolean("best")) ? "eli-best" : null
795    }
796    static String getIcon(Object e) {
797        if (e instanceof ImageryInfo) return e.getIcon()
798        return e.get("properties").getString("icon", null)
799    }
800    static String getAttributionText(Object e) {
801        if (e instanceof ImageryInfo) return e.getAttributionText(0, null, null)
802        try {return e.get("properties").get("attribution").getString("text", null)} catch (NullPointerException ex) {return null}
803    }
804    static String getAttributionUrl(Object e) {
805        if (e instanceof ImageryInfo) return e.getAttributionLinkURL()
806        try {return e.get("properties").get("attribution").getString("url", null)} catch (NullPointerException ex) {return null}
807    }
808    static String getTermsOfUseText(Object e) {
809        if (e instanceof ImageryInfo) return e.getTermsOfUseText()
810        return null
811    }
812    static String getTermsOfUseUrl(Object e) {
813        if (e instanceof ImageryInfo) return e.getTermsOfUseURL()
814        return null
815    }
816    static String getPermissionReferenceUrl(Object e) {
817        if (e instanceof ImageryInfo) return e.getPermissionReferenceURL()
818        return e.get("properties").getString("license_url", null)
819    }
820    static Map<String,String> getDescriptions(Object e) {
821        Map<String,String> res = new HashMap<String, String>()
822        if (e instanceof ImageryInfo) {
823          String a = e.getDescription()
824          if (a) res.put("en", a)
825        } else {
826          String a = e.get("properties").getString("description", null)
827          if (a) res.put("en", a)
828        }
829        return res
830    }
831    static Boolean getValidGeoreference(Object e) {
832        if (e instanceof ImageryInfo) return e.isGeoreferenceValid()
833        return false
834    }
835    String getDescription(Object o) {
836        def url = getUrl(o)
837        def cc = getCountryCode(o)
838        if (cc == null) {
839            def j = josmUrls.get(url)
840            if (j != null) cc = getCountryCode(j)
841            if (cc == null) {
842                def e = eliUrls.get(url)
843                if (e != null) cc = getCountryCode(e)
844            }
845        }
846        if (cc == null) {
847            cc = ''
848        } else {
849            cc = "[$cc] "
850        }
851        def d = cc + getName(o) + " - " + getUrl(o)
852        if (options.shorten) {
853            def MAXLEN = 140
854            if (d.length() > MAXLEN) d = d.substring(0, MAXLEN-1) + "..."
855        }
856        return d
857    }
858}
Note: See TracBrowser for help on using the repository browser.