diff --git a/src/main/java/org/openstreetmap/josm/plugins/mapwithai/MapWithAIPlugin.java b/src/main/java/org/openstreetmap/josm/plugins/mapwithai/MapWithAIPlugin.java index d903a74..e4250ae 100644 --- a/src/main/java/org/openstreetmap/josm/plugins/mapwithai/MapWithAIPlugin.java +++ b/src/main/java/org/openstreetmap/josm/plugins/mapwithai/MapWithAIPlugin.java @@ -18,6 +18,7 @@ import javax.swing.JMenuItem; import org.openstreetmap.josm.actions.JosmAction; import org.openstreetmap.josm.data.Version; +import org.openstreetmap.josm.data.validation.OsmValidator; import org.openstreetmap.josm.gui.MainApplication; import org.openstreetmap.josm.gui.MainMenu; import org.openstreetmap.josm.gui.MapFrame; @@ -34,6 +35,7 @@ import org.openstreetmap.josm.plugins.mapwithai.backend.MapWithAIObject; import org.openstreetmap.josm.plugins.mapwithai.backend.MapWithAIRemoteControl; import org.openstreetmap.josm.plugins.mapwithai.backend.MapWithAIUploadHook; import org.openstreetmap.josm.plugins.mapwithai.backend.MergeDuplicateWaysAction; +import org.openstreetmap.josm.plugins.mapwithai.data.validation.tests.RoutingIslandsTest; import org.openstreetmap.josm.plugins.mapwithai.frontend.MapWithAIDownloadReader; import org.openstreetmap.josm.spi.preferences.Config; import org.openstreetmap.josm.tools.Destroyable; @@ -78,6 +80,8 @@ public final class MapWithAIPlugin extends Plugin implements Destroyable { } } + OsmValidator.addTest(RoutingIslandsTest.class); + if (!Config.getPref().getKeySet().contains(PAINTSTYLE_PREEXISTS)) { Config.getPref().putBoolean(PAINTSTYLE_PREEXISTS, MapWithAIDataUtils.checkIfMapWithAIPaintStyleExists()); } diff --git a/src/main/java/org/openstreetmap/josm/plugins/mapwithai/data/validation/tests/RoutingIslandsTest.java b/src/main/java/org/openstreetmap/josm/plugins/mapwithai/data/validation/tests/RoutingIslandsTest.java new file mode 100644 index 0000000..06b5f14 --- /dev/null +++ b/src/main/java/org/openstreetmap/josm/plugins/mapwithai/data/validation/tests/RoutingIslandsTest.java @@ -0,0 +1,462 @@ +// License: GPL. For details, see LICENSE file. +package org.openstreetmap.josm.plugins.mapwithai.data.validation.tests; + +import static org.openstreetmap.josm.tools.I18n.tr; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.BiPredicate; +import java.util.stream.Collectors; + +import org.openstreetmap.josm.data.osm.Node; +import org.openstreetmap.josm.data.osm.OsmPrimitive; +import org.openstreetmap.josm.data.osm.Relation; +import org.openstreetmap.josm.data.osm.TagMap; +import org.openstreetmap.josm.data.osm.Way; +import org.openstreetmap.josm.data.preferences.sources.ValidatorPrefHelper; +import org.openstreetmap.josm.data.validation.Severity; +import org.openstreetmap.josm.data.validation.Test; +import org.openstreetmap.josm.data.validation.TestError; +import org.openstreetmap.josm.gui.progress.ProgressMonitor; +import org.openstreetmap.josm.plugins.mapwithai.tools.Access; +import org.openstreetmap.josm.spi.preferences.Config; +import org.openstreetmap.josm.tools.Pair; + +/** + * A test for routing islands + * + * @author Taylor Smock + * @since xxx + */ +public class RoutingIslandsTest extends Test { + + private static final Map SEVERITY_MAP = new HashMap<>(); + /** The code for the routing island validation test */ + public static final int ROUTING_ISLAND = 55000; + /** The code for ways that are not connected to other ways, and are routable */ + public static final int LONELY_WAY = ROUTING_ISLAND + 1; + static { + SEVERITY_MAP.put(ROUTING_ISLAND, Severity.OTHER); + SEVERITY_MAP.put(LONELY_WAY, Severity.ERROR); + } + + private static final String HIGHWAY = "highway"; + private static final String WATERWAY = "waterway"; + + /** + * This is mostly as a sanity check, and to avoid infinite recursion (shouldn't + * happen, but still) + */ + private static final int MAX_LOOPS = 1000; + /** Highways to check for routing connectivity */ + private Set potentialHighways; + /** Waterways to check for routing connectivity */ + private Set potentialWaterways; + + /** + * Constructs a new {@code RightAngleBuildingTest} test. + */ + public RoutingIslandsTest() { + super(tr("Routing islands"), tr("Checks for roads that cannot be reached or left.")); + super.setPartialSelection(false); + } + + @Override + public void startTest(ProgressMonitor monitor) { + super.startTest(monitor); + potentialHighways = new HashSet<>(); + potentialWaterways = new HashSet<>(); + } + + @Override + public void endTest() { + Access.AccessTags.getByTransportType(Access.AccessTags.LAND_TRANSPORT_TYPE).parallelStream().forEach(mode -> { + runTest(mode.getKey(), potentialHighways); + progressMonitor.setCustomText(mode.getKey()); + }); + Access.AccessTags.getByTransportType(Access.AccessTags.WATER_TRANSPORT_TYPE).parallelStream().forEach(mode -> { + progressMonitor.setCustomText(mode.getKey()); + runTest(mode.getKey(), potentialWaterways); + }); + super.endTest(); + } + + @Override + public void visit(Way way) { + if (way.isUsable() && way.getNodes().parallelStream().anyMatch(node -> way.getDataSet().getDataSourceBounds() + .parallelStream().anyMatch(source -> source.contains(node.getCoor())))) { + if ((way.hasKey(HIGHWAY) || way.hasKey(WATERWAY)) + && way.getNodes().parallelStream().flatMap(node -> node.getReferrers().parallelStream()).distinct() + .allMatch(way::equals) + && way.getNodes().parallelStream().noneMatch(Node::isOutsideDownloadArea)) { + errors.add(TestError.builder(this, SEVERITY_MAP.get(LONELY_WAY), LONELY_WAY).primitives(way) + .message(tr("Routable way not connected to other ways")).build()); + } else if ((ValidatorPrefHelper.PREF_OTHER.get() || ValidatorPrefHelper.PREF_OTHER_UPLOAD.get() + || !Severity.OTHER.equals(SEVERITY_MAP.get(ROUTING_ISLAND)))) { + if (way.hasKey(HIGHWAY)) { + potentialHighways.add(way); + } else if (way.hasKey(WATERWAY)) { + potentialWaterways.add(way); + } + } + } + } + + private void runTest(String currentTransportMode, Collection potentialWays) { + Set incomingWays = new HashSet<>(); + Set outgoingWays = new HashSet<>(); + findConnectedWays(currentTransportMode, potentialWays, incomingWays, outgoingWays); + Set toIgnore = potentialWays.parallelStream() + .filter(way -> incomingWays.contains(way) || outgoingWays.contains(way)) + .filter(way -> !Access.getPositiveAccessValues().contains( + getDefaultAccessTags(way).getOrDefault(currentTransportMode, Access.AccessTags.NO.getKey()))) + .collect(Collectors.toSet()); + incomingWays.removeAll(toIgnore); + outgoingWays.removeAll(toIgnore); + + checkForUnconnectedWays(incomingWays, outgoingWays, currentTransportMode); + List>> problematic = collectConnected(potentialWays.parallelStream() + .filter(way -> !incomingWays.contains(way) || !outgoingWays.contains(way)) + .filter(way -> Access.getPositiveAccessValues().contains( + getDefaultAccessTags(way).getOrDefault(currentTransportMode, Access.AccessTags.NO.getKey()))) + .collect(Collectors.toSet())).parallelStream() + .map(way -> new Pair<>((incomingWays.containsAll(way) ? "outgoing" : "incoming"), way)) + .collect(Collectors.toList()); + createErrors(problematic, currentTransportMode, potentialWays); + } + + /** + * Find ways that may be connected to the wider network + * + * @param currentTransportMode The current mode of transport + * @param potentialWays The ways to check for connections + * @param incomingWays A collection that will have incoming ways after + * this method is called + * @param outgoingWays A collection that will have outgoing ways after + * this method is called + */ + private static void findConnectedWays(String currentTransportMode, Collection potentialWays, + Collection incomingWays, Collection outgoingWays) { + for (Way way : potentialWays) { + if (way.isUsable() && way.isOutsideDownloadArea()) { + Node firstNode = firstNode(way, currentTransportMode); + Node lastNode = lastNode(way, currentTransportMode); + if (isOneway(way, currentTransportMode) != 0 && firstNode != null + && firstNode.isOutsideDownloadArea()) { + incomingWays.add(way); + } + if (isOneway(way, currentTransportMode) != 0 && lastNode != null && lastNode.isOutsideDownloadArea()) { + outgoingWays.add(way); + } + if (isOneway(way, currentTransportMode) == 0 && firstNode != null // Don't need to test lastNode + && (way.firstNode().isOutsideDownloadArea() || way.lastNode().isOutsideDownloadArea())) { + incomingWays.add(way); + outgoingWays.add(way); + } + } + } + } + + /** + * Take a collection of ways and modify it so that it is a list of connected + * ways + * + * @param ways A collection of ways that may or may not be connected + * @return a list of sets of ways that are connected + */ + private static List> collectConnected(Collection ways) { + ArrayList> collected = new ArrayList<>(); + ArrayList listOfWays = new ArrayList<>(ways); + final int maxLoop = Config.getPref().getInt("validator.routingislands.maxrecursion", MAX_LOOPS); + for (int i = 0; i < listOfWays.size(); i++) { + Way initial = listOfWays.get(i); + Set connected = new HashSet<>(); + connected.add(initial); + int loopCounter = 0; + while (!getConnected(connected) && loopCounter < maxLoop) { + loopCounter++; + } + if (listOfWays.removeAll(connected)) { + i--; // NOSONAR not an issue -- this ensures that everything is accounted for, only + // triggers when ways removed + } + collected.add(connected); + } + return collected; + } + + private static boolean getConnected(Collection ways) { + TagMap defaultAccess = getDefaultAccessTags(ways.iterator().next()); + return ways.addAll(ways.parallelStream().flatMap(way -> way.getNodes().parallelStream()) + .flatMap(node -> node.getReferrers().parallelStream()).filter(Way.class::isInstance) + .map(Way.class::cast).filter(way -> getDefaultAccessTags(way).equals(defaultAccess)) + .collect(Collectors.toSet())); + } + + private void createErrors(List>> problematic, String mode, Collection potentialWays) { + for (Pair> ways : problematic) { + errors.add( + TestError.builder(this, SEVERITY_MAP.getOrDefault(ROUTING_ISLAND, Severity.OTHER), ROUTING_ISLAND) + .message(tr("Routing island"), "{1}: {0}", tr(ways.a), mode == null ? "default" : mode) + .primitives(ways.b).build()); + } + } + + /** + * Check for unconnected ways + * + * @param incoming The current incoming ways (will be modified) + * @param outgoing The current outgoing ways (will be modified) + * @param currentTransportMode The transport mode we are investigating (may be + * {@code null}) + */ + public static void checkForUnconnectedWays(Collection incoming, Collection outgoing, + String currentTransportMode) { + int loopCount = 0; + int maxLoops = Config.getPref().getInt("validator.routingislands.maxrecursion", MAX_LOOPS); + do { + loopCount++; + } while (loopCount <= maxLoops && getWaysFor(incoming, currentTransportMode, + (way, oldWay) -> oldWay.containsNode(firstNode(way, currentTransportMode)) + && checkAccessibility(oldWay, way, currentTransportMode))); + loopCount = 0; + do { + loopCount++; + } while (loopCount <= maxLoops && getWaysFor(outgoing, currentTransportMode, + (way, oldWay) -> oldWay.containsNode(lastNode(way, currentTransportMode)) + && checkAccessibility(oldWay, way, currentTransportMode))); + } + + private static boolean getWaysFor(Collection directional, String currentTransportMode, + BiPredicate predicate) { + Set toAdd = new HashSet<>(); + for (Way way : directional) { + for (Node node : way.getNodes()) { + Set referrers = node.getReferrers(true).parallelStream().filter(Way.class::isInstance) + .map(Way.class::cast).filter(tWay -> !directional.contains(tWay)).collect(Collectors.toSet()); + for (Way tWay : referrers) { + if (isOneway(tWay, currentTransportMode) == 0 || predicate.test(tWay, way) || tWay.isClosed()) { + toAdd.add(tWay); + } + } + } + } + return directional.addAll(toAdd); + } + + /** + * Check if I can get to way to from way from (currently doesn't work with via + * ways) + * + * @param from The from way + * @param to The to way + * @param currentTransportMode The specific transport mode to check + * @return {@code true} if the to way can be accessed from the from way TODO + * clean up and work with via ways + */ + public static boolean checkAccessibility(Way from, Way to, String currentTransportMode) { + boolean isAccessible = true; + + List relations = from.getReferrers().parallelStream().distinct().filter(Relation.class::isInstance) + .map(Relation.class::cast).filter(relation -> "restriction".equals(relation.get("type"))) + .collect(Collectors.toList()); + for (Relation relation : relations) { + if (((relation.hasKey("except") && relation.get("except").contains(currentTransportMode)) + || (currentTransportMode == null || currentTransportMode.trim().isEmpty())) + && relation.getMembersFor(Collections.singleton(from)).parallelStream() + .anyMatch(member -> "from".equals(member.getRole())) + && relation.getMembersFor(Collections.singleton(to)).parallelStream() + .anyMatch(member -> "to".equals(member.getRole()))) { + isAccessible = false; + } + } + return isAccessible; + } + + /** + * Check if a node connects to the outside world + * + * @param node The node to check + * @return true if outside download area, connects to an aeroport, or a water + * transport + */ + public static Boolean outsideConnections(Node node) { + boolean outsideConnections = false; + if (node.isOutsideDownloadArea() || node.hasTag("amenity", "parking_entrance", "parking", "parking_space", + "motorcycle_parking", "ferry_terminal")) { + outsideConnections = true; + } + return outsideConnections; + } + + /** + * Check if a way is oneway for a specific transport type + * + * @param way The way to look at + * @param transportType The specific transport type + * @return See {@link Way#isOneway} (but may additionally return {@code null} if + * the transport type cannot route down that way) + */ + public static Integer isOneway(Way way, String transportType) { + if (transportType == null || transportType.trim().isEmpty()) { + return way.isOneway(); + } + String forward = transportType.concat(":forward"); + String backward = transportType.concat(":backward"); + boolean possibleForward = "yes".equals(way.get(forward)) || (!way.hasKey(forward) && way.isOneway() != -1); + boolean possibleBackward = "yes".equals(way.get(backward)) || (!way.hasKey(backward) && way.isOneway() != 1); + if (transportType.equals(Access.AccessTags.FOOT.getKey()) && !"footway".equals(way.get("highway")) + && !way.hasTag("foot:forward") && !way.hasTag("foot:backward")) { + return 0; // Foot is almost never oneway, especially on generic road types. There are some + // cases on mountain paths. + } + if (possibleForward && !possibleBackward) { + return 1; + } else if (!possibleForward && possibleBackward) { + return -1; + } else if (!possibleBackward) { + return null; + } + return 0; + } + + /** + * Get the first node of a way respecting the oneway for a transport type + * + * @param way The way to get the node from + * @param transportType The transport type + * @return The first node for the specified transport type, or null if it is not + * routable + */ + public static Node firstNode(Way way, String transportType) { + Integer oneway = isOneway(way, transportType); + Node node = (Integer.valueOf(-1).equals(oneway)) ? way.lastNode() : way.firstNode(); + + Map accessValues = getDefaultAccessTags(way); + boolean accessible = Access.getPositiveAccessValues() + .contains(accessValues.getOrDefault(transportType, Access.AccessTags.NO.getKey())); + return (transportType == null || accessible) ? node : null; + } + + /** + * Get the last node of a way respecting the oneway for a transport type + * + * @param way The way to get the node from + * @param transportType The transport type + * @return The last node for the specified transport type, or the last node of + * the way, or null if it is not routable + */ + public static Node lastNode(Way way, String transportType) { + Integer oneway = isOneway(way, transportType); + Node node = (Integer.valueOf(-1).equals(oneway)) ? way.firstNode() : way.lastNode(); + Map accessValues = getDefaultAccessTags(way); + boolean accessible = Access.getPositiveAccessValues() + .contains(accessValues.getOrDefault(transportType, Access.AccessTags.NO.getKey())); + return (transportType == null || accessible) ? node : null; + } + + /** + * Get the default access tags for a primitive + * + * @param primitive The primitive to get access tags for + * @return The map of access tags to access + */ + public static TagMap getDefaultAccessTags(OsmPrimitive primitive) { + TagMap access = new TagMap(); + final TagMap tags; + if (primitive.hasKey(HIGHWAY)) { + tags = getDefaultHighwayAccessTags(primitive.getKeys()); + } else if (primitive.hasKey(WATERWAY)) { + tags = getDefaultWaterwayAccessTags(primitive.getKeys()); + } else { + tags = new TagMap(); + } + tags.putAll(Access.expandAccessValues(tags)); + + for (String direction : Arrays.asList("", "forward:", "backward:")) { + Access.getTransportModes().parallelStream().map(direction::concat).filter(tags::containsKey) + .forEach(mode -> access.put(mode, tags.get(direction.concat(mode)))); + } + return access; + } + + private static TagMap getDefaultWaterwayAccessTags(TagMap tags) { + if ("river".equals(tags.get(WATERWAY))) { + tags.putIfAbsent("boat", Access.AccessTags.YES.getKey()); + } + return tags; + } + + private static TagMap getDefaultHighwayAccessTags(TagMap tags) { + String highway = tags.get(HIGHWAY); + + if (tags.containsKey("sidewalk") && !tags.get("sidewalk").equals(Access.AccessTags.NO.getKey())) { + tags.putIfAbsent(Access.AccessTags.FOOT.getKey(), Access.AccessTags.YES.getKey()); + } + + if (tags.keySet().parallelStream() + .anyMatch(str -> str.contains("cycleway") && !Access.AccessTags.NO.getKey().equals(tags.get(str)))) { + tags.putIfAbsent(Access.AccessTags.BICYCLE.getKey(), Access.AccessTags.YES.getKey()); + } + + if ("residential".equals(highway)) { + tags.putIfAbsent(Access.AccessTags.VEHICLE.getKey(), Access.AccessTags.YES.getKey()); + tags.putIfAbsent(Access.AccessTags.FOOT.getKey(), Access.AccessTags.YES.getKey()); + tags.putIfAbsent(Access.AccessTags.BICYCLE.getKey(), Access.AccessTags.YES.getKey()); + } else if (Arrays.asList("service", "unclassified", "tertiary", "tertiary_link").contains(highway)) { + tags.putIfAbsent(Access.AccessTags.VEHICLE.getKey(), Access.AccessTags.YES.getKey()); + } else if (Arrays.asList("secondary", "secondary_link").contains(highway)) { + tags.putIfAbsent(Access.AccessTags.VEHICLE.getKey(), Access.AccessTags.YES.getKey()); + } else if (Arrays.asList("primary", "primary_link").contains(highway)) { + tags.putIfAbsent(Access.AccessTags.VEHICLE.getKey(), Access.AccessTags.YES.getKey()); + tags.putIfAbsent(Access.AccessTags.HGV.getKey(), Access.AccessTags.YES.getKey()); + } else if (Arrays.asList("motorway", "trunk", "motorway_link", "trunk_link").contains(highway)) { + tags.putIfAbsent(Access.AccessTags.VEHICLE.getKey(), Access.AccessTags.YES.getKey()); + tags.putIfAbsent(Access.AccessTags.BICYCLE.getKey(), Access.AccessTags.NO.getKey()); + tags.putIfAbsent(Access.AccessTags.FOOT.getKey(), Access.AccessTags.NO.getKey()); + } else if ("steps".equals(highway)) { + tags.putIfAbsent(Access.AccessTags.ACCESS_KEY.getKey(), Access.AccessTags.NO.getKey()); + tags.putIfAbsent(Access.AccessTags.FOOT.getKey(), Access.AccessTags.YES.getKey()); + } else if ("path".equals(highway)) { + tags.putIfAbsent(Access.AccessTags.MOTOR_VEHICLE.getKey(), Access.AccessTags.NO.getKey()); + tags.putIfAbsent(Access.AccessTags.EMERGENCY.getKey(), Access.AccessTags.DESTINATION.getKey()); + } else if ("footway".equals(highway)) { + tags.putIfAbsent(Access.AccessTags.FOOT.getKey(), Access.AccessTags.DESIGNATED.getKey()); + } else if ("bus_guideway".equals(highway)) { + tags.putIfAbsent(Access.AccessTags.ACCESS_KEY.getKey(), Access.AccessTags.NO.getKey()); + tags.putIfAbsent(Access.AccessTags.BUS.getKey(), Access.AccessTags.DESIGNATED.getKey()); + } else if ("road".equals(highway)) { // Don't expect these to be routable + tags.putIfAbsent(Access.AccessTags.ACCESS_KEY.getKey(), Access.AccessTags.NO.getKey()); + } else { + tags.putIfAbsent(Access.AccessTags.ACCESS_KEY.getKey(), Access.AccessTags.YES.getKey()); + } + return tags; + } + + /** + * Get the error level for a test + * + * @param test The integer value of the test error + * @return The severity for the test + */ + public static Severity getErrorLevel(int test) { + return SEVERITY_MAP.get(test); + } + + /** + * Set the error level for a test + * + * @param test The integer value of the test error + * @param severity The new severity for the test + */ + public static void setErrorLevel(int test, Severity severity) { + SEVERITY_MAP.put(test, severity); + } +} diff --git a/src/main/java/org/openstreetmap/josm/plugins/mapwithai/tools/Access.java b/src/main/java/org/openstreetmap/josm/plugins/mapwithai/tools/Access.java new file mode 100644 index 0000000..d2e0e12 --- /dev/null +++ b/src/main/java/org/openstreetmap/josm/plugins/mapwithai/tools/Access.java @@ -0,0 +1,688 @@ +// License: GPL. For details, see LICENSE file. +package org.openstreetmap.josm.plugins.mapwithai.tools; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +import org.openstreetmap.josm.data.osm.OsmPrimitive; + +/** + * Access tag related utilities + * + * @see Key:access + * + * @author Taylor Smock + * @since xxx + */ +public class Access { + /** + * Holds access tags to avoid typos + */ + public enum AccessTags { + /** Air, land, and sea */ + ALL_TRANSPORT_TYPE("all"), + + /** + * @see Key:access + */ + ACCESS_KEY("access", ALL_TRANSPORT_TYPE), + + // Access tag values + /** + * @see Tag:access%3Dyes + */ + YES("yes"), + /** + * @see Tag:access%3Dofficial + */ + OFFICIAL("official"), + /** + * @see Tag:access%3Ddesignated + */ + DESIGNATED("designated"), + /** + * @see Tag:access%3Ddestination + */ + DESTINATION("destination"), + /** + * @see Tag:access%3Ddelivery + */ + DELIVERY("delivery"), + /** + * @see Tag:access%3Dcustomers + */ + CUSTOMERS("customers"), + /** + * @see Tag:access%3Dpermissive + */ + PERMISSIVE("permissive"), + /** + * @see Tag:access%3Dagricultural + */ + AGRICULTURAL("agricultural"), + /** + * @see Tag:access%3Dforestry + */ + FORESTRY("forestry"), + /** + * @see Tag:access%3Dprivate + */ + PRIVATE("private"), + /** + * @see Tag:access%3Dno + */ + NO("no"), + /** + * @see Tag:access%3Ddiscouraged + */ + DISCOURAGED("discouraged"), + /** + * @see Tag:access%3Duse_sidepath + */ + USE_SIDEPATH("use_sidepath"), + /** + * @see Tag:access%3Ddismount + */ + DISMOUNT("dismount"), + // Land + /** Land transport types */ + LAND_TRANSPORT_TYPE("land", ALL_TRANSPORT_TYPE), + /** + * @see Key:vehicle + */ + VEHICLE("vehicle", LAND_TRANSPORT_TYPE), + /** + * @see Key:motor_vehicle + */ + MOTOR_VEHICLE("motor_vehicle", LAND_TRANSPORT_TYPE), + /** + * @see Key:trailer + */ + TRAILER("trailer", LAND_TRANSPORT_TYPE), + /** @see Key:foot */ + FOOT("foot", LAND_TRANSPORT_TYPE), + /** @see Key:ski */ + SKI("ski", LAND_TRANSPORT_TYPE), + /** + * @see Key:inline_skates + */ + INLINE_SKATES("inline_skates", LAND_TRANSPORT_TYPE), + /** + * @see Key:ice_skates + */ + ICE_SKATES("ice_skates", LAND_TRANSPORT_TYPE), + /** + * @see Key:horse + */ + HORSE("horse", LAND_TRANSPORT_TYPE), + /** + * @see Key:bicycle + */ + BICYCLE("bicycle", LAND_TRANSPORT_TYPE), + /** + * @see Key:carriage + */ + CARRIAGE("carriage", LAND_TRANSPORT_TYPE), + /** + * @see Key:caravan + */ + CARAVAN("caravan", LAND_TRANSPORT_TYPE), + /** + * @see Key:motorcycle + */ + MOTORCYCLE("motorcycle", LAND_TRANSPORT_TYPE), + /** + * @see Key:moped + */ + MOPED("moped", LAND_TRANSPORT_TYPE), + /** @see Key:mofa */ + MOFA("mofa", LAND_TRANSPORT_TYPE), + /** + * @see Key:motorcar + */ + MOTORCAR("motorcar", LAND_TRANSPORT_TYPE), + /** + * @see Key:motorhome + */ + MOTORHOME("motorhome", LAND_TRANSPORT_TYPE), + /** @see Key:psv */ + PSV("psv", LAND_TRANSPORT_TYPE), + /** @see Key:bus */ + BUS("bus", LAND_TRANSPORT_TYPE), + /** @see Key:taxi */ + TAXI("taxi", LAND_TRANSPORT_TYPE), + /** + * @see Key:tourist_bus + */ + TOURIST_BUS("tourist_bus", LAND_TRANSPORT_TYPE), + /** + * @see Key:goods + */ + GOODS("goods", LAND_TRANSPORT_TYPE), + /** @see Key:hgv */ + HGV("hgv", LAND_TRANSPORT_TYPE), + /** @see Key:atv */ + ATV("atv", LAND_TRANSPORT_TYPE), + /** + * @see Key:snowmobile + */ + SNOWMOBILE("snowmobile", LAND_TRANSPORT_TYPE), + /** + * @see Key:hgv_articulated + */ + HGV_ARTICULATED("hgv_articulated", LAND_TRANSPORT_TYPE), + /** @see Key:ski */ + SKI_NORDIC("ski:nordic", LAND_TRANSPORT_TYPE), + /** @see Key:ski */ + SKI_ALPINE("ski:alpine", LAND_TRANSPORT_TYPE), + /** @see Key:ski */ + SKI_TELEMARK("ski:telemark", LAND_TRANSPORT_TYPE), + /** + * @see Key:coach + */ + COACH("coach", LAND_TRANSPORT_TYPE), + /** + * @see Key:golf_cart + */ + GOLF_CART("golf_cart", LAND_TRANSPORT_TYPE), + /** + * @see Key:minibus + */ + MINIBUS("minibus", LAND_TRANSPORT_TYPE), + /** + * @see Key:share_taxi + */ + SHARE_TAXI("share_taxi", LAND_TRANSPORT_TYPE), + /** @see Key:hov */ + HOV("hov", LAND_TRANSPORT_TYPE), + /** + * @see Key:car_sharing + */ + CAR_SHARING("car_sharing", LAND_TRANSPORT_TYPE), + /** + * Routers should default to {@code yes}, regardless of higher access rules, + * assuming it is navigatible by vehicle + * + * @see Key:emergency + */ + EMERGENCY("emergency", LAND_TRANSPORT_TYPE), + /** + * @see Key:hazmat + */ + HAZMAT("hazmat", LAND_TRANSPORT_TYPE), + /** + * @see Key:disabled + */ + DISABLED("disabled", LAND_TRANSPORT_TYPE), + + // Water + /** Water transport type */ + WATER_TRANSPORT_TYPE("water", ALL_TRANSPORT_TYPE), + /** + * @see Key:swimming + */ + SWIMMING("swimming", WATER_TRANSPORT_TYPE), + /** @see Key:boat */ + BOAT("boat", WATER_TRANSPORT_TYPE), + /** + * @see Key:fishing_vessel + */ + FISHING_VESSEL("fishing_vessel", WATER_TRANSPORT_TYPE), + /** @see Key:ship */ + SHIP("ship", WATER_TRANSPORT_TYPE), + /** + * @see Key:motorboat + */ + MOTORBOAT("motorboat", WATER_TRANSPORT_TYPE), + /** + * @see Key:sailboat + */ + SAILBOAT("sailboat", WATER_TRANSPORT_TYPE), + /** + * @see Key:canoe + */ + CANOE("canoe", WATER_TRANSPORT_TYPE), + /** + * @see Key:passenger + */ + PASSENGER("passenger", WATER_TRANSPORT_TYPE), + /** + * @see Key:cargo + */ + CARGO("cargo", WATER_TRANSPORT_TYPE), + /** @see Key:isps */ + ISPS("isps", WATER_TRANSPORT_TYPE), + /** @see Key:bulk */ + BULK("bulk", WATER_TRANSPORT_TYPE), + /** + * @see Key:tanker + */ + TANKER("tanker", WATER_TRANSPORT_TYPE), + /** + * @see Key:container + */ + CONTAINER("container", WATER_TRANSPORT_TYPE), + /** @see Key:imdg */ + IMDG("imdg", WATER_TRANSPORT_TYPE), + /** + * @see Key:tanker + */ + TANKER_GAS("tanker:gas", WATER_TRANSPORT_TYPE), + /** + * @see Key:tanker + */ + TANKER_OIL("tanker:oil", WATER_TRANSPORT_TYPE), + /** + * @see Key:tanker + */ + TANKER_CHEMICAL("tanker:chemical", WATER_TRANSPORT_TYPE), + /** + * @see Key:tanker + */ + TANKER_SINGLEHULL("tanker:singlehull", WATER_TRANSPORT_TYPE), + + // Trains + /** Rail transport type */ + RAIL_TRANSPORT_TYPE("rail", ALL_TRANSPORT_TYPE), + /** + * @see Key:train + */ + TRAIN("train", RAIL_TRANSPORT_TYPE); + + private String key; + private AccessTags type; + + AccessTags(String key) { + this.key = key; + this.type = null; + } + + AccessTags(String key, AccessTags type) { + this.key = key; + this.type = type; + } + + /** + * @return The key for the enum + */ + public String getKey() { + return key; + } + + /** + * @return The AccessTags transport type + * (RAIL_TRANSPORT_TYPE/WATER_TRANSPORT_TYPE/etc) + */ + public AccessTags getTransportType() { + return type; + } + + /** + * Check if this is a parent transport type (air/sea/water/all) + * + * @param potentialDescendant The AccessTags that we want to check + * @return true if valueOf is a child transport type of this + */ + public boolean parentOf(AccessTags potentialDescendant) { + AccessTags tmp = potentialDescendant; + while (tmp != null && tmp != this) { + tmp = tmp.getTransportType(); + } + return tmp == this; + } + + /** + * Get the enum that matches the mode + * + * @param childrenMode The mode to get the access tag + * @return The AccessTags enum that matches the childrenMode, or null + */ + public static AccessTags get(String childrenMode) { + for (AccessTags value : values()) { + if (value.getKey().equalsIgnoreCase(childrenMode)) { + return value; + } + } + return null; + } + + /** + * Get access tags that match a certain type + * + * @param type {@link AccessTags#WATER_TRANSPORT_TYPE}, + * {@link AccessTags#LAND_TRANSPORT_TYPE}, + * {@link AccessTags#RAIL_TRANSPORT_TYPE}, or + * {@link AccessTags#ALL_TRANSPORT_TYPE} + * @return A collection of access tags that match the given transport type + */ + public static Collection getByTransportType(AccessTags type) { + return Arrays.stream(values()).filter(type::parentOf).collect(Collectors.toList()); + } + } + + /** + * The key for children modes for the map, see {@link Access#getAccessMethods} + */ + public static final String CHILDREN = "children"; + /** The key for parent modes for the map, see {@link Access#getAccessMethods} */ + public static final String PARENT = "parent"; + /** This set has keys that indicate that access is possible */ + private static final Set POSITIVE_ACCESS = new HashSet<>( + Arrays.asList(AccessTags.YES, AccessTags.OFFICIAL, AccessTags.DESIGNATED, AccessTags.DESTINATION, + AccessTags.DELIVERY, AccessTags.CUSTOMERS, AccessTags.PERMISSIVE, AccessTags.AGRICULTURAL, + AccessTags.FORESTRY).stream().map(AccessTags::getKey).collect(Collectors.toSet())); + /** This set has all basic restriction values (yes/no/permissive/private/...) */ + private static final Set RESTRICTION_VALUES = new HashSet<>(Arrays.asList(AccessTags.PRIVATE, AccessTags.NO) + .stream().map(AccessTags::getKey).collect(Collectors.toSet())); + /** This set has transport modes (access/foot/ski/motor_vehicle/vehicle/...) */ + private static final Set TRANSPORT_MODES = new HashSet<>(Arrays.asList(AccessTags.ACCESS_KEY, + AccessTags.FOOT, AccessTags.SKI, AccessTags.INLINE_SKATES, AccessTags.ICE_SKATES, AccessTags.HORSE, + AccessTags.VEHICLE, AccessTags.BICYCLE, AccessTags.CARRIAGE, AccessTags.TRAILER, AccessTags.CARAVAN, + AccessTags.MOTOR_VEHICLE, AccessTags.MOTORCYCLE, AccessTags.MOPED, AccessTags.MOFA, AccessTags.MOTORCAR, + AccessTags.MOTORHOME, AccessTags.PSV, AccessTags.BUS, AccessTags.TAXI, AccessTags.TOURIST_BUS, + AccessTags.GOODS, AccessTags.HGV, AccessTags.AGRICULTURAL, AccessTags.ATV, AccessTags.SNOWMOBILE, + AccessTags.HGV_ARTICULATED, AccessTags.SKI_NORDIC, AccessTags.SKI_ALPINE, AccessTags.SKI_TELEMARK, + AccessTags.COACH, AccessTags.GOLF_CART + /* + * ,"minibus","share_taxi","hov","car_sharing","emergency","hazmat","disabled" + */).stream().map(AccessTags::getKey).collect(Collectors.toSet())); + + /** Map> */ + private static final Map>> accessMethods = new HashMap<>(); + static { + RESTRICTION_VALUES.addAll(POSITIVE_ACCESS); + defaultInheritance(); + } + + private Access() { + // Hide the constructor + } + + /** + * Create the default access inheritance, as defined at + * {@link "https://wiki.openstreetmap.org/wiki/Key:access#Transport_mode_restrictions"} + */ + private static void defaultInheritance() { + addMode(null, AccessTags.ACCESS_KEY); + + // Land + addModes(AccessTags.ACCESS_KEY, AccessTags.FOOT, AccessTags.SKI, AccessTags.INLINE_SKATES, + AccessTags.ICE_SKATES, AccessTags.HORSE, AccessTags.VEHICLE); + addModes(AccessTags.SKI, AccessTags.SKI_NORDIC, AccessTags.SKI_ALPINE, AccessTags.SKI_TELEMARK); + addModes(AccessTags.VEHICLE, AccessTags.BICYCLE, AccessTags.CARRIAGE, AccessTags.TRAILER, + AccessTags.MOTOR_VEHICLE); + addModes(AccessTags.TRAILER, AccessTags.CARAVAN); + addModes(AccessTags.MOTOR_VEHICLE, AccessTags.MOTORCYCLE, AccessTags.MOPED, AccessTags.MOFA, + AccessTags.MOTORCAR, AccessTags.MOTORHOME, AccessTags.TOURIST_BUS, AccessTags.COACH, AccessTags.GOODS, + AccessTags.HGV, AccessTags.AGRICULTURAL, AccessTags.GOLF_CART, AccessTags.ATV, AccessTags.SNOWMOBILE, + AccessTags.PSV, AccessTags.HOV, AccessTags.CAR_SHARING, AccessTags.EMERGENCY, AccessTags.HAZMAT, + AccessTags.DISABLED); + addMode(AccessTags.HGV, AccessTags.HGV_ARTICULATED); + addModes(AccessTags.PSV, AccessTags.BUS, AccessTags.MINIBUS, AccessTags.SHARE_TAXI, AccessTags.TAXI); + + // Water + addModes(AccessTags.ACCESS_KEY, AccessTags.SWIMMING, AccessTags.BOAT, AccessTags.FISHING_VESSEL, + AccessTags.SHIP); + addModes(AccessTags.BOAT, AccessTags.MOTORBOAT, AccessTags.SAILBOAT, AccessTags.CANOE); + addModes(AccessTags.SHIP, AccessTags.PASSENGER, AccessTags.CARGO, AccessTags.ISPS); + addModes(AccessTags.CARGO, AccessTags.BULK, AccessTags.TANKER, AccessTags.CONTAINER, AccessTags.IMDG); + addModes(AccessTags.TANKER, AccessTags.TANKER_GAS, AccessTags.TANKER_OIL, AccessTags.TANKER_CHEMICAL, + AccessTags.TANKER_SINGLEHULL); + + // Rail + addModes(AccessTags.ACCESS_KEY, AccessTags.TRAIN); + } + + /** + * Add multiple modes with a common parent + * + * @param parent The parent of all the modes + * @param modes The modes to add + */ + public static void addModes(AccessTags parent, AccessTags... modes) { + for (AccessTags mode : modes) { + addMode(parent, mode); + } + } + + /** + * Add modes to a list, modifying parents as needed + * + * @param mode The mode to be added + * @param parent The parent of the mode + */ + public static void addMode(AccessTags parent, AccessTags mode) { + Objects.requireNonNull(mode, "Mode must not be null"); + if (parent != null) { + Map> parentMap = accessMethods.getOrDefault(parent.getKey(), new HashMap<>()); + accessMethods.putIfAbsent(parent.getKey(), parentMap); + List parentChildren = parentMap.getOrDefault(CHILDREN, new ArrayList<>()); + if (!parentChildren.contains(mode.getKey())) { + parentChildren.add(mode.getKey()); + } + parentMap.putIfAbsent(CHILDREN, parentChildren); + } + Map> modeMap = accessMethods.getOrDefault(mode.getKey(), new HashMap<>()); + accessMethods.putIfAbsent(mode.getKey(), modeMap); + List modeParent = modeMap.getOrDefault(PARENT, + Collections.singletonList(parent == null ? null : parent.getKey())); + modeMap.putIfAbsent(PARENT, modeParent); + } + + /** + * Get the number of parents a mode has + * + * @param mode The mode with parents + * @return The number of parents the mode has + */ + public static int depth(String mode) { + String tempMode = mode; + int maxCount = accessMethods.size(); + while (tempMode != null && maxCount > 0) { + tempMode = accessMethods.getOrDefault(tempMode, Collections.emptyMap()) + .getOrDefault(PARENT, Collections.emptyList()).get(0); + if (tempMode != null) { + maxCount--; + } + } + return accessMethods.size() - maxCount; + } + + /** + * Expand access modes to cover the children of that access mode (currently only + * supports the default hierarchy) + * + * @param mode The transport mode + * @param access The access value (the children transport modes inherit this + * value) + * @return A map of the mode and its children (does not include parents) + */ + public static Map expandAccessMode(String mode, String access) { + return expandAccessMode(mode, access, AccessTags.ALL_TRANSPORT_TYPE); + } + + /** + * Expand access modes to cover the children of that access mode (currently only + * supports the default hierarchy) + * + * @param mode The transport mode + * @param access The access value (the children transport modes inherit + * this value) + * @param transportType {@link AccessTags#ALL_TRANSPORT_TYPE}, + * {@link AccessTags#LAND_TRANSPORT_TYPE}, + * {@link AccessTags#WATER_TRANSPORT_TYPE}, + * {@link AccessTags#RAIL_TRANSPORT_TYPE} + * @return A map of the mode and its children (does not include parents) + */ + public static Map expandAccessMode(String mode, String access, AccessTags transportType) { + Map accessModes = new HashMap<>(); + accessModes.put(mode, access); + if (accessMethods.containsKey(mode)) { + for (String childrenMode : accessMethods.getOrDefault(mode, Collections.emptyMap()).getOrDefault(CHILDREN, + Collections.emptyList())) { + if (transportType.parentOf(AccessTags.get(childrenMode))) { + accessModes.putAll(expandAccessMode(childrenMode, access, transportType)); + } + } + } + return accessModes; + } + + /** + * Merge two access maps (more specific wins) + * + * @param map1 A map with access values (see {@link Access#expandAccessMode}) + * @param map2 A map with access values (see {@link Access#expandAccessMode}) + * @return The merged map + */ + public static Map mergeMaps(Map map1, Map map2) { + Map merged; + if (map1.keySet().containsAll(map2.keySet())) { + merged = new HashMap<>(map1); + merged.putAll(map2); + } else { // if they don't overlap or if map2 contains all of map1 + merged = new HashMap<>(map2); + merged.putAll(map1); + } + return merged; + } + + /** + * Get the set of values that can generally be considered to be accessible + * + * @return A set of values that can be used for routing purposes (unmodifiable) + */ + public static Set getPositiveAccessValues() { + return Collections.unmodifiableSet(POSITIVE_ACCESS); + } + + /** + * Get the valid restriction values ({@code unknown} is not included). See + * + * @return Valid values for restrictions (unmodifiable) + * @see Key:access#List_of_possible_values + */ + public static Set getRestrictionValues() { + return Collections.unmodifiableSet(RESTRICTION_VALUES); + } + + /** + * Get the valid transport modes. See + * + * @return Value transport modes (unmodifiable) + * @see Key:access#Transport_mode_restrictions + */ + public static Set getTransportModes() { + return Collections.unmodifiableSet(TRANSPORT_MODES); + } + + /** + * Get the access method hierarchy. + * + * @return The hierarchy for access modes (unmodifiable) + * @see Key:access#Transport_mode_restrictions + */ + public static Map>> getAccessMethods() { + Map>> map = new HashMap<>(); + for (Entry>> entry : map.entrySet()) { + Map> tMap = new HashMap<>(); + entry.getValue().forEach((key, list) -> tMap.put(key, Collections.unmodifiableList(list))); + map.put(entry.getKey(), Collections.unmodifiableMap(tMap)); + } + return Collections.unmodifiableMap(map); + } + + /** + * Get the implied access values for a primitive + * + * @param primitive A primitive with access values + * @param transportType {@link AccessTags#ALL_TRANSPORT_TYPE}, + * {@link AccessTags#LAND_TRANSPORT_TYPE}, + * {@link AccessTags#WATER_TRANSPORT_TYPE}, + * {@link AccessTags#RAIL_TRANSPORT_TYPE} + * @return The implied access values (for example, "hgv=designated" adds + * "hgv_articulated=designated") + */ + public static Map getAccessValues(OsmPrimitive primitive, AccessTags transportType) { + Map accessValues = new HashMap<>(); + TRANSPORT_MODES.stream().filter(primitive::hasKey) + .map(mode -> expandAccessMode(mode, primitive.get(mode), transportType)).forEach(modeAccess -> { + Map tMap = mergeMaps(accessValues, modeAccess); + accessValues.clear(); + accessValues.putAll(tMap); + }); + return accessValues; + } + + /** + * Expand a map of access values + * + * @param accessValues A map of mode, access type values + * @return The expanded access values + */ + public static Map expandAccessValues(Map accessValues) { + Map modes = new HashMap<>(); + List> list = accessValues.entrySet().stream() + .map(entry -> expandAccessMode(entry.getKey(), entry.getValue())) + .sorted(Comparator.comparingInt(Map::size)).collect(Collectors.toCollection(ArrayList::new)); + Collections.reverse(list); + for (Map access : list) { + modes = mergeMaps(modes, access); + } + return modes; + } +} diff --git a/test/unit/org/openstreetmap/josm/plugins/mapwithai/data/validation/tests/RoutingIslandsTestTest.java b/test/unit/org/openstreetmap/josm/plugins/mapwithai/data/validation/tests/RoutingIslandsTestTest.java new file mode 100644 index 0000000..674f00e --- /dev/null +++ b/test/unit/org/openstreetmap/josm/plugins/mapwithai/data/validation/tests/RoutingIslandsTestTest.java @@ -0,0 +1,365 @@ +// License: GPL. For details, see LICENSE file. +package org.openstreetmap.josm.plugins.mapwithai.data.validation.tests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; + +import org.junit.Rule; +import org.junit.Test; +import org.openstreetmap.josm.TestUtils; +import org.openstreetmap.josm.data.Bounds; +import org.openstreetmap.josm.data.DataSource; +import org.openstreetmap.josm.data.coor.LatLon; +import org.openstreetmap.josm.data.osm.DataSet; +import org.openstreetmap.josm.data.osm.Node; +import org.openstreetmap.josm.data.osm.OsmPrimitive; +import org.openstreetmap.josm.data.osm.Way; +import org.openstreetmap.josm.data.validation.Severity; +import org.openstreetmap.josm.spi.preferences.Config; +import org.openstreetmap.josm.testutils.JOSMTestRules; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; + +/** + * Test class for {@link RoutingIslandsTest} + * + * @author Taylor Smock + * @since xxx + */ +public class RoutingIslandsTestTest { + /** + * Setup test. + */ + @Rule + @SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD") + public JOSMTestRules rule = new JOSMTestRules().projection().preferences(); + + /** + * Test method for {@link RoutingIslandsTest#RoutingIslandsTest()} and the + * testing apparatus + */ + @Test + public void testRoutingIslandsTest() { + RoutingIslandsTest.setErrorLevel(RoutingIslandsTest.ROUTING_ISLAND, Severity.WARNING); + RoutingIslandsTest test = new RoutingIslandsTest(); + test.startTest(null); + test.endTest(); + assertTrue(test.getErrors().isEmpty()); + + DataSet ds = new DataSet(); + + Way way1 = TestUtils.newWay("highway=residential", new Node(new LatLon(0, 0)), new Node(new LatLon(1, 1))); + Way way2 = TestUtils.newWay("highway=residential", new Node(new LatLon(-1, 0)), way1.firstNode()); + addToDataSet(ds, way1); + addToDataSet(ds, way2); + + ds.addDataSource(new DataSource(new Bounds(0, 0, 1, 1), "openstreetmap.org")); + + test.clear(); + test.startTest(null); + test.visit(ds.allPrimitives()); + test.endTest(); + assertTrue(test.getErrors().isEmpty()); + + ds.addDataSource(new DataSource(new Bounds(-5, -5, 5, 5), "openstreetmap.org")); + test.clear(); + test.startTest(null); + test.visit(ds.allPrimitives()); + test.endTest(); + assertFalse(test.getErrors().isEmpty()); + assertEquals(2, test.getErrors().get(0).getPrimitives().size()); + + ds.clear(); + way1 = TestUtils.newWay("highway=motorway oneway=yes", new Node(new LatLon(39.1156655, -108.5465434)), + new Node(new LatLon(39.1157251, -108.5496874)), new Node(new LatLon(39.11592, -108.5566841))); + way2 = TestUtils.newWay("highway=motorway oneway=yes", new Node(new LatLon(39.1157244, -108.55674)), + new Node(new LatLon(39.1155548, -108.5496901)), new Node(new LatLon(39.1154827, -108.5462431))); + addToDataSet(ds, way1); + addToDataSet(ds, way2); + ds.addDataSource( + new DataSource(new Bounds(new LatLon(39.1136949, -108.558445), new LatLon(39.117242, -108.5489166)), + "openstreetmap.org")); + test.clear(); + test.startTest(null); + test.visit(ds.allPrimitives()); + test.endTest(); + assertFalse(test.getErrors().isEmpty()); + Way way3 = TestUtils.newWay("highway=motorway oneway=no", way1.getNode(1), way2.getNode(1)); + addToDataSet(ds, way3); + test.clear(); + test.startTest(null); + test.visit(ds.allPrimitives()); + test.endTest(); + assertFalse(test.getErrors().isEmpty()); + + Node tNode = new Node(new LatLon(39.1158845, -108.5599312)); + addToDataSet(ds, tNode); + way1.addNode(tNode); + tNode = new Node(new LatLon(39.115723, -108.5599239)); + addToDataSet(ds, tNode); + way2.addNode(0, tNode); + test.clear(); + test.startTest(null); + test.visit(ds.allPrimitives()); + test.endTest(); + assertTrue(test.getErrors().isEmpty()); + } + + /** + * Test roundabouts + */ + @Test + public void testRoundabouts() { + RoutingIslandsTest test = new RoutingIslandsTest(); + Way roundabout = TestUtils.newWay("highway=residential junction=roundabout oneway=yes", + new Node(new LatLon(39.119582, -108.5262686)), new Node(new LatLon(39.1196494, -108.5260935)), + new Node(new LatLon(39.1197572, -108.5260784)), new Node(new LatLon(39.1197929, -108.526391)), + new Node(new LatLon(39.1196595, -108.5264047))); + roundabout.addNode(roundabout.firstNode()); // close it up + DataSet ds = new DataSet(); + addToDataSet(ds, roundabout); + ds.addDataSource( + new DataSource(new Bounds(new LatLon(39.1182025, -108.527574), new LatLon(39.1210588, -108.5251112)), + "openstreetmap.org")); + Way incomingFlare = TestUtils.newWay("highway=residential oneway=yes", + new Node(new LatLon(39.1196377, -108.5257567)), roundabout.getNode(3)); + addToDataSet(ds, incomingFlare); + Way outgoingFlare = TestUtils.newWay("highway=residential oneway=yes", roundabout.getNode(2), + incomingFlare.firstNode()); + addToDataSet(ds, outgoingFlare); + + Way outgoingRoad = TestUtils.newWay("highway=residential", incomingFlare.firstNode(), + new Node(new LatLon(39.1175184, -108.5219623))); + addToDataSet(ds, outgoingRoad); + + test.startTest(null); + test.visit(ds.allPrimitives()); + test.endTest(); + assertTrue(test.getErrors().isEmpty()); + } + + /** + * Test method for {@link RoutingIslandsTest#checkForUnconnectedWays}. + */ + @Test + public void testCheckForUnconnectedWaysIncoming() { + RoutingIslandsTest.checkForUnconnectedWays(Collections.emptySet(), Collections.emptySet(), null); + Way way1 = TestUtils.newWay("highway=residential oneway=yes", new Node(new LatLon(0, 0)), + new Node(new LatLon(1, 1))); + Set incomingSet = new HashSet<>(); + DataSet ds = new DataSet(); + way1.getNodes().forEach(ds::addPrimitive); + ds.addPrimitive(way1); + incomingSet.add(way1); + RoutingIslandsTest.checkForUnconnectedWays(incomingSet, Collections.emptySet(), null); + assertEquals(1, incomingSet.size()); + assertSame(way1, incomingSet.iterator().next()); + + Way way2 = TestUtils.newWay("highway=residential", way1.firstNode(), new Node(new LatLon(-1, -2))); + way2.getNodes().parallelStream().filter(node -> node.getDataSet() == null).forEach(ds::addPrimitive); + ds.addPrimitive(way2); + + RoutingIslandsTest.checkForUnconnectedWays(incomingSet, Collections.emptySet(), null); + assertEquals(2, incomingSet.size()); + assertTrue(incomingSet.parallelStream().allMatch(way -> Arrays.asList(way1, way2).contains(way))); + + Way way3 = TestUtils.newWay("highway=residential", way2.lastNode(), new Node(new LatLon(-2, -1))); + way3.getNodes().parallelStream().filter(node -> node.getDataSet() == null).forEach(ds::addPrimitive); + ds.addPrimitive(way3); + + incomingSet.clear(); + incomingSet.add(way1); + RoutingIslandsTest.checkForUnconnectedWays(incomingSet, Collections.emptySet(), null); + assertEquals(3, incomingSet.size()); + assertTrue(incomingSet.parallelStream().allMatch(way -> Arrays.asList(way1, way2, way3).contains(way))); + + Config.getPref().putInt("validator.routingislands.maxrecursion", 1); + incomingSet.clear(); + incomingSet.add(way1); + RoutingIslandsTest.checkForUnconnectedWays(incomingSet, Collections.emptySet(), null); + assertEquals(2, incomingSet.size()); + assertTrue(incomingSet.parallelStream().allMatch(way -> Arrays.asList(way1, way2).contains(way))); + } + + /** + * Test method for {@link RoutingIslandsTest#checkForUnconnectedWays}. + */ + @Test + public void testCheckForUnconnectedWaysOutgoing() { + RoutingIslandsTest.checkForUnconnectedWays(Collections.emptySet(), Collections.emptySet(), null); + Way way1 = TestUtils.newWay("highway=residential oneway=yes", new Node(new LatLon(0, 0)), + new Node(new LatLon(1, 1))); + Set outgoingSet = new HashSet<>(); + DataSet ds = new DataSet(); + way1.getNodes().forEach(ds::addPrimitive); + ds.addPrimitive(way1); + outgoingSet.add(way1); + RoutingIslandsTest.checkForUnconnectedWays(Collections.emptySet(), outgoingSet, null); + assertEquals(1, outgoingSet.size()); + assertSame(way1, outgoingSet.iterator().next()); + + Way way2 = TestUtils.newWay("highway=residential", way1.firstNode(), new Node(new LatLon(-1, -2))); + way2.getNodes().parallelStream().filter(node -> node.getDataSet() == null).forEach(ds::addPrimitive); + ds.addPrimitive(way2); + + RoutingIslandsTest.checkForUnconnectedWays(Collections.emptySet(), outgoingSet, null); + assertEquals(2, outgoingSet.size()); + assertTrue(outgoingSet.parallelStream().allMatch(way -> Arrays.asList(way1, way2).contains(way))); + + Way way3 = TestUtils.newWay("highway=residential", way2.lastNode(), new Node(new LatLon(-2, -1))); + way3.getNodes().parallelStream().filter(node -> node.getDataSet() == null).forEach(ds::addPrimitive); + ds.addPrimitive(way3); + + outgoingSet.clear(); + outgoingSet.add(way1); + RoutingIslandsTest.checkForUnconnectedWays(Collections.emptySet(), outgoingSet, null); + assertEquals(3, outgoingSet.size()); + assertTrue(outgoingSet.parallelStream().allMatch(way -> Arrays.asList(way1, way2, way3).contains(way))); + + Config.getPref().putInt("validator.routingislands.maxrecursion", 1); + outgoingSet.clear(); + outgoingSet.add(way1); + RoutingIslandsTest.checkForUnconnectedWays(Collections.emptySet(), outgoingSet, null); + assertEquals(2, outgoingSet.size()); + assertTrue(outgoingSet.parallelStream().allMatch(way -> Arrays.asList(way1, way2).contains(way))); + } + + /** + * Test method for {@link RoutingIslandsTest#outsideConnections(Node)}. + */ + @Test + public void testOutsideConnections() { + Node node = new Node(new LatLon(0, 0)); + DataSet ds = new DataSet(node); + ds.addDataSource(new DataSource(new Bounds(-0.1, -0.1, -0.01, -0.01), "Test bounds")); + node.setOsmId(1, 1); + assertTrue(RoutingIslandsTest.outsideConnections(node)); + ds.addDataSource(new DataSource(new Bounds(-0.1, -0.1, 0.1, 0.1), "Test bounds")); + assertFalse(RoutingIslandsTest.outsideConnections(node)); + node.put("amenity", "parking_entrance"); + assertTrue(RoutingIslandsTest.outsideConnections(node)); + } + + /** + * Test method for {@link RoutingIslandsTest#isOneway(Way, String)}. + */ + @Test + public void testIsOneway() { + Way way = TestUtils.newWay("highway=residential", new Node(new LatLon(0, 0)), new Node(new LatLon(1, 1))); + assertEquals(Integer.valueOf(0), RoutingIslandsTest.isOneway(way, null)); + assertEquals(Integer.valueOf(0), RoutingIslandsTest.isOneway(way, " ")); + way.put("oneway", "yes"); + assertEquals(Integer.valueOf(1), RoutingIslandsTest.isOneway(way, null)); + assertEquals(Integer.valueOf(1), RoutingIslandsTest.isOneway(way, " ")); + way.put("oneway", "-1"); + assertEquals(Integer.valueOf(-1), RoutingIslandsTest.isOneway(way, null)); + assertEquals(Integer.valueOf(-1), RoutingIslandsTest.isOneway(way, " ")); + + way.put("vehicle:forward", "yes"); + assertEquals(Integer.valueOf(0), RoutingIslandsTest.isOneway(way, "vehicle")); + way.put("vehicle:backward", "no"); + assertEquals(Integer.valueOf(1), RoutingIslandsTest.isOneway(way, "vehicle")); + way.put("vehicle:forward", "no"); + assertNull(RoutingIslandsTest.isOneway(way, "vehicle")); + way.put("vehicle:backward", "yes"); + assertEquals(Integer.valueOf(-1), RoutingIslandsTest.isOneway(way, "vehicle")); + + way.put("oneway", "yes"); + way.remove("vehicle:backward"); + way.remove("vehicle:forward"); + assertEquals(Integer.valueOf(1), RoutingIslandsTest.isOneway(way, "vehicle")); + way.remove("oneway"); + assertEquals(Integer.valueOf(0), RoutingIslandsTest.isOneway(way, "vehicle")); + + way.put("oneway", "-1"); + assertEquals(Integer.valueOf(-1), RoutingIslandsTest.isOneway(way, "vehicle")); + } + + /** + * Test method for {@link RoutingIslandsTest#firstNode(Way, String)}. + */ + @Test + public void testFirstNode() { + Way way = TestUtils.newWay("highway=residential", new Node(new LatLon(0, 0)), new Node(new LatLon(1, 1))); + assertEquals(way.firstNode(), RoutingIslandsTest.firstNode(way, null)); + way.put("oneway", "yes"); + assertEquals(way.firstNode(), RoutingIslandsTest.firstNode(way, null)); + way.put("oneway", "-1"); + assertEquals(way.lastNode(), RoutingIslandsTest.firstNode(way, null)); + + way.put("vehicle:forward", "yes"); + assertEquals(way.firstNode(), RoutingIslandsTest.firstNode(way, "vehicle")); + way.put("vehicle:backward", "no"); + assertEquals(way.firstNode(), RoutingIslandsTest.firstNode(way, "vehicle")); + way.put("vehicle:forward", "no"); + assertEquals(way.firstNode(), RoutingIslandsTest.firstNode(way, "vehicle")); + way.put("vehicle:backward", "yes"); + assertEquals(way.lastNode(), RoutingIslandsTest.firstNode(way, "vehicle")); + } + + /** + * Test method for {@link RoutingIslandsTest#lastNode(Way, String)}. + */ + @Test + public void testLastNode() { + Way way = TestUtils.newWay("highway=residential", new Node(new LatLon(0, 0)), new Node(new LatLon(1, 1))); + assertEquals(way.lastNode(), RoutingIslandsTest.lastNode(way, null)); + way.put("oneway", "yes"); + assertEquals(way.lastNode(), RoutingIslandsTest.lastNode(way, null)); + way.put("oneway", "-1"); + assertEquals(way.firstNode(), RoutingIslandsTest.lastNode(way, null)); + + way.put("vehicle:forward", "yes"); + assertEquals(way.lastNode(), RoutingIslandsTest.lastNode(way, "vehicle")); + way.put("vehicle:backward", "no"); + assertEquals(way.lastNode(), RoutingIslandsTest.lastNode(way, "vehicle")); + way.put("vehicle:forward", "no"); + assertEquals(way.lastNode(), RoutingIslandsTest.lastNode(way, "vehicle")); + way.put("vehicle:backward", "yes"); + assertEquals(way.firstNode(), RoutingIslandsTest.lastNode(way, "vehicle")); + } + + /** + * Test with a way that by default does not give access to motor vehicles + */ + @Test + public void testNoAccessWay() { + Way i70w = TestUtils.newWay("highway=motorway hgv=designated", new Node(new LatLon(39.1058104, -108.5258586)), + new Node(new LatLon(39.1052235, -108.5293733))); + Way i70e = TestUtils.newWay("highway=motorway hgv=designated", new Node(new LatLon(39.1049905, -108.5293074)), + new Node(new LatLon(39.1055829, -108.5257975))); + Way testPath = TestUtils.newWay("highway=footway", i70w.lastNode(true), i70e.firstNode(true)); + DataSet ds = new DataSet(); + Arrays.asList(i70w, i70e, testPath).forEach(way -> addToDataSet(ds, way)); + + RoutingIslandsTest test = new RoutingIslandsTest(); + test.startTest(null); + test.visit(ds.allPrimitives()); + test.endTest(); + } + + private static void addToDataSet(DataSet ds, OsmPrimitive primitive) { + if (primitive instanceof Way) { + ((Way) primitive).getNodes().parallelStream().distinct().filter(node -> node.getDataSet() == null) + .forEach(ds::addPrimitive); + } + if (primitive.getDataSet() == null) { + ds.addPrimitive(primitive); + } + Long id = Math.max(ds.allPrimitives().parallelStream().mapToLong(prim -> prim.getId()).max().orElse(0L), 0L); + for (OsmPrimitive osm : ds.allPrimitives().parallelStream().filter(prim -> prim.getUniqueId() < 0) + .collect(Collectors.toList())) { + id++; + osm.setOsmId(id, 1); + } + } +}