Ticket #18364: 18364.3.patch

File 18364.3.patch, 69.5 KB (added by taylor.smock, 6 years ago)

Mark routable ways that are not connected to any other way (i.e., a single way) as an error, unless a node is outside the download area. This patch does not deal with Node.isOutSideDownloadArea returning false when the node is new/undeleted.

  • src/org/openstreetmap/josm/data/validation/OsmValidator.java

     
    6060import org.openstreetmap.josm.data.validation.tests.PublicTransportRouteTest;
    6161import org.openstreetmap.josm.data.validation.tests.RelationChecker;
    6262import org.openstreetmap.josm.data.validation.tests.RightAngleBuildingTest;
     63import org.openstreetmap.josm.data.validation.tests.RoutingIslandsTest;
    6364import org.openstreetmap.josm.data.validation.tests.SelfIntersectingWay;
    6465import org.openstreetmap.josm.data.validation.tests.SharpAngles;
    6566import org.openstreetmap.josm.data.validation.tests.SimilarNamedWays;
     
    150151        PublicTransportRouteTest.class, // 3600 .. 3699
    151152        RightAngleBuildingTest.class, // 3700 .. 3799
    152153        SharpAngles.class, // 3800 .. 3899
     154        RoutingIslandsTest.class, // 3900 .. 3999
    153155    };
    154156
    155157    /**
  • src/org/openstreetmap/josm/data/validation/tests/RoutingIslandsTest.java

     
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.data.validation.tests;
     3
     4import static org.openstreetmap.josm.tools.I18n.tr;
     5
     6import java.util.ArrayList;
     7import java.util.Arrays;
     8import java.util.Collection;
     9import java.util.Collections;
     10import java.util.HashMap;
     11import java.util.HashSet;
     12import java.util.List;
     13import java.util.Map;
     14import java.util.Set;
     15import java.util.function.BiPredicate;
     16import java.util.stream.Collectors;
     17
     18import org.openstreetmap.josm.data.osm.Node;
     19import org.openstreetmap.josm.data.osm.OsmPrimitive;
     20import org.openstreetmap.josm.data.osm.Relation;
     21import org.openstreetmap.josm.data.osm.TagMap;
     22import org.openstreetmap.josm.data.osm.Way;
     23import org.openstreetmap.josm.data.preferences.sources.ValidatorPrefHelper;
     24import org.openstreetmap.josm.data.validation.Severity;
     25import org.openstreetmap.josm.data.validation.Test;
     26import org.openstreetmap.josm.data.validation.TestError;
     27import org.openstreetmap.josm.gui.progress.ProgressMonitor;
     28import org.openstreetmap.josm.spi.preferences.Config;
     29import org.openstreetmap.josm.tools.Access;
     30import org.openstreetmap.josm.tools.Pair;
     31
     32/**
     33 * A test for routing islands
     34 *
     35 * @author Taylor Smock
     36 * @since xxx
     37 */
     38public class RoutingIslandsTest extends Test {
     39
     40    private static final Map<Integer, Severity> SEVERITY_MAP = new HashMap<>();
     41    /** The code for the routing island validation test */
     42    public static final int ROUTING_ISLAND = 3900;
     43    /** The code for ways that are not connected to other ways, and are routable */
     44    public static final int LONELY_WAY = 3901;
     45    static {
     46        SEVERITY_MAP.put(ROUTING_ISLAND, Severity.OTHER);
     47        SEVERITY_MAP.put(LONELY_WAY, Severity.ERROR);
     48    }
     49
     50    private static final String HIGHWAY = "highway";
     51    private static final String WATERWAY = "waterway";
     52
     53    /**
     54     * This is mostly as a sanity check, and to avoid infinite recursion (shouldn't
     55     * happen, but still)
     56     */
     57    private static final int MAX_LOOPS = 1000;
     58    /** Highways to check for routing connectivity */
     59    private Set<Way> potentialHighways;
     60    /** Waterways to check for routing connectivity */
     61    private Set<Way> potentialWaterways;
     62
     63    /**
     64     * Constructs a new {@code RightAngleBuildingTest} test.
     65     */
     66    public RoutingIslandsTest() {
     67        super(tr("Routing islands"), tr("Checks for roads that cannot be reached or left."));
     68        super.setPartialSelection(false);
     69    }
     70
     71    @Override
     72    public void startTest(ProgressMonitor monitor) {
     73        super.startTest(monitor);
     74        potentialHighways = new HashSet<>();
     75        potentialWaterways = new HashSet<>();
     76    }
     77
     78    @Override
     79    public void endTest() {
     80        Access.AccessTags.getByTransportType(Access.AccessTags.LAND_TRANSPORT_TYPE).parallelStream().forEach(mode -> {
     81            runTest(mode.getKey(), potentialHighways);
     82            progressMonitor.setCustomText(mode.getKey());
     83        });
     84        Access.AccessTags.getByTransportType(Access.AccessTags.WATER_TRANSPORT_TYPE).parallelStream().forEach(mode -> {
     85            progressMonitor.setCustomText(mode.getKey());
     86            runTest(mode.getKey(), potentialWaterways);
     87        });
     88        super.endTest();
     89    }
     90
     91    @Override
     92    public void visit(Way way) {
     93        if (way.isUsable() && way.getNodes().parallelStream().anyMatch(node -> way.getDataSet().getDataSourceBounds()
     94                .parallelStream().anyMatch(source -> source.contains(node.getCoor())))) {
     95            if ((way.hasKey(HIGHWAY) || way.hasKey(WATERWAY))
     96                    && way.getNodes().parallelStream().flatMap(node -> node.getReferrers().parallelStream()).distinct()
     97                            .allMatch(way::equals)
     98                    && way.getNodes().parallelStream().noneMatch(Node::isOutsideDownloadArea)) {
     99                errors.add(TestError.builder(this, SEVERITY_MAP.get(LONELY_WAY), LONELY_WAY).primitives(way)
     100                        .message(tr("Routable way not connected to other ways")).build());
     101            } else if ((ValidatorPrefHelper.PREF_OTHER.get() || ValidatorPrefHelper.PREF_OTHER_UPLOAD.get()
     102                    || !Severity.OTHER.equals(SEVERITY_MAP.get(ROUTING_ISLAND)))) {
     103                if (way.hasKey(HIGHWAY)) {
     104                    potentialHighways.add(way);
     105                } else if (way.hasKey(WATERWAY)) {
     106                    potentialWaterways.add(way);
     107                }
     108            }
     109        }
     110    }
     111
     112    private void runTest(String currentTransportMode, Collection<Way> potentialWays) {
     113        Set<Way> incomingWays = new HashSet<>();
     114        Set<Way> outgoingWays = new HashSet<>();
     115        findConnectedWays(currentTransportMode, potentialWays, incomingWays, outgoingWays);
     116        Set<Way> toIgnore = potentialWays.parallelStream()
     117                .filter(way -> incomingWays.contains(way) || outgoingWays.contains(way))
     118                .filter(way -> !Access.getPositiveAccessValues().contains(
     119                        getDefaultAccessTags(way).getOrDefault(currentTransportMode, Access.AccessTags.NO.getKey())))
     120                .collect(Collectors.toSet());
     121        incomingWays.removeAll(toIgnore);
     122        outgoingWays.removeAll(toIgnore);
     123
     124        checkForUnconnectedWays(incomingWays, outgoingWays, currentTransportMode);
     125        List<Pair<String, Set<Way>>> problematic = collectConnected(potentialWays.parallelStream()
     126                .filter(way -> !incomingWays.contains(way) || !outgoingWays.contains(way))
     127                .filter(way -> Access.getPositiveAccessValues().contains(
     128                        getDefaultAccessTags(way).getOrDefault(currentTransportMode, Access.AccessTags.NO.getKey())))
     129                .collect(Collectors.toSet())).parallelStream()
     130                        .map(way -> new Pair<>((incomingWays.containsAll(way) ? "outgoing" : "incoming"), way))
     131                        .collect(Collectors.toList());
     132        createErrors(problematic, currentTransportMode, potentialWays);
     133    }
     134
     135    /**
     136     * Find ways that may be connected to the wider network
     137     *
     138     * @param currentTransportMode The current mode of transport
     139     * @param potentialWays        The ways to check for connections
     140     * @param incomingWays         A collection that will have incoming ways after
     141     *                             this method is called
     142     * @param outgoingWays         A collection that will have outgoing ways after
     143     *                             this method is called
     144     */
     145    private static void findConnectedWays(String currentTransportMode, Collection<Way> potentialWays,
     146            Collection<Way> incomingWays, Collection<Way> outgoingWays) {
     147        for (Way way : potentialWays) {
     148            if (way.isUsable() && way.isOutsideDownloadArea()) {
     149                Node firstNode = firstNode(way, currentTransportMode);
     150                Node lastNode = lastNode(way, currentTransportMode);
     151                if (isOneway(way, currentTransportMode) != 0 && firstNode != null && firstNode.isOutsideDownloadArea())
     152                    incomingWays.add(way);
     153                if (isOneway(way, currentTransportMode) != 0 && lastNode != null && lastNode.isOutsideDownloadArea()) {
     154                    outgoingWays.add(way);
     155                }
     156                if (isOneway(way, currentTransportMode) == 0 && firstNode != null // Don't need to test lastNode
     157                        && (way.firstNode().isOutsideDownloadArea() || way.lastNode().isOutsideDownloadArea())) {
     158                    incomingWays.add(way);
     159                    outgoingWays.add(way);
     160                }
     161            }
     162        }
     163    }
     164
     165    /**
     166     * Take a collection of ways and modify it so that it is a list of connected
     167     * ways
     168     *
     169     * @param ways A collection of ways that may or may not be connected
     170     * @return a list of sets of ways that are connected
     171     */
     172    private static List<Set<Way>> collectConnected(Collection<Way> ways) {
     173        ArrayList<Set<Way>> collected = new ArrayList<>();
     174        ArrayList<Way> listOfWays = new ArrayList<>(ways);
     175        final int maxLoop = Config.getPref().getInt("validator.routingislands.maxrecursion", MAX_LOOPS);
     176        for (int i = 0; i < listOfWays.size(); i++) {
     177            Way initial = listOfWays.get(i);
     178            Set<Way> connected = new HashSet<>();
     179            connected.add(initial);
     180            int loopCounter = 0;
     181            while (!getConnected(connected) && loopCounter < maxLoop) {
     182                loopCounter++;
     183            }
     184            if (listOfWays.removeAll(connected))
     185                i--; // NOSONAR not an issue -- this ensures that everything is accounted for, only
     186                     // triggers when ways removed
     187            collected.add(connected);
     188        }
     189        return collected;
     190    }
     191
     192    private static boolean getConnected(Collection<Way> ways) {
     193        TagMap defaultAccess = getDefaultAccessTags(ways.iterator().next());
     194        return ways.addAll(ways.parallelStream().flatMap(way -> way.getNodes().parallelStream())
     195                .flatMap(node -> node.getReferrers().parallelStream()).filter(Way.class::isInstance)
     196                .map(Way.class::cast).filter(way -> getDefaultAccessTags(way).equals(defaultAccess))
     197                .collect(Collectors.toSet()));
     198    }
     199
     200    private void createErrors(List<Pair<String, Set<Way>>> problematic, String mode, Collection<Way> potentialWays) {
     201        for (Pair<String, Set<Way>> ways : problematic) {
     202            errors.add(
     203                    TestError.builder(this, SEVERITY_MAP.getOrDefault(ROUTING_ISLAND, Severity.OTHER), ROUTING_ISLAND)
     204                            .message(tr("Routing island"), "{1}: {0}", tr(ways.a), mode == null ? "default" : mode)
     205                            .primitives(ways.b).build());
     206        }
     207    }
     208
     209    /**
     210     * Check for unconnected ways
     211     *
     212     * @param incoming             The current incoming ways (will be modified)
     213     * @param outgoing             The current outgoing ways (will be modified)
     214     * @param currentTransportMode The transport mode we are investigating (may be
     215     *                             {@code null})
     216     */
     217    public static void checkForUnconnectedWays(Collection<Way> incoming, Collection<Way> outgoing,
     218            String currentTransportMode) {
     219        int loopCount = 0;
     220        int maxLoops = Config.getPref().getInt("validator.routingislands.maxrecursion", MAX_LOOPS);
     221        do {
     222            loopCount++;
     223        } while (loopCount <= maxLoops && getWaysFor(incoming, currentTransportMode,
     224                (way, oldWay) -> oldWay.containsNode(firstNode(way, currentTransportMode))
     225                        && checkAccessibility(oldWay, way, currentTransportMode)));
     226        loopCount = 0;
     227        do {
     228            loopCount++;
     229        } while (loopCount <= maxLoops && getWaysFor(outgoing, currentTransportMode,
     230                (way, oldWay) -> oldWay.containsNode(lastNode(way, currentTransportMode))
     231                        && checkAccessibility(oldWay, way, currentTransportMode)));
     232    }
     233
     234    private static boolean getWaysFor(Collection<Way> directional, String currentTransportMode,
     235            BiPredicate<Way, Way> predicate) {
     236        Set<Way> toAdd = new HashSet<>();
     237        for (Way way : directional) {
     238            for (Node node : way.getNodes()) {
     239                Set<Way> referrers = node.getReferrers(true).parallelStream().filter(Way.class::isInstance)
     240                        .map(Way.class::cast).filter(tWay -> !directional.contains(tWay)).collect(Collectors.toSet());
     241                for (Way tWay : referrers) {
     242                    if (isOneway(tWay, currentTransportMode) == 0 || predicate.test(tWay, way)
     243                            || tWay.isClosed()) {
     244                        toAdd.add(tWay);
     245                    }
     246                }
     247            }
     248        }
     249        return directional.addAll(toAdd);
     250    }
     251
     252    /**
     253     * Check if I can get to way to from way from (currently doesn't work with via
     254     * ways)
     255     *
     256     * @param from                 The from way
     257     * @param to                   The to way
     258     * @param currentTransportMode The specific transport mode to check
     259     * @return {@code true} if the to way can be accessed from the from way TODO
     260     *         clean up and work with via ways
     261     */
     262    public static boolean checkAccessibility(Way from, Way to, String currentTransportMode) {
     263        boolean isAccessible = true;
     264
     265        List<Relation> relations = from.getReferrers().parallelStream().distinct().filter(Relation.class::isInstance)
     266                .map(Relation.class::cast).filter(relation -> "restriction".equals(relation.get("type")))
     267                .collect(Collectors.toList());
     268        for (Relation relation : relations) {
     269            if (((relation.hasKey("except") && relation.get("except").contains(currentTransportMode))
     270                    || (currentTransportMode == null || currentTransportMode.trim().isEmpty()))
     271                    && relation.getMembersFor(Collections.singleton(from)).parallelStream()
     272                            .anyMatch(member -> "from".equals(member.getRole()))
     273                    && relation.getMembersFor(Collections.singleton(to)).parallelStream()
     274                            .anyMatch(member -> "to".equals(member.getRole()))) {
     275                isAccessible = false;
     276            }
     277        }
     278        return isAccessible;
     279    }
     280
     281    /**
     282     * Check if a node connects to the outside world
     283     *
     284     * @param node The node to check
     285     * @return true if outside download area, connects to an aeroport, or a water
     286     *         transport
     287     */
     288    public static Boolean outsideConnections(Node node) {
     289        boolean outsideConnections = false;
     290        if (node.isOutsideDownloadArea() || node.hasTag("amenity", "parking_entrance", "parking", "parking_space",
     291                "motorcycle_parking", "ferry_terminal"))
     292            outsideConnections = true;
     293        return outsideConnections;
     294    }
     295
     296    /**
     297     * Check if a way is oneway for a specific transport type
     298     *
     299     * @param way           The way to look at
     300     * @param transportType The specific transport type
     301     * @return See {@link Way#isOneway} (but may additionally return {@code null} if
     302     *         the transport type cannot route down that way)
     303     */
     304    public static Integer isOneway(Way way, String transportType) {
     305        if (transportType == null || transportType.trim().isEmpty()) {
     306            return way.isOneway();
     307        }
     308        String forward = transportType.concat(":forward");
     309        String backward = transportType.concat(":backward");
     310        boolean possibleForward = "yes".equals(way.get(forward)) || (!way.hasKey(forward) && way.isOneway() != -1);
     311        boolean possibleBackward = "yes".equals(way.get(backward)) || (!way.hasKey(backward) && way.isOneway() != 1);
     312        if (transportType.equals(Access.AccessTags.FOOT.getKey()) && !"footway".equals(way.get("highway"))
     313                && !way.hasTag("foot:forward") && !way.hasTag("foot:backward")) {
     314            return 0; // Foot is almost never oneway, especially on generic road types. There are some
     315                      // cases on mountain paths.
     316        }
     317        if (possibleForward && !possibleBackward) {
     318            return 1;
     319        } else if (!possibleForward && possibleBackward) {
     320            return -1;
     321        } else if (!possibleBackward) {
     322            return null;
     323        }
     324        return 0;
     325    }
     326
     327    /**
     328     * Get the first node of a way respecting the oneway for a transport type
     329     *
     330     * @param way           The way to get the node from
     331     * @param transportType The transport type
     332     * @return The first node for the specified transport type, or null if it is not
     333     *         routable
     334     */
     335    public static Node firstNode(Way way, String transportType) {
     336        Integer oneway = isOneway(way, transportType);
     337        Node node = (Integer.valueOf(-1).equals(oneway)) ? way.lastNode() : way.firstNode();
     338        Way tWay = new Way(way);
     339        tWay.clearOsmMetadata();
     340
     341        Map<String, String> accessValues = getDefaultAccessTags(way);
     342        boolean accessible = Access.getPositiveAccessValues()
     343                .contains(accessValues.getOrDefault(transportType, Access.AccessTags.NO.getKey()));
     344        return (transportType == null || accessible) ? node : null;
     345
     346    }
     347
     348    /**
     349     * Get the last node of a way respecting the oneway for a transport type
     350     *
     351     * @param way           The way to get the node from
     352     * @param transportType The transport type
     353     * @return The last node for the specified transport type, or the last node of
     354     *         the way, or null if it is not routable
     355     */
     356    public static Node lastNode(Way way, String transportType) {
     357        Integer oneway = isOneway(way, transportType);
     358        Node node = (Integer.valueOf(-1).equals(oneway)) ? way.firstNode() : way.lastNode();
     359        Map<String, String> accessValues = getDefaultAccessTags(way);
     360        boolean accessible = Access.getPositiveAccessValues()
     361                .contains(accessValues.getOrDefault(transportType, Access.AccessTags.NO.getKey()));
     362        return (transportType == null || accessible) ? node : null;
     363    }
     364
     365    /**
     366     * Get the default access tags for a primitive
     367     *
     368     * @param primitive The primitive to get access tags for
     369     * @return The map of access tags to access
     370     */
     371    public static TagMap getDefaultAccessTags(OsmPrimitive primitive) {
     372        TagMap access = new TagMap();
     373        final TagMap tags;
     374        if (primitive.hasKey(HIGHWAY)) {
     375            tags = getDefaultHighwayAccessTags(primitive.getKeys());
     376        } else if (primitive.hasKey(WATERWAY)) {
     377            tags = getDefaultWaterwayAccessTags(primitive.getKeys());
     378        } else {
     379            tags = new TagMap();
     380        }
     381        tags.putAll(Access.expandAccessValues(tags));
     382
     383        for (String direction : Arrays.asList("", "forward:", "backward:")) {
     384            Access.getTransportModes().parallelStream().map(direction::concat).filter(tags::containsKey)
     385                    .forEach(mode -> access.put(mode, tags.get(direction.concat(mode))));
     386        }
     387        return access;
     388    }
     389
     390    private static TagMap getDefaultWaterwayAccessTags(TagMap tags) {
     391        if ("river".equals(tags.get(WATERWAY))) {
     392            tags.putIfAbsent("boat", Access.AccessTags.YES.getKey());
     393        }
     394        return tags;
     395    }
     396
     397    private static TagMap getDefaultHighwayAccessTags(TagMap tags) {
     398        String highway = tags.get(HIGHWAY);
     399
     400        if (tags.containsKey("sidewalk") && !tags.get("sidewalk").equals(Access.AccessTags.NO.getKey())) {
     401            tags.putIfAbsent(Access.AccessTags.FOOT.getKey(), Access.AccessTags.YES.getKey());
     402        }
     403
     404        if (tags.keySet().parallelStream()
     405                .anyMatch(str -> str.contains("cycleway") && !Access.AccessTags.NO.getKey().equals(tags.get(str)))) {
     406            tags.putIfAbsent(Access.AccessTags.BICYCLE.getKey(), Access.AccessTags.YES.getKey());
     407        }
     408
     409        if ("residential".equals(highway)) {
     410            tags.putIfAbsent(Access.AccessTags.VEHICLE.getKey(), Access.AccessTags.YES.getKey());
     411            tags.putIfAbsent(Access.AccessTags.FOOT.getKey(), Access.AccessTags.YES.getKey());
     412            tags.putIfAbsent(Access.AccessTags.BICYCLE.getKey(), Access.AccessTags.YES.getKey());
     413        } else if (Arrays.asList("service", "unclassified", "tertiary", "tertiary_link").contains(highway)) {
     414            tags.putIfAbsent(Access.AccessTags.VEHICLE.getKey(), Access.AccessTags.YES.getKey());
     415        } else if (Arrays.asList("secondary", "secondary_link").contains(highway)) {
     416            tags.putIfAbsent(Access.AccessTags.VEHICLE.getKey(), Access.AccessTags.YES.getKey());
     417        } else if (Arrays.asList("primary", "primary_link").contains(highway)) {
     418            tags.putIfAbsent(Access.AccessTags.VEHICLE.getKey(), Access.AccessTags.YES.getKey());
     419            tags.putIfAbsent(Access.AccessTags.HGV.getKey(), Access.AccessTags.YES.getKey());
     420        } else if (Arrays.asList("motorway", "trunk", "motorway_link", "trunk_link").contains(highway)) {
     421            tags.putIfAbsent(Access.AccessTags.VEHICLE.getKey(), Access.AccessTags.YES.getKey());
     422            tags.putIfAbsent(Access.AccessTags.BICYCLE.getKey(), Access.AccessTags.NO.getKey());
     423            tags.putIfAbsent(Access.AccessTags.FOOT.getKey(), Access.AccessTags.NO.getKey());
     424        } else if ("steps".equals(highway)) {
     425            tags.putIfAbsent(Access.AccessTags.ACCESS_KEY.getKey(), Access.AccessTags.NO.getKey());
     426            tags.putIfAbsent(Access.AccessTags.FOOT.getKey(), Access.AccessTags.YES.getKey());
     427        } else if ("path".equals(highway)) {
     428            tags.putIfAbsent(Access.AccessTags.MOTOR_VEHICLE.getKey(), Access.AccessTags.NO.getKey());
     429            tags.putIfAbsent(Access.AccessTags.EMERGENCY.getKey(), Access.AccessTags.DESTINATION.getKey());
     430        } else if ("footway".equals(highway)) {
     431            tags.putIfAbsent(Access.AccessTags.FOOT.getKey(), Access.AccessTags.DESIGNATED.getKey());
     432        } else if ("bus_guideway".equals(highway)) {
     433            tags.putIfAbsent(Access.AccessTags.ACCESS_KEY.getKey(), Access.AccessTags.NO.getKey());
     434            tags.putIfAbsent(Access.AccessTags.BUS.getKey(), Access.AccessTags.DESIGNATED.getKey());
     435        } else if ("road".equals(highway)) { // Don't expect these to be routable
     436            tags.putIfAbsent(Access.AccessTags.ACCESS_KEY.getKey(), Access.AccessTags.NO.getKey());
     437        } else {
     438            tags.putIfAbsent(Access.AccessTags.ACCESS_KEY.getKey(), Access.AccessTags.YES.getKey());
     439        }
     440        return tags;
     441    }
     442
     443    /**
     444     * Get the error level for a test
     445     *
     446     * @param test The integer value of the test error
     447     * @return The severity for the test
     448     */
     449    public static Severity getErrorLevel(int test) {
     450        return SEVERITY_MAP.get(test);
     451    }
     452
     453    /**
     454     * Set the error level for a test
     455     *
     456     * @param test     The integer value of the test error
     457     * @param severity The new severity for the test
     458     */
     459    public static void setErrorLevel(int test, Severity severity) {
     460        SEVERITY_MAP.put(test, severity);
     461    }
     462}
  • src/org/openstreetmap/josm/tools/Access.java

     
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.tools;
     3
     4import java.util.ArrayList;
     5import java.util.Arrays;
     6import java.util.Collection;
     7import java.util.Collections;
     8import java.util.Comparator;
     9import java.util.HashMap;
     10import java.util.HashSet;
     11import java.util.List;
     12import java.util.Map;
     13import java.util.Map.Entry;
     14import java.util.Objects;
     15import java.util.Set;
     16import java.util.stream.Collectors;
     17
     18import org.openstreetmap.josm.data.osm.OsmPrimitive;
     19
     20/**
     21 * Access tag related utilities
     22 *
     23 * @see <a href="https://wiki.openstreetmap.org/wiki/Key:access">Key:access</a>
     24 *
     25 * @author Taylor Smock
     26 * @since xxx
     27 */
     28public class Access {
     29    /**
     30     * Holds access tags to avoid typos
     31     */
     32    public enum AccessTags {
     33        /** Air, land, and sea */
     34        ALL_TRANSPORT_TYPE("all"),
     35
     36        /**
     37         * @see <a href="https://wiki.openstreetmap.org/wiki/Key:access">Key:access</a>
     38         */
     39        ACCESS_KEY("access", ALL_TRANSPORT_TYPE),
     40
     41        // Access tag values
     42        /**
     43         * @see <a href=
     44         *      "https://wiki.openstreetmap.org/wiki/Tag:access%3Dyes">Tag:access%3Dyes</a>
     45         */
     46        YES("yes"),
     47        /**
     48         * @see <a href=
     49         *      "https://wiki.openstreetmap.org/wiki/Tag:access%3Dofficial">Tag:access%3Dofficial</a>
     50         */
     51        OFFICIAL("official"),
     52        /**
     53         * @see <a href=
     54         *      "https://wiki.openstreetmap.org/wiki/Tag:access%3Ddesignated">Tag:access%3Ddesignated</a>
     55         */
     56        DESIGNATED("designated"),
     57        /**
     58         * @see <a href=
     59         *      "https://wiki.openstreetmap.org/wiki/Tag:access%3Ddestination">Tag:access%3Ddestination</a>
     60         */
     61        DESTINATION("destination"),
     62        /**
     63         * @see <a href=
     64         *      "https://wiki.openstreetmap.org/wiki/Tag:access%3Ddelivery">Tag:access%3Ddelivery</a>
     65         */
     66        DELIVERY("delivery"),
     67        /**
     68         * @see <a href=
     69         *      "https://wiki.openstreetmap.org/wiki/Tag:access%3Dcustomers">Tag:access%3Dcustomers</a>
     70         */
     71        CUSTOMERS("customers"),
     72        /**
     73         * @see <a href=
     74         *      "https://wiki.openstreetmap.org/wiki/Tag:access%3Dpermissive">Tag:access%3Dpermissive</a>
     75         */
     76        PERMISSIVE("permissive"),
     77        /**
     78         * @see <a href=
     79         *      "https://wiki.openstreetmap.org/wiki/Tag:access%3Dagricultural">Tag:access%3Dagricultural</a>
     80         */
     81        AGRICULTURAL("agricultural"),
     82        /**
     83         * @see <a href=
     84         *      "https://wiki.openstreetmap.org/wiki/Tag:access%3Dforestry">Tag:access%3Dforestry</a>
     85         */
     86        FORESTRY("forestry"),
     87        /**
     88         * @see <a href=
     89         *      "https://wiki.openstreetmap.org/wiki/Tag:access%3Dprivate">Tag:access%3Dprivate</a>
     90         */
     91        PRIVATE("private"),
     92        /**
     93         * @see <a href=
     94         *      "https://wiki.openstreetmap.org/wiki/Tag:access%3Dno">Tag:access%3Dno</a>
     95         */
     96        NO("no"),
     97        /**
     98         * @see <a href=
     99         *      "https://wiki.openstreetmap.org/wiki/Tag:access%3Ddiscouraged">Tag:access%3Ddiscouraged</a>
     100         */
     101        DISCOURAGED("discouraged"),
     102        /**
     103         * @see <a href=
     104         *      "https://wiki.openstreetmap.org/wiki/Tag:access%3Duse_sidepath">Tag:access%3Duse_sidepath</a>
     105         */
     106        USE_SIDEPATH("use_sidepath"),
     107        /**
     108         * @see <a href=
     109         *      "https://wiki.openstreetmap.org/wiki/Tag:access%3Ddismount">Tag:access%3Ddismount</a>
     110         */
     111        DISMOUNT("dismount"),
     112        // Land
     113        /** Land transport types */
     114        LAND_TRANSPORT_TYPE("land", ALL_TRANSPORT_TYPE),
     115        /**
     116         * @see <a href=
     117         *      "https://wiki.openstreetmap.org/wiki/Key:vehicle">Key:vehicle</a>
     118         */
     119        VEHICLE("vehicle", LAND_TRANSPORT_TYPE),
     120        /**
     121         * @see <a href=
     122         *      "https://wiki.openstreetmap.org/wiki/Key:motor_vehicle">Key:motor_vehicle</a>
     123         */
     124        MOTOR_VEHICLE("motor_vehicle", LAND_TRANSPORT_TYPE),
     125        /**
     126         * @see <a href=
     127         *      "https://wiki.openstreetmap.org/wiki/Key:trailer">Key:trailer</a>
     128         */
     129        TRAILER("trailer", LAND_TRANSPORT_TYPE),
     130        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:foot">Key:foot</a> */
     131        FOOT("foot", LAND_TRANSPORT_TYPE),
     132        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:ski">Key:ski</a> */
     133        SKI("ski", LAND_TRANSPORT_TYPE),
     134        /**
     135         * @see <a href=
     136         *      "https://wiki.openstreetmap.org/wiki/Key:inline_skates">Key:inline_skates</a>
     137         */
     138        INLINE_SKATES("inline_skates", LAND_TRANSPORT_TYPE),
     139        /**
     140         * @see <a href=
     141         *      "https://wiki.openstreetmap.org/wiki/Key:ice_skates">Key:ice_skates</a>
     142         */
     143        ICE_SKATES("ice_skates", LAND_TRANSPORT_TYPE),
     144        /**
     145         * @see <a href="https://wiki.openstreetmap.org/wiki/Key:horse">Key:horse</a>
     146         */
     147        HORSE("horse", LAND_TRANSPORT_TYPE),
     148        /**
     149         * @see <a href=
     150         *      "https://wiki.openstreetmap.org/wiki/Key:bicycle">Key:bicycle</a>
     151         */
     152        BICYCLE("bicycle", LAND_TRANSPORT_TYPE),
     153        /**
     154         * @see <a href=
     155         *      "https://wiki.openstreetmap.org/wiki/Key:carriage">Key:carriage</a>
     156         */
     157        CARRIAGE("carriage", LAND_TRANSPORT_TYPE),
     158        /**
     159         * @see <a href=
     160         *      "https://wiki.openstreetmap.org/wiki/Key:caravan">Key:caravan</a>
     161         */
     162        CARAVAN("caravan", LAND_TRANSPORT_TYPE),
     163        /**
     164         * @see <a href=
     165         *      "https://wiki.openstreetmap.org/wiki/Key:motorcycle">Key:motorcycle</a>
     166         */
     167        MOTORCYCLE("motorcycle", LAND_TRANSPORT_TYPE),
     168        /**
     169         * @see <a href="https://wiki.openstreetmap.org/wiki/Key:moped">Key:moped</a>
     170         */
     171        MOPED("moped", LAND_TRANSPORT_TYPE),
     172        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:mofa">Key:mofa</a> */
     173        MOFA("mofa", LAND_TRANSPORT_TYPE),
     174        /**
     175         * @see <a href=
     176         *      "https://wiki.openstreetmap.org/wiki/Key:motorcar">Key:motorcar</a>
     177         */
     178        MOTORCAR("motorcar", LAND_TRANSPORT_TYPE),
     179        /**
     180         * @see <a href=
     181         *      "https://wiki.openstreetmap.org/wiki/Key:motorhome">Key:motorhome</a>
     182         */
     183        MOTORHOME("motorhome", LAND_TRANSPORT_TYPE),
     184        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:psv">Key:psv</a> */
     185        PSV("psv", LAND_TRANSPORT_TYPE),
     186        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:bus">Key:bus</a> */
     187        BUS("bus", LAND_TRANSPORT_TYPE),
     188        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:taxi">Key:taxi</a> */
     189        TAXI("taxi", LAND_TRANSPORT_TYPE),
     190        /**
     191         * @see <a href=
     192         *      "https://wiki.openstreetmap.org/wiki/Key:tourist_bus">Key:tourist_bus</a>
     193         */
     194        TOURIST_BUS("tourist_bus", LAND_TRANSPORT_TYPE),
     195        /**
     196         * @see <a href="https://wiki.openstreetmap.org/wiki/Key:goods">Key:goods</a>
     197         */
     198        GOODS("goods", LAND_TRANSPORT_TYPE),
     199        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:hgv">Key:hgv</a> */
     200        HGV("hgv", LAND_TRANSPORT_TYPE),
     201        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:atv">Key:atv</a> */
     202        ATV("atv", LAND_TRANSPORT_TYPE),
     203        /**
     204         * @see <a href=
     205         *      "https://wiki.openstreetmap.org/wiki/Key:snowmobile">Key:snowmobile</a>
     206         */
     207        SNOWMOBILE("snowmobile", LAND_TRANSPORT_TYPE),
     208        /**
     209         * @see <a href=
     210         *      "https://wiki.openstreetmap.org/wiki/Key:hgv_articulated">Key:hgv_articulated</a>
     211         */
     212        HGV_ARTICULATED("hgv_articulated", LAND_TRANSPORT_TYPE),
     213        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:ski">Key:ski</a> */
     214        SKI_NORDIC("ski:nordic", LAND_TRANSPORT_TYPE),
     215        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:ski">Key:ski</a> */
     216        SKI_ALPINE("ski:alpine", LAND_TRANSPORT_TYPE),
     217        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:ski">Key:ski</a> */
     218        SKI_TELEMARK("ski:telemark", LAND_TRANSPORT_TYPE),
     219        /**
     220         * @see <a href="https://wiki.openstreetmap.org/wiki/Key:coach">Key:coach</a>
     221         */
     222        COACH("coach", LAND_TRANSPORT_TYPE),
     223        /**
     224         * @see <a href=
     225         *      "https://wiki.openstreetmap.org/wiki/Key:golf_cart">Key:golf_cart</a>
     226         */
     227        GOLF_CART("golf_cart", LAND_TRANSPORT_TYPE),
     228        /**
     229         * @see <a href=
     230         *      "https://wiki.openstreetmap.org/wiki/Key:minibus">Key:minibus</a>
     231         */
     232        MINIBUS("minibus", LAND_TRANSPORT_TYPE),
     233        /**
     234         * @see <a href=
     235         *      "https://wiki.openstreetmap.org/wiki/Key:share_taxi">Key:share_taxi</a>
     236         */
     237        SHARE_TAXI("share_taxi", LAND_TRANSPORT_TYPE),
     238        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:hov">Key:hov</a> */
     239        HOV("hov", LAND_TRANSPORT_TYPE),
     240        /**
     241         * @see <a href=
     242         *      "https://wiki.openstreetmap.org/wiki/Key:car_sharing">Key:car_sharing</a>
     243         */
     244        CAR_SHARING("car_sharing", LAND_TRANSPORT_TYPE),
     245        /**
     246         * Routers should default to {@code yes}, regardless of higher access rules,
     247         * assuming it is navigatible by vehicle
     248         *
     249         * @see <a href=
     250         *      "https://wiki.openstreetmap.org/wiki/Key:emergency">Key:emergency</a>
     251         */
     252        EMERGENCY("emergency", LAND_TRANSPORT_TYPE),
     253        /**
     254         * @see <a href="https://wiki.openstreetmap.org/wiki/Key:hazmat">Key:hazmat</a>
     255         */
     256        HAZMAT("hazmat", LAND_TRANSPORT_TYPE),
     257        /**
     258         * @see <a href=
     259         *      "https://wiki.openstreetmap.org/wiki/Key:disabled">Key:disabled</a>
     260         */
     261        DISABLED("disabled", LAND_TRANSPORT_TYPE),
     262
     263        // Water
     264        /** Water transport type */
     265        WATER_TRANSPORT_TYPE("water", ALL_TRANSPORT_TYPE),
     266        /**
     267         * @see <a href=
     268         *      "https://wiki.openstreetmap.org/wiki/Key:swimming">Key:swimming</a>
     269         */
     270        SWIMMING("swimming", WATER_TRANSPORT_TYPE),
     271        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:boat">Key:boat</a> */
     272        BOAT("boat", WATER_TRANSPORT_TYPE),
     273        /**
     274         * @see <a href=
     275         *      "https://wiki.openstreetmap.org/wiki/Key:fishing_vessel">Key:fishing_vessel</a>
     276         */
     277        FISHING_VESSEL("fishing_vessel", WATER_TRANSPORT_TYPE),
     278        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:ship">Key:ship</a> */
     279        SHIP("ship", WATER_TRANSPORT_TYPE),
     280        /**
     281         * @see <a href=
     282         *      "https://wiki.openstreetmap.org/wiki/Key:motorboat">Key:motorboat</a>
     283         */
     284        MOTORBOAT("motorboat", WATER_TRANSPORT_TYPE),
     285        /**
     286         * @see <a href=
     287         *      "https://wiki.openstreetmap.org/wiki/Key:sailboat">Key:sailboat</a>
     288         */
     289        SAILBOAT("sailboat", WATER_TRANSPORT_TYPE),
     290        /**
     291         * @see <a href="https://wiki.openstreetmap.org/wiki/Key:canoe">Key:canoe</a>
     292         */
     293        CANOE("canoe", WATER_TRANSPORT_TYPE),
     294        /**
     295         * @see <a href=
     296         *      "https://wiki.openstreetmap.org/wiki/Key:passenger">Key:passenger</a>
     297         */
     298        PASSENGER("passenger", WATER_TRANSPORT_TYPE),
     299        /**
     300         * @see <a href="https://wiki.openstreetmap.org/wiki/Key:cargo">Key:cargo</a>
     301         */
     302        CARGO("cargo", WATER_TRANSPORT_TYPE),
     303        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:isps">Key:isps</a> */
     304        ISPS("isps", WATER_TRANSPORT_TYPE),
     305        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:bulk">Key:bulk</a> */
     306        BULK("bulk", WATER_TRANSPORT_TYPE),
     307        /**
     308         * @see <a href="https://wiki.openstreetmap.org/wiki/Key:tanker">Key:tanker</a>
     309         */
     310        TANKER("tanker", WATER_TRANSPORT_TYPE),
     311        /**
     312         * @see <a href=
     313         *      "https://wiki.openstreetmap.org/wiki/Key:container">Key:container</a>
     314         */
     315        CONTAINER("container", WATER_TRANSPORT_TYPE),
     316        /** @see <a href="https://wiki.openstreetmap.org/wiki/Key:imdg">Key:imdg</a> */
     317        IMDG("imdg", WATER_TRANSPORT_TYPE),
     318        /**
     319         * @see <a href="https://wiki.openstreetmap.org/wiki/Key:tanker">Key:tanker</a>
     320         */
     321        TANKER_GAS("tanker:gas", WATER_TRANSPORT_TYPE),
     322        /**
     323         * @see <a href="https://wiki.openstreetmap.org/wiki/Key:tanker">Key:tanker</a>
     324         */
     325        TANKER_OIL("tanker:oil", WATER_TRANSPORT_TYPE),
     326        /**
     327         * @see <a href="https://wiki.openstreetmap.org/wiki/Key:tanker">Key:tanker</a>
     328         */
     329        TANKER_CHEMICAL("tanker:chemical", WATER_TRANSPORT_TYPE),
     330        /**
     331         * @see <a href="https://wiki.openstreetmap.org/wiki/Key:tanker">Key:tanker</a>
     332         */
     333        TANKER_SINGLEHULL("tanker:singlehull", WATER_TRANSPORT_TYPE),
     334
     335        // Trains
     336        /** Rail transport type */
     337        RAIL_TRANSPORT_TYPE("rail", ALL_TRANSPORT_TYPE),
     338        /**
     339         * @see <a href="https://wiki.openstreetmap.org/wiki/Key:train">Key:train</a>
     340         */
     341        TRAIN("train", RAIL_TRANSPORT_TYPE);
     342
     343        private String key;
     344        private AccessTags type;
     345
     346        AccessTags(String key) {
     347            this.key = key;
     348            this.type = null;
     349        }
     350
     351        AccessTags(String key, AccessTags type) {
     352            this.key = key;
     353            this.type = type;
     354        }
     355
     356        /**
     357         * @return The key for the enum
     358         */
     359        public String getKey() {
     360            return key;
     361        }
     362
     363        /**
     364         * @return The AccessTags transport type
     365         *         (RAIL_TRANSPORT_TYPE/WATER_TRANSPORT_TYPE/etc)
     366         */
     367        public AccessTags getTransportType() {
     368            return type;
     369        }
     370
     371        /**
     372         * Check if this is a parent transport type (air/sea/water/all)
     373         *
     374         * @param potentialDescendant The AccessTags that we want to check
     375         * @return true if valueOf is a child transport type of this
     376         */
     377        public boolean parentOf(AccessTags potentialDescendant) {
     378            AccessTags tmp = potentialDescendant;
     379            while (tmp != null && tmp != this) {
     380                tmp = tmp.getTransportType();
     381            }
     382            return tmp == this;
     383        }
     384
     385        /**
     386         * Get the enum that matches the mode
     387         *
     388         * @param childrenMode The mode to get the access tag
     389         * @return The AccessTags enum that matches the childrenMode, or null
     390         */
     391        public static AccessTags get(String childrenMode) {
     392            for (AccessTags value : values()) {
     393                if (value.getKey().equalsIgnoreCase(childrenMode)) {
     394                    return value;
     395                }
     396            }
     397            return null;
     398        }
     399
     400        /**
     401         * Get access tags that match a certain type
     402         *
     403         * @param type {@link AccessTags#WATER_TRANSPORT_TYPE},
     404         *             {@link AccessTags#LAND_TRANSPORT_TYPE},
     405         *             {@link AccessTags#RAIL_TRANSPORT_TYPE}, or
     406         *             {@link AccessTags#ALL_TRANSPORT_TYPE}
     407         * @return A collection of access tags that match the given transport type
     408         */
     409        public static Collection<AccessTags> getByTransportType(AccessTags type) {
     410            return Arrays.stream(values()).filter(type::parentOf).collect(Collectors.toList());
     411        }
     412    }
     413    /**
     414     * The key for children modes for the map, see {@link Access#getAccessMethods}
     415     */
     416    public static final String CHILDREN = "children";
     417    /** The key for parent modes for the map, see {@link Access#getAccessMethods} */
     418    public static final String PARENT = "parent";
     419    /** This set has keys that indicate that access is possible */
     420    private static final Set<String> POSITIVE_ACCESS = new HashSet<>(Arrays.asList(AccessTags.YES, AccessTags.OFFICIAL,
     421            AccessTags.DESIGNATED, AccessTags.DESTINATION, AccessTags.DELIVERY, AccessTags.CUSTOMERS,
     422            AccessTags.PERMISSIVE, AccessTags.AGRICULTURAL, AccessTags.FORESTRY).stream().map(AccessTags::getKey)
     423            .collect(Collectors.toSet()));
     424    /** This set has all basic restriction values (yes/no/permissive/private/...) */
     425    private static final Set<String> RESTRICTION_VALUES = new HashSet<>(
     426            Arrays.asList(AccessTags.PRIVATE, AccessTags.NO).stream().map(AccessTags::getKey)
     427                    .collect(Collectors.toSet()));
     428    /** This set has transport modes (access/foot/ski/motor_vehicle/vehicle/...) */
     429    private static final Set<String> TRANSPORT_MODES = new HashSet<>(
     430            Arrays.asList(AccessTags.ACCESS_KEY, AccessTags.FOOT, AccessTags.SKI, AccessTags.INLINE_SKATES,
     431                    AccessTags.ICE_SKATES, AccessTags.HORSE, AccessTags.VEHICLE, AccessTags.BICYCLE,
     432                    AccessTags.CARRIAGE, AccessTags.TRAILER, AccessTags.CARAVAN, AccessTags.MOTOR_VEHICLE,
     433                    AccessTags.MOTORCYCLE, AccessTags.MOPED, AccessTags.MOFA, AccessTags.MOTORCAR, AccessTags.MOTORHOME,
     434                    AccessTags.PSV, AccessTags.BUS, AccessTags.TAXI, AccessTags.TOURIST_BUS, AccessTags.GOODS,
     435                    AccessTags.HGV, AccessTags.AGRICULTURAL, AccessTags.ATV,
     436                    AccessTags.SNOWMOBILE, AccessTags.HGV_ARTICULATED, AccessTags.SKI_NORDIC, AccessTags.SKI_ALPINE,
     437                    AccessTags.SKI_TELEMARK, AccessTags.COACH, AccessTags.GOLF_CART
     438            /*
     439             * ,"minibus","share_taxi","hov","car_sharing","emergency","hazmat","disabled"
     440             */).stream().map(AccessTags::getKey).collect(Collectors.toSet()));
     441
     442    /** Map<Access Method, Map<Parent/Child, List<Access Methods>> */
     443    private static final Map<String, Map<String, List<String>>> accessMethods = new HashMap<>();
     444    static {
     445        RESTRICTION_VALUES.addAll(POSITIVE_ACCESS);
     446        defaultInheritance();
     447    }
     448
     449    private Access() {
     450        // Hide the constructor
     451    }
     452
     453    /**
     454     * Create the default access inheritance, as defined at
     455     * {@link "https://wiki.openstreetmap.org/wiki/Key:access#Transport_mode_restrictions"}
     456     */
     457    private static void defaultInheritance() {
     458        addMode(null, AccessTags.ACCESS_KEY);
     459
     460        // Land
     461        addModes(AccessTags.ACCESS_KEY, AccessTags.FOOT, AccessTags.SKI, AccessTags.INLINE_SKATES,
     462                AccessTags.ICE_SKATES, AccessTags.HORSE, AccessTags.VEHICLE);
     463        addModes(AccessTags.SKI, AccessTags.SKI_NORDIC, AccessTags.SKI_ALPINE, AccessTags.SKI_TELEMARK);
     464        addModes(AccessTags.VEHICLE, AccessTags.BICYCLE, AccessTags.CARRIAGE, AccessTags.TRAILER,
     465                AccessTags.MOTOR_VEHICLE);
     466        addModes(AccessTags.TRAILER, AccessTags.CARAVAN);
     467        addModes(AccessTags.MOTOR_VEHICLE, AccessTags.MOTORCYCLE, AccessTags.MOPED, AccessTags.MOFA,
     468                AccessTags.MOTORCAR, AccessTags.MOTORHOME, AccessTags.TOURIST_BUS, AccessTags.COACH, AccessTags.GOODS,
     469                AccessTags.HGV, AccessTags.AGRICULTURAL, AccessTags.GOLF_CART, AccessTags.ATV, AccessTags.SNOWMOBILE,
     470                AccessTags.PSV, AccessTags.HOV, AccessTags.CAR_SHARING, AccessTags.EMERGENCY, AccessTags.HAZMAT,
     471                AccessTags.DISABLED);
     472        addMode(AccessTags.HGV, AccessTags.HGV_ARTICULATED);
     473        addModes(AccessTags.PSV, AccessTags.BUS, AccessTags.MINIBUS, AccessTags.SHARE_TAXI, AccessTags.TAXI);
     474
     475        // Water
     476        addModes(AccessTags.ACCESS_KEY, AccessTags.SWIMMING, AccessTags.BOAT, AccessTags.FISHING_VESSEL,
     477                AccessTags.SHIP);
     478        addModes(AccessTags.BOAT, AccessTags.MOTORBOAT, AccessTags.SAILBOAT, AccessTags.CANOE);
     479        addModes(AccessTags.SHIP, AccessTags.PASSENGER, AccessTags.CARGO, AccessTags.ISPS);
     480        addModes(AccessTags.CARGO, AccessTags.BULK, AccessTags.TANKER, AccessTags.CONTAINER, AccessTags.IMDG);
     481        addModes(AccessTags.TANKER, AccessTags.TANKER_GAS, AccessTags.TANKER_OIL, AccessTags.TANKER_CHEMICAL,
     482                AccessTags.TANKER_SINGLEHULL);
     483
     484        // Rail
     485        addModes(AccessTags.ACCESS_KEY, AccessTags.TRAIN);
     486    }
     487
     488    /**
     489     * Add multiple modes with a common parent
     490     *
     491     * @param parent The parent of all the modes
     492     * @param modes  The modes to add
     493     */
     494    public static void addModes(AccessTags parent, AccessTags... modes) {
     495        for (AccessTags mode : modes) {
     496            addMode(parent, mode);
     497        }
     498    }
     499
     500    /**
     501     * Add modes to a list, modifying parents as needed
     502     *
     503     * @param mode   The mode to be added
     504     * @param parent The parent of the mode
     505     */
     506    public static void addMode(AccessTags parent, AccessTags mode) {
     507        Objects.requireNonNull(mode, "Mode must not be null");
     508        if (parent != null) {
     509            Map<String, List<String>> parentMap = accessMethods.getOrDefault(parent.getKey(), new HashMap<>());
     510            accessMethods.putIfAbsent(parent.getKey(), parentMap);
     511            List<String> parentChildren = parentMap.getOrDefault(CHILDREN, new ArrayList<>());
     512            if (!parentChildren.contains(mode.getKey()))
     513                parentChildren.add(mode.getKey());
     514            parentMap.putIfAbsent(CHILDREN, parentChildren);
     515        }
     516        Map<String, List<String>> modeMap = accessMethods.getOrDefault(mode.getKey(), new HashMap<>());
     517        accessMethods.putIfAbsent(mode.getKey(), modeMap);
     518        List<String> modeParent = modeMap.getOrDefault(PARENT,
     519                Collections.singletonList(parent == null ? null : parent.getKey()));
     520        modeMap.putIfAbsent(PARENT, modeParent);
     521    }
     522
     523    /**
     524     * Get the number of parents a mode has
     525     *
     526     * @param mode The mode with parents
     527     * @return The number of parents the mode has
     528     */
     529    public static int depth(String mode) {
     530        String tempMode = mode;
     531        int maxCount = accessMethods.size();
     532        while (tempMode != null && maxCount > 0) {
     533            tempMode = accessMethods.getOrDefault(tempMode, Collections.emptyMap())
     534                    .getOrDefault(PARENT, Collections.emptyList()).get(0);
     535            if (tempMode != null)
     536                maxCount--;
     537        }
     538        return accessMethods.size() - maxCount;
     539    }
     540
     541    /**
     542     * Expand access modes to cover the children of that access mode (currently only
     543     * supports the default hierarchy)
     544     *
     545     * @param mode   The transport mode
     546     * @param access The access value (the children transport modes inherit this
     547     *               value)
     548     * @return A map of the mode and its children (does not include parents)
     549     */
     550    public static Map<String, String> expandAccessMode(String mode, String access) {
     551        return expandAccessMode(mode, access, AccessTags.ALL_TRANSPORT_TYPE);
     552    }
     553
     554    /**
     555     * Expand access modes to cover the children of that access mode (currently only
     556     * supports the default hierarchy)
     557     *
     558     * @param mode          The transport mode
     559     * @param access        The access value (the children transport modes inherit
     560     *                      this value)
     561     * @param transportType {@link AccessTags#ALL_TRANSPORT_TYPE},
     562     *                      {@link AccessTags#LAND_TRANSPORT_TYPE},
     563     *                      {@link AccessTags#WATER_TRANSPORT_TYPE},
     564     *                      {@link AccessTags#RAIL_TRANSPORT_TYPE}
     565     * @return A map of the mode and its children (does not include parents)
     566     */
     567    public static Map<String, String> expandAccessMode(String mode, String access, AccessTags transportType) {
     568        Map<String, String> accessModes = new HashMap<>();
     569        accessModes.put(mode, access);
     570        if (accessMethods.containsKey(mode)) {
     571            for (String childrenMode : accessMethods.getOrDefault(mode, Collections.emptyMap()).getOrDefault(CHILDREN,
     572                    Collections.emptyList())) {
     573                if (transportType.parentOf(AccessTags.get(childrenMode)))
     574                    accessModes.putAll(expandAccessMode(childrenMode, access, transportType));
     575            }
     576        }
     577        return accessModes;
     578    }
     579
     580    /**
     581     * Merge two access maps (more specific wins)
     582     *
     583     * @param map1 A map with access values (see {@link Access#expandAccessMode})
     584     * @param map2 A map with access values (see {@link Access#expandAccessMode})
     585     * @return The merged map
     586     */
     587    public static Map<String, String> mergeMaps(Map<String, String> map1, Map<String, String> map2) {
     588        Map<String, String> merged;
     589        if (map1.keySet().containsAll(map2.keySet())) {
     590            merged = new HashMap<>(map1);
     591            merged.putAll(map2);
     592        } else { // if they don't overlap or if map2 contains all of map1
     593            merged = new HashMap<>(map2);
     594            merged.putAll(map1);
     595        }
     596        return merged;
     597    }
     598
     599    /**
     600     * Get the set of values that can generally be considered to be accessible
     601     *
     602     * @return A set of values that can be used for routing purposes (unmodifiable)
     603     */
     604    public static Set<String> getPositiveAccessValues() {
     605        return Collections.unmodifiableSet(POSITIVE_ACCESS);
     606    }
     607
     608    /**
     609     * Get the valid restriction values ({@code unknown} is not included). See
     610     *
     611     * @return Valid values for restrictions (unmodifiable)
     612     * @see <a href=
     613     *      "https://wiki.openstreetmap.org/wiki/Key:access#List_of_possible_values">Key:access#List_of_possible_values</a>
     614     */
     615    public static Set<String> getRestrictionValues() {
     616        return Collections.unmodifiableSet(RESTRICTION_VALUES);
     617    }
     618
     619    /**
     620     * Get the valid transport modes. See
     621     *
     622     * @return Value transport modes (unmodifiable)
     623     * @see <a href=
     624     *      "https://wiki.openstreetmap.org/wiki/Key:access#Transport_mode_restrictions">Key:access#Transport_mode_restrictions</a>
     625     */
     626    public static Set<String> getTransportModes() {
     627        return Collections.unmodifiableSet(TRANSPORT_MODES);
     628    }
     629
     630    /**
     631     * Get the access method hierarchy.
     632     *
     633     * @return The hierarchy for access modes (unmodifiable)
     634     * @see <a href=
     635     *      "https://wiki.openstreetmap.org/wiki/Key:access#Transport_mode_restrictions">Key:access#Transport_mode_restrictions</a>
     636     */
     637    public static Map<String, Map<String, List<String>>> getAccessMethods() {
     638        Map<String, Map<String, List<String>>> map = new HashMap<>();
     639        for (Entry<String, Map<String, List<String>>> entry : map.entrySet()) {
     640            Map<String, List<String>> tMap = new HashMap<>();
     641            entry.getValue().forEach((key, list) -> tMap.put(key, Collections.unmodifiableList(list)));
     642            map.put(entry.getKey(), Collections.unmodifiableMap(tMap));
     643        }
     644        return Collections.unmodifiableMap(map);
     645    }
     646
     647    /**
     648     * Get the implied access values for a primitive
     649     *
     650     * @param primitive     A primitive with access values
     651     * @param transportType {@link AccessTags#ALL_TRANSPORT_TYPE},
     652     *                      {@link AccessTags#LAND_TRANSPORT_TYPE},
     653     *                      {@link AccessTags#WATER_TRANSPORT_TYPE},
     654     *                      {@link AccessTags#RAIL_TRANSPORT_TYPE}
     655     * @return The implied access values (for example, "hgv=designated" adds
     656     *         "hgv_articulated=designated")
     657     */
     658    public static Map<String, String> getAccessValues(OsmPrimitive primitive, AccessTags transportType) {
     659        Map<String, String> accessValues = new HashMap<>();
     660        TRANSPORT_MODES.stream().filter(primitive::hasKey)
     661                .map(mode -> expandAccessMode(mode, primitive.get(mode), transportType))
     662                .forEach(modeAccess -> {
     663                    Map<String, String> tMap = mergeMaps(accessValues, modeAccess);
     664                    accessValues.clear();
     665                    accessValues.putAll(tMap);
     666                });
     667        return accessValues;
     668    }
     669
     670    /**
     671     * Expand a map of access values
     672     *
     673     * @param accessValues A map of mode, access type values
     674     * @return The expanded access values
     675     */
     676    public static Map<String, String> expandAccessValues(Map<String, String> accessValues) {
     677        Map<String, String> modes = new HashMap<>();
     678        List<Map<String, String>> list = accessValues.entrySet().stream()
     679                .map(entry -> expandAccessMode(entry.getKey(), entry.getValue()))
     680                .sorted(Comparator.comparingInt(Map::size))
     681                .collect(Collectors.toCollection(ArrayList::new));
     682        Collections.reverse(list);
     683        for (Map<String, String> access : list) {
     684            modes = mergeMaps(modes, access);
     685        }
     686        return modes;
     687    }
     688}
  • test/unit/org/openstreetmap/josm/data/validation/tests/RoutingIslandsTestTest.java

     
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.data.validation.tests;
     3
     4import static org.junit.Assert.assertEquals;
     5import static org.junit.Assert.assertFalse;
     6import static org.junit.Assert.assertNull;
     7import static org.junit.Assert.assertSame;
     8import static org.junit.Assert.assertTrue;
     9
     10import java.util.Arrays;
     11import java.util.Collections;
     12import java.util.HashSet;
     13import java.util.Set;
     14import java.util.stream.Collectors;
     15
     16import org.junit.Rule;
     17import org.junit.Test;
     18import org.openstreetmap.josm.TestUtils;
     19import org.openstreetmap.josm.data.Bounds;
     20import org.openstreetmap.josm.data.DataSource;
     21import org.openstreetmap.josm.data.coor.LatLon;
     22import org.openstreetmap.josm.data.osm.DataSet;
     23import org.openstreetmap.josm.data.osm.Node;
     24import org.openstreetmap.josm.data.osm.OsmPrimitive;
     25import org.openstreetmap.josm.data.osm.Way;
     26import org.openstreetmap.josm.data.validation.Severity;
     27import org.openstreetmap.josm.spi.preferences.Config;
     28import org.openstreetmap.josm.testutils.JOSMTestRules;
     29
     30import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
     31
     32/**
     33 * Test class for {@link RoutingIslandsTest}
     34 *
     35 * @author Taylor Smock
     36 * @since xxx
     37 */
     38public class RoutingIslandsTestTest {
     39    /**
     40     * Setup test.
     41     */
     42    @Rule
     43    @SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
     44    public JOSMTestRules rule = new JOSMTestRules().projection().preferences();
     45
     46    /**
     47     * Test method for {@link RoutingIslandsTest#RoutingIslandsTest()} and the
     48     * testing apparatus
     49     */
     50    @Test
     51    public void testRoutingIslandsTest() {
     52        RoutingIslandsTest.setErrorLevel(RoutingIslandsTest.ROUTING_ISLAND, Severity.WARNING);
     53        RoutingIslandsTest test = new RoutingIslandsTest();
     54        test.startTest(null);
     55        test.endTest();
     56        assertTrue(test.getErrors().isEmpty());
     57
     58        DataSet ds = new DataSet();
     59
     60        Way way1 = TestUtils.newWay("highway=residential", new Node(new LatLon(0, 0)), new Node(new LatLon(1, 1)));
     61        Way way2 = TestUtils.newWay("highway=residential", new Node(new LatLon(-1, 0)), way1.firstNode());
     62        addToDataSet(ds, way1);
     63        addToDataSet(ds, way2);
     64
     65        ds.addDataSource(new DataSource(new Bounds(0, 0, 1, 1), "openstreetmap.org"));
     66
     67        test.clear();
     68        test.startTest(null);
     69        test.visit(ds.allPrimitives());
     70        test.endTest();
     71        assertTrue(test.getErrors().isEmpty());
     72
     73        ds.addDataSource(new DataSource(new Bounds(-5, -5, 5, 5), "openstreetmap.org"));
     74        test.clear();
     75        test.startTest(null);
     76        test.visit(ds.allPrimitives());
     77        test.endTest();
     78        assertEquals(1, test.getErrors().size());
     79        assertEquals(2, test.getErrors().get(0).getPrimitives().size());
     80
     81        ds.clear();
     82        way1 = TestUtils.newWay("highway=motorway oneway=yes", new Node(new LatLon(39.1156655, -108.5465434)),
     83                new Node(new LatLon(39.1157251, -108.5496874)), new Node(new LatLon(39.11592, -108.5566841)));
     84        way2 = TestUtils.newWay("highway=motorway oneway=yes", new Node(new LatLon(39.1157244, -108.55674)),
     85                new Node(new LatLon(39.1155548, -108.5496901)), new Node(new LatLon(39.1154827, -108.5462431)));
     86        addToDataSet(ds, way1);
     87        addToDataSet(ds, way2);
     88        ds.addDataSource(
     89                new DataSource(new Bounds(new LatLon(39.1136949, -108.558445), new LatLon(39.117242, -108.5489166)),
     90                        "openstreetmap.org"));
     91        test.clear();
     92        test.startTest(null);
     93        test.visit(ds.allPrimitives());
     94        test.endTest();
     95        assertEquals(2, test.getErrors().size());
     96        Way way3 = TestUtils.newWay("highway=motorway oneway=no", way1.getNode(1), way2.getNode(1));
     97        addToDataSet(ds, way3);
     98        test.clear();
     99        test.startTest(null);
     100        test.visit(ds.allPrimitives());
     101        test.endTest();
     102        assertEquals(2, test.getErrors().size());
     103
     104        Node tNode = new Node(new LatLon(39.1158845, -108.5599312));
     105        addToDataSet(ds, tNode);
     106        way1.addNode(tNode);
     107        tNode = new Node(new LatLon(39.115723, -108.5599239));
     108        addToDataSet(ds, tNode);
     109        way2.addNode(0, tNode);
     110        test.clear();
     111        test.startTest(null);
     112        test.visit(ds.allPrimitives());
     113        test.endTest();
     114        assertTrue(test.getErrors().isEmpty());
     115    }
     116
     117    /**
     118     * Test roundabouts
     119     */
     120    @Test
     121    public void testRoundabouts() {
     122        RoutingIslandsTest test = new RoutingIslandsTest();
     123        Way roundabout = TestUtils.newWay("highway=residential junction=roundabout oneway=yes",
     124                new Node(new LatLon(39.119582, -108.5262686)), new Node(new LatLon(39.1196494, -108.5260935)),
     125                new Node(new LatLon(39.1197572, -108.5260784)), new Node(new LatLon(39.1197929, -108.526391)),
     126                new Node(new LatLon(39.1196595, -108.5264047)));
     127        roundabout.addNode(roundabout.firstNode()); // close it up
     128        DataSet ds = new DataSet();
     129        addToDataSet(ds, roundabout);
     130        ds.addDataSource(
     131                new DataSource(new Bounds(new LatLon(39.1182025, -108.527574), new LatLon(39.1210588, -108.5251112)),
     132                        "openstreetmap.org"));
     133        Way incomingFlare = TestUtils.newWay("highway=residential oneway=yes",
     134                new Node(new LatLon(39.1196377, -108.5257567)), roundabout.getNode(3));
     135        addToDataSet(ds, incomingFlare);
     136        Way outgoingFlare = TestUtils.newWay("highway=residential oneway=yes", roundabout.getNode(2),
     137                incomingFlare.firstNode());
     138        addToDataSet(ds, outgoingFlare);
     139
     140        Way outgoingRoad = TestUtils.newWay("highway=residential", incomingFlare.firstNode(),
     141                new Node(new LatLon(39.1175184, -108.5219623)));
     142        addToDataSet(ds, outgoingRoad);
     143
     144        test.startTest(null);
     145        test.visit(ds.allPrimitives());
     146        test.endTest();
     147        assertTrue(test.getErrors().isEmpty());
     148    }
     149
     150    /**
     151     * Test method for {@link RoutingIslandsTest#checkForUnconnectedWays}.
     152     */
     153    @Test
     154    public void testCheckForUnconnectedWaysIncoming() {
     155        RoutingIslandsTest.checkForUnconnectedWays(Collections.emptySet(), Collections.emptySet(), null);
     156        Way way1 = TestUtils.newWay("highway=residential oneway=yes", new Node(new LatLon(0, 0)),
     157                new Node(new LatLon(1, 1)));
     158        Set<Way> incomingSet = new HashSet<>();
     159        DataSet ds = new DataSet();
     160        way1.getNodes().forEach(ds::addPrimitive);
     161        ds.addPrimitive(way1);
     162        incomingSet.add(way1);
     163        RoutingIslandsTest.checkForUnconnectedWays(incomingSet, Collections.emptySet(), null);
     164        assertEquals(1, incomingSet.size());
     165        assertSame(way1, incomingSet.iterator().next());
     166
     167        Way way2 = TestUtils.newWay("highway=residential", way1.firstNode(), new Node(new LatLon(-1, -2)));
     168        way2.getNodes().parallelStream().filter(node -> node.getDataSet() == null).forEach(ds::addPrimitive);
     169        ds.addPrimitive(way2);
     170
     171        RoutingIslandsTest.checkForUnconnectedWays(incomingSet, Collections.emptySet(), null);
     172        assertEquals(2, incomingSet.size());
     173        assertTrue(incomingSet.parallelStream().allMatch(way -> Arrays.asList(way1, way2).contains(way)));
     174
     175        Way way3 = TestUtils.newWay("highway=residential", way2.lastNode(), new Node(new LatLon(-2, -1)));
     176        way3.getNodes().parallelStream().filter(node -> node.getDataSet() == null).forEach(ds::addPrimitive);
     177        ds.addPrimitive(way3);
     178
     179        incomingSet.clear();
     180        incomingSet.add(way1);
     181        RoutingIslandsTest.checkForUnconnectedWays(incomingSet, Collections.emptySet(), null);
     182        assertEquals(3, incomingSet.size());
     183        assertTrue(incomingSet.parallelStream().allMatch(way -> Arrays.asList(way1, way2, way3).contains(way)));
     184
     185        Config.getPref().putInt("validator.routingislands.maxrecursion", 1);
     186        incomingSet.clear();
     187        incomingSet.add(way1);
     188        RoutingIslandsTest.checkForUnconnectedWays(incomingSet, Collections.emptySet(), null);
     189        assertEquals(2, incomingSet.size());
     190        assertTrue(incomingSet.parallelStream().allMatch(way -> Arrays.asList(way1, way2).contains(way)));
     191    }
     192
     193    /**
     194     * Test method for {@link RoutingIslandsTest#checkForUnconnectedWays}.
     195     */
     196    @Test
     197    public void testCheckForUnconnectedWaysOutgoing() {
     198        RoutingIslandsTest.checkForUnconnectedWays(Collections.emptySet(), Collections.emptySet(), null);
     199        Way way1 = TestUtils.newWay("highway=residential oneway=yes", new Node(new LatLon(0, 0)),
     200                new Node(new LatLon(1, 1)));
     201        Set<Way> outgoingSet = new HashSet<>();
     202        DataSet ds = new DataSet();
     203        way1.getNodes().forEach(ds::addPrimitive);
     204        ds.addPrimitive(way1);
     205        outgoingSet.add(way1);
     206        RoutingIslandsTest.checkForUnconnectedWays(Collections.emptySet(), outgoingSet, null);
     207        assertEquals(1, outgoingSet.size());
     208        assertSame(way1, outgoingSet.iterator().next());
     209
     210        Way way2 = TestUtils.newWay("highway=residential", way1.firstNode(), new Node(new LatLon(-1, -2)));
     211        way2.getNodes().parallelStream().filter(node -> node.getDataSet() == null).forEach(ds::addPrimitive);
     212        ds.addPrimitive(way2);
     213
     214        RoutingIslandsTest.checkForUnconnectedWays(Collections.emptySet(), outgoingSet, null);
     215        assertEquals(2, outgoingSet.size());
     216        assertTrue(outgoingSet.parallelStream().allMatch(way -> Arrays.asList(way1, way2).contains(way)));
     217
     218        Way way3 = TestUtils.newWay("highway=residential", way2.lastNode(), new Node(new LatLon(-2, -1)));
     219        way3.getNodes().parallelStream().filter(node -> node.getDataSet() == null).forEach(ds::addPrimitive);
     220        ds.addPrimitive(way3);
     221
     222        outgoingSet.clear();
     223        outgoingSet.add(way1);
     224        RoutingIslandsTest.checkForUnconnectedWays(Collections.emptySet(), outgoingSet, null);
     225        assertEquals(3, outgoingSet.size());
     226        assertTrue(outgoingSet.parallelStream().allMatch(way -> Arrays.asList(way1, way2, way3).contains(way)));
     227
     228        Config.getPref().putInt("validator.routingislands.maxrecursion", 1);
     229        outgoingSet.clear();
     230        outgoingSet.add(way1);
     231        RoutingIslandsTest.checkForUnconnectedWays(Collections.emptySet(), outgoingSet, null);
     232        assertEquals(2, outgoingSet.size());
     233        assertTrue(outgoingSet.parallelStream().allMatch(way -> Arrays.asList(way1, way2).contains(way)));
     234    }
     235
     236    /**
     237     * Test method for {@link RoutingIslandsTest#outsideConnections(Node)}.
     238     */
     239    @Test
     240    public void testOutsideConnections() {
     241        Node node = new Node(new LatLon(0, 0));
     242        DataSet ds = new DataSet(node);
     243        ds.addDataSource(new DataSource(new Bounds(-0.1, -0.1, -0.01, -0.01), "Test bounds"));
     244        node.setOsmId(1, 1);
     245        assertTrue(RoutingIslandsTest.outsideConnections(node));
     246        ds.addDataSource(new DataSource(new Bounds(-0.1, -0.1, 0.1, 0.1), "Test bounds"));
     247        assertFalse(RoutingIslandsTest.outsideConnections(node));
     248        node.put("amenity", "parking_entrance");
     249        assertTrue(RoutingIslandsTest.outsideConnections(node));
     250    }
     251
     252    /**
     253     * Test method for {@link RoutingIslandsTest#isOneway(Way, String)}.
     254     */
     255    @Test
     256    public void testIsOneway() {
     257        Way way = TestUtils.newWay("highway=residential", new Node(new LatLon(0, 0)), new Node(new LatLon(1, 1)));
     258        assertEquals(Integer.valueOf(0), RoutingIslandsTest.isOneway(way, null));
     259        assertEquals(Integer.valueOf(0), RoutingIslandsTest.isOneway(way, " "));
     260        way.put("oneway", "yes");
     261        assertEquals(Integer.valueOf(1), RoutingIslandsTest.isOneway(way, null));
     262        assertEquals(Integer.valueOf(1), RoutingIslandsTest.isOneway(way, " "));
     263        way.put("oneway", "-1");
     264        assertEquals(Integer.valueOf(-1), RoutingIslandsTest.isOneway(way, null));
     265        assertEquals(Integer.valueOf(-1), RoutingIslandsTest.isOneway(way, " "));
     266
     267        way.put("vehicle:forward", "yes");
     268        assertEquals(Integer.valueOf(0), RoutingIslandsTest.isOneway(way, "vehicle"));
     269        way.put("vehicle:backward", "no");
     270        assertEquals(Integer.valueOf(1), RoutingIslandsTest.isOneway(way, "vehicle"));
     271        way.put("vehicle:forward", "no");
     272        assertNull(RoutingIslandsTest.isOneway(way, "vehicle"));
     273        way.put("vehicle:backward", "yes");
     274        assertEquals(Integer.valueOf(-1), RoutingIslandsTest.isOneway(way, "vehicle"));
     275
     276        way.put("oneway", "yes");
     277        way.remove("vehicle:backward");
     278        way.remove("vehicle:forward");
     279        assertEquals(Integer.valueOf(1), RoutingIslandsTest.isOneway(way, "vehicle"));
     280        way.remove("oneway");
     281        assertEquals(Integer.valueOf(0), RoutingIslandsTest.isOneway(way, "vehicle"));
     282
     283        way.put("oneway", "-1");
     284        assertEquals(Integer.valueOf(-1), RoutingIslandsTest.isOneway(way, "vehicle"));
     285    }
     286
     287    /**
     288     * Test method for {@link RoutingIslandsTest#firstNode(Way, String)}.
     289     */
     290    @Test
     291    public void testFirstNode() {
     292        Way way = TestUtils.newWay("highway=residential", new Node(new LatLon(0, 0)), new Node(new LatLon(1, 1)));
     293        assertEquals(way.firstNode(), RoutingIslandsTest.firstNode(way, null));
     294        way.put("oneway", "yes");
     295        assertEquals(way.firstNode(), RoutingIslandsTest.firstNode(way, null));
     296        way.put("oneway", "-1");
     297        assertEquals(way.lastNode(), RoutingIslandsTest.firstNode(way, null));
     298
     299        way.put("vehicle:forward", "yes");
     300        assertEquals(way.firstNode(), RoutingIslandsTest.firstNode(way, "vehicle"));
     301        way.put("vehicle:backward", "no");
     302        assertEquals(way.firstNode(), RoutingIslandsTest.firstNode(way, "vehicle"));
     303        way.put("vehicle:forward", "no");
     304        assertEquals(way.firstNode(), RoutingIslandsTest.firstNode(way, "vehicle"));
     305        way.put("vehicle:backward", "yes");
     306        assertEquals(way.lastNode(), RoutingIslandsTest.firstNode(way, "vehicle"));
     307    }
     308
     309    /**
     310     * Test method for {@link RoutingIslandsTest#lastNode(Way, String)}.
     311     */
     312    @Test
     313    public void testLastNode() {
     314        Way way = TestUtils.newWay("highway=residential", new Node(new LatLon(0, 0)), new Node(new LatLon(1, 1)));
     315        assertEquals(way.lastNode(), RoutingIslandsTest.lastNode(way, null));
     316        way.put("oneway", "yes");
     317        assertEquals(way.lastNode(), RoutingIslandsTest.lastNode(way, null));
     318        way.put("oneway", "-1");
     319        assertEquals(way.firstNode(), RoutingIslandsTest.lastNode(way, null));
     320
     321        way.put("vehicle:forward", "yes");
     322        assertEquals(way.lastNode(), RoutingIslandsTest.lastNode(way, "vehicle"));
     323        way.put("vehicle:backward", "no");
     324        assertEquals(way.lastNode(), RoutingIslandsTest.lastNode(way, "vehicle"));
     325        way.put("vehicle:forward", "no");
     326        assertEquals(way.lastNode(), RoutingIslandsTest.lastNode(way, "vehicle"));
     327        way.put("vehicle:backward", "yes");
     328        assertEquals(way.firstNode(), RoutingIslandsTest.lastNode(way, "vehicle"));
     329    }
     330
     331    /**
     332     * Test with a way that by default does not give access to motor vehicles
     333     */
     334    @Test
     335    public void testNoAccessWay() {
     336        Way i70w = TestUtils.newWay("highway=motorway hgv=designated", new Node(new LatLon(39.1058104, -108.5258586)),
     337                new Node(new LatLon(39.1052235, -108.5293733)));
     338        Way i70e = TestUtils.newWay("highway=motorway hgv=designated", new Node(new LatLon(39.1049905, -108.5293074)),
     339                new Node(new LatLon(39.1055829, -108.5257975)));
     340        Way testPath = TestUtils.newWay("highway=footway", i70w.lastNode(true), i70e.firstNode(true));
     341        DataSet ds = new DataSet();
     342        Arrays.asList(i70w, i70e, testPath).forEach(way -> addToDataSet(ds, way));
     343
     344        RoutingIslandsTest test = new RoutingIslandsTest();
     345        test.startTest(null);
     346        test.visit(ds.allPrimitives());
     347        test.endTest();
     348    }
     349
     350    private static void addToDataSet(DataSet ds, OsmPrimitive primitive) {
     351        if (primitive instanceof Way) {
     352            ((Way) primitive).getNodes().parallelStream().distinct().filter(node -> node.getDataSet() == null)
     353                    .forEach(ds::addPrimitive);
     354        }
     355        if (primitive.getDataSet() == null)
     356            ds.addPrimitive(primitive);
     357        Long id = Math.max(ds.allPrimitives().parallelStream().mapToLong(prim -> prim.getId()).max().orElse(0L), 0L);
     358        for (OsmPrimitive osm : ds.allPrimitives().parallelStream().filter(prim -> prim.getUniqueId() < 0)
     359                .collect(Collectors.toList())) {
     360            id++;
     361            osm.setOsmId(id, 1);
     362        }
     363    }
     364}