001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.imagery;
003
004import static org.openstreetmap.josm.tools.I18n.marktr;
005import static org.openstreetmap.josm.tools.I18n.tr;
006
007import java.io.IOException;
008import java.util.Arrays;
009import java.util.Map;
010import java.util.Objects;
011import java.util.Optional;
012import java.util.regex.Matcher;
013import java.util.regex.Pattern;
014
015import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
016import org.openstreetmap.josm.spi.preferences.Config;
017
018/**
019 * Patterns that can be replaced in imagery URLs.
020 * @since 17578
021 */
022public final class ImageryPatterns {
023
024    // CHECKSTYLE.OFF: SingleSpaceSeparator
025    static final Pattern PATTERN_HEADER = Pattern.compile("\\{header\\(([^,]+),([^}]+)\\)\\}");
026    static final Pattern PATTERN_PROJ   = Pattern.compile("\\{proj\\}");
027    static final Pattern PATTERN_WKID   = Pattern.compile("\\{wkid\\}");
028    static final Pattern PATTERN_BBOX   = Pattern.compile("\\{bbox\\}");
029    static final Pattern PATTERN_W      = Pattern.compile("\\{w\\}");
030    static final Pattern PATTERN_S      = Pattern.compile("\\{s\\}");
031    static final Pattern PATTERN_E      = Pattern.compile("\\{e\\}");
032    static final Pattern PATTERN_N      = Pattern.compile("\\{n\\}");
033    static final Pattern PATTERN_WIDTH  = Pattern.compile("\\{width\\}");
034    static final Pattern PATTERN_HEIGHT = Pattern.compile("\\{height\\}");
035    static final Pattern PATTERN_TIME   = Pattern.compile("\\{time\\}"); // Sentinel-2
036    static final Pattern PATTERN_PARAM  = Pattern.compile("\\{([^}]+)\\}");
037    /**
038     * The api key pattern is used to allow us to quickly switch apikeys. This is functionally the same as the pattern
039     * in {@link org.openstreetmap.gui.jmapviewer.tilesources.TemplatedTMSTileSource}.
040     */
041    static final Pattern PATTERN_API_KEY = Pattern.compile("\\{apikey}");
042    // CHECKSTYLE.ON: SingleSpaceSeparator
043
044    private static final Pattern[] ALL_WMS_PATTERNS = {
045            PATTERN_HEADER, PATTERN_PROJ, PATTERN_WKID, PATTERN_BBOX,
046            PATTERN_W, PATTERN_S, PATTERN_E, PATTERN_N,
047            PATTERN_WIDTH, PATTERN_HEIGHT, PATTERN_TIME,
048            PATTERN_API_KEY
049    };
050
051    private static final Pattern[] ALL_WMTS_PATTERNS = {
052            PATTERN_HEADER, PATTERN_API_KEY
053    };
054
055    private ImageryPatterns() {
056        // Hide public constructor
057    }
058
059    private static void checkUrlPatterns(String url, Pattern[] allPatterns, String errMessage) {
060        Matcher m = PATTERN_PARAM.matcher(Objects.requireNonNull(url, "url"));
061        while (m.find()) {
062            if (Arrays.stream(allPatterns).noneMatch(pattern -> pattern.matcher(m.group()).matches())) {
063                throw new IllegalArgumentException(tr(errMessage, m.group(), url));
064            }
065        }
066    }
067
068    static void checkWmsUrlPatterns(String url) {
069        checkUrlPatterns(url, ALL_WMS_PATTERNS,
070                marktr("{0} is not a valid WMS argument. Please check this server URL:\n{1}"));
071    }
072
073    static void checkWmtsUrlPatterns(String url) {
074        checkUrlPatterns(url, ALL_WMTS_PATTERNS,
075                marktr("{0} is not a valid WMTS argument. Please check this server URL:\n{1}"));
076    }
077
078    static String handleHeaderTemplate(String url, Map<String, String> headers) {
079        StringBuffer output = new StringBuffer();
080        Matcher matcher = PATTERN_HEADER.matcher(url);
081        while (matcher.find()) {
082            headers.put(matcher.group(1), matcher.group(2));
083            matcher.appendReplacement(output, "");
084        }
085        matcher.appendTail(output);
086        return output.toString();
087    }
088
089    /**
090     * Handle the {@link #PATTERN_API_KEY} replacement
091     * @param id The id of the info
092     * @param url The templated url
093     * @return The templated url with {@link #PATTERN_API_KEY} replaced
094     */
095    static String handleApiKeyTemplate(final String id, final String url) {
096        if (id != null && url != null) {
097            final Matcher matcher = PATTERN_API_KEY.matcher(url);
098            if (matcher.find()) {
099                try {
100                    return Optional.ofNullable(FeatureAdapter.retrieveApiKey(id))
101                            .map(matcher::replaceAll)
102                            /* None of the configured API key sites had an API key for the id. */
103                            .orElseThrow(() -> {
104                                // Give a more complete error message so that users can fix the problem without
105                                // opening a bug report. Hopefully.
106                                final String message;
107                                if (Config.getPref().getKeySet().contains("apikey.sites")) {
108                                    message = tr("Advanced preference ''{0}'' is not default. Please consider resetting it.", "apikey.sites");
109                                } else {
110                                    message = tr("API key for imagery with id={0} may not be available.", id);
111                                }
112                                return new IOException(message);
113                            });
114                } catch (IOException e) {
115                    // Match rough behavior in JMapViewer TemplatedTMSTileSource, but with better error message.
116                    throw new IllegalArgumentException(tr("Could not retrieve API key for imagery with id={0}. Cannot add layer.\n{1}",
117                            id, e.getMessage()), e);
118                }
119            }
120        }
121        return url;
122    }
123}