source: josm/trunk/scripts/TagInfoExtract.java@ 19137

Last change on this file since 19137 was 19113, checked in by taylor.smock, 3 months ago

Update PMD to 7.2.0

A bunch of rules were deprecated and replaced and the XPath expressions had to be updated from XPath 1 to XPath 3.

File size: 27.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2
3import java.awt.Graphics2D;
4import java.awt.image.BufferedImage;
5import java.io.BufferedReader;
6import java.io.IOException;
7import java.io.OutputStream;
8import java.io.StringWriter;
9import java.io.UncheckedIOException;
10import java.io.Writer;
11import java.nio.file.Files;
12import java.nio.file.Path;
13import java.nio.file.Paths;
14import java.time.Instant;
15import java.time.ZoneId;
16import java.time.format.DateTimeFormatter;
17import java.util.ArrayList;
18import java.util.Arrays;
19import java.util.Collection;
20import java.util.Collections;
21import java.util.EnumSet;
22import java.util.HashSet;
23import java.util.LinkedHashMap;
24import java.util.List;
25import java.util.Locale;
26import java.util.Map;
27import java.util.Optional;
28import java.util.Set;
29import java.util.regex.Matcher;
30import java.util.regex.Pattern;
31import java.util.stream.Collectors;
32import java.util.stream.Stream;
33
34import javax.imageio.ImageIO;
35
36import org.openstreetmap.josm.actions.DeleteAction;
37import org.openstreetmap.josm.command.DeleteCommand;
38import org.openstreetmap.josm.data.Preferences;
39import org.openstreetmap.josm.data.Version;
40import org.openstreetmap.josm.data.coor.LatLon;
41import org.openstreetmap.josm.data.osm.Node;
42import org.openstreetmap.josm.data.osm.OsmPrimitive;
43import org.openstreetmap.josm.data.osm.Tag;
44import org.openstreetmap.josm.data.osm.Way;
45import org.openstreetmap.josm.data.osm.visitor.paint.MapPaintSettings;
46import org.openstreetmap.josm.data.osm.visitor.paint.StyledMapRenderer;
47import org.openstreetmap.josm.data.preferences.JosmBaseDirectories;
48import org.openstreetmap.josm.data.preferences.JosmUrls;
49import org.openstreetmap.josm.data.preferences.sources.ExtendedSourceEntry;
50import org.openstreetmap.josm.data.preferences.sources.SourceEntry;
51import org.openstreetmap.josm.data.projection.ProjectionRegistry;
52import org.openstreetmap.josm.data.projection.Projections;
53import org.openstreetmap.josm.gui.NavigatableComponent;
54import org.openstreetmap.josm.gui.mappaint.Cascade;
55import org.openstreetmap.josm.gui.mappaint.Environment;
56import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
57import org.openstreetmap.josm.gui.mappaint.MultiCascade;
58import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory;
59import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule;
60import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
61import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser;
62import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.ParseException;
63import org.openstreetmap.josm.gui.mappaint.styleelement.AreaElement;
64import org.openstreetmap.josm.gui.mappaint.styleelement.LineElement;
65import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement;
66import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
67import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset;
68import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetReader;
69import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetType;
70import org.openstreetmap.josm.gui.tagging.presets.items.CheckGroup;
71import org.openstreetmap.josm.gui.tagging.presets.items.KeyedItem;
72import org.openstreetmap.josm.io.CachedFile;
73import org.openstreetmap.josm.io.OsmTransferException;
74import org.openstreetmap.josm.spi.preferences.Config;
75import org.openstreetmap.josm.tools.Http1Client;
76import org.openstreetmap.josm.tools.HttpClient;
77import org.openstreetmap.josm.tools.Logging;
78import org.openstreetmap.josm.tools.OptionParser;
79import org.openstreetmap.josm.tools.Territories;
80import org.openstreetmap.josm.tools.Utils;
81import org.xml.sax.SAXException;
82
83import jakarta.json.Json;
84import jakarta.json.JsonArrayBuilder;
85import jakarta.json.JsonObjectBuilder;
86import jakarta.json.JsonWriter;
87import jakarta.json.stream.JsonGenerator;
88
89/**
90 * Extracts tag information for the taginfo project.
91 * <p>
92 * Run from the base directory of a JOSM checkout:
93 * <p>
94 * <pre>
95 * java -cp dist/josm-custom.jar TagInfoExtract --type mappaint
96 * java -cp dist/josm-custom.jar TagInfoExtract --type presets
97 * java -cp dist/josm-custom.jar TagInfoExtract --type external_presets
98 * </pre>
99 */
100public class TagInfoExtract {
101
102 /**
103 * Main method.
104 * @param args Main program arguments
105 * @throws IOException if an IO exception occurs
106 * @throws OsmTransferException if something happened when communicating with the OSM server
107 * @throws ParseException if there was an issue parsing MapCSS
108 * @throws SAXException if there was an issue parsing XML
109 */
110 public static void main(String[] args) throws IOException, OsmTransferException, ParseException, SAXException {
111 HttpClient.setFactory(Http1Client::new);
112 TagInfoExtract script = new TagInfoExtract();
113 script.parseCommandLineArguments(args);
114 script.init();
115 switch (script.options.mode) {
116 case MAPPAINT:
117 script.new StyleSheet().run();
118 break;
119 case PRESETS:
120 script.new Presets().run();
121 break;
122 case EXTERNAL_PRESETS:
123 script.new ExternalPresets().run();
124 break;
125 default:
126 throw new IllegalStateException("Invalid type " + script.options.mode);
127 }
128 if (!script.options.noexit) {
129 System.exit(0);
130 }
131 }
132
133 enum Mode {
134 MAPPAINT, PRESETS, EXTERNAL_PRESETS
135 }
136
137 private final Options options = new Options();
138
139 /**
140 * Parse command line arguments.
141 * @param args command line arguments
142 */
143 private void parseCommandLineArguments(String[] args) {
144 if (args.length == 1 && "--help".equals(args[0])) {
145 this.usage();
146 }
147 final OptionParser parser = new OptionParser(getClass().getName());
148 parser.addArgumentParameter("type", OptionParser.OptionCount.REQUIRED, options::setMode);
149 parser.addArgumentParameter("input", OptionParser.OptionCount.OPTIONAL, options::setInputFile);
150 parser.addArgumentParameter("output", OptionParser.OptionCount.OPTIONAL, options::setOutputFile);
151 parser.addArgumentParameter("imgdir", OptionParser.OptionCount.OPTIONAL, options::setImageDir);
152 parser.addArgumentParameter("imgurlprefix", OptionParser.OptionCount.OPTIONAL, options::setImageUrlPrefix);
153 parser.addFlagParameter("noexit", options::setNoExit);
154 parser.addFlagParameter("help", this::usage);
155 parser.parseOptionsOrExit(Arrays.asList(args));
156 }
157
158 private void usage() {
159 System.out.println("java " + getClass().getName());
160 System.out.println(" --type TYPE\tthe project type to be generated: " + Arrays.toString(Mode.values()));
161 System.out.println(" --input FILE\tthe input file to use (overrides defaults for types mappaint, presets)");
162 System.out.println(" --output FILE\tthe output file to use (defaults to STDOUT)");
163 System.out.println(" --imgdir DIRECTORY\tthe directory to put the generated images in (default: " + options.imageDir + ")");
164 System.out.println(" --imgurlprefix STRING\timage URLs prefix for generated image files (public path on webserver)");
165 System.out.println(" --noexit\tdo not call System.exit(), for use from Ant script");
166 System.out.println(" --help\tshow this help");
167 System.exit(0);
168 }
169
170 private static final class Options {
171 Mode mode;
172 int josmSvnRevision = Version.getInstance().getVersion();
173 Path baseDir = Paths.get("");
174 Path imageDir = Paths.get("taginfo-img");
175 String imageUrlPrefix;
176 CachedFile inputFile;
177 Path outputFile;
178 boolean noexit;
179
180 void setMode(String value) {
181 mode = Mode.valueOf(value.toUpperCase(Locale.ENGLISH));
182 switch (mode) {
183 case MAPPAINT:
184 inputFile = new CachedFile("resource://styles/standard/elemstyles.mapcss");
185 break;
186 case PRESETS:
187 inputFile = new CachedFile("resource://data/defaultpresets.xml");
188 break;
189 default:
190 inputFile = null;
191 }
192 }
193
194 void setInputFile(String value) {
195 inputFile = new CachedFile(value);
196 }
197
198 void setOutputFile(String value) {
199 outputFile = Paths.get(value);
200 }
201
202 void setImageDir(String value) {
203 imageDir = Paths.get(value);
204 }
205
206 void setImageUrlPrefix(String value) {
207 imageUrlPrefix = value;
208 }
209
210 void setNoExit() {
211 noexit = true;
212 }
213
214 /**
215 * Determine full image url (can refer to JOSM or OSM repository).
216 * @param path the image path
217 * @return full image url
218 */
219 private String findImageUrl(String path) {
220 final Path f = baseDir.resolve("resources").resolve("images").resolve(path);
221 if (Files.exists(f)) {
222 return "https://josm.openstreetmap.de/export/" + josmSvnRevision + "/josm/trunk/resources/images/" + path;
223 }
224 throw new IllegalStateException("Cannot find image url for " + path);
225 }
226 }
227
228 private abstract class Extractor {
229 abstract void run() throws IOException, OsmTransferException, ParseException, SAXException;
230
231 void writeJson(String name, String description, Iterable<TagInfoTag> tags) throws IOException {
232 try (Writer writer = options.outputFile != null ? Files.newBufferedWriter(options.outputFile) : new StringWriter();
233 JsonWriter json = Json
234 .createWriterFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true))
235 .createWriter(writer)) {
236 JsonObjectBuilder project = Json.createObjectBuilder()
237 .add("name", name)
238 .add("description", description)
239 .add("project_url", JosmUrls.getInstance().getJOSMWebsite())
240 .add("icon_url", options.findImageUrl("logo_16x16x8.png"))
241 .add("contact_name", "JOSM developer team")
242 .add("contact_email", "josm-dev@openstreetmap.org");
243 final JsonArrayBuilder jsonTags = Json.createArrayBuilder();
244 for (TagInfoTag t : tags) {
245 jsonTags.add(t.toJson());
246 }
247 json.writeObject(Json.createObjectBuilder()
248 .add("data_format", 1)
249 .add("data_updated", DateTimeFormatter.ofPattern("yyyyMMdd'T'hhmmss'Z'").withZone(ZoneId.of("Z")).format(Instant.now()))
250 .add("project", project)
251 .add("tags", jsonTags)
252 .build());
253 if (options.outputFile == null) {
254 System.out.println(writer);
255 }
256 }
257 }
258 }
259
260 private class Presets extends Extractor {
261
262 @Override
263 void run() throws IOException, OsmTransferException, SAXException {
264 try (BufferedReader reader = options.inputFile.getContentReader()) {
265 Collection<TaggingPreset> presets = TaggingPresetReader.readAll(reader, true);
266 List<TagInfoTag> tags = convertPresets(presets, "", true);
267 Logging.info("Converting {0} internal presets", tags.size());
268 writeJson("JOSM main presets", "Tags supported by the default presets in the OSM editor JOSM", tags);
269 }
270 }
271
272 List<TagInfoTag> convertPresets(Iterable<TaggingPreset> presets, String descriptionPrefix, boolean addImages) {
273 final List<TagInfoTag> tags = new ArrayList<>();
274 final Map<Tag, TagInfoTag> requiredTags = new LinkedHashMap<>();
275 final Map<Tag, TagInfoTag> optionalTags = new LinkedHashMap<>();
276 for (TaggingPreset preset : presets) {
277 preset.data.stream()
278 .flatMap(item -> item instanceof KeyedItem
279 ? Stream.of(((KeyedItem) item))
280 : item instanceof CheckGroup
281 ? ((CheckGroup) item).checks.stream()
282 : Stream.empty())
283 .forEach(item -> {
284 for (String value : values(item)) {
285 Set<TagInfoTag.Type> types = TagInfoTag.Type.forPresetTypes(preset.types);
286 if (item.isKeyRequired()) {
287 fillTagsMap(requiredTags, item, value, preset.getName(), types,
288 descriptionPrefix + TagInfoTag.REQUIRED_FOR_COUNT + ": ",
289 addImages && preset.iconName != null ? options.findImageUrl(preset.iconName) : null);
290 } else {
291 fillTagsMap(optionalTags, item, value, preset.getName(), types,
292 descriptionPrefix + TagInfoTag.OPTIONAL_FOR_COUNT + ": ", null);
293 }
294 }
295 });
296 }
297 tags.addAll(requiredTags.values());
298 tags.addAll(optionalTags.values());
299 return tags;
300 }
301
302 private void fillTagsMap(Map<Tag, TagInfoTag> optionalTags, KeyedItem item, String value,
303 String presetName, Set<TagInfoTag.Type> types, String descriptionPrefix, String iconUrl) {
304 optionalTags.compute(new Tag(item.key, value), (osmTag, tagInfoTag) -> {
305 if (tagInfoTag == null) {
306 return new TagInfoTag(descriptionPrefix + presetName, item.key, value, types, iconUrl);
307 } else {
308 tagInfoTag.descriptions.add(presetName);
309 tagInfoTag.objectTypes.addAll(types);
310 return tagInfoTag;
311 }
312 });
313 }
314
315 private Collection<String> values(KeyedItem item) {
316 final Collection<String> values = item.getValues();
317 return values.isEmpty() || values.size() > 50 ? Collections.singleton(null) : values;
318 }
319 }
320
321 private final class ExternalPresets extends Presets {
322
323 @Override
324 void run() throws IOException, OsmTransferException, SAXException {
325 TaggingPresetReader.setLoadIcons(false);
326 final Collection<ExtendedSourceEntry> sources = new TaggingPresetPreference.TaggingPresetSourceEditor().loadAndGetAvailableSources();
327 final List<TagInfoTag> tags = new ArrayList<>();
328 for (SourceEntry source : sources) {
329 if (source.url.startsWith("resource")) {
330 // default presets
331 continue;
332 }
333 try {
334 Logging.info("Loading {0}", source.url);
335 Collection<TaggingPreset> presets = TaggingPresetReader.readAll(source.url, false);
336 final List<TagInfoTag> t = convertPresets(presets, source.title + " ", false);
337 Logging.info("Converted {0} presets of {1} to {2} tags", presets.size(), source.title, t.size());
338 tags.addAll(t);
339 } catch (Exception ex) {
340 Logging.warn("Skipping {0} due to error", source.url);
341 Logging.warn(ex);
342 }
343 }
344 writeJson("JOSM user presets", "Tags supported by the user contributed presets to the OSM editors JOSM and Vespucci", tags);
345 }
346 }
347
348 private final class StyleSheet extends Extractor {
349 private MapCSSStyleSource styleSource;
350
351 @Override
352 void run() throws IOException, ParseException {
353 init();
354 parseStyleSheet();
355 final List<TagInfoTag> tags = convertStyleSheet();
356 writeJson("JOSM main mappaint style", "Tags supported by the main mappaint style in the OSM editor JOSM", tags);
357 }
358
359 /**
360 * Read the style sheet file and parse the MapCSS code.
361 * @throws IOException if any I/O error occurs
362 * @throws ParseException in case of parsing error
363 */
364 private void parseStyleSheet() throws IOException, ParseException {
365 try (BufferedReader reader = options.inputFile.getContentReader()) {
366 MapCSSParser parser = new MapCSSParser(reader, MapCSSParser.LexicalState.DEFAULT);
367 styleSource = new MapCSSStyleSource("");
368 styleSource.url = "";
369 parser.sheet(styleSource);
370 }
371 }
372
373 /**
374 * Collect all the tag from the style sheet.
375 * @return list of taginfo tags
376 */
377 private List<TagInfoTag> convertStyleSheet() {
378 return styleSource.rules.stream()
379 .flatMap(rule -> rule.selectors.stream())
380 .flatMap(selector -> selector.getConditions().stream())
381 .filter(ConditionFactory.SimpleKeyValueCondition.class::isInstance)
382 .map(ConditionFactory.SimpleKeyValueCondition.class::cast)
383 .map(condition -> condition.asTag(null))
384 .distinct()
385 .map(tag -> {
386 String iconUrl = null;
387 final EnumSet<TagInfoTag.Type> types = EnumSet.noneOf(TagInfoTag.Type.class);
388 Optional<String> nodeUrl = new NodeChecker(tag).findUrl(true);
389 if (nodeUrl.isPresent()) {
390 iconUrl = nodeUrl.get();
391 types.add(TagInfoTag.Type.NODE);
392 }
393 Optional<String> wayUrl = new WayChecker(tag).findUrl(iconUrl == null);
394 if (wayUrl.isPresent()) {
395 if (iconUrl == null) {
396 iconUrl = wayUrl.get();
397 }
398 types.add(TagInfoTag.Type.WAY);
399 }
400 Optional<String> areaUrl = new AreaChecker(tag).findUrl(iconUrl == null);
401 if (areaUrl.isPresent()) {
402 if (iconUrl == null) {
403 iconUrl = areaUrl.get();
404 }
405 types.add(TagInfoTag.Type.AREA);
406 }
407 return new TagInfoTag(null, tag.getKey(), tag.getValue(), types, iconUrl);
408 })
409 .collect(Collectors.toList());
410 }
411
412 /**
413 * Check if a certain tag is supported by the style as node / way / area.
414 */
415 private abstract class Checker {
416 private final Pattern reservedChars = Pattern.compile("[<>:\"|\\?\\*]");
417
418 Checker(Tag tag) {
419 this.tag = tag;
420 }
421
422 Environment applyStylesheet(OsmPrimitive osm) {
423 osm.put(tag);
424 MultiCascade mc = new MultiCascade();
425
426 Environment env = new Environment(osm, mc, null, styleSource);
427 for (MapCSSRule r : styleSource.rules) {
428 env.clearSelectorMatchingInformation();
429 if (r.matches(env)) {
430 // ignore selector range
431 if (env.layer == null) {
432 env.layer = "default";
433 }
434 r.execute(env);
435 }
436 }
437 env.layer = "default";
438 return env;
439 }
440
441 /**
442 * Create image file from StyleElement.
443 * @param element style element
444 * @param type object type
445 * @param nc navigable component
446 *
447 * @return the URL
448 */
449 String createImage(StyleElement element, final String type, NavigatableComponent nc) {
450 BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
451 Graphics2D g = img.createGraphics();
452 g.setClip(0, 0, 16, 16);
453 StyledMapRenderer renderer = new StyledMapRenderer(g, nc, false);
454 renderer.getSettings(false);
455 element.paintPrimitive(osm, MapPaintSettings.INSTANCE, renderer, false, false, false);
456 final String imageName = type + "_" + normalize(tag.toString()) + ".png";
457 try (OutputStream out = Files.newOutputStream(options.imageDir.resolve(imageName))) {
458 ImageIO.write(img, "png", out);
459 } catch (IOException e) {
460 throw new UncheckedIOException(e);
461 }
462 final String baseUrl = options.imageUrlPrefix != null ? options.imageUrlPrefix : options.imageDir.toString();
463 return baseUrl + "/" + imageName;
464 }
465
466 /**
467 * Normalizes tag so that it can used as a filename on all platforms, including Windows.
468 * @param tag OSM tag, that can contain illegal path characters
469 * @return OSM tag with all illegal path characters replaced by underscore ('_')
470 */
471 String normalize(String tag) {
472 Matcher m = reservedChars.matcher(tag);
473 return m.find() ? m.replaceAll("_") : tag;
474 }
475
476 /**
477 * Checks, if tag is supported and find URL for image icon in this case.
478 *
479 * @param generateImage if true, create or find a suitable image icon and return URL,
480 * if false, just check if tag is supported and return true or false
481 * @return URL for image icon if tag is supported
482 */
483 abstract Optional<String> findUrl(boolean generateImage);
484
485 protected Tag tag;
486 protected OsmPrimitive osm;
487 }
488
489 private class NodeChecker extends Checker {
490 NodeChecker(Tag tag) {
491 super(tag);
492 }
493
494 @Override
495 Optional<String> findUrl(boolean generateImage) {
496 this.osm = new Node(LatLon.ZERO);
497 Environment env = applyStylesheet(osm);
498 Cascade c = env.getCascade("default");
499 Object image = c.get("icon-image");
500 if (image instanceof MapPaintStyles.IconReference && !((MapPaintStyles.IconReference) image).isDeprecatedIcon()) {
501 return Optional.of(options.findImageUrl(((MapPaintStyles.IconReference) image).iconName));
502 }
503 return Optional.empty();
504 }
505 }
506
507 private class WayChecker extends Checker {
508 WayChecker(Tag tag) {
509 super(tag);
510 }
511
512 @Override
513 Optional<String> findUrl(boolean generateImage) {
514 this.osm = new Way();
515 NavigatableComponent nc = new NavigatableComponent();
516 Node n1 = new Node(nc.getLatLon(2, 8));
517 Node n2 = new Node(nc.getLatLon(14, 8));
518 ((Way) osm).addNode(n1);
519 ((Way) osm).addNode(n2);
520 Environment env = applyStylesheet(osm);
521 LineElement les = LineElement.createLine(env);
522 if (les != null) {
523 return Optional.of(generateImage ? createImage(les, "way", nc) : "");
524 }
525 return Optional.empty();
526 }
527 }
528
529 private class AreaChecker extends Checker {
530 AreaChecker(Tag tag) {
531 super(tag);
532 }
533
534 @Override
535 Optional<String> findUrl(boolean generateImage) {
536 this.osm = new Way();
537 NavigatableComponent nc = new NavigatableComponent();
538 Node n1 = new Node(nc.getLatLon(2, 2));
539 Node n2 = new Node(nc.getLatLon(14, 2));
540 Node n3 = new Node(nc.getLatLon(14, 14));
541 Node n4 = new Node(nc.getLatLon(2, 14));
542 ((Way) osm).addNode(n1);
543 ((Way) osm).addNode(n2);
544 ((Way) osm).addNode(n3);
545 ((Way) osm).addNode(n4);
546 ((Way) osm).addNode(n1);
547 Environment env = applyStylesheet(osm);
548 AreaElement aes = AreaElement.create(env);
549 if (aes != null) {
550 if (!generateImage) return Optional.of("");
551 return Optional.of(createImage(aes, "area", nc));
552 }
553 return Optional.empty();
554 }
555 }
556 }
557
558 /**
559 * POJO representing a <a href="https://wiki.openstreetmap.org/wiki/Taginfo/Projects">Taginfo tag</a>.
560 */
561 private static class TagInfoTag {
562 static final String REQUIRED_FOR_COUNT = "Required for {count}";
563 static final String OPTIONAL_FOR_COUNT = "Optional for {count}";
564 final Collection<String> descriptions = new ArrayList<>();
565 final String key;
566 final String value;
567 final Set<Type> objectTypes;
568 final String iconURL;
569
570 TagInfoTag(String description, String key, String value, Set<Type> objectTypes, String iconURL) {
571 if (description != null) {
572 this.descriptions.add(description);
573 }
574 this.key = key;
575 this.value = value;
576 this.objectTypes = objectTypes;
577 this.iconURL = iconURL;
578 }
579
580 JsonObjectBuilder toJson() {
581 final JsonObjectBuilder object = Json.createObjectBuilder();
582 if (!descriptions.isEmpty()) {
583 final int size = descriptions.size();
584 object.add("description", String.join(", ", Utils.limit(descriptions, 8, "..."))
585 .replace(REQUIRED_FOR_COUNT, size > 3 ? "Required for " + size : "Required for")
586 .replace(OPTIONAL_FOR_COUNT, size > 3 ? "Optional for " + size : "Optional for"));
587 }
588 object.add("key", key);
589 if (value != null) {
590 object.add("value", value);
591 }
592 if ((!objectTypes.isEmpty())) {
593 final JsonArrayBuilder types = Json.createArrayBuilder();
594 objectTypes.stream().map(Enum::name).map(String::toLowerCase).forEach(types::add);
595 object.add("object_types", types);
596 }
597 if (iconURL != null) {
598 object.add("icon_url", iconURL);
599 }
600 return object;
601 }
602
603 enum Type {
604 NODE, WAY, AREA, RELATION;
605
606 static TagInfoTag.Type forPresetType(TaggingPresetType type) {
607 switch (type) {
608 case CLOSEDWAY:
609 return AREA;
610 case MULTIPOLYGON:
611 return RELATION;
612 default:
613 return valueOf(type.toString());
614 }
615 }
616
617 static Set<TagInfoTag.Type> forPresetTypes(Set<TaggingPresetType> types) {
618 return types == null ? new HashSet<>() : types.stream()
619 .map(Type::forPresetType)
620 .collect(Collectors.toCollection(() -> EnumSet.noneOf(Type.class)));
621 }
622 }
623 }
624
625 /**
626 * Initialize the script.
627 * @throws IOException if any I/O error occurs
628 */
629 private void init() throws IOException {
630 Logging.setLogLevel(Logging.LEVEL_INFO);
631 Preferences.main().enableSaveOnPut(false);
632 Config.setPreferencesInstance(Preferences.main());
633 Config.setBaseDirectoriesProvider(JosmBaseDirectories.getInstance());
634 Config.setUrlsProvider(JosmUrls.getInstance());
635 ProjectionRegistry.setProjection(Projections.getProjectionByCode("EPSG:3857"));
636 Path tmpdir = Files.createTempDirectory(options.baseDir, "pref");
637 tmpdir.toFile().deleteOnExit();
638 System.setProperty("josm.home", tmpdir.toString());
639 DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback);
640 Territories.initializeInternalData();
641 Files.createDirectories(options.imageDir);
642 }
643}
Note: See TracBrowser for help on using the repository browser.