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

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

load Preferences in ImageryCompare script to fix deep NPE at initialization

  • Property svn:eol-style set to native
File size: 46.0 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.Preferences
26import org.openstreetmap.josm.data.imagery.ImageryInfo
27import org.openstreetmap.josm.data.imagery.Shape
28import org.openstreetmap.josm.data.preferences.JosmBaseDirectories
29import org.openstreetmap.josm.data.projection.Projections
30import org.openstreetmap.josm.data.validation.routines.DomainValidator
31import org.openstreetmap.josm.io.imagery.ImageryReader
32import org.openstreetmap.josm.spi.preferences.Config
33
34class SyncEditorLayerIndex {
35
36    List<ImageryInfo> josmEntries;
37    JsonArray eliEntries;
38
39    def eliUrls = new HashMap<String, JsonObject>()
40    def josmUrls = new HashMap<String, ImageryInfo>()
41    def josmMirrors = new HashMap<String, ImageryInfo>()
42    static def oldproj = new HashMap<String, String>()
43    static def ignoreproj = new LinkedList<String>()
44
45    static String eliInputFile = 'imagery_eli.geojson'
46    static String josmInputFile = 'imagery_josm.imagery.xml'
47    static String ignoreInputFile = 'imagery_josm.ignores.txt'
48    static FileOutputStream outputFile = null
49    static OutputStreamWriter outputStream = null
50    def skip = [:]
51
52    static def options
53
54    /**
55     * Main method.
56     */
57    static main(def args) {
58        Locale.setDefault(Locale.ROOT);
59        parse_command_line_arguments(args)
60        def pref = new Preferences(JosmBaseDirectories.getInstance())
61        pref.init(false)
62        Config.setPreferencesInstance(pref)
63        def script = new SyncEditorLayerIndex()
64        script.setupProj()
65        script.loadSkip()
66        script.start()
67        script.loadJosmEntries()
68        if(options.josmxml) {
69            def file = new FileOutputStream(options.josmxml)
70            def stream = new OutputStreamWriter(file, "UTF-8")
71            script.printentries(script.josmEntries, stream)
72            stream.close();
73            file.close();
74        }
75        script.loadELIEntries()
76        if(options.elixml) {
77            def file = new FileOutputStream(options.elixml)
78            def stream = new OutputStreamWriter(file, "UTF-8")
79            script.printentries(script.eliEntries, stream)
80            stream.close();
81            file.close();
82        }
83        script.checkInOneButNotTheOther()
84        script.checkCommonEntries()
85        script.end()
86        if(outputStream != null) {
87            outputStream.close();
88        }
89        if(outputFile != null) {
90            outputFile.close();
91        }
92    }
93
94    /**
95     * Parse command line arguments.
96     */
97    static void parse_command_line_arguments(args) {
98        def cli = new CliBuilder(width: 160)
99        cli.o(longOpt:'output', args:1, argName: "output", "Output file, - prints to stdout (default: -)")
100        cli.e(longOpt:'eli_input', args:1, argName:"eli_input", "Input file for the editor layer index (geojson). Default is $eliInputFile (current directory).")
101        cli.j(longOpt:'josm_input', args:1, argName:"josm_input", "Input file for the JOSM imagery list (xml). Default is $josmInputFile (current directory).")
102        cli.i(longOpt:'ignore_input', args:1, argName:"ignore_input", "Input file for the ignore list. Default is $ignoreInputFile (current directory).")
103        cli.s(longOpt:'shorten', "shorten the output, so it is easier to read in a console window")
104        cli.n(longOpt:'noskip', argName:"noskip", "don't skip known entries")
105        cli.x(longOpt:'xhtmlbody', argName:"xhtmlbody", "create XHTML body for display in a web page")
106        cli.X(longOpt:'xhtml', argName:"xhtml", "create XHTML for display in a web page")
107        cli.p(longOpt:'elixml', args:1, argName:"elixml", "ELI entries for use in JOSM as XML file (incomplete)")
108        cli.q(longOpt:'josmxml', args:1, argName:"josmxml", "JOSM entries reoutput as XML file (incomplete)")
109        cli.m(longOpt:'noeli', argName:"noeli", "don't show output for ELI problems")
110        cli.c(longOpt:'encoding', args:1, argName:"encoding", "output encoding (defaults to UTF-8 or cp850 on Windows)")
111        cli.h(longOpt:'help', "show this help")
112        options = cli.parse(args)
113
114        if (options.h) {
115            cli.usage()
116            System.exit(0)
117        }
118        if (options.eli_input) {
119            eliInputFile = options.eli_input
120        }
121        if (options.josm_input) {
122            josmInputFile = options.josm_input
123        }
124        if (options.ignore_input) {
125            ignoreInputFile = options.ignore_input
126        }
127        if (options.output && options.output != "-") {
128            outputFile = new FileOutputStream(options.output)
129            outputStream = new OutputStreamWriter(outputFile, options.encoding ? options.encoding : "UTF-8")
130        } else if (options.encoding) {
131            outputStream = new OutputStreamWriter(System.out, options.encoding)
132        }
133    }
134
135    void setupProj() {
136        oldproj.put("EPSG:3359", "EPSG:3404")
137        oldproj.put("EPSG:3785", "EPSG:3857")
138        oldproj.put("EPSG:31297", "EPGS:31287")
139        oldproj.put("EPSG:31464", "EPSG:31468")
140        oldproj.put("EPSG:54004", "EPSG:3857")
141        oldproj.put("EPSG:102100", "EPSG:3857")
142        oldproj.put("EPSG:102113", "EPSG:3857")
143        oldproj.put("EPSG:900913", "EPGS:3857")
144        ignoreproj.add("EPSG:4267")
145        ignoreproj.add("EPSG:5221")
146        ignoreproj.add("EPSG:5514")
147        ignoreproj.add("EPSG:32019")
148        ignoreproj.add("EPSG:102066")
149        ignoreproj.add("EPSG:102067")
150        ignoreproj.add("EPSG:102685")
151        ignoreproj.add("EPSG:102711")
152    }
153
154    void loadSkip() {
155        def fr = new InputStreamReader(new FileInputStream(ignoreInputFile), "UTF-8")
156        def line
157
158        while((line = fr.readLine()) != null) {
159            def res = (line =~ /^\|\| *(ELI|Ignore) *\|\| *\{\{\{(.+)\}\}\} *\|\|/)
160            if(res.count)
161            {
162                if(res[0][1].equals("Ignore")) {
163                    skip[res[0][2]] = "green"
164                } else {
165                    skip[res[0][2]] = "darkgoldenrod"
166                }
167            }
168        }
169    }
170
171    void myprintlnfinal(String s) {
172        if(outputStream != null) {
173            outputStream.write(s+System.getProperty("line.separator"))
174        } else {
175            println s
176        }
177    }
178
179    void myprintln(String s) {
180        if(skip.containsKey(s)) {
181            String color = skip.get(s)
182            skip.remove(s)
183            if(options.xhtmlbody || options.xhtml) {
184                s = "<pre style=\"margin:3px;color:"+color+"\">"+s.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")+"</pre>"
185            }
186            if (!options.noskip) {
187                return
188            }
189        } else if(options.xhtmlbody || options.xhtml) {
190            String color = s.startsWith("***") ? "black" : ((s.startsWith("+ ") || s.startsWith("+++ ELI")) ? "blue" :
191            (s.startsWith("#") ? "indigo" : (s.startsWith("!") ? "orange" : "red")))
192            s = "<pre style=\"margin:3px;color:"+color+"\">"+s.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")+"</pre>"
193        }
194        if ((s.startsWith("+ ") || s.startsWith("+++ ELI") || s.startsWith("#")) && options.noeli) {
195            return
196        }
197        myprintlnfinal(s)
198    }
199
200    void start() {
201        if (options.xhtml) {
202            myprintlnfinal "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"
203            myprintlnfinal "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/><title>JOSM - ELI differences</title></head><body>\n"
204        }
205    }
206
207    void end() {
208        for (def s: skip.keySet()) {
209            myprintln "+++ Obsolete skip entry: " + s
210        }
211        if (options.xhtml) {
212            myprintlnfinal "</body></html>\n"
213        }
214    }
215
216    void loadELIEntries() {
217        def fr = new InputStreamReader(new FileInputStream(eliInputFile), "UTF-8")
218        JsonReader jr = Json.createReader(fr)
219        eliEntries = jr.readObject().get("features")
220        jr.close()
221
222        for (def e : eliEntries) {
223            def url = getUrlStripped(e)
224            if (url.contains("{z}")) {
225                myprintln "+++ ELI-URL uses {z} instead of {zoom}: "+url
226                url = url.replace("{z}","{zoom}")
227            }
228            if (eliUrls.containsKey(url)) {
229                myprintln "+++ ELI-URL is not unique: "+url
230            } else {
231                eliUrls.put(url, e)
232            }
233            def s = e.get("properties").get("available_projections")
234            if (s) {
235                def old = new LinkedList<String>()
236                for (def p : s) {
237                    def proj = p.getString()
238                    if(oldproj.containsKey(proj) || ("CRS:84".equals(proj) && !(url =~ /(?i)version=1\.3/))) {
239                        old.add(proj)
240                    }
241                }
242                if (old) {
243                    def str = String.join(", ", old)
244                    myprintln "+ ELI Projections ${str} not useful: ${getDescription(e)}"
245                }
246            }
247        }
248        myprintln "*** Loaded ${eliEntries.size()} entries (ELI). ***"
249    }
250    String cdata(def s, boolean escape = false) {
251        if(escape) {
252            return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
253        } else if(s =~ /[<>&]/)
254            return "<![CDATA[$s]]>"
255       return s
256    }
257
258    String maininfo(def entry, String offset) {
259        String t = getType(entry)
260        String res = offset + "<type>$t</type>\n"
261        res += offset + "<url>${cdata(getUrl(entry))}</url>\n"
262        if(getMinZoom(entry) != null)
263            res += offset + "<min-zoom>${getMinZoom(entry)}</min-zoom>\n"
264        if(getMaxZoom(entry) != null)
265            res += offset + "<max-zoom>${getMaxZoom(entry)}</max-zoom>\n"
266        if (t == "wms") {
267            def p = getProjections(entry)
268            if (p) {
269                res += offset + "<projections>\n"
270                for (def c : p)
271                    res += offset + "    <code>$c</code>\n"
272                res += offset + "</projections>\n"
273            }
274        }
275        return res
276    }
277
278    void printentries(def entries, def stream) {
279        DecimalFormat df = new DecimalFormat("#.#######")
280        df.setRoundingMode(java.math.RoundingMode.CEILING)
281        stream.write "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
282        stream.write "<imagery xmlns=\"http://josm.openstreetmap.de/maps-1.0\">\n"
283        for (def e : entries) {
284            stream.write("    <entry"
285                + ("eli-best".equals(getQuality(e)) ? " eli-best=\"true\"" : "" )
286                + (getOverlay(e) ? " overlay=\"true\"" : "" )
287                + ">\n")
288            stream.write "        <name>${cdata(getName(e), true)}</name>\n"
289            stream.write "        <id>${getId(e)}</id>\n"
290            def t
291            if((t = getDate(e)))
292                stream.write "        <date>$t</date>\n"
293            if((t = getCountryCode(e)))
294                stream.write "        <country-code>$t</country-code>\n"
295            if((getDefault(e)))
296                stream.write "        <default>true</default>\n"
297            stream.write maininfo(e, "        ")
298            if((t = getAttributionText(e)))
299                stream.write "        <attribution-text mandatory=\"true\">${cdata(t, true)}</attribution-text>\n"
300            if((t = getAttributionUrl(e)))
301                stream.write "        <attribution-url>${cdata(t)}</attribution-url>\n"
302            if((t = getLogoImage(e)))
303                stream.write "        <logo-image>${cdata(t, true)}</logo-image>\n"
304            if((t = getLogoUrl(e)))
305                stream.write "        <logo-url>${cdata(t)}</logo-url>\n"
306            if((t = getTermsOfUseText(e)))
307                stream.write "        <terms-of-use-text>${cdata(t, true)}</terms-of-use-text>\n"
308            if((t = getTermsOfUseUrl(e)))
309                stream.write "        <terms-of-use-url>${cdata(t)}</terms-of-use-url>\n"
310            if((t = getPermissionReferenceUrl(e)))
311                stream.write "        <permission-ref>${cdata(t)}</permission-ref>\n"
312            if((getValidGeoreference(e)))
313                stream.write "        <valid-georeference>true</valid-georeference>\n"
314            if((t = getIcon(e)))
315                stream.write "        <icon>${cdata(t)}</icon>\n"
316            for (def d : getDescriptions(e)) {
317                    stream.write "        <description lang=\"${d.getKey()}\">${d.getValue()}</description>\n"
318            }
319            for (def m : getMirrors(e)) {
320                    stream.write "        <mirror>\n"+maininfo(m, "            ")+"        </mirror>\n"
321            }
322            def minlat = 1000
323            def minlon = 1000
324            def maxlat = -1000
325            def maxlon = -1000
326            def shapes = ""
327            def sep = "\n            "
328            for(def s: getShapes(e)) {
329                shapes += "            <shape>"
330                def i = 0
331                for(def p: s.getPoints()) {
332                    def lat = p.getLat()
333                    def lon = p.getLon()
334                    if(lat > maxlat) maxlat = lat
335                    if(lon > maxlon) maxlon = lon
336                    if(lat < minlat) minlat = lat
337                    if(lon < minlon) minlon = lon
338                    if(!(i++%3)) {
339                        shapes += sep + "    "
340                    }
341                    shapes += "<point lat='${df.format(lat)}' lon='${df.format(lon)}'/>"
342                }
343                shapes += sep + "</shape>\n"
344            }
345            if(shapes) {
346                stream.write "        <bounds min-lat='${df.format(minlat)}' min-lon='${df.format(minlon)}' max-lat='${df.format(maxlat)}' max-lon='${df.format(maxlon)}'>\n"
347                stream.write shapes + "        </bounds>\n"
348            }
349            stream.write "    </entry>\n"
350        }
351        stream.write "</imagery>\n"
352        stream.close()
353    }
354
355    void loadJosmEntries() {
356        def reader = new ImageryReader(josmInputFile)
357        josmEntries = reader.parse()
358
359        for (def e : josmEntries) {
360            def url = getUrlStripped(e)
361            if (url.contains("{z}")) {
362                myprintln "+++ JOSM-URL uses {z} instead of {zoom}: "+url
363                url = url.replace("{z}","{zoom}")
364            }
365            if (josmUrls.containsKey(url)) {
366                myprintln "+++ JOSM-URL is not unique: "+url
367            } else {
368                josmUrls.put(url, e)
369            }
370            for (def m : e.getMirrors()) {
371                url = getUrlStripped(m)
372                m.origName = m.getOriginalName().replaceAll(" mirror server( \\d+)?","")
373                if (josmUrls.containsKey(url)) {
374                    myprintln "+++ JOSM-Mirror-URL is not unique: "+url
375                } else {
376                    josmUrls.put(url, m)
377                    josmMirrors.put(url, m)
378                }
379            }
380        }
381        myprintln "*** Loaded ${josmEntries.size()} entries (JOSM). ***"
382    }
383
384    void checkInOneButNotTheOther() {
385        def le = new LinkedList<String>(eliUrls.keySet())
386        def lj = new LinkedList<String>(josmUrls.keySet())
387
388        def ke = new LinkedList<String>(le)
389        for (def url : ke) {
390            if(lj.contains(url)) {
391                le.remove(url)
392                lj.remove(url)
393            }
394        }
395
396        if(le && lj) {
397            ke = new LinkedList<String>(le)
398            for (def urle : ke) {
399                def e = eliUrls.get(urle)
400                def ide = getId(e)
401                String urlhttps = urle.replace("http:","https:")
402                if(lj.contains(urlhttps))
403                {
404                    myprintln "+ Missing https: ${getDescription(e)}"
405                    eliUrls.put(urlhttps, eliUrls.get(urle))
406                    eliUrls.remove(urle)
407                    le.remove(urle)
408                    lj.remove(urlhttps)
409                } else if(ide) {
410                    def kj = new LinkedList<String>(lj)
411                    for (def urlj : kj) {
412                        def j = josmUrls.get(urlj)
413                        def idj = getId(j)
414
415                        if (ide.equals(idj) && getType(j) == getType(e)) {
416                            myprintln "* URL for id ${idj} differs ($urle): ${getDescription(j)}"
417                            le.remove(urle)
418                            lj.remove(urlj)
419                            /* replace key for this entry with JOSM URL */
420                            eliUrls.remove(e)
421                            eliUrls.put(urlj,e)
422                            break;
423                        }
424                    }
425                }
426            }
427        }
428
429        myprintln "*** URLs found in ELI but not in JOSM (${le.size()}): ***"
430        le.sort()
431        if (!le.isEmpty()) {
432            for (def l : le) {
433                myprintln "-  " + getDescription(eliUrls.get(l))
434            }
435        }
436        myprintln "*** URLs found in JOSM but not in ELI (${lj.size()}): ***"
437        lj.sort()
438        if (!lj.isEmpty()) {
439            for (def l : lj) {
440                myprintln "+  " + getDescription(josmUrls.get(l))
441            }
442        }
443    }
444
445    void checkCommonEntries() {
446        myprintln "*** Same URL, but different name: ***"
447        for (def url : eliUrls.keySet()) {
448            def e = eliUrls.get(url)
449            if (!josmUrls.containsKey(url)) continue
450            def j = josmUrls.get(url)
451            def ename = getName(e).replace("'","\u2019")
452            def jname = getName(j).replace("'","\u2019")
453            if (!ename.equals(jname)) {
454                myprintln "* Name differs ('${getName(e)}' != '${getName(j)}'): ${getUrl(j)}"
455            }
456        }
457
458        myprintln "*** Same URL, but different Id: ***"
459        for (def url : eliUrls.keySet()) {
460            def e = eliUrls.get(url)
461            if (!josmUrls.containsKey(url)) continue
462            def j = josmUrls.get(url)
463            def ename = getId(e)
464            def jname = getId(j)
465            if (!ename.equals(jname)) {
466                myprintln "# Id differs ('${getId(e)}' != '${getId(j)}'): ${getUrl(j)}"
467            }
468        }
469
470        myprintln "*** Same URL, but different type: ***"
471        for (def url : eliUrls.keySet()) {
472            def e = eliUrls.get(url)
473            if (!josmUrls.containsKey(url)) continue
474            def j = josmUrls.get(url)
475            if (!getType(e).equals(getType(j))) {
476                myprintln "* Type differs (${getType(e)} != ${getType(j)}): ${getName(j)} - ${getUrl(j)}"
477            }
478        }
479
480        myprintln "*** Same URL, but different zoom bounds: ***"
481        for (def url : eliUrls.keySet()) {
482            def e = eliUrls.get(url)
483            if (!josmUrls.containsKey(url)) continue
484            def j = josmUrls.get(url)
485
486            Integer eMinZoom = getMinZoom(e)
487            Integer jMinZoom = getMinZoom(j)
488            if (eMinZoom != jMinZoom  && !(eMinZoom == 0 && jMinZoom == null)) {
489                myprintln "* Minzoom differs (${eMinZoom} != ${jMinZoom}): ${getDescription(j)}"
490            }
491            Integer eMaxZoom = getMaxZoom(e)
492            Integer jMaxZoom = getMaxZoom(j)
493            if (eMaxZoom != jMaxZoom) {
494                myprintln "* Maxzoom differs (${eMaxZoom} != ${jMaxZoom}): ${getDescription(j)}"
495            }
496        }
497
498        myprintln "*** Same URL, but different country code: ***"
499        for (def url : eliUrls.keySet()) {
500            def e = eliUrls.get(url)
501            if (!josmUrls.containsKey(url)) continue
502            def j = josmUrls.get(url)
503            if (!getCountryCode(e).equals(getCountryCode(j))) {
504                myprintln "* Country code differs (${getCountryCode(e)} != ${getCountryCode(j)}): ${getDescription(j)}"
505            }
506        }
507        myprintln "*** Same URL, but different quality: ***"
508        for (def url : eliUrls.keySet()) {
509            def e = eliUrls.get(url)
510            if (!josmUrls.containsKey(url)) {
511              def q = getQuality(e)
512              if("eli-best".equals(q)) {
513                myprintln "- Quality best entry not in JOSM for ${getDescription(e)}"
514              }
515              continue
516            }
517            def j = josmUrls.get(url)
518            if (!getQuality(e).equals(getQuality(j))) {
519                myprintln "* Quality differs (${getQuality(e)} != ${getQuality(j)}): ${getDescription(j)}"
520            }
521        }
522        myprintln "*** Same URL, but different dates: ***"
523        for (def url : eliUrls.keySet()) {
524            def ed = getDate(eliUrls.get(url))
525            if (!josmUrls.containsKey(url)) continue
526            def j = josmUrls.get(url)
527            def jd = getDate(j)
528            // The forms 2015;- or -;2015 or 2015;2015 are handled equal to 2015
529            String ef = ed.replaceAll("\\A-;","").replaceAll(";-\\z","").replaceAll("\\A([0-9-]+);\\1\\z","\$1")
530            // ELI has a strange and inconsistent used end_date definition, so we try again with subtraction by one
531            String ed2 = ed
532            def reg = (ed =~ /^(.*;)(\d\d\d\d)(-(\d\d)(-(\d\d))?)?$/)
533            if(reg != null && reg.count == 1) {
534                Calendar cal = Calendar.getInstance()
535                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)
536                cal.add(Calendar.DAY_OF_MONTH, -1)
537                ed2 = reg[0][1] + cal.get(Calendar.YEAR)
538                if (reg[0][4] != null)
539                    ed2 += "-" + String.format("%02d", cal.get(Calendar.MONTH)+1)
540                if (reg[0][6] != null)
541                    ed2 += "-" + String.format("%02d", cal.get(Calendar.DAY_OF_MONTH))
542            }
543            String ef2 = ed2.replaceAll("\\A-;","").replaceAll(";-\\z","").replaceAll("\\A([0-9-]+);\\1\\z","\$1")
544            if (!ed.equals(jd) && !ef.equals(jd) && !ed2.equals(jd) && !ef2.equals(jd)) {
545                String t = "'${ed}'"
546                if (!ed.equals(ef)) {
547                    t += " or '${ef}'"
548                }
549                if (jd.isEmpty()) {
550                    myprintln "- Missing JOSM date (${t}): ${getDescription(j)}"
551                } else if (!ed.isEmpty()) {
552                    myprintln "* Date differs ('${t}' != '${jd}'): ${getDescription(j)}"
553                } else if (!options.nomissingeli) {
554                    myprintln "+ Missing ELI date ('${jd}'): ${getDescription(j)}"
555                }
556            }
557        }
558        myprintln "*** Same URL, but different information: ***"
559        for (def url : eliUrls.keySet()) {
560            if (!josmUrls.containsKey(url)) continue
561            def e = eliUrls.get(url)
562            def j = josmUrls.get(url)
563
564            def et = getDescriptions(e)
565            def jt = getDescriptions(j)
566            et = (et.size() > 0) ? et["en"] : ""
567            jt = (jt.size() > 0) ? jt["en"] : ""
568            if (!et.equals(jt)) {
569                if (!jt) {
570                    myprintln "- Missing JOSM description (${et}): ${getDescription(j)}"
571                } else if (et) {
572                    myprintln "* Description differs ('${et}' != '${jt}'): ${getDescription(j)}"
573                } else if (!options.nomissingeli) {
574                    myprintln "+ Missing ELI description ('${jt}'): ${getDescription(j)}"
575                }
576            }
577
578            et = getPermissionReferenceUrl(e)
579            jt = getPermissionReferenceUrl(j)
580            def jt2 = getTermsOfUseUrl(j)
581            if (!jt) jt = jt2
582            if (!et.equals(jt)) {
583                if (!jt) {
584                    myprintln "- Missing JOSM license URL (${et}): ${getDescription(j)}"
585                } else if (et) {
586                    def ethttps = et.replace("http:","https:")
587                    if(!jt2 || !(jt2.equals(ethttps) || jt2.equals(et+"/") || jt2.equals(ethttps+"/"))) {
588                        if(jt.equals(ethttps) || jt.equals(et+"/") || jt.equals(ethttps+"/")) {
589                            myprintln "+ License URL differs ('${et}' != '${jt}'): ${getDescription(j)}"
590                        } else {
591                            def ja = getAttributionUrl(j)
592                            if (ja && (ja.equals(et) || ja.equals(ethttps) || ja.equals(et+"/") || ja.equals(ethttps+"/"))) {
593                               myprintln "+ ELI License URL in JOSM Attribution: ${getDescription(j)}"
594                            } else {
595                                myprintln "* License URL differs ('${et}' != '${jt}'): ${getDescription(j)}"
596                            }
597                        }
598                    }
599                } else if (!options.nomissingeli) {
600                    myprintln "+ Missing ELI license URL ('${jt}'): ${getDescription(j)}"
601                }
602            }
603
604            et = getAttributionUrl(e)
605            jt = getAttributionUrl(j)
606            if (!et.equals(jt)) {
607                if (!jt) {
608                    myprintln "- Missing JOSM attribution URL (${et}): ${getDescription(j)}"
609                } else if (et) {
610                    def ethttps = et.replace("http:","https:")
611                    if(jt.equals(ethttps) || jt.equals(et+"/") || jt.equals(ethttps+"/")) {
612                        myprintln "+ Attribution URL differs ('${et}' != '${jt}'): ${getDescription(j)}"
613                    } else {
614                        myprintln "* Attribution URL differs ('${et}' != '${jt}'): ${getDescription(j)}"
615                    }
616                } else if (!options.nomissingeli) {
617                    myprintln "+ Missing ELI attribution URL ('${jt}'): ${getDescription(j)}"
618                }
619            }
620
621            et = getAttributionText(e)
622            jt = getAttributionText(j)
623            if (!et.equals(jt)) {
624                if (!jt) {
625                    myprintln "- Missing JOSM attribution text (${et}): ${getDescription(j)}"
626                } else if (et) {
627                    myprintln "* Attribution text differs ('${et}' != '${jt}'): ${getDescription(j)}"
628                } else if (!options.nomissingeli) {
629                    myprintln "+ Missing ELI attribution text ('${jt}'): ${getDescription(j)}"
630                }
631            }
632
633            et = getProjections(e)
634            jt = getProjections(j)
635            if (et) { et = new LinkedList(et); Collections.sort(et); et = String.join(" ", et) }
636            if (jt) { jt = new LinkedList(jt); Collections.sort(jt); jt = String.join(" ", jt) }
637            if (!et.equals(jt)) {
638                if (!jt) {
639                    def t = getType(e)
640                    if(t == "wms_endpoint" || t == "tms") {
641                        myprintln "+ ELI projections for type ${t}: ${getDescription(j)}"
642                    }
643                    else {
644                        myprintln "- Missing JOSM projections (${et}): ${getDescription(j)}"
645                    }
646                } else if (et) {
647                    if("EPSG:3857 EPSG:4326".equals(et) || "EPSG:3857".equals(et) || "EPSG:4326".equals(et)) {
648                        myprintln "+ ELI has minimal projections ('${et}' != '${jt}'): ${getDescription(j)}"
649                    } else {
650                        myprintln "* Projections differ ('${et}' != '${jt}'): ${getDescription(j)}"
651                    }
652                } else if (!options.nomissingeli && !getType(e).equals("tms")) {
653                    myprintln "+ Missing ELI projections ('${jt}'): ${getDescription(j)}"
654                }
655            }
656
657            et = getDefault(e)
658            jt = getDefault(j)
659            if (!et.equals(jt)) {
660                if (!jt) {
661                    myprintln "- Missing JOSM default: ${getDescription(j)}"
662                } else if (!options.nomissingeli) {
663                    myprintln "+ Missing ELI default: ${getDescription(j)}"
664                }
665            }
666            et = getOverlay(e)
667            jt = getOverlay(j)
668            if (!et.equals(jt)) {
669                if (!jt) {
670                    myprintln "- Missing JOSM overlay flag: ${getDescription(j)}"
671                } else if (!options.nomissingeli) {
672                    myprintln "+ Missing ELI overlay flag: ${getDescription(j)}"
673                }
674            }
675        }
676        myprintln "*** Mismatching shapes: ***"
677        for (def url : josmUrls.keySet()) {
678            def j = josmUrls.get(url)
679            def num = 1
680            for (def shape : getShapes(j)) {
681                def p = shape.getPoints()
682                if(!p[0].equals(p[p.size()-1])) {
683                    myprintln "+++ JOSM shape $num unclosed: ${getDescription(j)}"
684                }
685                for (def nump = 1; nump < p.size(); ++nump) {
686                    if (p[nump-1] == p[nump]) {
687                        myprintln "+++ JOSM shape $num double point at ${nump-1}: ${getDescription(j)}"
688                    }
689                }
690                ++num
691            }
692        }
693        for (def url : eliUrls.keySet()) {
694            def e = eliUrls.get(url)
695            def num = 1
696            def s = getShapes(e)
697            for (def shape : s) {
698                def p = shape.getPoints()
699                if(!p[0].equals(p[p.size()-1]) && !options.nomissingeli) {
700                    myprintln "+++ ELI shape $num unclosed: ${getDescription(e)}"
701                }
702                for (def nump = 1; nump < p.size(); ++nump) {
703                    if (p[nump-1] == p[nump]) {
704                        myprintln "+++ ELI shape $num double point at ${nump-1}: ${getDescription(e)}"
705                    }
706                }
707                ++num
708            }
709            if (!josmUrls.containsKey(url)) {
710                continue
711            }
712            def j = josmUrls.get(url)
713            def js = getShapes(j)
714            if(!s.size() && js.size()) {
715                if(!options.nomissingeli) {
716                    myprintln "+ No ELI shape: ${getDescription(j)}"
717                }
718            } else if(!js.size() && s.size()) {
719                // don't report boundary like 5 point shapes as difference
720                if (s.size() != 1 || s[0].getPoints().size() != 5) {
721                    myprintln "- No JOSM shape: ${getDescription(j)}"
722                }
723            } else if(s.size() != js.size()) {
724                myprintln "* Different number of shapes (${s.size()} != ${js.size()}): ${getDescription(j)}"
725            } else {
726                for(def nums = 0; nums < s.size(); ++nums) {
727                    def ep = s[nums].getPoints()
728                    def jp = js[nums].getPoints()
729                    if(ep.size() != jp.size()) {
730                        myprintln "* Different number of points for shape ${nums+1} (${ep.size()} ! = ${jp.size()})): ${getDescription(j)}"
731                    } else {
732                        for(def nump = 0; nump < ep.size(); ++nump) {
733                            def ept = ep[nump]
734                            def jpt = jp[nump]
735                            if(Math.abs(ept.getLat()-jpt.getLat()) > 0.000001 || Math.abs(ept.getLon()-jpt.getLon()) > 0.000001) {
736                                myprintln "* Different coordinate for point ${nump+1} of shape ${nums+1}: ${getDescription(j)}"
737                                nump = ep.size()
738                                num = s.size()
739                            }
740                        }
741                    }
742                }
743            }
744        }
745        myprintln "*** Mismatching icons: ***"
746        for (def url : eliUrls.keySet()) {
747            def e = eliUrls.get(url)
748            if (!josmUrls.containsKey(url)) {
749                continue
750            }
751            def j = josmUrls.get(url)
752            def ij = getIcon(j)
753            def ie = getIcon(e)
754            if(ij != null && ie == null) {
755                if(!options.nomissingeli) {
756                    myprintln "+ No ELI icon: ${getDescription(j)}"
757                }
758            } else if(ij == null && ie != null) {
759                myprintln "- No JOSM icon: ${getDescription(j)}"
760            } else if(!ij.equals(ie)) {
761                myprintln "* Different icons: ${getDescription(j)}"
762            }
763        }
764        myprintln "*** Miscellaneous checks: ***"
765        def josmIds = new HashMap<String, ImageryInfo>()
766        def all = Projections.getAllProjectionCodes()
767        DomainValidator dv = DomainValidator.getInstance();
768        for (def url : josmUrls.keySet()) {
769            def j = josmUrls.get(url)
770            def id = getId(j)
771            if("wms".equals(getType(j))) {
772                if(!getProjections(j)) {
773                    myprintln "* WMS without projections: ${getDescription(j)}"
774                } else {
775                    def unsupported = new LinkedList<String>()
776                    def old = new LinkedList<String>()
777                    for (def p : getProjectionsUnstripped(j)) {
778                        if("CRS:84".equals(p)) {
779                            if(!(url =~ /(?i)version=1\.3/)) {
780                                myprintln "* CRS:84 without WMS 1.3: ${getDescription(j)}"
781                            }
782                        } else if(oldproj.containsKey(p)) {
783                            old.add(p)
784                        } else if(!all.contains(p) && !ignoreproj.contains(p)) {
785                            unsupported.add(p)
786                        }
787                    }
788                    if (unsupported) {
789                        def s = String.join(", ", unsupported)
790                        myprintln "* Projections ${s} not supported by JOSM: ${getDescription(j)}"
791                    }
792                    for (def o : old) {
793                        myprintln "* Projection ${o} is an old unsupported code and has been replaced by ${oldproj.get(o)}: ${getDescription(j)}"
794                    }
795                }
796                if((url =~ /(?i)version=1\.3/) && !(url =~ /[Cc][Rr][Ss]=\{proj\}/)) {
797                    myprintln "* WMS 1.3 with strange CRS specification: ${getDescription(j)}"
798                }
799                if((url =~ /(?i)version=1\.1/) && !(url =~ /[Ss][Rr][Ss]=\{proj\}/)) {
800                    myprintln "* WMS 1.1 with strange SRS specification: ${getDescription(j)}"
801                }
802            }
803            def urls = new LinkedList<String>()
804            if(!"scanex".equals(getType(j))) {
805              urls += url
806            }
807            def jt = getPermissionReferenceUrl(j)
808            if(jt && !"Public Domain".equals(jt))
809              urls += jt
810            jt = getTermsOfUseUrl(j)
811            if(jt)
812              urls += jt
813            jt = getAttributionUrl(j)
814            if(jt)
815              urls += jt
816            jt = getIcon(j)
817            if(jt && !(jt =~ /^data:image\/png;base64,/))
818              urls += jt
819            for(def u : urls) {
820                def m = u =~ /^https?:\/\/([^\/]+?)(:\d+)?\//
821                if(!m)
822                    myprintln "* Strange URL '${u}': ${getDescription(j)}"
823                else {
824                    def domain = m[0][1].replaceAll("\\{switch:.*\\}","x")
825                    def port = m[0][2]
826                    if (!(domain =~ /^\d+\.\d+\.\d+\.\d+$/) && !dv.isValid(domain))
827                        myprintln "* Strange Domain '${domain}': ${getDescription(j)}"
828                    else if (port != null && (port == ":80" || port == ":443")) {
829                        myprintln "* Useless port '${port}': ${getDescription(j)}"
830                    }
831                }
832            }
833
834            if(josmMirrors.containsKey(url)) {
835                continue
836            }
837            if(id == null) {
838                myprintln "* No JOSM-ID: ${getDescription(j)}"
839            } else if(josmIds.containsKey(id)) {
840                myprintln "* JOSM-ID ${id} not unique: ${getDescription(j)}"
841            } else {
842                josmIds.put(id, j)
843            }
844            def d = getDate(j)
845            if(!d.isEmpty()) {
846                def reg = (d =~ /^(-|(\d\d\d\d)(-(\d\d)(-(\d\d))?)?)(;(-|(\d\d\d\d)(-(\d\d)(-(\d\d))?)?))?$/)
847                if(reg == null || reg.count != 1) {
848                    myprintln "* JOSM-Date '${d}' is strange: ${getDescription(j)}"
849                } else {
850                    try {
851                        def first = verifyDate(reg[0][2],reg[0][4],reg[0][6])
852                        def second = verifyDate(reg[0][9],reg[0][11],reg[0][13])
853                        if(second.compareTo(first) < 0) {
854                            myprintln "* JOSM-Date '${d}' is strange (second earlier than first): ${getDescription(j)}"
855                        }
856                    }
857                    catch (Exception e) {
858                        myprintln "* JOSM-Date '${d}' is strange (${e.getMessage()}): ${getDescription(j)}"
859                    }
860                }
861            }
862            if(getAttributionUrl(j) && !getAttributionText(j)) {
863                myprintln "* Attribution link without text: ${getDescription(j)}"
864            }
865            if(getLogoUrl(j) && !getLogoImage(j)) {
866                myprintln "* Logo link without image: ${getDescription(j)}"
867            }
868            if(getTermsOfUseText(j) && !getTermsOfUseUrl(j)) {
869                myprintln "* Terms of Use text without link: ${getDescription(j)}"
870            }
871            def js = getShapes(j)
872            if(js.size()) {
873                def minlat = 1000
874                def minlon = 1000
875                def maxlat = -1000
876                def maxlon = -1000
877                for(def s: js) {
878                    for(def p: s.getPoints()) {
879                        def lat = p.getLat()
880                        def lon = p.getLon()
881                        if(lat > maxlat) maxlat = lat
882                        if(lon > maxlon) maxlon = lon
883                        if(lat < minlat) minlat = lat
884                        if(lon < minlon) minlon = lon
885                    }
886                }
887                def b = j.getBounds()
888                if(b.getMinLat() != minlat || b.getMinLon() != minlon || b.getMaxLat() != maxlat || b.getMaxLon() != maxlon) {
889                    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)}"
890                }
891            }
892        }
893    }
894
895    /**
896     * Utility functions that allow uniform access for both ImageryInfo and JsonObject.
897     */
898    static String getUrl(Object e) {
899        if (e instanceof ImageryInfo) return e.url
900        return e.get("properties").getString("url")
901    }
902    static String getUrlStripped(Object e) {
903        return getUrl(e).replaceAll("\\?(apikey|access_token)=.*","")
904    }
905    static String getDate(Object e) {
906        if (e instanceof ImageryInfo) return e.date ? e.date : ""
907        def p = e.get("properties")
908        def start = p.containsKey("start_date") ? p.getString("start_date") : ""
909        def end = p.containsKey("end_date") ? p.getString("end_date") : ""
910        if(!start.isEmpty() && !end.isEmpty())
911            return start+";"+end
912        else if(!start.isEmpty())
913            return start+";-"
914        else if(!end.isEmpty())
915            return "-;"+end
916        return ""
917    }
918    static Date verifyDate(String year, String month, String day) {
919        def date
920        if(year == null) {
921            date = "3000-01-01"
922        } else {
923            date = year + "-" + (month == null ? "01" : month) + "-" + (day == null ? "01" : day)
924        }
925        def df = new java.text.SimpleDateFormat("yyyy-MM-dd")
926        df.setLenient(false)
927        return df.parse(date)
928    }
929    static String getId(Object e) {
930        if (e instanceof ImageryInfo) return e.getId()
931        return e.get("properties").getString("id")
932    }
933    static String getName(Object e) {
934        if (e instanceof ImageryInfo) return e.getOriginalName()
935        return e.get("properties").getString("name")
936    }
937    static List<Object> getMirrors(Object e) {
938        if (e instanceof ImageryInfo) return e.getMirrors()
939        return []
940    }
941    static List<Object> getProjections(Object e) {
942        def r = []
943        def u = getProjectionsUnstripped(e)
944        if(u) {
945            for (def p : u) {
946                if(!oldproj.containsKey(p) && !("CRS:84".equals(p) && !(getUrlStripped(e) =~ /(?i)version=1\.3/))) {
947                    r += p
948                }
949            }
950        }
951        return r
952    }
953    static List<Object> getProjectionsUnstripped(Object e) {
954        def r
955        if (e instanceof ImageryInfo) {
956            r = e.getServerProjections()
957        } else {
958            def s = e.get("properties").get("available_projections")
959            if (s) {
960                r = []
961                for (def p : s) {
962                    r += p.getString()
963                }
964            }
965        }
966        return r ? r : []
967    }
968    static List<Shape> getShapes(Object e) {
969        if (e instanceof ImageryInfo) {
970            def bounds = e.getBounds()
971            if(bounds != null) {
972                return bounds.getShapes()
973            }
974            return []
975        }
976        if(!e.isNull("geometry")) {
977            def ex = e.get("geometry")
978            if(ex != null && !ex.isNull("coordinates")) {
979                def poly = ex.get("coordinates")
980                List<Shape> l = []
981                for(def shapes: poly) {
982                    def s = new Shape()
983                    for(def point: shapes) {
984                        def lon = point[0].toString()
985                        def lat = point[1].toString()
986                        s.addPoint(lat, lon)
987                    }
988                    l.add(s)
989                }
990                return l
991            }
992        }
993        return []
994    }
995    static String getType(Object e) {
996        if (e instanceof ImageryInfo) return e.getImageryType().getTypeString()
997        return e.get("properties").getString("type")
998    }
999    static Integer getMinZoom(Object e) {
1000        if (e instanceof ImageryInfo) {
1001            if("wms".equals(getType(e)) && e.getName() =~ / mirror/)
1002                return null;
1003            int mz = e.getMinZoom()
1004            return mz == 0 ? null : mz
1005        } else {
1006            def num = e.get("properties").getJsonNumber("min_zoom")
1007            if (num == null) return null
1008            return num.intValue()
1009        }
1010    }
1011    static Integer getMaxZoom(Object e) {
1012        if (e instanceof ImageryInfo) {
1013            if("wms".equals(getType(e)) && e.getName() =~ / mirror/)
1014                return null;
1015            int mz = e.getMaxZoom()
1016            return mz == 0 ? null : mz
1017        } else {
1018            def num = e.get("properties").getJsonNumber("max_zoom")
1019            if (num == null) return null
1020            return num.intValue()
1021        }
1022    }
1023    static String getCountryCode(Object e) {
1024        if (e instanceof ImageryInfo) return "".equals(e.getCountryCode()) ? null : e.getCountryCode()
1025        return e.get("properties").getString("country_code", null)
1026    }
1027    static String getQuality(Object e) {
1028        if (e instanceof ImageryInfo) return e.isBestMarked() ? "eli-best" : null
1029        return (e.get("properties").containsKey("best")
1030            && e.get("properties").getBoolean("best")) ? "eli-best" : null
1031    }
1032    static Boolean getOverlay(Object e) {
1033        if (e instanceof ImageryInfo) return e.isOverlay()
1034        return (e.get("properties").containsKey("overlay")
1035            && e.get("properties").getBoolean("overlay"))
1036    }
1037    static String getIcon(Object e) {
1038        if (e instanceof ImageryInfo) return e.getIcon()
1039        return e.get("properties").getString("icon", null)
1040    }
1041    static String getAttributionText(Object e) {
1042        if (e instanceof ImageryInfo) return e.getAttributionText(0, null, null)
1043        try {return e.get("properties").get("attribution").getString("text", null)} catch (NullPointerException ex) {return null}
1044    }
1045    static String getAttributionUrl(Object e) {
1046        if (e instanceof ImageryInfo) return e.getAttributionLinkURL()
1047        try {return e.get("properties").get("attribution").getString("url", null)} catch (NullPointerException ex) {return null}
1048    }
1049    static String getTermsOfUseText(Object e) {
1050        if (e instanceof ImageryInfo) return e.getTermsOfUseText()
1051        return null
1052    }
1053    static String getTermsOfUseUrl(Object e) {
1054        if (e instanceof ImageryInfo) return e.getTermsOfUseURL()
1055        return null
1056    }
1057    static String getLogoImage(Object e) {
1058        if (e instanceof ImageryInfo) return e.getAttributionImageRaw()
1059        return null
1060    }
1061    static String getLogoUrl(Object e) {
1062        if (e instanceof ImageryInfo) return e.getAttributionImageURL()
1063        return null
1064    }
1065    static String getPermissionReferenceUrl(Object e) {
1066        if (e instanceof ImageryInfo) return e.getPermissionReferenceURL()
1067        return e.get("properties").getString("license_url", null)
1068    }
1069    static Map<String,String> getDescriptions(Object e) {
1070        Map<String,String> res = new HashMap<String, String>()
1071        if (e instanceof ImageryInfo) {
1072          String a = e.getDescription()
1073          if (a) res.put("en", a)
1074        } else {
1075          String a = e.get("properties").getString("description", null)
1076          if (a) res.put("en", a)
1077        }
1078        return res
1079    }
1080    static Boolean getValidGeoreference(Object e) {
1081        if (e instanceof ImageryInfo) return e.isGeoreferenceValid()
1082        return false
1083    }
1084    static Boolean getDefault(Object e) {
1085        if (e instanceof ImageryInfo) return e.isDefaultEntry()
1086        return e.get("properties").getBoolean("default", false)
1087    }
1088    String getDescription(Object o) {
1089        def url = getUrl(o)
1090        def cc = getCountryCode(o)
1091        if (cc == null) {
1092            def j = josmUrls.get(url)
1093            if (j != null) cc = getCountryCode(j)
1094            if (cc == null) {
1095                def e = eliUrls.get(url)
1096                if (e != null) cc = getCountryCode(e)
1097            }
1098        }
1099        if (cc == null) {
1100            cc = ''
1101        } else {
1102            cc = "[$cc] "
1103        }
1104        def d = cc + getName(o) + " - " + getUrl(o)
1105        if (options.shorten) {
1106            def MAXLEN = 140
1107            if (d.length() > MAXLEN) d = d.substring(0, MAXLEN-1) + "..."
1108        }
1109        return d
1110    }
1111}
Note: See TracBrowser for help on using the repository browser.