source: josm/trunk/src/org/openstreetmap/josm/tools/RightAndLefthandTraffic.java@ 14091

Last change on this file since 14091 was 14032, checked in by Don-vip, 6 years ago

fix #16489 - NPE at RightAndLefthandTraffic.isRightHandTraffic

  • Property svn:eol-style set to native
File size: 7.5 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import java.io.File;
5import java.io.IOException;
6import java.io.InputStream;
7import java.io.OutputStreamWriter;
8import java.io.PrintWriter;
9import java.io.Writer;
10import java.nio.charset.StandardCharsets;
11import java.nio.file.Files;
12import java.nio.file.InvalidPathException;
13import java.nio.file.Paths;
14import java.util.ArrayList;
15import java.util.Collection;
16import java.util.Collections;
17import java.util.List;
18import java.util.Set;
19
20import org.openstreetmap.josm.actions.JoinAreasAction;
21import org.openstreetmap.josm.actions.JoinAreasAction.JoinAreasResult;
22import org.openstreetmap.josm.actions.JoinAreasAction.Multipolygon;
23import org.openstreetmap.josm.command.PurgeCommand;
24import org.openstreetmap.josm.data.coor.LatLon;
25import org.openstreetmap.josm.data.osm.DataSet;
26import org.openstreetmap.josm.data.osm.DownloadPolicy;
27import org.openstreetmap.josm.data.osm.OsmPrimitive;
28import org.openstreetmap.josm.data.osm.Relation;
29import org.openstreetmap.josm.data.osm.RelationMember;
30import org.openstreetmap.josm.data.osm.UploadPolicy;
31import org.openstreetmap.josm.data.osm.Way;
32import org.openstreetmap.josm.io.IllegalDataException;
33import org.openstreetmap.josm.io.OsmReader;
34import org.openstreetmap.josm.io.OsmWriter;
35import org.openstreetmap.josm.io.OsmWriterFactory;
36import org.openstreetmap.josm.spi.preferences.Config;
37
38/**
39 * Look up, if there is right- or left-hand traffic at a certain place.
40 * See <a href="https://en.wikipedia.org/wiki/Left-_and_right-hand_traffic">Left- and right-hand traffic</a>
41 */
42public final class RightAndLefthandTraffic {
43
44 private static final String DRIVING_SIDE = "driving_side";
45 private static final String LEFT = "left";
46 private static final String RIGHT = "right";
47
48 private static volatile GeoPropertyIndex<Boolean> rlCache;
49
50 private RightAndLefthandTraffic() {
51 // Hide implicit public constructor for utility classes
52 }
53
54 /**
55 * Check if there is right-hand traffic at a certain location.
56 *
57 * @param ll the coordinates of the point
58 * @return true if there is right-hand traffic, false if there is left-hand traffic
59 */
60 public static synchronized boolean isRightHandTraffic(LatLon ll) {
61 Boolean value = rlCache.get(ll);
62 return value == null || !value;
63 }
64
65 /**
66 * Initializes Right and lefthand traffic data.
67 * TODO: Synchronization can be refined inside the {@link GeoPropertyIndex} as most look-ups are read-only.
68 */
69 public static synchronized void initialize() {
70 Collection<Way> optimizedWays = loadOptimizedBoundaries();
71 if (optimizedWays.isEmpty()) {
72 optimizedWays = computeOptimizedBoundaries();
73 try {
74 saveOptimizedBoundaries(optimizedWays);
75 } catch (IOException | SecurityException e) {
76 Logging.log(Logging.LEVEL_ERROR, "Unable to save optimized boundaries", e);
77 }
78 }
79 rlCache = new GeoPropertyIndex<>(new DefaultGeoProperty(optimizedWays), 24);
80 }
81
82 private static Collection<Way> computeOptimizedBoundaries() {
83 Collection<Way> ways = new ArrayList<>();
84 Collection<OsmPrimitive> toPurge = new ArrayList<>();
85 // Find all outer ways of left-driving countries. Many of them are adjacent (African and Asian states)
86 DataSet data = Territories.getDataSet();
87 Collection<Relation> allRelations = data.getRelations();
88 Collection<Way> allWays = data.getWays();
89 for (Way w : allWays) {
90 if (LEFT.equals(w.get(DRIVING_SIDE))) {
91 addWayIfNotInner(ways, w);
92 }
93 }
94 for (Relation r : allRelations) {
95 if (r.isMultipolygon() && LEFT.equals(r.get(DRIVING_SIDE))) {
96 for (RelationMember rm : r.getMembers()) {
97 if (rm.isWay() && "outer".equals(rm.getRole()) && !RIGHT.equals(rm.getMember().get(DRIVING_SIDE))) {
98 addWayIfNotInner(ways, (Way) rm.getMember());
99 }
100 }
101 }
102 }
103 toPurge.addAll(allRelations);
104 toPurge.addAll(allWays);
105 toPurge.removeAll(ways);
106 // Remove ways from parent relations for following optimizations
107 for (Relation r : OsmPrimitive.getParentRelations(ways)) {
108 r.setMembers(null);
109 }
110 // Remove all tags to avoid any conflict
111 for (Way w : ways) {
112 w.removeAll();
113 }
114 // Purge all other ways and relations so dataset only contains lefthand traffic data
115 PurgeCommand.build(toPurge, null).executeCommand();
116 // Combine adjacent countries into a single polygon
117 Collection<Way> optimizedWays = new ArrayList<>();
118 List<Multipolygon> areas = JoinAreasAction.collectMultipolygons(ways);
119 if (areas != null) {
120 try {
121 JoinAreasResult result = new JoinAreasAction(false).joinAreas(areas);
122 if (result.hasChanges()) {
123 for (Multipolygon mp : result.getPolygons()) {
124 optimizedWays.add(mp.getOuterWay());
125 }
126 }
127 } catch (UserCancelException ex) {
128 Logging.warn(ex);
129 } catch (JosmRuntimeException ex) {
130 // Workaround to #10511 / #14185. To remove when #10511 is solved
131 Logging.error(ex);
132 }
133 }
134 if (optimizedWays.isEmpty()) {
135 // Problem: don't optimize
136 Logging.warn("Unable to join left-driving countries polygons");
137 optimizedWays.addAll(ways);
138 }
139 return optimizedWays;
140 }
141
142 /**
143 * Adds w to ways, except if it is an inner way of another lefthand driving multipolygon,
144 * as Lesotho in South Africa and Cyprus village in British Cyprus base.
145 * @param ways ways
146 * @param w way
147 */
148 private static void addWayIfNotInner(Collection<Way> ways, Way w) {
149 Set<Way> s = Collections.singleton(w);
150 for (Relation r : OsmPrimitive.getParentRelations(s)) {
151 if (r.isMultipolygon() && LEFT.equals(r.get(DRIVING_SIDE)) &&
152 "inner".equals(r.getMembersFor(s).iterator().next().getRole())) {
153 if (Logging.isDebugEnabled()) {
154 Logging.debug("Skipping {0} because inner part of {1}", w.get("name:en"), r.get("name:en"));
155 }
156 return;
157 }
158 }
159 ways.add(w);
160 }
161
162 private static void saveOptimizedBoundaries(Collection<Way> optimizedWays) throws IOException {
163 DataSet ds = optimizedWays.iterator().next().getDataSet();
164 File file = new File(Config.getDirs().getCacheDirectory(true), "left-right-hand-traffic.osm");
165 try (Writer writer = new OutputStreamWriter(Files.newOutputStream(file.toPath()), StandardCharsets.UTF_8);
166 OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(writer), false, ds.getVersion())
167 ) {
168 w.header(DownloadPolicy.NORMAL, UploadPolicy.DISCOURAGED);
169 w.writeContent(ds);
170 w.footer();
171 }
172 }
173
174 private static Collection<Way> loadOptimizedBoundaries() {
175 try (InputStream is = Files.newInputStream(Paths.get(
176 Config.getDirs().getCacheDirectory(false).getPath(), "left-right-hand-traffic.osm"))) {
177 return OsmReader.parseDataSet(is, null).getWays();
178 } catch (IllegalDataException | IOException | InvalidPathException | SecurityException ex) {
179 Logging.trace(ex);
180 return Collections.emptyList();
181 }
182 }
183}
Note: See TracBrowser for help on using the repository browser.