001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.util.regex.Matcher;
007import java.util.regex.Pattern;
008
009import org.openstreetmap.josm.data.Bounds;
010
011/**
012 * Parses a Geo URL (as specified in <a href="https://tools.ietf.org/html/rfc5870">RFC 5870</a>) into {@link Bounds}.
013 *
014 * Note that Geo URLs are also handled by {@link OsmUrlToBounds}.
015 */
016public final class GeoUrlToBounds {
017
018    /**
019     * The pattern of a geo: url, having named match groups.
020     */
021    public static final Pattern PATTERN = Pattern.compile(
022            "geo:(?<lat>[+-]?[0-9.]+),(?<lon>[+-]?[0-9.]+)(?<crs>;crs=wgs84)?(?<uncertainty>;u=[0-9.]+)?(\\?z=(?<zoom>[0-9]+))?");
023
024    private GeoUrlToBounds() {
025        // Hide default constructor for utils classes
026    }
027
028    /**
029     * Parses a Geo URL (as specified in <a href="https://tools.ietf.org/html/rfc5870">RFC 5870</a>) into {@link Bounds}.
030     * @param url the URL to be parsed
031     * @return the parsed {@link Bounds}
032     */
033    public static Bounds parse(final String url) {
034        CheckParameterUtil.ensureParameterNotNull(url, "url");
035        final Matcher m = PATTERN.matcher(url);
036        if (m.matches()) {
037            final double lat;
038            final double lon;
039            final int zoom;
040            try {
041                lat = Double.parseDouble(m.group("lat"));
042            } catch (NumberFormatException e) {
043                Logging.warn(tr("URL does not contain valid {0}", tr("latitude")), e);
044                return null;
045            }
046            try {
047                lon = Double.parseDouble(m.group("lon"));
048            } catch (NumberFormatException e) {
049                Logging.warn(tr("URL does not contain valid {0}", tr("longitude")), e);
050                return null;
051            }
052            try {
053                zoom = m.group("zoom") != null ? Integer.parseInt(m.group("zoom")) : 18;
054            } catch (NumberFormatException e) {
055                Logging.warn(tr("URL does not contain valid {0}", tr("zoom")), e);
056                return null;
057            }
058            return OsmUrlToBounds.positionToBounds(lat, lon, zoom);
059        } else {
060            return null;
061        }
062    }
063}