| 1 | // License: GPL. For details, see LICENSE file.
|
|---|
| 2 | package org.openstreetmap.josm.io.imagery;
|
|---|
| 3 |
|
|---|
| 4 | import java.io.IOException;
|
|---|
| 5 | import java.net.HttpURLConnection;
|
|---|
| 6 | import java.net.URL;
|
|---|
| 7 | import java.util.Collections;
|
|---|
| 8 | import java.util.HashMap;
|
|---|
| 9 | import java.util.List;
|
|---|
| 10 | import java.util.Map;
|
|---|
| 11 |
|
|---|
| 12 | import org.openstreetmap.josm.data.Preferences;
|
|---|
| 13 | import org.openstreetmap.josm.spi.preferences.Config;
|
|---|
| 14 | import org.openstreetmap.josm.tools.HttpClient;
|
|---|
| 15 | import org.openstreetmap.josm.tools.HttpClient.Response;
|
|---|
| 16 | import org.openstreetmap.josm.tools.Utils;
|
|---|
| 17 |
|
|---|
| 18 | /**
|
|---|
| 19 | * Provider of confidential imagery API keys.
|
|---|
| 20 | * @since 15855
|
|---|
| 21 | */
|
|---|
| 22 | public final class ApiKeyProvider {
|
|---|
| 23 |
|
|---|
| 24 | private static final Map<String, String> CACHE = new HashMap<>();
|
|---|
| 25 |
|
|---|
| 26 | private ApiKeyProvider() {
|
|---|
| 27 | // Hide public constructor
|
|---|
| 28 | }
|
|---|
| 29 |
|
|---|
| 30 | private static List<String> getApiKeySites() {
|
|---|
| 31 | return Preferences.main().getList("apikey.sites",
|
|---|
| 32 | Collections.singletonList(Config.getUrls().getJOSMWebsite()+"/mapkey/"));
|
|---|
| 33 | }
|
|---|
| 34 |
|
|---|
| 35 | /**
|
|---|
| 36 | * Retrieves the API key for the given imagery id.
|
|---|
| 37 | * @param imageryId imagery id
|
|---|
| 38 | * @return the API key for the given imagery id
|
|---|
| 39 | * @throws IOException in case of I/O error
|
|---|
| 40 | */
|
|---|
| 41 | public static String retrieveApiKey(String imageryId) throws IOException {
|
|---|
| 42 | if (CACHE.containsKey(imageryId)) {
|
|---|
| 43 | return CACHE.get(imageryId);
|
|---|
| 44 | }
|
|---|
| 45 | for (String siteUrl : getApiKeySites()) {
|
|---|
| 46 | Response response = HttpClient.create(new URL(siteUrl + imageryId)).connect();
|
|---|
| 47 | try {
|
|---|
| 48 | if (response.getResponseCode() == HttpURLConnection.HTTP_OK) {
|
|---|
| 49 | String key = Utils.strip(response.fetchContent());
|
|---|
| 50 | CACHE.put(imageryId, key);
|
|---|
| 51 | return key;
|
|---|
| 52 | }
|
|---|
| 53 | } finally {
|
|---|
| 54 | response.disconnect();
|
|---|
| 55 | }
|
|---|
| 56 | }
|
|---|
| 57 | return null;
|
|---|
| 58 | }
|
|---|
| 59 | }
|
|---|