001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io.imagery;
003
004import java.io.IOException;
005import java.net.HttpURLConnection;
006import java.net.URL;
007import java.util.Collections;
008import java.util.HashMap;
009import java.util.List;
010import java.util.Map;
011
012import org.openstreetmap.josm.data.Preferences;
013import org.openstreetmap.josm.spi.preferences.Config;
014import org.openstreetmap.josm.tools.HttpClient;
015import org.openstreetmap.josm.tools.HttpClient.Response;
016import org.openstreetmap.josm.tools.Utils;
017
018/**
019 * Provider of confidential imagery API keys.
020 * @since 15855
021 */
022public final class ApiKeyProvider {
023
024    private static final Map<String, String> CACHE = new HashMap<>();
025
026    private ApiKeyProvider() {
027        // Hide public constructor
028    }
029
030    private static List<String> getApiKeySites() {
031        return Preferences.main().getList("apikey.sites",
032                Collections.singletonList(Config.getUrls().getJOSMWebsite()+"/mapkey/"));
033    }
034
035    /**
036     * Retrieves the API key for the given imagery id.
037     * @param imageryId imagery id
038     * @return the API key for the given imagery id
039     * @throws IOException in case of I/O error
040     */
041    public static String retrieveApiKey(String imageryId) throws IOException {
042        if (CACHE.containsKey(imageryId)) {
043            return CACHE.get(imageryId);
044        }
045        for (String siteUrl : getApiKeySites()) {
046            Response response = HttpClient.create(new URL(siteUrl + imageryId)).connect();
047            try {
048                if (response.getResponseCode() == HttpURLConnection.HTTP_OK) {
049                    String key = Utils.strip(response.fetchContent());
050                    CACHE.put(imageryId, key);
051                    return key;
052                }
053            } finally {
054                response.disconnect();
055            }
056        }
057        return null;
058    }
059}